@leviyuan/lodestar 0.21.2 → 0.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/lodestar.js +142 -142
  2. package/package.json +1 -1
package/dist/lodestar.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as xL}from"node:module";var UL=Object.create;var{getPrototypeOf:OL,defineProperty:E5,getOwnPropertyNames:AL}=Object;var NL=Object.prototype.hasOwnProperty;function RL($){return this[$]}var TL,EL,QX=($,Z,J)=>{var Q=$!=null&&typeof $==="object";if(Q){var Y=Z?TL??=new WeakMap:EL??=new WeakMap,V=Y.get($);if(V)return V}J=$!=null?UL(OL($)):{};let X=Z||!$||!$.__esModule?E5(J,"default",{value:$,enumerable:!0}):J;for(let z of AL($))if(!NL.call(X,z))E5(X,z,{get:RL.bind($,z),enumerable:!0});if(Q)Y.set($,X);return X};var YX=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var SL=($)=>$;function CL($,Z){this[$]=SL.bind(null,Z)}var H1=($,Z)=>{for(var J in Z)E5($,J,{get:Z[J],enumerable:!0,configurable:!0,set:CL.bind(Z,J)})};var R=($,Z)=>()=>($&&(Z=$($=0)),Z);var z4=xL(import.meta.url);var S5=YX((dS,zX)=>{var{homedir:VX}=z4("node:os"),{join:R9}=z4("node:path");function XX(){if(process.env.LODESTAR_DATA_DIR)return process.env.LODESTAR_DATA_DIR;if(process.env.XDG_DATA_HOME)return R9(process.env.XDG_DATA_HOME,"lodestar");if(process.platform==="win32")return R9(process.env.LOCALAPPDATA??R9(VX(),"AppData","Local"),"Lodestar");return R9(VX(),".local","share","lodestar")}function bL(){return R9(XX(),"managed-claude-plugin")}zX.exports={lodestarDataDir:XX,managedClaudePluginDir:bL}});import{homedir as kL}from"node:os";import{join as e}from"node:path";function vL($,Z,J){if($)return $;if(Z)return e(Z,"lodestar");return J}function fL(){if(wL)return e(process.env.APPDATA??e(HX,"AppData","Roaming"),"Lodestar");return e(HX,".config","lodestar")}var W3,HX,wL,C5,$0,c0,D$,H4,x5,b5,k5,w5,GX,WX,v5,K3,X2,KX,B3,G4,W4,BX,jX,_X,f5,PX,LX,y5,h5,qX,I5,z2,j3;var H0=R(()=>{W3=QX(S5(),1),HX=kL(),wL=process.platform==="win32";C5=vL(process.env.LODESTAR_CONFIG_DIR,process.env.XDG_CONFIG_HOME,fL()),$0=W3.lodestarDataDir(),c0=process.env.LODESTAR_CONFIG??e(C5,"config.toml"),D$=e($0,"daemon.pid"),H4=e($0,"daemon.log"),x5=e($0,"session-chat-map.json"),b5=e($0,"session-resume-map.json"),k5=e($0,"session-turns-map.json"),w5=e($0,"session-model-map.json"),GX=e($0,"claude-translation-context"),WX=e($0,"claude-translation-traces"),v5=e($0,"temp-session-leases.json"),K3=e($0,"tasklist-map.json"),X2=e($0,"agent-runs"),KX=e($0,"agent-project-client.json"),B3=e($0,"agent-session-ids.json"),G4=W3.managedClaudePluginDir(),W4=e($0,"dsh"),BX=e($0,"codex-accounts"),jX=e($0,"codex-accounts.json"),_X=e($0,"codex-quota-blocks.json"),f5=e($0,"agent-runtimes"),PX=e($0,"context-window-cache.json"),LX=e($0,"notify-callbacks.json"),y5=e($0,"alive-on-shutdown.json"),h5=e($0,"inbox"),qX=e($0,"file-deliveries"),I5=e($0,"file-delivery-groups.json"),z2=e($0,"debug.sock"),j3=e($0,"debug-context.json")});import{execFileSync as m5}from"node:child_process";import{readFileSync as DX,readlinkSync as yL,writeFileSync as hL}from"node:fs";import{isAbsolute as IL,resolve as _3,win32 as g5}from"node:path";function gL(){if(!process.argv[1])throw Error("无法确定 daemon 入口路径");return _3(process.argv[1])}function mL($){if(!/^[1-9]\d*$/.test($.trim()))return null;let Z=Number($.trim());return Number.isSafeInteger(Z)&&Z<=2147483647?Z:null}function p5($){try{return process.kill($,0),!0}catch(Z){if(Z.code==="ESRCH")return!1;throw Z}}function pL($){if(!p5($))return null;try{let Z;if(process.platform==="linux")Z=DX(`/proc/${$}/cmdline`,"utf8");else if(process.platform==="darwin")Z=m5("ps",["-p",String($),"-o","args="],{encoding:"utf8",timeout:2000});else if(process.platform==="win32")Z=m5("powershell",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference='Stop'; (Get-CimInstance Win32_Process -Filter 'ProcessId=${$}' -ErrorAction Stop).CommandLine`],{encoding:"utf8",timeout:5000});else throw Error(`不支持查询 ${process.platform} 平台的进程入口`);if(!Z.trim())throw Error(`PID ${$} 的命令行为空,无法核对 daemon 身份`);return Z.trim()}catch(Z){if(!p5($))return null;throw Error(`无法读取 PID ${$} 的命令行: ${Z instanceof Error?Z.message:String(Z)}`,{cause:Z})}}function iL($){let Z=$[0]?.replace(/\\/g,"/").split("/").pop()?.toLowerCase();if(!Z||!/^(?:node|nodejs|bun)(?:\.exe)?$/.test(Z))return null;let J=Z.startsWith("bun"),Q=J?lL:cL,Y=J?dL:uL,V=!1,X=1;while(X<$.length){let z=$[X];if(/^-[ep]/.test(z)||z==="--eval"||z==="--print"||/^(?:--eval|--print)=/.test(z))return null;if(!J&&(z==="-c"||z==="--check"||z==="--run"||z.startsWith("--run=")))return null;if(z==="--")return X+1;if(!z.startsWith("-")){if(J&&!V&&z==="run"){V=!0,X++;continue}return X}let H=z.split("=")[0];if(Q.has(H))X+=z.includes("=")?1:2;else if(Y.has(H))X++;else throw Error(`无法安全核对 daemon 入口: 未识别的 ${Z} 选项 ${z}`)}return null}function nL($){if(process.platform==="linux")return yL(`/proc/${$}/cwd`);if(process.platform==="darwin"){let J=m5("lsof",["-a","-p",String($),"-d","cwd","-Fn"],{encoding:"utf8",timeout:2000}).split(`
3
- `).find((Q)=>Q.startsWith("n"))?.slice(1);if(J)return J}throw Error(`无法确定 PID ${$} 的工作目录,不能核对相对 daemon 入口`)}function aL($,Z){if(!Number.isSafeInteger($)||$<=0||$>2147483647||!Z)return!1;let J=pL($);if(J===null)return!1;let Q=process.platform==="linux"?J.split("\x00").filter(Boolean):(J.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map((X)=>X.replace(/^(?:"(.*)"|'(.*)')$/,"$1$2")),Y=iL(Q);if(Y===null||!Q[Y])return!1;let V=Q[Y];if(process.platform==="win32"){if(!g5.isAbsolute(V))throw Error(`PID ${$} 使用相对入口,无法安全核对 daemon 身份`);return g5.normalize(V).toLowerCase()===g5.normalize(Z).toLowerCase()}if(process.platform==="darwin"&&Z.startsWith(`${V} `))throw Error(`PID ${$} 的入口包含无法区分的空格,不能安全核对 daemon 身份`);if(!IL(V))V=_3(nL($),V);return _3(V)===_3(Z)}function P3($){let Z;try{Z=DX($,"utf8")}catch(V){if(V.code==="ENOENT")return{state:"continue"};throw V}let J=Z.split(`
4
- `),Q=mL(J[0]??""),Y=(J[1]??"").trim();if(Q===null)throw Error(`PID 文件格式坏: ${$}`);if(!Y)return p5(Q)?{state:"exit",pid:Q}:{state:"continue"};return aL(Q,Y)?{state:"exit",pid:Q}:{state:"continue"}}function FX($){hL($,`${process.pid}
5
- ${gL()}`)}var cL,uL,lL,dL;var c5=R(()=>{cL=new Set(["-r","--require","--import","--loader","--experimental-loader","--conditions","-C","--inspect-port","--title","--icu-data-dir","--openssl-config","--redirect-warnings","--diagnostic-dir","--report-directory","--report-filename","--env-file","--env-file-if-exists","--watch-path","--unhandled-rejections","--max-old-space-size","--max-semi-space-size","--stack-size"]),uL=new Set(["--enable-source-maps","--no-warnings","--trace-warnings","--trace-uncaught","--preserve-symlinks","--preserve-symlinks-main","--inspect","--inspect-brk","--watch","--watch-preserve-output","--experimental-strip-types","--experimental-transform-types"]),lL=new Set(["--preload","--cwd","--config","-c","--env-file","--tsconfig-override"]),dL=new Set(["--hot","--watch","--smol","--no-clear-screen","--silent","--bun","--no-install"])});import{execFile as oL}from"node:child_process";import{readFile as sL}from"node:fs/promises";import{homedir as tL}from"node:os";import{join as MX}from"node:path";import{promisify as rL}from"node:util";import{Address4 as L3,Address6 as q3}from"ip-address";function K4($,Z){return $[Z.toLowerCase()]?.trim()||$[Z]?.trim()||void 0}function U3($){let Z=$.hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z.endsWith(".localhost")||Z==="::1"||/^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(Z)||/^::ffff:(?:127\.|7f[0-9a-f]{2}:)/.test(Z)}function u5($,Z=""){let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=$.port||($.protocol==="https:"?"443":"80");return Z.split(/[,;\s]+/).filter(Boolean).some((Y)=>{let V=Y.toLowerCase();if(V==="*")return!0;if(V==="<local>")return!J.includes(".")&&!J.includes(":");if(V.includes("/")){if(L3.isValid(V))return L3.isValid(J)&&new L3(J).isInSubnet(new L3(V));if(q3.isValid(V))return q3.isValid(J)&&new q3(J).isInSubnet(new q3(V));throw Error("network proxy: invalid IP range in bypass list")}let X=V.match(/^(\[[^\]]+\]|[^:]+):(\d+)$/);if(X&&X[2]!==Q)return!1;let z=(X?X[1]:V).replace(/^\[|\]$/g,"").replace(/^\*?\./,"");return J===z||J.endsWith(`.${z}`)})}function UX($,Z){let J;try{J=new URL($)}catch{throw Error(`network proxy: ${Z} contains an invalid proxy URL`)}if(!["http:","https:"].includes(J.protocol))throw Error(`network proxy: ${Z} must use an HTTP(S) proxy; SOCKS and PAC are not supported`);if(!J.hostname||J.search||J.hash||J.pathname&&J.pathname!=="/")throw Error(`network proxy: ${Z} must contain a proxy host and port without a path or query`);return J.href}function OX($,Z,J={}){if(!["http:","https:"].includes($.protocol))throw Error(`network: unsupported URL protocol ${$.protocol}`);if(U3($)||u5($,K4(Z,"NO_PROXY")))return;let Q=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY",Y=K4(Z,Q)||K4(Z,"ALL_PROXY");if(Y)return UX(Y,"environment");if(J.unsupported)throw Error(`network proxy: ${J.unsupported}`);if(u5($,J.bypass))return;let V=($.protocol==="https:"?J.https:J.http)||J.all;return V?UX(V,"system settings"):void 0}function M3($,Z,J="http"){if(typeof $!=="string"||!$.trim()||!Number.isInteger(Number(Z))||Number(Z)<1||Number(Z)>65535)throw Error("network proxy: system proxy has an invalid host or port");let Q=$.includes(":")&&!$.startsWith("[")?`[${$}]`:$;return`${J}://${Q}:${Z}`}function $q($){if($.AutoConfigURL)return{unsupported:"Windows PAC proxy is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(!$.ProxyEnable)return $.AutoDetect?{unsupported:"Windows automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"}:{};if(typeof $.ProxyServer!=="string"||!$.ProxyServer.trim())throw Error("network proxy: Windows proxy is enabled without a server");let Z={bypass:String($.ProxyOverride??"")};for(let J of $.ProxyServer.split(";").map((Q)=>Q.trim()).filter(Boolean)){let Q=J.match(/^(http|https|socks)=(.+)$/i),Y=Q?Q[2]:J,V=/^[a-z][\w+.-]*:\/\//i.test(Y)?Y:`http://${Y}`;if(!Q)Z.all=V;else if(Q[1].toLowerCase()==="socks")Z.all=`socks://${Y.replace(/^socks\w*:\/\//,"")}`;else Z[Q[1].toLowerCase()]=V}return Z}function Zq($){let Z=(Y)=>$.match(new RegExp(`^\\s*${Y}\\s*:\\s*(.*?)\\s*$`,"m"))?.[1];if(Z("ProxyAutoConfigEnable")==="1"||Z("ProxyAutoDiscoveryEnable")==="1")return{unsupported:"macOS PAC/automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};let J={};if(Z("HTTPEnable")==="1")J.http=M3(Z("HTTPProxy"),Z("HTTPPort"));if(Z("HTTPSEnable")==="1")J.https=M3(Z("HTTPSProxy"),Z("HTTPSPort"));if(Z("SOCKSEnable")==="1")J.all=M3(Z("SOCKSProxy"),Z("SOCKSPort"),"socks");let Q=$.match(/ExceptionsList\s*:\s*<array>\s*\{([^}]*)\}/)?.[1]??"";if(J.bypass=[...Q.matchAll(/^\s*\d+\s*:\s*(.*?)\s*$/gm)].map((Y)=>Y[1]).join(","),Z("ExcludeSimpleHostnames")==="1")J.bypass+=",<local>";return J}function D3($){if($===void 0)return"";if(!/^(['"]).*\1$/.test($))throw Error("network proxy: invalid GNOME proxy string");return $.slice(1,-1).replace(/\\([\\'"])/g,"$1")}function Jq($){let Z=new Map($.split(`
6
- `).filter(Boolean).map((Y)=>{let V=Y.match(/^org\.gnome\.system\.proxy(\.\w+)?\s+([\w-]+)\s+(.*)$/);if(!V)throw Error("network proxy: invalid GNOME proxy settings");return[`${V[1]??""}/${V[2]}`,V[3]]})),J=D3(Z.get("/mode"));if(J==="none")return{};if(J==="auto")return{unsupported:"GNOME PAC proxy is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(J!=="manual")throw Error("network proxy: unknown GNOME proxy mode");let Q={};for(let Y of["http","https","socks"]){let V=D3(Z.get(`.${Y}/host`));if(!V)continue;let X=new URL(M3(V,Z.get(`.${Y}/port`),Y==="socks"?"socks":"http"));if(Y==="http"&&Z.get(".http/use-authentication")==="true")X.username=D3(Z.get(".http/authentication-user")),X.password=D3(Z.get(".http/authentication-password"));Q[Y==="socks"?"all":Y]=X.href}if(Z.get("/use-same-proxy")==="true"&&Q.http)Q.https=Q.http;return Q.bypass=[...(Z.get("/ignore-hosts")??"").matchAll(/'((?:\\.|[^'])*)'/g)].map((Y)=>Y[1]).join(","),Q}function Qq($){let Z=$.match(/^\[Proxy Settings\]\s*\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m)?.[1];if(Z===void 0)return;let J=new Map(Z.split(`
7
- `).filter((V)=>V.includes("=")).map((V)=>{let X=V.indexOf("=");return[V.slice(0,X).trim(),V.slice(X+1).trim()]})),Q=J.get("ProxyType")??"0";if(Q==="0"||Q==="4")return{};if(Q!=="1")return{unsupported:"KDE PAC/automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(J.get("ReversedException")==="true")return{unsupported:"KDE reversed proxy exceptions are not supported"};let Y={bypass:J.get("NoProxyFor")};for(let V of["http","https","socks"]){let X=J.get(`${V}Proxy`);if(!X)continue;let z=X.replace(/\s+(\d+)$/,":$1");Y[V==="socks"?"all":V]=/^[a-z][\w+.-]*:\/\//i.test(z)?z:`${V==="socks"?"socks":"http"}://${z}`}return Y}async function F3($,Z,J=5000){let{stdout:Q}=await eL($,Z,{encoding:"utf8",timeout:J,maxBuffer:262144,windowsHide:!0});return Q}async function Vq(){if(process.platform==="win32")return $q(JSON.parse(await F3("powershell.exe",["-NoProfile","-NonInteractive","-Command",Yq],15000)));if(process.platform==="darwin")return Zq(await F3("/usr/sbin/scutil",["--proxy"]));if(process.platform==="linux"){let $=MX(process.env.XDG_CONFIG_HOME||MX(tL(),".config"),"kioslaverc");try{let J=Qq(await sL($,"utf8"));if(J&&(!process.env.XDG_CURRENT_DESKTOP||/kde/i.test(process.env.XDG_CURRENT_DESKTOP)))return J}catch(J){if(J?.code!=="ENOENT")throw J}let Z;try{Z=await F3("gsettings",["list-schemas"])}catch(J){if(J?.code==="ENOENT")return{};throw J}if(!Z.split(/\r?\n/).includes("org.gnome.system.proxy"))return{};return Jq(await F3("gsettings",["list-recursively","org.gnome.system.proxy"]))}return{}}function Xq($=Vq,Z=process.env,J=Date.now){let Q;return async(Y)=>{if(U3(Y)||u5(Y,K4(Z,"NO_PROXY"))||K4(Z,Y.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY")||K4(Z,"ALL_PROXY"))return OX(Y,Z);if(!Q||Q.until<=J()){let V=$().catch((X)=>{if(Q?.value===V)Q=void 0;if(X instanceof Error&&X.message.startsWith("network proxy:"))throw X;let z=X instanceof Error?X.code??X.name:"unknown error";throw Error(`network proxy: failed to read ${process.platform} system proxy settings (${z})`,{cause:X})});Q={until:J()+30000,value:V}}return OX(Y,Z,await Q.value)}}var eL,Yq,AX;var NX=R(()=>{eL=rL(oL);Yq=String.raw`
2
+ import{createRequire as xL}from"node:module";var UL=Object.create;var{getPrototypeOf:OL,defineProperty:E5,getOwnPropertyNames:AL}=Object;var NL=Object.prototype.hasOwnProperty;function RL($){return this[$]}var TL,EL,QX=($,Z,J)=>{var Q=$!=null&&typeof $==="object";if(Q){var Y=Z?TL??=new WeakMap:EL??=new WeakMap,V=Y.get($);if(V)return V}J=$!=null?UL(OL($)):{};let X=Z||!$||!$.__esModule?E5(J,"default",{value:$,enumerable:!0}):J;for(let z of AL($))if(!NL.call(X,z))E5(X,z,{get:RL.bind($,z),enumerable:!0});if(Q)Y.set($,X);return X};var YX=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var SL=($)=>$;function CL($,Z){this[$]=SL.bind(null,Z)}var H1=($,Z)=>{for(var J in Z)E5($,J,{get:Z[J],enumerable:!0,configurable:!0,set:CL.bind(Z,J)})};var R=($,Z)=>()=>($&&(Z=$($=0)),Z);var z4=xL(import.meta.url);var S5=YX((dS,zX)=>{var{homedir:VX}=z4("node:os"),{join:R9}=z4("node:path");function XX(){if(process.env.LODESTAR_DATA_DIR)return process.env.LODESTAR_DATA_DIR;if(process.env.XDG_DATA_HOME)return R9(process.env.XDG_DATA_HOME,"lodestar");if(process.platform==="win32")return R9(process.env.LOCALAPPDATA??R9(VX(),"AppData","Local"),"Lodestar");return R9(VX(),".local","share","lodestar")}function bL(){return R9(XX(),"managed-claude-plugin")}zX.exports={lodestarDataDir:XX,managedClaudePluginDir:bL}});import{homedir as kL}from"node:os";import{join as e}from"node:path";function vL($,Z,J){if($)return $;if(Z)return e(Z,"lodestar");return J}function yL(){if(wL)return e(process.env.APPDATA??e(HX,"AppData","Roaming"),"Lodestar");return e(HX,".config","lodestar")}var W3,HX,wL,C5,$0,c0,F$,H4,x5,b5,k5,w5,GX,WX,v5,K3,X2,KX,B3,G4,W4,BX,jX,_X,y5,PX,LX,f5,h5,qX,I5,z2,j3;var H0=R(()=>{W3=QX(S5(),1),HX=kL(),wL=process.platform==="win32";C5=vL(process.env.LODESTAR_CONFIG_DIR,process.env.XDG_CONFIG_HOME,yL()),$0=W3.lodestarDataDir(),c0=process.env.LODESTAR_CONFIG??e(C5,"config.toml"),F$=e($0,"daemon.pid"),H4=e($0,"daemon.log"),x5=e($0,"session-chat-map.json"),b5=e($0,"session-resume-map.json"),k5=e($0,"session-turns-map.json"),w5=e($0,"session-model-map.json"),GX=e($0,"claude-translation-context"),WX=e($0,"claude-translation-traces"),v5=e($0,"temp-session-leases.json"),K3=e($0,"tasklist-map.json"),X2=e($0,"agent-runs"),KX=e($0,"agent-project-client.json"),B3=e($0,"agent-session-ids.json"),G4=W3.managedClaudePluginDir(),W4=e($0,"dsh"),BX=e($0,"codex-accounts"),jX=e($0,"codex-accounts.json"),_X=e($0,"codex-quota-blocks.json"),y5=e($0,"agent-runtimes"),PX=e($0,"context-window-cache.json"),LX=e($0,"notify-callbacks.json"),f5=e($0,"alive-on-shutdown.json"),h5=e($0,"inbox"),qX=e($0,"file-deliveries"),I5=e($0,"file-delivery-groups.json"),z2=e($0,"debug.sock"),j3=e($0,"debug-context.json")});import{execFileSync as m5}from"node:child_process";import{readFileSync as FX,readlinkSync as fL,writeFileSync as hL}from"node:fs";import{isAbsolute as IL,resolve as _3,win32 as g5}from"node:path";function gL(){if(!process.argv[1])throw Error("无法确定 daemon 入口路径");return _3(process.argv[1])}function mL($){if(!/^[1-9]\d*$/.test($.trim()))return null;let Z=Number($.trim());return Number.isSafeInteger(Z)&&Z<=2147483647?Z:null}function p5($){try{return process.kill($,0),!0}catch(Z){if(Z.code==="ESRCH")return!1;throw Z}}function pL($){if(!p5($))return null;try{let Z;if(process.platform==="linux")Z=FX(`/proc/${$}/cmdline`,"utf8");else if(process.platform==="darwin")Z=m5("ps",["-p",String($),"-o","args="],{encoding:"utf8",timeout:2000});else if(process.platform==="win32")Z=m5("powershell",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference='Stop'; (Get-CimInstance Win32_Process -Filter 'ProcessId=${$}' -ErrorAction Stop).CommandLine`],{encoding:"utf8",timeout:5000});else throw Error(`不支持查询 ${process.platform} 平台的进程入口`);if(!Z.trim())throw Error(`PID ${$} 的命令行为空,无法核对 daemon 身份`);return Z.trim()}catch(Z){if(!p5($))return null;throw Error(`无法读取 PID ${$} 的命令行: ${Z instanceof Error?Z.message:String(Z)}`,{cause:Z})}}function iL($){let Z=$[0]?.replace(/\\/g,"/").split("/").pop()?.toLowerCase();if(!Z||!/^(?:node|nodejs|bun)(?:\.exe)?$/.test(Z))return null;let J=Z.startsWith("bun"),Q=J?lL:cL,Y=J?dL:uL,V=!1,X=1;while(X<$.length){let z=$[X];if(/^-[ep]/.test(z)||z==="--eval"||z==="--print"||/^(?:--eval|--print)=/.test(z))return null;if(!J&&(z==="-c"||z==="--check"||z==="--run"||z.startsWith("--run=")))return null;if(z==="--")return X+1;if(!z.startsWith("-")){if(J&&!V&&z==="run"){V=!0,X++;continue}return X}let H=z.split("=")[0];if(Q.has(H))X+=z.includes("=")?1:2;else if(Y.has(H))X++;else throw Error(`无法安全核对 daemon 入口: 未识别的 ${Z} 选项 ${z}`)}return null}function nL($){if(process.platform==="linux")return fL(`/proc/${$}/cwd`);if(process.platform==="darwin"){let J=m5("lsof",["-a","-p",String($),"-d","cwd","-Fn"],{encoding:"utf8",timeout:2000}).split(`
3
+ `).find((Q)=>Q.startsWith("n"))?.slice(1);if(J)return J}throw Error(`无法确定 PID ${$} 的工作目录,不能核对相对 daemon 入口`)}function aL($,Z){if(!Number.isSafeInteger($)||$<=0||$>2147483647||!Z)return!1;let J=pL($);if(J===null)return!1;let Q=process.platform==="linux"?J.split("\x00").filter(Boolean):(J.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map((X)=>X.replace(/^(?:"(.*)"|'(.*)')$/,"$1$2")),Y=iL(Q);if(Y===null||!Q[Y])return!1;let V=Q[Y];if(process.platform==="win32"){if(!g5.isAbsolute(V))throw Error(`PID ${$} 使用相对入口,无法安全核对 daemon 身份`);return g5.normalize(V).toLowerCase()===g5.normalize(Z).toLowerCase()}if(process.platform==="darwin"&&Z.startsWith(`${V} `))throw Error(`PID ${$} 的入口包含无法区分的空格,不能安全核对 daemon 身份`);if(!IL(V))V=_3(nL($),V);return _3(V)===_3(Z)}function P3($){let Z;try{Z=FX($,"utf8")}catch(V){if(V.code==="ENOENT")return{state:"continue"};throw V}let J=Z.split(`
4
+ `),Q=mL(J[0]??""),Y=(J[1]??"").trim();if(Q===null)throw Error(`PID 文件格式坏: ${$}`);if(!Y)return p5(Q)?{state:"exit",pid:Q}:{state:"continue"};return aL(Q,Y)?{state:"exit",pid:Q}:{state:"continue"}}function DX($){hL($,`${process.pid}
5
+ ${gL()}`)}var cL,uL,lL,dL;var c5=R(()=>{cL=new Set(["-r","--require","--import","--loader","--experimental-loader","--conditions","-C","--inspect-port","--title","--icu-data-dir","--openssl-config","--redirect-warnings","--diagnostic-dir","--report-directory","--report-filename","--env-file","--env-file-if-exists","--watch-path","--unhandled-rejections","--max-old-space-size","--max-semi-space-size","--stack-size"]),uL=new Set(["--enable-source-maps","--no-warnings","--trace-warnings","--trace-uncaught","--preserve-symlinks","--preserve-symlinks-main","--inspect","--inspect-brk","--watch","--watch-preserve-output","--experimental-strip-types","--experimental-transform-types"]),lL=new Set(["--preload","--cwd","--config","-c","--env-file","--tsconfig-override"]),dL=new Set(["--hot","--watch","--smol","--no-clear-screen","--silent","--bun","--no-install"])});import{execFile as oL}from"node:child_process";import{readFile as sL}from"node:fs/promises";import{homedir as tL}from"node:os";import{join as MX}from"node:path";import{promisify as rL}from"node:util";import{Address4 as L3,Address6 as q3}from"ip-address";function K4($,Z){return $[Z.toLowerCase()]?.trim()||$[Z]?.trim()||void 0}function U3($){let Z=$.hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z.endsWith(".localhost")||Z==="::1"||/^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(Z)||/^::ffff:(?:127\.|7f[0-9a-f]{2}:)/.test(Z)}function u5($,Z=""){let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=$.port||($.protocol==="https:"?"443":"80");return Z.split(/[,;\s]+/).filter(Boolean).some((Y)=>{let V=Y.toLowerCase();if(V==="*")return!0;if(V==="<local>")return!J.includes(".")&&!J.includes(":");if(V.includes("/")){if(L3.isValid(V))return L3.isValid(J)&&new L3(J).isInSubnet(new L3(V));if(q3.isValid(V))return q3.isValid(J)&&new q3(J).isInSubnet(new q3(V));throw Error("network proxy: invalid IP range in bypass list")}let X=V.match(/^(\[[^\]]+\]|[^:]+):(\d+)$/);if(X&&X[2]!==Q)return!1;let z=(X?X[1]:V).replace(/^\[|\]$/g,"").replace(/^\*?\./,"");return J===z||J.endsWith(`.${z}`)})}function UX($,Z){let J;try{J=new URL($)}catch{throw Error(`network proxy: ${Z} contains an invalid proxy URL`)}if(!["http:","https:"].includes(J.protocol))throw Error(`network proxy: ${Z} must use an HTTP(S) proxy; SOCKS and PAC are not supported`);if(!J.hostname||J.search||J.hash||J.pathname&&J.pathname!=="/")throw Error(`network proxy: ${Z} must contain a proxy host and port without a path or query`);return J.href}function OX($,Z,J={}){if(!["http:","https:"].includes($.protocol))throw Error(`network: unsupported URL protocol ${$.protocol}`);if(U3($)||u5($,K4(Z,"NO_PROXY")))return;let Q=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY",Y=K4(Z,Q)||K4(Z,"ALL_PROXY");if(Y)return UX(Y,"environment");if(J.unsupported)throw Error(`network proxy: ${J.unsupported}`);if(u5($,J.bypass))return;let V=($.protocol==="https:"?J.https:J.http)||J.all;return V?UX(V,"system settings"):void 0}function M3($,Z,J="http"){if(typeof $!=="string"||!$.trim()||!Number.isInteger(Number(Z))||Number(Z)<1||Number(Z)>65535)throw Error("network proxy: system proxy has an invalid host or port");let Q=$.includes(":")&&!$.startsWith("[")?`[${$}]`:$;return`${J}://${Q}:${Z}`}function $q($){if($.AutoConfigURL)return{unsupported:"Windows PAC proxy is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(!$.ProxyEnable)return $.AutoDetect?{unsupported:"Windows automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"}:{};if(typeof $.ProxyServer!=="string"||!$.ProxyServer.trim())throw Error("network proxy: Windows proxy is enabled without a server");let Z={bypass:String($.ProxyOverride??"")};for(let J of $.ProxyServer.split(";").map((Q)=>Q.trim()).filter(Boolean)){let Q=J.match(/^(http|https|socks)=(.+)$/i),Y=Q?Q[2]:J,V=/^[a-z][\w+.-]*:\/\//i.test(Y)?Y:`http://${Y}`;if(!Q)Z.all=V;else if(Q[1].toLowerCase()==="socks")Z.all=`socks://${Y.replace(/^socks\w*:\/\//,"")}`;else Z[Q[1].toLowerCase()]=V}return Z}function Zq($){let Z=(Y)=>$.match(new RegExp(`^\\s*${Y}\\s*:\\s*(.*?)\\s*$`,"m"))?.[1];if(Z("ProxyAutoConfigEnable")==="1"||Z("ProxyAutoDiscoveryEnable")==="1")return{unsupported:"macOS PAC/automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};let J={};if(Z("HTTPEnable")==="1")J.http=M3(Z("HTTPProxy"),Z("HTTPPort"));if(Z("HTTPSEnable")==="1")J.https=M3(Z("HTTPSProxy"),Z("HTTPSPort"));if(Z("SOCKSEnable")==="1")J.all=M3(Z("SOCKSProxy"),Z("SOCKSPort"),"socks");let Q=$.match(/ExceptionsList\s*:\s*<array>\s*\{([^}]*)\}/)?.[1]??"";if(J.bypass=[...Q.matchAll(/^\s*\d+\s*:\s*(.*?)\s*$/gm)].map((Y)=>Y[1]).join(","),Z("ExcludeSimpleHostnames")==="1")J.bypass+=",<local>";return J}function F3($){if($===void 0)return"";if(!/^(['"]).*\1$/.test($))throw Error("network proxy: invalid GNOME proxy string");return $.slice(1,-1).replace(/\\([\\'"])/g,"$1")}function Jq($){let Z=new Map($.split(`
6
+ `).filter(Boolean).map((Y)=>{let V=Y.match(/^org\.gnome\.system\.proxy(\.\w+)?\s+([\w-]+)\s+(.*)$/);if(!V)throw Error("network proxy: invalid GNOME proxy settings");return[`${V[1]??""}/${V[2]}`,V[3]]})),J=F3(Z.get("/mode"));if(J==="none")return{};if(J==="auto")return{unsupported:"GNOME PAC proxy is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(J!=="manual")throw Error("network proxy: unknown GNOME proxy mode");let Q={};for(let Y of["http","https","socks"]){let V=F3(Z.get(`.${Y}/host`));if(!V)continue;let X=new URL(M3(V,Z.get(`.${Y}/port`),Y==="socks"?"socks":"http"));if(Y==="http"&&Z.get(".http/use-authentication")==="true")X.username=F3(Z.get(".http/authentication-user")),X.password=F3(Z.get(".http/authentication-password"));Q[Y==="socks"?"all":Y]=X.href}if(Z.get("/use-same-proxy")==="true"&&Q.http)Q.https=Q.http;return Q.bypass=[...(Z.get("/ignore-hosts")??"").matchAll(/'((?:\\.|[^'])*)'/g)].map((Y)=>Y[1]).join(","),Q}function Qq($){let Z=$.match(/^\[Proxy Settings\]\s*\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m)?.[1];if(Z===void 0)return;let J=new Map(Z.split(`
7
+ `).filter((V)=>V.includes("=")).map((V)=>{let X=V.indexOf("=");return[V.slice(0,X).trim(),V.slice(X+1).trim()]})),Q=J.get("ProxyType")??"0";if(Q==="0"||Q==="4")return{};if(Q!=="1")return{unsupported:"KDE PAC/automatic proxy discovery is not supported; configure a manual HTTP(S) proxy or proxy environment variables"};if(J.get("ReversedException")==="true")return{unsupported:"KDE reversed proxy exceptions are not supported"};let Y={bypass:J.get("NoProxyFor")};for(let V of["http","https","socks"]){let X=J.get(`${V}Proxy`);if(!X)continue;let z=X.replace(/\s+(\d+)$/,":$1");Y[V==="socks"?"all":V]=/^[a-z][\w+.-]*:\/\//i.test(z)?z:`${V==="socks"?"socks":"http"}://${z}`}return Y}async function D3($,Z,J=5000){let{stdout:Q}=await eL($,Z,{encoding:"utf8",timeout:J,maxBuffer:262144,windowsHide:!0});return Q}async function Vq(){if(process.platform==="win32")return $q(JSON.parse(await D3("powershell.exe",["-NoProfile","-NonInteractive","-Command",Yq],15000)));if(process.platform==="darwin")return Zq(await D3("/usr/sbin/scutil",["--proxy"]));if(process.platform==="linux"){let $=MX(process.env.XDG_CONFIG_HOME||MX(tL(),".config"),"kioslaverc");try{let J=Qq(await sL($,"utf8"));if(J&&(!process.env.XDG_CURRENT_DESKTOP||/kde/i.test(process.env.XDG_CURRENT_DESKTOP)))return J}catch(J){if(J?.code!=="ENOENT")throw J}let Z;try{Z=await D3("gsettings",["list-schemas"])}catch(J){if(J?.code==="ENOENT")return{};throw J}if(!Z.split(/\r?\n/).includes("org.gnome.system.proxy"))return{};return Jq(await D3("gsettings",["list-recursively","org.gnome.system.proxy"]))}return{}}function Xq($=Vq,Z=process.env,J=Date.now){let Q;return async(Y)=>{if(U3(Y)||u5(Y,K4(Z,"NO_PROXY"))||K4(Z,Y.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY")||K4(Z,"ALL_PROXY"))return OX(Y,Z);if(!Q||Q.until<=J()){let V=$().catch((X)=>{if(Q?.value===V)Q=void 0;if(X instanceof Error&&X.message.startsWith("network proxy:"))throw X;let z=X instanceof Error?X.code??X.name:"unknown error";throw Error(`network proxy: failed to read ${process.platform} system proxy settings (${z})`,{cause:X})});Q={until:J()+30000,value:V}}return OX(Y,Z,await Q.value)}}var eL,Yq,AX;var NX=R(()=>{eL=rL(oL);Yq=String.raw`
8
8
  $ErrorActionPreference = 'Stop'
9
9
  [Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
10
10
  Add-Type @'
@@ -42,55 +42,55 @@ try {
42
42
  if ($pointer -ne [IntPtr]::Zero) { [void][LodestarProxy]::GlobalFree($pointer) }
43
43
  }
44
44
  }
45
- `;AX=Xq()});import{Agent as zq}from"node:http";import{Agent as Hq}from"node:https";import{Readable as RX}from"node:stream";import Gq from"node-fetch";import{HttpProxyAgent as Wq}from"http-proxy-agent";import{HttpsProxyAgent as Kq}from"https-proxy-agent";function _q($,Z){if(!Z)return $.protocol==="https:"?jq:Bq;return $.protocol==="https:"?new Kq(Z):new Wq(Z)}async function Pq($,Z,J){if(typeof Bun<"u"){let X=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY";if(!J&&(process.env[X.toLowerCase()]||process.env[X])){let z=await import("undici");return TX??=new z.Agent,await z.fetch($,{...Z,redirect:"manual",dispatcher:TX})}return globalThis.fetch($.href,{...Z,redirect:"manual",...J?{proxy:J}:{}})}let Q=new Request($,{...Z,redirect:"manual",duplex:"half"});if(Q.body&&!Q.headers.has("content-length")&&!Q.headers.has("transfer-encoding"))Q.headers.set("transfer-encoding","chunked");let Y=await Gq($,{method:Q.method,headers:Object.fromEntries(Q.headers),body:Q.body?RX.fromWeb(Q.body):void 0,signal:Q.signal,agent:_q($,J),redirect:"manual"}),V=Q.method==="HEAD"||[204,205,304].includes(Y.status)||!Y.body?null:RX.toWeb(Y.body);return new Response(V,{status:Y.status,statusText:Y.statusText,headers:[...Y.headers]})}async function EX($,Z,J,Q=AX){let Y=new URL($),V={...Z};for(let X=0;;X++){if(!["http:","https:"].includes(Y.protocol))throw Error(`network: unsupported URL protocol ${Y.protocol}`);if(J&&!U3(Y))throw Error("network: local request must remain on loopback");V.signal?.throwIfAborted();let z=J?void 0:await Q(Y),H=await Pq(Y,V,z),G=H.headers.get("location");if(![301,302,303,307,308].includes(H.status)||!G||Z.redirect==="manual")return H;if(await H.body?.cancel(),Z.redirect==="error")throw Error("network: redirect rejected");if(X>=20)throw Error("network: too many redirects");let W=new URL(G,Y),K=new Headers(V.headers);if(W.origin!==Y.origin)for(let _ of["authorization","proxy-authorization","cookie","host"])K.delete(_);let B=(V.method??"GET").toUpperCase();if(H.status===303&&B!=="HEAD"||[301,302].includes(H.status)&&B==="POST"){V={...V,method:"GET",body:void 0};for(let _ of["content-type","content-length","content-encoding"])K.delete(_)}else if(V.body instanceof ReadableStream)throw Error("network: cannot replay a streamed body after redirect");V.headers=K,Y=W}}function V0($,Z={}){return EX($,Z,!1)}function SX($,Z={}){return EX($,Z,!0)}var Bq,jq,TX;var u0=R(()=>{NX();Bq=new zq({keepAlive:!0}),jq=new Hq({keepAlive:!0})});function B4($){return $!==null&&typeof $==="object"?$:void 0}function x0($){return typeof $==="string"&&$.trim()?$:void 0}function O3($){return typeof $==="number"&&Number.isFinite($)?$:x0($)}function c$($,Z){let J=B4($);if(!J)return;if(typeof J.get==="function"){let Y=x0(J.get.call($,Z));if(Y!==void 0)return Y}let Q=Object.keys(J).find((Y)=>Y.toLowerCase()===Z);return Q===void 0?void 0:x0(J[Q])}function l5($){return x0($?.logId)??x0($?.log_id)??x0(B4($?.error)?.log_id)}function k$($){let Z=B4($),J=B4(Z?.response),Q=B4(Z?.data),Y=O3(Z?.code),V=O3(Q?.code),X=typeof Y==="number"||typeof Y==="string"&&/^\d+$/.test(Y)||x0(Z?.apiMessage)!==void 0||x0(Z?.msg)!==void 0,z=V!==0&&V!=="0"&&(V!==void 0||x0(Q?.msg)!==void 0||l5(Q)!==void 0),H=B4(J?.data)??(!X&&z?Q:void 0),G=J?.headers,W=Z?.headers,K=J?.status??Z?.status??Z?.httpStatus;return{code:O3(H?.code)??O3(Z?.code),message:x0(H?.apiMessage)??x0(H?.msg)??x0(H?.message)??x0(Z?.apiMessage)??x0(Z?.msg)??x0(Z?.message)??x0($)??"MISS",logId:l5(H)??l5(Z)??c$(G,"x-tt-logid")??c$(W,"x-tt-logid")??c$(G,"x-request-id")??c$(W,"x-request-id")??c$(G,"request-id")??c$(W,"request-id"),status:typeof K==="number"?K:void 0,retryAfter:x0(Z?.retryAfter)??c$(G,"retry-after")??c$(W,"retry-after")??c$(G,"x-ogw-ratelimit-reset")??c$(W,"x-ogw-ratelimit-reset")}}function w($){let Z=k$($);return`code=${Z.code??"MISS"} message=${Z.message} log_id=${Z.logId??"MISS"}`}import{appendFileSync as bX,mkdirSync as Lq,readdirSync as qq,unlinkSync as kX,existsSync as CX,statSync as Dq,renameSync as Fq,readFileSync as Mq}from"node:fs";import{join as wX}from"node:path";function n5($="development"){return $!=="test"}function vX($){let Z=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0");return`${Z}-${J}-${Q}`}function fX($,Z=$0){return wX(Z,`${d5}${vX($)}${i5}`)}function Oq($){if(!$.startsWith(d5)||!$.endsWith(i5))return null;let Z=$.slice(d5.length,$.length-i5.length),J=/^(\d{4})-(\d{2})-(\d{2})$/.exec(Z);if(!J)return null;let Q=new Date(Number(J[1]),Number(J[2])-1,Number(J[3]));return Number.isNaN(Q.getTime())?null:Q}function yX($,Z=new Date,J=Uq){let Q;try{Q=qq($)}catch{return 0}let Y=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),V=0;for(let X of Q){let z=Oq(X);if(!z)continue;if(Math.round((Y.getTime()-z.getTime())/86400000)<J)continue;try{kX(wX($,X)),V++}catch{}}return V}function Aq(){try{if(!CX(H4))return;let $=Dq(H4);if(!$.isFile()||$.size===0)return;let Z=fX($.mtime);if(CX(Z)){bX(Z,Mq(H4)),kX(H4);return}Fq(H4,Z)}catch{}}function j($){let Z=new Date,J=`[${Z.toISOString()}] ${$}
46
- `;if(process.stderr.write(J),!n5())return;try{let Q=vX(Z);if(xX!==Q)xX=Q,yX($0,Z);bX(fX(Z),J)}catch{}}var Uq=7,d5="daemon-",i5=".log",xX=null;var I=R(()=>{H0();if(n5())try{Lq($0,{recursive:!0})}catch{}if(n5()){Aq();try{yX($0)}catch{}}});function A3($,Z={}){if(!$||typeof $!=="object")return!1;let{status:J,code:Q,message:Y}=k$($);if(Z.api==="cardkit"&&(Q===300308||Q==="300308")&&/^server internal error[.!]?$/i.test(Y.trim()))return!0;if(Q===99991400||Q===230020||Q===1061045||J!==void 0&&Nq.has(J))return!0;if(typeof J==="number"&&J>=400)return!1;if(typeof Q==="string"&&Rq.has(Q)||"name"in $&&$.name==="TimeoutError")return!0;return"cause"in $&&$.cause!==$&&A3($.cause,Z)}function IX($){let Z=k$($).retryAfter;if(typeof Z!=="string"||!Z.trim())return 0;let J=Number(Z),Q=Number.isFinite(J)?J*1000:Date.parse(Z)-Date.now();return Number.isFinite(Q)?Math.max(0,Q):0}class H2{maxRetries;deadline;retries=0;lastFailure;constructor($=60000,Z=1/0){this.maxRetries=Z;this.deadline=Date.now()+$}remainingMs(){return Math.max(0,this.deadline-Date.now())}timeoutMs($){let Z=this.remainingMs();if(Z<=0)throw this.lastFailure??new DOMException("Feishu output recovery window expired","TimeoutError");return Math.min($,Z)}async waitUntilDeadline(){while(this.remainingMs()>0)await new Promise(($)=>setTimeout($,this.remainingMs()))}async waitForRetry($,Z,J=0){this.lastFailure=Z;let Q=this.remainingMs();if(Q<=0||this.retries>=this.maxRetries)return!1;let Y=hX[Math.min(this.retries++,hX.length-1)],V=Math.max(Y,J,IX(Z)),X=Date.now()+V,z=X<this.deadline;j(`feishu: ${$} failed: ${w(Z)}; ${z?`retry in ${V}ms (recovery remaining ${Q}ms)`:`waiting ${Q}ms for recovery deadline; next retry requires ${V}ms`}`);let H=Math.min(this.deadline,X);while(Date.now()<H)await new Promise((G)=>setTimeout(G,H-Date.now()));return z&&this.remainingMs()>0}}async function G2($,Z,J={}){let Q=Date.now();for(let Y=0;;Y++){J.recovery?.timeoutMs(60000);try{let V=await Z();if(Y>0)j(`feishu: ${$} recovered: attempts=${Y+1} elapsed=${Date.now()-Q}ms`);return V}catch(V){let X=A3(V,J);if(J.recovery){if(X&&await J.recovery.waitForRetry($,V))continue;j(`feishu: ${$} attempt ${Y+1} failed: ${w(V)}; FINAL`)}else{let z=Math.max(a5[Y]??0,IX(V)),H=X&&Y<a5.length&&z<=60000;if(j(`feishu: ${$} attempt ${Y+1}/${a5.length+1} failed: ${w(V)}; ${H?`retry in ${z}ms`:"FINAL"}`),H){await new Promise((G)=>setTimeout(G,z));continue}}if(!(V instanceof l0)&&V&&typeof V==="object"&&"response"in V){let z=k$(V),H=new l0(`${$}: ${w(V)}`,z.status,z.code,z.retryAfter,z.logId,z.message);throw H.cause=V,H}throw V}}}async function F$($,Z){let J=await $.text(),Q=$.headers.get("retry-after")??$.headers.get("x-ogw-ratelimit-reset"),Y=k$({headers:$.headers}),V;try{V=JSON.parse(J)}catch{let X=`invalid JSON — ${J.slice(0,200)}`,z={message:X,logId:Y.logId};throw new l0(`${Z} HTTP ${$.status}: ${w(z)}`,$.status,void 0,Q,z.logId,X)}if(!$.ok||V?.code!==0){let X=k$({response:{data:V,headers:$.headers,status:$.status}});throw new l0(`${Z} HTTP ${$.status}: ${w(X)}`,$.status,X.code,Q,X.logId,X.message)}return V}var a5,hX,Nq,Rq,l0;var j4=R(()=>{I();a5=[1000,4000],hX=[3000,8000,15000],Nq=new Set([408,429,500,502,503,504]),Rq=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EPIPE","EAI_AGAIN","ConnectionRefused","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]);l0=class l0 extends Error{status;code;retryAfter;logId;apiMessage;constructor($,Z,J,Q,Y,V=$){super($);this.status=Z;this.code=J;this.retryAfter=Q;this.logId=Y;this.apiMessage=V;this.name="FeishuRequestError"}}});function y0($,Z=[]){let J=$ instanceof Error?$.message:String($);if($ instanceof Error&&$.cause instanceof Error&&!J.includes($.cause.message))J+=`;${$.cause.message}`;for(let Y of Z)if(Y)J=J.replaceAll(Y,"[redacted]");let Q="";if(/HTTP 401\b|code=(?:401|1000|1001|1003|1005)\b|authentication_error/i.test(J))Q="认证失败,请检查 API Key 是否完整、有效,并确认 Key 与接口所属平台一致";else if(/HTTP 403\b|code=(?:403|1220)\b|permission_error/i.test(J))Q="访问被拒绝,请检查账号及 API Key 的接口权限";else if(/HTTP 429\b|code=(?:429|1302|1305|1308|1309|1310|1311)\b/i.test(J))Q="请求受限,请按接口说明检查套餐、额度或稍后重试";else if(/timeout|timed out|aborted|超时/i.test(J))Q="请求超时,请检查网络和代理后重试";else if(/fetch failed|failed to fetch|ECONN|ENOTFOUND|EAI_AGAIN|network|代理/i.test(J))Q="连接失败,请检查网络、代理和接口地址后重试";else if(/HTTP 404\b/i.test(J))Q="模型接口不存在,请检查 API 地址";else if(/HTTP 5\d\d\b/i.test(J))Q="上游服务异常,请稍后重试";else if(/data 数组|有效 JSON|无效条目|模型 id 无效/i.test(J))Q="模型接口返回异常,请检查 API 地址;持续出现时请反馈诊断信息";else if(/模型目录为空|catalog is empty/i.test(J))Q="账号未返回可用模型,请检查套餐和模型权限";return Q&&!J.startsWith(Q)?`${Q}(${J})`:J}function o5($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function gX($){return typeof $==="string"||typeof $==="number"?String($):void 0}async function u$($,Z,J){try{if(!Z.trim())throw Error(`${J}: 请填写 API Key`);return await Tq($,Z,J)}catch(Q){throw Error(y0(Q,[Z]))}}async function Tq($,Z,J){let Q=await V0($,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(1e4)}),Y=await Q.text(),V;try{V=JSON.parse(Y)}catch(K){throw Error(`${J} HTTP ${Q.status}: 响应不是有效 JSON`,{cause:K})}let X=o5(V)?V:void 0,z=o5(X?.error)?X.error:void 0,H=gX(z?.code??z?.type??X?.code),G=gX(z?.message??X?.msg??X?.message??X?.error),W=X?.success===!1||X?.error!=null||H!==void 0&&H!=="0"&&H!=="200";if(!Q.ok||W){let K=[H!==void 0?`code=${H}`:"",G].filter(Boolean).join(": "),B=`${J} HTTP ${Q.status}${K?`: ${K}`:""}`;throw Error(Z?B.replaceAll(Z,"[redacted]"):B)}if(!Array.isArray(X?.data))throw Error(`${J} 缺少 data 数组`);if(!X.data.length)throw Error(`${J} 模型目录为空`);if(!X.data.every(o5))throw Error(`${J} 模型目录包含无效条目`);return X.data}var _4=R(()=>{u0()});function T9($){let Z;try{Z=new URL($)}catch{throw Error("GLM 接口地址无效,请使用 https://open.bigmodel.cn/api/anthropic 或 https://api.z.ai/api/anthropic")}if(Z.protocol!=="https:"||!["open.bigmodel.cn","dev.bigmodel.cn","api.z.ai"].includes(Z.hostname)||Z.username||Z.password||Z.search||Z.hash||Z.pathname.replace(/\/+$/,"")!=="/api/anthropic")throw Error("GLM Claude Code 需要智谱或 Z.ai 的 /api/anthropic HTTPS 端点;Key 须与平台一致");return Z.toString().replace(/\/+$/,"")}async function L4($,Z){return(await u$(`${T9($)}/v1/models`,Z,"GLM models")).map((Q)=>{let Y=typeof Q.display_name==="string"&&Q.display_name?Q.display_name:Q.id;if(typeof Y!=="string"||!Y.trim())throw Error("GLM models 模型 id 无效");return Y})}var P4="https://open.bigmodel.cn/api/anthropic";var E9=R(()=>{_4()});import{chmodSync as Eq,closeSync as s5,fsyncSync as mX,mkdirSync as Sq,openSync as pX,renameSync as Cq,unlinkSync as xq,writeFileSync as bq}from"node:fs";import{randomUUID as kq}from"node:crypto";import{dirname as cX}from"node:path";function yq($){let Z=cX($);Sq(Z,{recursive:!0,mode:fq})}function uX($,Z,J){yq($);let Q=`${$}.${process.pid}.${kq()}.tmp`,Y=null;try{Y=pX(Q,"wx",J),bq(Y,Z),mX(Y),s5(Y),Y=null,Cq(Q,$);try{Eq($,J)}catch{}if(process.platform!=="win32"){let V=null;try{V=pX(cX($),"r"),mX(V)}catch{}finally{if(V!==null)try{s5(V)}catch{}}}}catch(V){if(Y!==null)try{s5(Y)}catch{}try{xq(Q)}catch{}throw V}}function Q$($,Z){uX($,Z,wq)}function lX($,Z){uX($,Z,vq)}function r($,Z){Q$($,JSON.stringify(Z,null,2)+`
47
- `)}var wq=384,vq=448,fq=448;var b0=()=>{};import{execFile as hq}from"node:child_process";import{spawn as Iq}from"cross-spawn";function mq($){if(!Number.isSafeInteger($)||$<=0)return Promise.reject(Error(`Invalid npm installer PID: ${$}`));return new Promise((Z,J)=>{hq("taskkill",["/PID",String($),"/T","/F"],{windowsHide:!0,timeout:1e4},(Q,Y,V)=>{if(Q)J(Error(`taskkill npm installer PID ${$} failed: ${Q.message}
48
- ${Y}${V}`));else Z()})})}async function t5($,Z,J={}){Z?.throwIfAborted();let Q=J.platform??process.platform,Y=J.timeoutMs??300000,V=J.terminationTimeoutMs??1e4;return await new Promise((X,z)=>{let H=(J.spawn??Iq)("npm",["install","--prefix",$,"--include=optional","--no-fund","--no-audit",`--registry=${gq}`],{cwd:$,stdio:["ignore","pipe","pipe"],shell:!1,windowsHide:!0}),G="",W,K,B=!1,_=!1,P,L=(O)=>{G=(G+O.toString()).slice(-16384)};H.stdout.on("data",L),H.stderr.on("data",L);let q=(O)=>{if(B)return;if(B=!0,clearTimeout(A),P)clearTimeout(P);if(Z?.removeEventListener("abort",U),O)z(O);else X()},D=(O)=>new N3(`${W?.message??"Agent runtime install failed"}; npm installer PID ${H.pid??"MISS"} termination unconfirmed: ${O}; partial directory retained: ${$}
49
- ${G}`),M=(O)=>{if(B||_||K)return;W??=Error(O),P=setTimeout(()=>q(D(`stdio did not close within ${V}ms`)),V),K=Promise.resolve().then(async()=>{if(_)throw Error("installer closed before process-tree termination started");if(!H.pid)throw Error("installer PID unavailable");if(Q==="win32")await(J.terminateWindows??mq)(H.pid);else if(!H.kill("SIGTERM"))throw Error("npm installer rejected SIGTERM")}),K.catch((N)=>q(D(N instanceof Error?N.message:String(N))))},U=()=>M("Agent runtime install aborted"),A=setTimeout(()=>M(`Agent runtime install timed out after ${Y}ms`),Y);if(Z?.addEventListener("abort",U,{once:!0}),H.on("error",(O)=>{if(W??=O,!H.pid)q(Error(`${O.message}
50
- ${G}`))}),H.once("close",async(O,N)=>{_=!0,clearTimeout(A),Z?.removeEventListener("abort",U);try{await K}catch(S){q(D(S instanceof Error?S.message:String(S)));return}if(W||O!==0)q(Error(`${W?.message??`npm install exited code=${O} signal=${N}`}
51
- ${G}`));else q()}),Z?.aborted)U()})}var gq="https://registry.npmjs.org",N3;var r5=R(()=>{N3=class N3 extends Error{}});import{createHash as pq,randomUUID as cq}from"node:crypto";import{createRequire as uq}from"node:module";import{existsSync as R3,readFileSync as iX}from"node:fs";import{mkdir as nX,mkdtemp as lq,readFile as aX,rename as oX,rm as S9,writeFile as sX}from"node:fs/promises";import{join as Y$,isAbsolute as dq}from"node:path";import{fileURLToPath as iq,pathToFileURL as nq}from"node:url";function tX($,Z=f5){let J=Y$(Z,$,"current.json");if(!R3(J))return null;let Q=JSON.parse(iX(J,"utf8"));if(!Number.isFinite(Q.checkedAt)||Q.directory!==void 0&&!dq(Q.directory))throw Error(`Invalid ${$} runtime state: ${J}`);return Q}function T3($){let Z=tX($);if(!Z?.directory)throw Error(`${$} runtime 未安装,请运行 lodestar-update --agents-only`);if(!R3(Z.directory))throw Error(`${$} runtime 安装目录不存在: ${Z.directory};请运行 lodestar-update --agents-only`);return Z.directory}function e5($,Z){return uq(Y$(T3($),"package.json")).resolve(Z)}function C9($,Z){let J=Y$(T3($),"node_modules",".bin",`${Z}${process.platform==="win32"?".cmd":""}`);if(!R3(J))throw Error(`${$} executable missing: ${J}`);return J}async function rX(){return import(nq(e5("claude","@anthropic-ai/claude-agent-sdk")).href)}async function tq($,Z,J){let Q=new AbortController,Y=()=>Q.abort(J?.reason);if(J?.addEventListener("abort",Y,{once:!0}),J?.aborted)Y();let V=setTimeout(()=>Q.abort(Error("npm registry request timed out")),30000);try{let X=await V0(`${sq}/${encodeURIComponent($)}/${encodeURIComponent(Z)}`,{signal:Q.signal});if(!X.ok)throw Error(`${$}@${Z}: npm HTTP ${X.status}`);let z=await X.json();if(z.name!==$||typeof z.version!=="string"||!z.version)throw Error(`Invalid npm manifest: ${$}@${Z}`);return z}finally{clearTimeout(V),J?.removeEventListener("abort",Y)}}async function rq($,Z){let J={};if($!=="dsh"){let X=await Promise.all(q4[$].map((z)=>Z(z,"latest")));for(let z of X)J[z.name]=z.version;return J}let Q=await Z("@deepseek-ai/dsh","latest"),Y=new Set(q4.dsh),V=new Set;while(Y.size){let X=[...Y].slice(0,12);for(let H of X)Y.delete(H),V.add(H);let z=await Promise.all(X.map((H)=>H===Q.name?Q:Z(H,Q.version)));for(let H of z){if(H.version!==Q.version)throw Error(`DSH release package mismatch: ${H.name}@${H.version}, expected ${Q.version}`);J[H.name]=H.version;for(let G of Object.keys({...H.dependencies,...H.peerDependencies,...H.optionalDependencies}))if(G.startsWith("@deepseek-ai/dsh")&&!V.has(G))Y.add(G)}}return J}async function b1($,Z=process.platform){for(let J=0;;J++)try{return await $()}catch(Q){let Y=Q.code;if(Z!=="win32"||!["EPERM","EACCES","EBUSY","ENOTEMPTY"].includes(Y??"")||J>=5)throw Q;await new Promise((V)=>setTimeout(V,100*(J+1)))}}async function eq($,Z){let J=Y$($,`current-${cq()}.json`),Q;try{await sX(J,JSON.stringify(Z)+`
52
- `,{mode:384}),await b1(()=>oX(J,Y$($,"current.json")))}catch(Y){throw Q=Y,Y}finally{try{await b1(()=>S9(J,{force:!0}))}catch(Y){if(Q)throw AggregateError([Q,Y],`${D4(Q)}; state temporary file cleanup failed: ${D4(Y)}`);throw Y}}}async function dX($,Z){for(let[J,Q]of Object.entries(Z)){let Y=JSON.parse(await aX(Y$($,"node_modules",J,"package.json"),"utf8"));if(Y.name!==J||Y.version!==Q)throw Error(`Invalid Agent runtime at ${$}: expected ${J}@${Q}, found ${Y.name}@${Y.version}`)}}async function $D($,Z){let J=Y$($,"update.lock"),Q=Date.now()+360000;for(;;){Z?.throwIfAborted();try{await nX(J);try{await b1(async()=>Q$(Y$(J,"pid"),String(process.pid)))}catch(Y){try{await b1(()=>S9(J,{recursive:!0}))}catch(V){throw AggregateError([Y,V],`${D4(Y)}; runtime update lock cleanup failed: ${D4(V)}`)}throw Y}return()=>b1(()=>S9(J,{recursive:!0}))}catch(Y){if(Y.code!=="EEXIST")throw Y;try{let V=Number(await aX(Y$(J,"pid"),"utf8"));if(!Number.isSafeInteger(V)||V<=0)throw Error(`Invalid runtime update lock: ${J}`);try{process.kill(V,0)}catch(X){if(X.code!=="ESRCH")throw X;await b1(()=>S9(J,{recursive:!0}));continue}}catch(V){if(V.code!=="ENOENT")throw V}if(Date.now()>=Q)throw Error(`Timed out waiting for runtime update lock: ${J}`);await new Promise((V)=>setTimeout(V,200))}}}async function E3($,Z={}){let J=Z.root??f5,Q=Y$(J,$);await nX(Q,{recursive:!0,mode:448});let Y=await $D(Q,Z.signal),V,X,z=!1;try{let H=tX($,J);Z.report?.(`${$}: 检查 upstream latest`);let G=await rq($,Z.metadata??((q,D)=>tq(q,D,Z.signal)));Z.signal?.throwIfAborted();let W=JSON.parse(iX(iq(new URL("../package.json",import.meta.url)),"utf8")),K={...W.overrides,...W.agentRuntimeOverrides?.[$]},B=pq("sha256").update(JSON.stringify({installFormat:$==="dsh"?3:2,versions:Object.entries(G).sort(),security:K,platform:process.platform,arch:process.arch})).digest("hex").slice(0,20),_=Y$(Q,B);if(!R3(_)){V=await lq(Y$(Q,".install-")),await sX(Y$(V,"package.json"),JSON.stringify({name:`lodestar-runtime-${$}`,version:G[q4[$][0]],private:!0,type:"module",dependencies:Object.fromEntries(q4[$].map((D)=>[D,G[D]])),overrides:{...K,...$==="dsh"?G:{}}})+`
53
- `,{mode:384}),await(Z.install??t5)(V,Z.signal),await dX(V,G),Z.signal?.throwIfAborted();let q=V;await b1(()=>oX(q,_)),V=void 0}else await dX(_,G);let P={directory:_,versions:G,checkedAt:Date.now()},L=H?.directory===_;return await eq(Q,P),Z.report?.(`${$}: ${q4[$][0]}@${G[q4[$][0]]}${L?" 已是 latest":" 已更新,新进程使用新版"}`),P}catch(H){throw X=H,z=H instanceof N3,H}finally{let H=[];if(V&&!z){let G=V;try{await b1(()=>S9(G,{recursive:!0}))}catch(W){H.push(W)}}try{await Y()}catch(G){H.push(G)}if(H.length){let G=X?[X,...H]:H;throw AggregateError(G,G.map(D4).join("; "))}}}function eX($,Z={}){let J=aq.filter((Q)=>Z.enabled?.[Q]===!0).map((Q)=>{let Y=new AbortController,V,X=setInterval(()=>{if(V)return;V=(Z.update??E3)(Q,{report:$,signal:Y.signal}).catch((z)=>$(`${Q} 自动更新未完成: ${D4(z)}`)).finally(()=>{V=void 0})},oq);return X.unref(),()=>{clearInterval(X),Y.abort()}});return()=>{for(let Q of J)Q()}}var aq,oq=21600000,sq="https://registry.npmjs.org",q4,D4=($)=>$ instanceof Error?$.message:String($);var F4=R(()=>{u0();H0();r5();b0();r5();aq=["codex","claude","dsh"],q4={codex:["@openai/codex"],claude:["@anthropic-ai/claude-code","@anthropic-ai/claude-agent-sdk","@anthropic-ai/sdk"],dsh:["@deepseek-ai/dsh","@deepseek-ai/dsh-llm-pi-ai","@deepseek-ai/dsh-tool-ask-user"]}});var Zz;var $z=R(()=>{Zz={scopes:{tenant:["verification:verification_information:readonly","tenant:tenant:readonly","im:message:send_as_bot","im:message","im:chat","im:chat:create","im:chat:delete","im:chat.members:read","im:chat.members:write_only","im:resource","im:message.urgent","im:message.group_msg","im:message.group_at_msg:readonly","cardkit:card:read","cardkit:card:write","drive:drive","drive:file:upload"],user:[]}}});var zz={};H1(zz,{writeClaudeGlmEnv:()=>Yz,testFeishuCreds:()=>Vz,spawnDaemonDetached:()=>Xz,runSetup:()=>_D});import{execFileSync as JD,spawn as C3}from"node:child_process";import{spawn as QD}from"cross-spawn";import{existsSync as ZZ,mkdirSync as Qz,readFileSync as YD}from"node:fs";import{createInterface as VD}from"node:readline/promises";import{dirname as XD,join as JZ}from"node:path";import{homedir as zD}from"node:os";import{fileURLToPath as HD}from"node:url";async function W2($,Z={}){while(!0){let J=Z.default?`${F.dim} [${Z.default}]${F.reset}`:"",Q=(await x9.question(`${F.cyan}? ${F.reset}${$}${J}
54
- ${F.green}>${F.reset} `)).trim();if(!Q&&Z.default!==void 0)return Z.default;if(!Q&&Z.required){console.log(`${F.red}必填,请重新输入${F.reset}`);continue}return Q}}function GD($){let Z="═".repeat(58);console.log(`
55
- ${F.bold}${F.cyan}╔${Z}╗${F.reset}`),console.log(`${F.bold}${F.cyan}║ ${$.padEnd(54)} ║${F.reset}`),console.log(`${F.bold}${F.cyan}╚${Z}╝${F.reset}
45
+ `;AX=Xq()});import{Agent as zq}from"node:http";import{Agent as Hq}from"node:https";import{Readable as RX}from"node:stream";import Gq from"node-fetch";import{HttpProxyAgent as Wq}from"http-proxy-agent";import{HttpsProxyAgent as Kq}from"https-proxy-agent";function _q($,Z){if(!Z)return $.protocol==="https:"?jq:Bq;return $.protocol==="https:"?new Kq(Z):new Wq(Z)}async function Pq($,Z,J){if(typeof Bun<"u"){let X=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY";if(!J&&(process.env[X.toLowerCase()]||process.env[X])){let z=await import("undici");return TX??=new z.Agent,await z.fetch($,{...Z,redirect:"manual",dispatcher:TX})}return globalThis.fetch($.href,{...Z,redirect:"manual",...J?{proxy:J}:{}})}let Q=new Request($,{...Z,redirect:"manual",duplex:"half"});if(Q.body&&!Q.headers.has("content-length")&&!Q.headers.has("transfer-encoding"))Q.headers.set("transfer-encoding","chunked");let Y=await Gq($,{method:Q.method,headers:Object.fromEntries(Q.headers),body:Q.body?RX.fromWeb(Q.body):void 0,signal:Q.signal,agent:_q($,J),redirect:"manual"}),V=Q.method==="HEAD"||[204,205,304].includes(Y.status)||!Y.body?null:RX.toWeb(Y.body);return new Response(V,{status:Y.status,statusText:Y.statusText,headers:[...Y.headers]})}async function EX($,Z,J,Q=AX){let Y=new URL($),V={...Z};for(let X=0;;X++){if(!["http:","https:"].includes(Y.protocol))throw Error(`network: unsupported URL protocol ${Y.protocol}`);if(J&&!U3(Y))throw Error("network: local request must remain on loopback");V.signal?.throwIfAborted();let z=J?void 0:await Q(Y),H=await Pq(Y,V,z),G=H.headers.get("location");if(![301,302,303,307,308].includes(H.status)||!G||Z.redirect==="manual")return H;if(await H.body?.cancel(),Z.redirect==="error")throw Error("network: redirect rejected");if(X>=20)throw Error("network: too many redirects");let W=new URL(G,Y),K=new Headers(V.headers);if(W.origin!==Y.origin)for(let _ of["authorization","proxy-authorization","cookie","host"])K.delete(_);let B=(V.method??"GET").toUpperCase();if(H.status===303&&B!=="HEAD"||[301,302].includes(H.status)&&B==="POST"){V={...V,method:"GET",body:void 0};for(let _ of["content-type","content-length","content-encoding"])K.delete(_)}else if(V.body instanceof ReadableStream)throw Error("network: cannot replay a streamed body after redirect");V.headers=K,Y=W}}function V0($,Z={}){return EX($,Z,!1)}function SX($,Z={}){return EX($,Z,!0)}var Bq,jq,TX;var u0=R(()=>{NX();Bq=new zq({keepAlive:!0}),jq=new Hq({keepAlive:!0})});function B4($){return $!==null&&typeof $==="object"?$:void 0}function x0($){return typeof $==="string"&&$.trim()?$:void 0}function O3($){return typeof $==="number"&&Number.isFinite($)?$:x0($)}function c$($,Z){let J=B4($);if(!J)return;if(typeof J.get==="function"){let Y=x0(J.get.call($,Z));if(Y!==void 0)return Y}let Q=Object.keys(J).find((Y)=>Y.toLowerCase()===Z);return Q===void 0?void 0:x0(J[Q])}function l5($){return x0($?.logId)??x0($?.log_id)??x0(B4($?.error)?.log_id)}function k$($){let Z=B4($),J=B4(Z?.response),Q=B4(Z?.data),Y=O3(Z?.code),V=O3(Q?.code),X=typeof Y==="number"||typeof Y==="string"&&/^\d+$/.test(Y)||x0(Z?.apiMessage)!==void 0||x0(Z?.msg)!==void 0,z=V!==0&&V!=="0"&&(V!==void 0||x0(Q?.msg)!==void 0||l5(Q)!==void 0),H=B4(J?.data)??(!X&&z?Q:void 0),G=J?.headers,W=Z?.headers,K=J?.status??Z?.status??Z?.httpStatus;return{code:O3(H?.code)??O3(Z?.code),message:x0(H?.apiMessage)??x0(H?.msg)??x0(H?.message)??x0(Z?.apiMessage)??x0(Z?.msg)??x0(Z?.message)??x0($)??"MISS",logId:l5(H)??l5(Z)??c$(G,"x-tt-logid")??c$(W,"x-tt-logid")??c$(G,"x-request-id")??c$(W,"x-request-id")??c$(G,"request-id")??c$(W,"request-id"),status:typeof K==="number"?K:void 0,retryAfter:x0(Z?.retryAfter)??c$(G,"retry-after")??c$(W,"retry-after")??c$(G,"x-ogw-ratelimit-reset")??c$(W,"x-ogw-ratelimit-reset")}}function w($){let Z=k$($);return`code=${Z.code??"MISS"} message=${Z.message} log_id=${Z.logId??"MISS"}`}import{appendFileSync as bX,mkdirSync as Lq,readdirSync as qq,unlinkSync as kX,existsSync as CX,statSync as Fq,renameSync as Dq,readFileSync as Mq}from"node:fs";import{join as wX}from"node:path";function n5($="development"){return $!=="test"}function vX($){let Z=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),Q=String($.getDate()).padStart(2,"0");return`${Z}-${J}-${Q}`}function yX($,Z=$0){return wX(Z,`${d5}${vX($)}${i5}`)}function Oq($){if(!$.startsWith(d5)||!$.endsWith(i5))return null;let Z=$.slice(d5.length,$.length-i5.length),J=/^(\d{4})-(\d{2})-(\d{2})$/.exec(Z);if(!J)return null;let Q=new Date(Number(J[1]),Number(J[2])-1,Number(J[3]));return Number.isNaN(Q.getTime())?null:Q}function fX($,Z=new Date,J=Uq){let Q;try{Q=qq($)}catch{return 0}let Y=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),V=0;for(let X of Q){let z=Oq(X);if(!z)continue;if(Math.round((Y.getTime()-z.getTime())/86400000)<J)continue;try{kX(wX($,X)),V++}catch{}}return V}function Aq(){try{if(!CX(H4))return;let $=Fq(H4);if(!$.isFile()||$.size===0)return;let Z=yX($.mtime);if(CX(Z)){bX(Z,Mq(H4)),kX(H4);return}Dq(H4,Z)}catch{}}function j($){let Z=new Date,J=`[${Z.toISOString()}] ${$}
46
+ `;if(process.stderr.write(J),!n5())return;try{let Q=vX(Z);if(xX!==Q)xX=Q,fX($0,Z);bX(yX(Z),J)}catch{}}var Uq=7,d5="daemon-",i5=".log",xX=null;var I=R(()=>{H0();if(n5())try{Lq($0,{recursive:!0})}catch{}if(n5()){Aq();try{fX($0)}catch{}}});function A3($,Z={}){if(!$||typeof $!=="object")return!1;let{status:J,code:Q,message:Y}=k$($);if(Z.api==="cardkit"&&(Q===300308||Q==="300308")&&/^server internal error[.!]?$/i.test(Y.trim()))return!0;if(Q===99991400||Q===230020||Q===1061045||J!==void 0&&Nq.has(J))return!0;if(typeof J==="number"&&J>=400)return!1;if(typeof Q==="string"&&Rq.has(Q)||"name"in $&&$.name==="TimeoutError")return!0;return"cause"in $&&$.cause!==$&&A3($.cause,Z)}function IX($){let Z=k$($).retryAfter;if(typeof Z!=="string"||!Z.trim())return 0;let J=Number(Z),Q=Number.isFinite(J)?J*1000:Date.parse(Z)-Date.now();return Number.isFinite(Q)?Math.max(0,Q):0}class H2{maxRetries;deadline;retries=0;lastFailure;constructor($=60000,Z=1/0){this.maxRetries=Z;this.deadline=Date.now()+$}remainingMs(){return Math.max(0,this.deadline-Date.now())}timeoutMs($){let Z=this.remainingMs();if(Z<=0)throw this.lastFailure??new DOMException("Feishu output recovery window expired","TimeoutError");return Math.min($,Z)}async waitUntilDeadline(){while(this.remainingMs()>0)await new Promise(($)=>setTimeout($,this.remainingMs()))}async waitForRetry($,Z,J=0){this.lastFailure=Z;let Q=this.remainingMs();if(Q<=0||this.retries>=this.maxRetries)return!1;let Y=hX[Math.min(this.retries++,hX.length-1)],V=Math.max(Y,J,IX(Z)),X=Date.now()+V,z=X<this.deadline;j(`feishu: ${$} failed: ${w(Z)}; ${z?`retry in ${V}ms (recovery remaining ${Q}ms)`:`waiting ${Q}ms for recovery deadline; next retry requires ${V}ms`}`);let H=Math.min(this.deadline,X);while(Date.now()<H)await new Promise((G)=>setTimeout(G,H-Date.now()));return z&&this.remainingMs()>0}}async function G2($,Z,J={}){let Q=Date.now();for(let Y=0;;Y++){J.recovery?.timeoutMs(60000);try{let V=await Z();if(Y>0)j(`feishu: ${$} recovered: attempts=${Y+1} elapsed=${Date.now()-Q}ms`);return V}catch(V){let X=A3(V,J);if(J.recovery){if(X&&await J.recovery.waitForRetry($,V))continue;j(`feishu: ${$} attempt ${Y+1} failed: ${w(V)}; FINAL`)}else{let z=Math.max(a5[Y]??0,IX(V)),H=X&&Y<a5.length&&z<=60000;if(j(`feishu: ${$} attempt ${Y+1}/${a5.length+1} failed: ${w(V)}; ${H?`retry in ${z}ms`:"FINAL"}`),H){await new Promise((G)=>setTimeout(G,z));continue}}if(!(V instanceof l0)&&V&&typeof V==="object"&&"response"in V){let z=k$(V),H=new l0(`${$}: ${w(V)}`,z.status,z.code,z.retryAfter,z.logId,z.message);throw H.cause=V,H}throw V}}}async function D$($,Z){let J=await $.text(),Q=$.headers.get("retry-after")??$.headers.get("x-ogw-ratelimit-reset"),Y=k$({headers:$.headers}),V;try{V=JSON.parse(J)}catch{let X=`invalid JSON — ${J.slice(0,200)}`,z={message:X,logId:Y.logId};throw new l0(`${Z} HTTP ${$.status}: ${w(z)}`,$.status,void 0,Q,z.logId,X)}if(!$.ok||V?.code!==0){let X=k$({response:{data:V,headers:$.headers,status:$.status}});throw new l0(`${Z} HTTP ${$.status}: ${w(X)}`,$.status,X.code,Q,X.logId,X.message)}return V}var a5,hX,Nq,Rq,l0;var j4=R(()=>{I();a5=[1000,4000],hX=[3000,8000,15000],Nq=new Set([408,429,500,502,503,504]),Rq=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EPIPE","EAI_AGAIN","ConnectionRefused","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]);l0=class l0 extends Error{status;code;retryAfter;logId;apiMessage;constructor($,Z,J,Q,Y,V=$){super($);this.status=Z;this.code=J;this.retryAfter=Q;this.logId=Y;this.apiMessage=V;this.name="FeishuRequestError"}}});function f0($,Z=[]){let J=$ instanceof Error?$.message:String($);if($ instanceof Error&&$.cause instanceof Error&&!J.includes($.cause.message))J+=`;${$.cause.message}`;for(let Y of Z)if(Y)J=J.replaceAll(Y,"[redacted]");let Q="";if(/HTTP 401\b|code=(?:401|1000|1001|1003|1005)\b|authentication_error/i.test(J))Q="认证失败,请检查 API Key 是否完整、有效,并确认 Key 与接口所属平台一致";else if(/HTTP 403\b|code=(?:403|1220)\b|permission_error/i.test(J))Q="访问被拒绝,请检查账号及 API Key 的接口权限";else if(/HTTP 429\b|code=(?:429|1302|1305|1308|1309|1310|1311)\b/i.test(J))Q="请求受限,请按接口说明检查套餐、额度或稍后重试";else if(/timeout|timed out|aborted|超时/i.test(J))Q="请求超时,请检查网络和代理后重试";else if(/fetch failed|failed to fetch|ECONN|ENOTFOUND|EAI_AGAIN|network|代理/i.test(J))Q="连接失败,请检查网络、代理和接口地址后重试";else if(/HTTP 404\b/i.test(J))Q="模型接口不存在,请检查 API 地址";else if(/HTTP 5\d\d\b/i.test(J))Q="上游服务异常,请稍后重试";else if(/data 数组|有效 JSON|无效条目|模型 id 无效/i.test(J))Q="模型接口返回异常,请检查 API 地址;持续出现时请反馈诊断信息";else if(/模型目录为空|catalog is empty/i.test(J))Q="账号未返回可用模型,请检查套餐和模型权限";return Q&&!J.startsWith(Q)?`${Q}(${J})`:J}function o5($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function gX($){return typeof $==="string"||typeof $==="number"?String($):void 0}async function u$($,Z,J){try{if(!Z.trim())throw Error(`${J}: 请填写 API Key`);return await Tq($,Z,J)}catch(Q){throw Error(f0(Q,[Z]))}}async function Tq($,Z,J){let Q=await V0($,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(1e4)}),Y=await Q.text(),V;try{V=JSON.parse(Y)}catch(K){throw Error(`${J} HTTP ${Q.status}: 响应不是有效 JSON`,{cause:K})}let X=o5(V)?V:void 0,z=o5(X?.error)?X.error:void 0,H=gX(z?.code??z?.type??X?.code),G=gX(z?.message??X?.msg??X?.message??X?.error),W=X?.success===!1||X?.error!=null||H!==void 0&&H!=="0"&&H!=="200";if(!Q.ok||W){let K=[H!==void 0?`code=${H}`:"",G].filter(Boolean).join(": "),B=`${J} HTTP ${Q.status}${K?`: ${K}`:""}`;throw Error(Z?B.replaceAll(Z,"[redacted]"):B)}if(!Array.isArray(X?.data))throw Error(`${J} 缺少 data 数组`);if(!X.data.length)throw Error(`${J} 模型目录为空`);if(!X.data.every(o5))throw Error(`${J} 模型目录包含无效条目`);return X.data}var _4=R(()=>{u0()});function T9($){let Z;try{Z=new URL($)}catch{throw Error("GLM 接口地址无效,请使用 https://open.bigmodel.cn/api/anthropic 或 https://api.z.ai/api/anthropic")}if(Z.protocol!=="https:"||!["open.bigmodel.cn","dev.bigmodel.cn","api.z.ai"].includes(Z.hostname)||Z.username||Z.password||Z.search||Z.hash||Z.pathname.replace(/\/+$/,"")!=="/api/anthropic")throw Error("GLM Claude Code 需要智谱或 Z.ai 的 /api/anthropic HTTPS 端点;Key 须与平台一致");return Z.toString().replace(/\/+$/,"")}async function L4($,Z){return(await u$(`${T9($)}/v1/models`,Z,"GLM models")).map((Q)=>{let Y=typeof Q.display_name==="string"&&Q.display_name?Q.display_name:Q.id;if(typeof Y!=="string"||!Y.trim())throw Error("GLM models 模型 id 无效");return Y})}var P4="https://open.bigmodel.cn/api/anthropic";var E9=R(()=>{_4()});import{chmodSync as Eq,closeSync as s5,fsyncSync as mX,mkdirSync as Sq,openSync as pX,renameSync as Cq,unlinkSync as xq,writeFileSync as bq}from"node:fs";import{randomUUID as kq}from"node:crypto";import{dirname as cX}from"node:path";function fq($){let Z=cX($);Sq(Z,{recursive:!0,mode:yq})}function uX($,Z,J){fq($);let Q=`${$}.${process.pid}.${kq()}.tmp`,Y=null;try{Y=pX(Q,"wx",J),bq(Y,Z),mX(Y),s5(Y),Y=null,Cq(Q,$);try{Eq($,J)}catch{}if(process.platform!=="win32"){let V=null;try{V=pX(cX($),"r"),mX(V)}catch{}finally{if(V!==null)try{s5(V)}catch{}}}}catch(V){if(Y!==null)try{s5(Y)}catch{}try{xq(Q)}catch{}throw V}}function Q$($,Z){uX($,Z,wq)}function lX($,Z){uX($,Z,vq)}function r($,Z){Q$($,JSON.stringify(Z,null,2)+`
47
+ `)}var wq=384,vq=448,yq=448;var b0=()=>{};import{execFile as hq}from"node:child_process";import{spawn as Iq}from"cross-spawn";function mq($){if(!Number.isSafeInteger($)||$<=0)return Promise.reject(Error(`Invalid npm installer PID: ${$}`));return new Promise((Z,J)=>{hq("taskkill",["/PID",String($),"/T","/F"],{windowsHide:!0,timeout:1e4},(Q,Y,V)=>{if(Q)J(Error(`taskkill npm installer PID ${$} failed: ${Q.message}
48
+ ${Y}${V}`));else Z()})})}async function t5($,Z,J={}){Z?.throwIfAborted();let Q=J.platform??process.platform,Y=J.timeoutMs??300000,V=J.terminationTimeoutMs??1e4;return await new Promise((X,z)=>{let H=(J.spawn??Iq)("npm",["install","--prefix",$,"--include=optional","--no-fund","--no-audit",`--registry=${gq}`],{cwd:$,stdio:["ignore","pipe","pipe"],shell:!1,windowsHide:!0}),G="",W,K,B=!1,_=!1,P,L=(O)=>{G=(G+O.toString()).slice(-16384)};H.stdout.on("data",L),H.stderr.on("data",L);let q=(O)=>{if(B)return;if(B=!0,clearTimeout(A),P)clearTimeout(P);if(Z?.removeEventListener("abort",U),O)z(O);else X()},F=(O)=>new N3(`${W?.message??"Agent runtime install failed"}; npm installer PID ${H.pid??"MISS"} termination unconfirmed: ${O}; partial directory retained: ${$}
49
+ ${G}`),M=(O)=>{if(B||_||K)return;W??=Error(O),P=setTimeout(()=>q(F(`stdio did not close within ${V}ms`)),V),K=Promise.resolve().then(async()=>{if(_)throw Error("installer closed before process-tree termination started");if(!H.pid)throw Error("installer PID unavailable");if(Q==="win32")await(J.terminateWindows??mq)(H.pid);else if(!H.kill("SIGTERM"))throw Error("npm installer rejected SIGTERM")}),K.catch((N)=>q(F(N instanceof Error?N.message:String(N))))},U=()=>M("Agent runtime install aborted"),A=setTimeout(()=>M(`Agent runtime install timed out after ${Y}ms`),Y);if(Z?.addEventListener("abort",U,{once:!0}),H.on("error",(O)=>{if(W??=O,!H.pid)q(Error(`${O.message}
50
+ ${G}`))}),H.once("close",async(O,N)=>{_=!0,clearTimeout(A),Z?.removeEventListener("abort",U);try{await K}catch(S){q(F(S instanceof Error?S.message:String(S)));return}if(W||O!==0)q(Error(`${W?.message??`npm install exited code=${O} signal=${N}`}
51
+ ${G}`));else q()}),Z?.aborted)U()})}var gq="https://registry.npmjs.org",N3;var r5=R(()=>{N3=class N3 extends Error{}});import{createHash as pq,randomUUID as cq}from"node:crypto";import{createRequire as uq}from"node:module";import{existsSync as R3,readFileSync as iX}from"node:fs";import{mkdir as nX,mkdtemp as lq,readFile as aX,rename as oX,rm as S9,writeFile as sX}from"node:fs/promises";import{join as Y$,isAbsolute as dq}from"node:path";import{fileURLToPath as iq,pathToFileURL as nq}from"node:url";function tX($,Z=y5){let J=Y$(Z,$,"current.json");if(!R3(J))return null;let Q=JSON.parse(iX(J,"utf8"));if(!Number.isFinite(Q.checkedAt)||Q.directory!==void 0&&!dq(Q.directory))throw Error(`Invalid ${$} runtime state: ${J}`);return Q}function T3($){let Z=tX($);if(!Z?.directory)throw Error(`${$} runtime 未安装,请运行 lodestar-update --agents-only`);if(!R3(Z.directory))throw Error(`${$} runtime 安装目录不存在: ${Z.directory};请运行 lodestar-update --agents-only`);return Z.directory}function e5($,Z){return uq(Y$(T3($),"package.json")).resolve(Z)}function C9($,Z){let J=Y$(T3($),"node_modules",".bin",`${Z}${process.platform==="win32"?".cmd":""}`);if(!R3(J))throw Error(`${$} executable missing: ${J}`);return J}async function rX(){return import(nq(e5("claude","@anthropic-ai/claude-agent-sdk")).href)}async function tq($,Z,J){let Q=new AbortController,Y=()=>Q.abort(J?.reason);if(J?.addEventListener("abort",Y,{once:!0}),J?.aborted)Y();let V=setTimeout(()=>Q.abort(Error("npm registry request timed out")),30000);try{let X=await V0(`${sq}/${encodeURIComponent($)}/${encodeURIComponent(Z)}`,{signal:Q.signal});if(!X.ok)throw Error(`${$}@${Z}: npm HTTP ${X.status}`);let z=await X.json();if(z.name!==$||typeof z.version!=="string"||!z.version)throw Error(`Invalid npm manifest: ${$}@${Z}`);return z}finally{clearTimeout(V),J?.removeEventListener("abort",Y)}}async function rq($,Z){let J={};if($!=="dsh"){let X=await Promise.all(q4[$].map((z)=>Z(z,"latest")));for(let z of X)J[z.name]=z.version;return J}let Q=await Z("@deepseek-ai/dsh","latest"),Y=new Set(q4.dsh),V=new Set;while(Y.size){let X=[...Y].slice(0,12);for(let H of X)Y.delete(H),V.add(H);let z=await Promise.all(X.map((H)=>H===Q.name?Q:Z(H,Q.version)));for(let H of z){if(H.version!==Q.version)throw Error(`DSH release package mismatch: ${H.name}@${H.version}, expected ${Q.version}`);J[H.name]=H.version;for(let G of Object.keys({...H.dependencies,...H.peerDependencies,...H.optionalDependencies}))if(G.startsWith("@deepseek-ai/dsh")&&!V.has(G))Y.add(G)}}return J}async function b1($,Z=process.platform){for(let J=0;;J++)try{return await $()}catch(Q){let Y=Q.code;if(Z!=="win32"||!["EPERM","EACCES","EBUSY","ENOTEMPTY"].includes(Y??"")||J>=5)throw Q;await new Promise((V)=>setTimeout(V,100*(J+1)))}}async function eq($,Z){let J=Y$($,`current-${cq()}.json`),Q;try{await sX(J,JSON.stringify(Z)+`
52
+ `,{mode:384}),await b1(()=>oX(J,Y$($,"current.json")))}catch(Y){throw Q=Y,Y}finally{try{await b1(()=>S9(J,{force:!0}))}catch(Y){if(Q)throw AggregateError([Q,Y],`${F4(Q)}; state temporary file cleanup failed: ${F4(Y)}`);throw Y}}}async function dX($,Z){for(let[J,Q]of Object.entries(Z)){let Y=JSON.parse(await aX(Y$($,"node_modules",J,"package.json"),"utf8"));if(Y.name!==J||Y.version!==Q)throw Error(`Invalid Agent runtime at ${$}: expected ${J}@${Q}, found ${Y.name}@${Y.version}`)}}async function $F($,Z){let J=Y$($,"update.lock"),Q=Date.now()+360000;for(;;){Z?.throwIfAborted();try{await nX(J);try{await b1(async()=>Q$(Y$(J,"pid"),String(process.pid)))}catch(Y){try{await b1(()=>S9(J,{recursive:!0}))}catch(V){throw AggregateError([Y,V],`${F4(Y)}; runtime update lock cleanup failed: ${F4(V)}`)}throw Y}return()=>b1(()=>S9(J,{recursive:!0}))}catch(Y){if(Y.code!=="EEXIST")throw Y;try{let V=Number(await aX(Y$(J,"pid"),"utf8"));if(!Number.isSafeInteger(V)||V<=0)throw Error(`Invalid runtime update lock: ${J}`);try{process.kill(V,0)}catch(X){if(X.code!=="ESRCH")throw X;await b1(()=>S9(J,{recursive:!0}));continue}}catch(V){if(V.code!=="ENOENT")throw V}if(Date.now()>=Q)throw Error(`Timed out waiting for runtime update lock: ${J}`);await new Promise((V)=>setTimeout(V,200))}}}async function E3($,Z={}){let J=Z.root??y5,Q=Y$(J,$);await nX(Q,{recursive:!0,mode:448});let Y=await $F(Q,Z.signal),V,X,z=!1;try{let H=tX($,J);Z.report?.(`${$}: 检查 upstream latest`);let G=await rq($,Z.metadata??((q,F)=>tq(q,F,Z.signal)));Z.signal?.throwIfAborted();let W=JSON.parse(iX(iq(new URL("../package.json",import.meta.url)),"utf8")),K={...W.overrides,...W.agentRuntimeOverrides?.[$]},B=pq("sha256").update(JSON.stringify({installFormat:$==="dsh"?3:2,versions:Object.entries(G).sort(),security:K,platform:process.platform,arch:process.arch})).digest("hex").slice(0,20),_=Y$(Q,B);if(!R3(_)){V=await lq(Y$(Q,".install-")),await sX(Y$(V,"package.json"),JSON.stringify({name:`lodestar-runtime-${$}`,version:G[q4[$][0]],private:!0,type:"module",dependencies:Object.fromEntries(q4[$].map((F)=>[F,G[F]])),overrides:{...K,...$==="dsh"?G:{}}})+`
53
+ `,{mode:384}),await(Z.install??t5)(V,Z.signal),await dX(V,G),Z.signal?.throwIfAborted();let q=V;await b1(()=>oX(q,_)),V=void 0}else await dX(_,G);let P={directory:_,versions:G,checkedAt:Date.now()},L=H?.directory===_;return await eq(Q,P),Z.report?.(`${$}: ${q4[$][0]}@${G[q4[$][0]]}${L?" 已是 latest":" 已更新,新进程使用新版"}`),P}catch(H){throw X=H,z=H instanceof N3,H}finally{let H=[];if(V&&!z){let G=V;try{await b1(()=>S9(G,{recursive:!0}))}catch(W){H.push(W)}}try{await Y()}catch(G){H.push(G)}if(H.length){let G=X?[X,...H]:H;throw AggregateError(G,G.map(F4).join("; "))}}}function eX($,Z={}){let J=aq.filter((Q)=>Z.enabled?.[Q]===!0).map((Q)=>{let Y=new AbortController,V,X=setInterval(()=>{if(V)return;V=(Z.update??E3)(Q,{report:$,signal:Y.signal}).catch((z)=>$(`${Q} 自动更新未完成: ${F4(z)}`)).finally(()=>{V=void 0})},oq);return X.unref(),()=>{clearInterval(X),Y.abort()}});return()=>{for(let Q of J)Q()}}var aq,oq=21600000,sq="https://registry.npmjs.org",q4,F4=($)=>$ instanceof Error?$.message:String($);var D4=R(()=>{u0();H0();r5();b0();r5();aq=["codex","claude","dsh"],q4={codex:["@openai/codex"],claude:["@anthropic-ai/claude-code","@anthropic-ai/claude-agent-sdk","@anthropic-ai/sdk"],dsh:["@deepseek-ai/dsh","@deepseek-ai/dsh-llm-pi-ai","@deepseek-ai/dsh-tool-ask-user"]}});var Zz;var $z=R(()=>{Zz={scopes:{tenant:["verification:verification_information:readonly","tenant:tenant:readonly","im:message:send_as_bot","im:message","im:chat","im:chat:create","im:chat:delete","im:chat.members:read","im:chat.members:write_only","im:resource","im:message.urgent","im:message.group_msg","im:message.group_at_msg:readonly","cardkit:card:read","cardkit:card:write","drive:drive","drive:file:upload"],user:[]}}});var zz={};H1(zz,{writeClaudeGlmEnv:()=>Yz,testFeishuCreds:()=>Vz,spawnDaemonDetached:()=>Xz,runSetup:()=>_F});import{execFileSync as JF,spawn as C3}from"node:child_process";import{spawn as QF}from"cross-spawn";import{existsSync as ZZ,mkdirSync as Qz,readFileSync as YF}from"node:fs";import{createInterface as VF}from"node:readline/promises";import{dirname as XF,join as JZ}from"node:path";import{homedir as zF}from"node:os";import{fileURLToPath as HF}from"node:url";async function W2($,Z={}){while(!0){let J=Z.default?`${D.dim} [${Z.default}]${D.reset}`:"",Q=(await x9.question(`${D.cyan}? ${D.reset}${$}${J}
54
+ ${D.green}>${D.reset} `)).trim();if(!Q&&Z.default!==void 0)return Z.default;if(!Q&&Z.required){console.log(`${D.red}必填,请重新输入${D.reset}`);continue}return Q}}function GF($){let Z="═".repeat(58);console.log(`
55
+ ${D.bold}${D.cyan}╔${Z}╗${D.reset}`),console.log(`${D.bold}${D.cyan}║ ${$.padEnd(54)} ║${D.reset}`),console.log(`${D.bold}${D.cyan}╚${Z}╝${D.reset}
56
56
  `)}function S3($,Z,J){console.log(`
57
- ${F.bold}${F.yellow}[${$}/${Z}] ${J}${F.reset}
58
- `)}function $Z($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function Jz($){try{let Z=JD($,["login","status"],{timeout:1e4,shell:process.platform==="win32"}).toString();return/Logged in using ChatGPT/i.test(Z)}catch{return!1}}async function WD($){return new Promise((Z)=>{let J=QD($,["login"],{stdio:"inherit",shell:!1});J.on("exit",(Q)=>Z(Q===0)),J.on("error",()=>Z(!1))})}function KD(){return process.env.CLAUDE_CONFIG_DIR||JZ(zD(),".claude")}async function BD($){let Z=await L4(P4,$),J=(H)=>{let G=H.match(/(\d+(?:\.\d+)?)/);return G?Number(G[1]):-1},Y=[...Z.filter((H)=>!/-Turbo|-Air/i.test(H))].sort((H,G)=>J(G)-J(H)),V=Y[0],X=Y[Y.length-1];if(!V)throw Error("GLM 模型目录中没有可用于 Claude Code slots 的模型");let z={ANTHROPIC_DEFAULT_OPUS_MODEL:`${V}[1m]`,ANTHROPIC_DEFAULT_SONNET_MODEL:`${V}[1m]`};if(X&&X!==V)z.ANTHROPIC_DEFAULT_HAIKU_MODEL=X;return z}async function Yz($){try{let Z=KD();Qz(Z,{recursive:!0});let J=JZ(Z,"settings.json"),Q={};if(ZZ(J)){let z=YD(J,"utf8");try{let H=JSON.parse(z);if(!H||typeof H!=="object"||Array.isArray(H))return{error:`${J} 内容不是 JSON 对象, 拒绝覆盖, 请手动检查`};Q=H}catch{return{error:`${J} 解析失败 (JSON 语法错), 拒绝覆盖, 请手动修复后重跑`}}}let Y=Q.env&&typeof Q.env==="object"&&!Array.isArray(Q.env)?Q.env:{},V=await BD($),X={ANTHROPIC_AUTH_TOKEN:$,ANTHROPIC_BASE_URL:P4,API_TIMEOUT_MS:"3000000",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"};return Object.assign(X,V),Q.env={...Y,...X},Q$(J,JSON.stringify(Q,null,2)+`
59
- `),{path:J}}catch(Z){return{error:Z?.message??String(Z)}}}function jD($){let Z=(J)=>console.error(`无法打开浏览器,请手动打开 ${$}: ${J instanceof Error?J.message:String(J)}`);try{let J;if(process.platform==="win32")J=C3(process.env.ComSpec??"cmd.exe",["/c","start",'""',$],{detached:!0,stdio:"ignore",windowsHide:!0});else if(process.platform==="darwin")J=C3("open",[$],{detached:!0,stdio:"ignore"});else J=C3("xdg-open",[$],{detached:!0,stdio:"ignore"});J.once("error",Z),J.unref()}catch(J){Z(J)}}async function Vz($,Z){try{let J=await V0("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:$,app_secret:Z}),signal:AbortSignal.timeout(15000)}),Q=await F$(J,"飞书凭据校验");if(Q.tenant_access_token)return{ok:!0};return{ok:!1,error:`飞书凭据校验缺少 tenant_access_token:${w(Q)}`}}catch(J){return{ok:!1,error:`飞书凭据校验失败:${w(J)}`}}}async function Xz(){try{let $=XD(HD(import.meta.url)),Z=JZ($,"lodestar.js");if(!ZZ(Z))return{error:`找不到 daemon bundle: ${Z}`};let J=C3(process.execPath,[Z],{detached:!0,stdio:"ignore",windowsHide:!0});return await new Promise((Q)=>{J.once("error",(Y)=>Q({error:Y.message})),J.once("spawn",()=>{J.unref(),Q(J.pid?{pid:J.pid}:{error:"daemon 启动后未返回 PID"})})})}catch($){return{error:$?.message??String($)}}}async function _D(){if(!process.stdin.isTTY)console.error(`${F.red}lodestar-setup: stdin 不是 TTY,无法交互式输入。${F.reset}`),console.error("请直接在 cmd / PowerShell / Terminal 里跑,不要 pipe 或重定向 stdin。"),process.exit(1);if(ZZ(c0)){if(console.log(`${F.yellow}发现已有配置: ${c0}${F.reset}`),(await W2("覆盖? (y/N)",{default:"n"})).toLowerCase()!=="y"){console.log("已取消"),x9.close();return}}GD("Lodestar 安装向导"),console.log("Lodestar 把 Feishu (飞书) 群聊接到 AI agent。"),console.log("默认后端是 Claude Code; Codex 是可选第二后端, 群里发 model 一键切换。"),console.log("每个群对应一个项目目录, agent 在那里跑、能读写文件。"),console.log(),console.log("支持本机已登录的 Claude Code 订阅,也可配置 GLM Coding Plan 或 Anthropic API key。"),console.log("Claude Code 订阅与第三方来源可在 model 面板中分别选择。"),console.log(),console.log("本向导依次做 4 件事:"),console.log(` ${F.dim}1) 确保 Claude Code CLI 已装好${F.reset}`),console.log(` ${F.dim}2) GLM Coding Plan API key (推荐, 可选) + Codex (可选)${F.reset}`),console.log(` ${F.dim}3) Feishu 自建应用 (含权限 / 事件 / 发版 + 凭据测试)${F.reset}`),console.log(` ${F.dim}4) 工作目录, 自动启动 daemon${F.reset}`),console.log(),await x9.question(`${F.dim}按 Enter 开始 (Ctrl+C 退出)...${F.reset}`),S3(1,4,"准备 Claude Code CLI"),await E3("claude",{report:(W)=>console.log(W)}),console.log(`${F.green}✓ Claude Code / SDK 已更新${F.reset}: ${F.dim}${C9("claude","claude")}${F.reset}`),console.log(),console.log(`${F.dim}下一步可选配 GLM Coding Plan 自动写入路由; 不配则用本机 Claude Code 现有配置。${F.reset}`),console.log(`${F.dim}使用 Claude 订阅时,在本机运行 \`claude auth login\`;完成后在 model 面板选择 Claude Code 订阅。${F.reset}`),S3(2,4,"GLM Coding Plan (推荐, 可选)"),console.log("GLM Coding Plan 给 Claude Code 接 GLM 系列模型 (支持 1M token 上下文, 中文友好)。"),console.log("订阅后在智谱开放平台拿一个 API key, 粘到下面 —— 向导自动写进 ~/.claude/settings.json。"),console.log(` ${F.dim}拿 key: https://open.bigmodel.cn → 控制台 → API Keys${F.reset}`),console.log(` ${F.dim}此项可选,直接回车跳过;以后可在群内发送 glm-setup <api_key> 补配。${F.reset}`),console.log(` ${F.dim}使用本机 Claude Code 或 Codex 订阅不需要 GLM Key。此处填写智谱国内站 Key;Z.ai 请之后用 glm-setup 指定对应地址。${F.reset}`),console.log();while(!0){let W=await W2("GLM API key (直接回车跳过)",{});if(!W){console.log(`${F.dim}已跳过 GLM, 以本机 Claude Code 现有配置启动。${F.reset}`);break}let K=await Yz(W);if("path"in K){console.log(`${F.green}✓ GLM 路由已写入${F.reset}: ${F.dim}${K.path}${F.reset}`),console.log(`${F.dim}模型 slots 按端点当前列表自动选取(最新一代 opus/sonnet, 1M ctx)${F.reset}`);break}else console.log(`${F.red}✗ GLM 配置失败:${F.reset} ${K.error}`),console.log(`${F.dim}请按错误提示处理后重新输入;直接回车可跳过,之后用群命令补配。${F.reset}`)}if(console.log(),console.log(`${F.bold}Codex (可选第二后端)${F.reset}`),console.log(` ${F.dim}想用 Codex 的话, 登录 ChatGPT 订阅即可, 模型/effort 走 ~/.codex/config.toml, 群里发 model 切换。${F.reset}`),(await W2("现在顺便配置 Codex 后端吗?",{default:"n"})).toLowerCase()==="y"){await E3("codex",{report:(K)=>console.log(K)});let W=C9("codex","codex");if(Jz(W))console.log(`${F.green}✓ Codex 已登录 ChatGPT${F.reset}`);else if(console.log(`${F.dim}启动 \`codex login\`...${F.reset}`),await WD(W)&&Jz(W))console.log(`${F.green}✓ Codex 已登录 ChatGPT${F.reset}`);else console.log(`${F.yellow}Codex 登录未完成 — 不影响默认 Claude 后端; 需要时随时跑 codex login。${F.reset}`)}else console.log(`${F.dim}已跳过 Codex (需要时随时跑 codex login, 群里发 model 切)。${F.reset}`);S3(3,4,"Feishu 自建应用");let Z="https://open.feishu.cn/app";console.log("打开飞书开放平台 (浏览器):"),console.log(` ${F.cyan}${Z}${F.reset}`),jD(Z),console.log(`${F.dim}(如果浏览器没自动开, 复制上面 URL 粘到浏览器)${F.reset}`),console.log(),console.log(`${F.bold}详细操作步骤:${F.reset}`),console.log(),console.log(` ${F.bold}① 创建应用${F.reset}`),console.log(` 点 "创建企业自建应用", 填名字 (如 ${F.dim}Lodestar${F.reset}), logo 随意。`),console.log(),console.log(` ${F.bold}② 添加机器人能力${F.reset}`),console.log(` 左侧菜单 "${F.cyan}添加应用能力${F.reset}" → 找到 "机器人" → 点 "${F.bold}添加${F.reset}" 按钮。`),console.log(),console.log(` ${F.bold}③ 申请权限 (左侧 "${F.cyan}权限管理${F.reset}" → "${F.bold}批量导入/导出权限${F.reset}")${F.reset}`),console.log(` ${F.yellow}选择应用身份权限,复制下方完整 JSON 批量导入,一次开齐账号信息、消息、卡片和云空间能力。${F.reset}`),console.log(JSON.stringify(Zz,null,2)),console.log(` ${F.dim}无需用户身份权限或飞书 CLI 登录。权限申请后须完成审批,并在步骤 ⑤ 发布飞书应用版本。${F.reset}`),console.log(` ${F.dim}清单包含以下用途;也可按名称逐项开通:${F.reset}`),console.log(` ${F.dim}账号与认证信息 (排障):${F.reset}`),console.log(` • ${F.bold}verification:verification_information:readonly${F.reset} ${F.dim}# 查看账号主体认证状态${F.reset}`),console.log(` • ${F.bold}tenant:tenant:readonly${F.reset} ${F.dim}# 查看租户基本信息${F.reset}`),console.log(` ${F.dim}消息类:${F.reset}`),console.log(` • ${F.bold}im:message:send_as_bot${F.reset} ${F.dim}# 以机器人身份发消息${F.reset}`),console.log(` • ${F.bold}im:message${F.reset} ${F.dim}# 接收/操作消息 (核心)${F.reset}`),console.log(` • ${F.bold}im:chat${F.reset} ${F.dim}# 读/写群信息 (匹配群名 ↔ 项目目录)${F.reset}`),console.log(` • ${F.bold}im:chat:create${F.reset} ${F.dim}# wt: 自动创建 worktree 群${F.reset}`),console.log(` • ${F.bold}im:chat:delete${F.reset} ${F.dim}# wt: 解散 worktree 群${F.reset}`),console.log(` • ${F.bold}im:chat.members:read${F.reset} ${F.dim}# wt: 判断发起人是否已在群内${F.reset}`),console.log(` • ${F.bold}im:chat.members:write_only${F.reset} ${F.dim}# wt: 把发起人拉进已有 worktree 群${F.reset}`),console.log(` • ${F.bold}im:resource${F.reset} ${F.dim}# 上传/下载附件 (图文双向)${F.reset}`),console.log(` • ${F.bold}im:message.urgent${F.reset} ${F.dim}# 加急推送 (锁屏通知 / Ask)${F.reset}`),console.log(` • ${F.bold}im:message.group_msg${F.reset} ${F.dim}# 敏感: 接收群里所有消息${F.reset}`),console.log(` ${F.dim}└ 关键: 没它机器人只收 @ 自己的消息, 拿不到群里其他对话, 一定要开${F.reset}`),console.log(` ${F.dim}└ 敏感权限要走审批: 申请时填用途, 个人开发者通常秒过${F.reset}`),console.log(` • ${F.bold}im:message.group_at_msg:readonly${F.reset} ${F.dim}# 读 @ 机器人消息 (兜底)${F.reset}`),console.log(` ${F.dim}卡片类 (Card Kit):${F.reset}`),console.log(` • ${F.bold}cardkit:card:read${F.reset} ${F.dim}# 读卡片状态${F.reset}`),console.log(` • ${F.bold}cardkit:card:write${F.reset} ${F.dim}# 创建/更新卡片 (流式渲染核心)${F.reset}`),console.log(` ${F.dim}云空间交付 (权限预先开通,功能仍按群开启):${F.reset}`),console.log(` • ${F.bold}drive:drive${F.reset} ${F.dim}# 上传、创建目录、协作者授权、关闭并核对文件链接分享${F.reset}`),console.log(` • ${F.bold}drive:file:upload${F.reset} ${F.dim}# 文件夹改名接口单独要求此权限${F.reset}`),console.log(` ${F.dim}默认仍直接发聊天附件;在指定群发送 files on 开启云空间,files off 恢复附件。${F.reset}`),console.log(` ${F.yellow}只取得 tenant_access_token 不代表以上权限已生效;缺少权限时群内命令会明确报错。${F.reset}`),console.log(),console.log(` ${F.bold}④ 订阅事件 (左侧 "${F.cyan}事件与回调${F.reset}", 拆两个子页:)${F.reset}`),console.log(` ${F.dim}a)${F.reset} ${F.bold}事件配置${F.reset} 页:`),console.log(` ${F.yellow}• "订阅方式" → 选 "长连接" → 点保存${F.reset}`),console.log(` • 添加事件: ${F.bold}im.message.receive_v1${F.reset} ${F.dim}# 收群消息${F.reset}`),console.log(` ${F.dim}b)${F.reset} ${F.bold}回调配置${F.reset} 页:`),console.log(` ${F.yellow}• "订阅方式" → 选 "长连接" → 点保存${F.reset}`),console.log(` • 添加事件: ${F.bold}card.action.trigger${F.reset} ${F.dim}# 卡片按钮点击回调${F.reset}`),console.log(),console.log(` ${F.bold}⑤ 发布版本${F.reset}`),console.log(` 页面顶部 "${F.bold}创建版本${F.reset}" → 滚到底点 "${F.bold}保存${F.reset}" → 弹框点 "${F.bold}发布${F.reset}"。`),console.log(` ${F.yellow}没发版的应用收不到任何事件 — 这步九成新手会忘!${F.reset}`),console.log(),console.log(` ${F.bold}⑥ 拿凭据${F.reset}`),console.log(` 左侧 "凭证与基础信息" → 顶部 ${F.bold}App ID${F.reset} (${F.dim}cli_...${F.reset}) 和 ${F.bold}App Secret${F.reset}, 待会粘到下面。`),console.log(),console.log(` ${F.bold}⑦ 把机器人拉进群${F.reset}`),console.log(" 想用的飞书群 → 群设置 → 群机器人 → 添加机器人 → 选你的应用。"),console.log(` ${F.yellow}群名要等于 projects_root 下的项目目录名${F.reset} (下一步设, 默认是用户主目录)。`),console.log();let J="",Q="";while(!0){J=await W2("App ID (以 cli_ 开头)",{required:!0}),Q=await W2("App Secret",{required:!0}),console.log(`${F.dim}测试中... (调 tenant_access_token endpoint)${F.reset}`);let W=await Vz(J,Q);if(W.ok){console.log(`${F.green}✓ Feishu 凭据测试通过${F.reset}`);break}if(console.log(`${F.red}✗ 测试失败:${F.reset} ${W.error}`),console.log(`${F.dim}最常见原因: app_id / app_secret 抄错, 或应用还没 "发布上线" (步骤 ⑤)。${F.reset}`),console.log(),(await W2("重新填? (Y/n)",{default:"y"})).toLowerCase()==="n")console.log(`${F.yellow}已取消, 配置未写盘。${F.reset}`),x9.close(),process.exit(1)}S3(4,4,"工作目录 + 启动"),console.log("每个 Feishu 群对应 projects_root 下同名的目录。"),console.log();let Y=process.platform==="win32"?process.env.USERPROFILE??"C:\\Users\\Default":process.env.HOME??"/root",V=await W2("projects_root",{default:Y});Qz(C5,{recursive:!0});let X=["# Lodestar config — generated by `lodestar-setup`","# Edit by hand or re-run setup to overwrite.","","[feishu]",`app_id = "${$Z(J)}"`,`app_secret = "${$Z(Q)}"`,"","[runtime]",`projects_root = "${$Z(V)}"`,"","[runtime.agent_auto_update]","codex = false","claude = false","dsh = false",""];Q$(c0,X.join(`
57
+ ${D.bold}${D.yellow}[${$}/${Z}] ${J}${D.reset}
58
+ `)}function $Z($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function Jz($){try{let Z=JF($,["login","status"],{timeout:1e4,shell:process.platform==="win32"}).toString();return/Logged in using ChatGPT/i.test(Z)}catch{return!1}}async function WF($){return new Promise((Z)=>{let J=QF($,["login"],{stdio:"inherit",shell:!1});J.on("exit",(Q)=>Z(Q===0)),J.on("error",()=>Z(!1))})}function KF(){return process.env.CLAUDE_CONFIG_DIR||JZ(zF(),".claude")}async function BF($){let Z=await L4(P4,$),J=(H)=>{let G=H.match(/(\d+(?:\.\d+)?)/);return G?Number(G[1]):-1},Y=[...Z.filter((H)=>!/-Turbo|-Air/i.test(H))].sort((H,G)=>J(G)-J(H)),V=Y[0],X=Y[Y.length-1];if(!V)throw Error("GLM 模型目录中没有可用于 Claude Code slots 的模型");let z={ANTHROPIC_DEFAULT_OPUS_MODEL:`${V}[1m]`,ANTHROPIC_DEFAULT_SONNET_MODEL:`${V}[1m]`};if(X&&X!==V)z.ANTHROPIC_DEFAULT_HAIKU_MODEL=X;return z}async function Yz($){try{let Z=KF();Qz(Z,{recursive:!0});let J=JZ(Z,"settings.json"),Q={};if(ZZ(J)){let z=YF(J,"utf8");try{let H=JSON.parse(z);if(!H||typeof H!=="object"||Array.isArray(H))return{error:`${J} 内容不是 JSON 对象, 拒绝覆盖, 请手动检查`};Q=H}catch{return{error:`${J} 解析失败 (JSON 语法错), 拒绝覆盖, 请手动修复后重跑`}}}let Y=Q.env&&typeof Q.env==="object"&&!Array.isArray(Q.env)?Q.env:{},V=await BF($),X={ANTHROPIC_AUTH_TOKEN:$,ANTHROPIC_BASE_URL:P4,API_TIMEOUT_MS:"3000000",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"};return Object.assign(X,V),Q.env={...Y,...X},Q$(J,JSON.stringify(Q,null,2)+`
59
+ `),{path:J}}catch(Z){return{error:Z?.message??String(Z)}}}function jF($){let Z=(J)=>console.error(`无法打开浏览器,请手动打开 ${$}: ${J instanceof Error?J.message:String(J)}`);try{let J;if(process.platform==="win32")J=C3(process.env.ComSpec??"cmd.exe",["/c","start",'""',$],{detached:!0,stdio:"ignore",windowsHide:!0});else if(process.platform==="darwin")J=C3("open",[$],{detached:!0,stdio:"ignore"});else J=C3("xdg-open",[$],{detached:!0,stdio:"ignore"});J.once("error",Z),J.unref()}catch(J){Z(J)}}async function Vz($,Z){try{let J=await V0("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:$,app_secret:Z}),signal:AbortSignal.timeout(15000)}),Q=await D$(J,"飞书凭据校验");if(Q.tenant_access_token)return{ok:!0};return{ok:!1,error:`飞书凭据校验缺少 tenant_access_token:${w(Q)}`}}catch(J){return{ok:!1,error:`飞书凭据校验失败:${w(J)}`}}}async function Xz(){try{let $=XF(HF(import.meta.url)),Z=JZ($,"lodestar.js");if(!ZZ(Z))return{error:`找不到 daemon bundle: ${Z}`};let J=C3(process.execPath,[Z],{detached:!0,stdio:"ignore",windowsHide:!0});return await new Promise((Q)=>{J.once("error",(Y)=>Q({error:Y.message})),J.once("spawn",()=>{J.unref(),Q(J.pid?{pid:J.pid}:{error:"daemon 启动后未返回 PID"})})})}catch($){return{error:$?.message??String($)}}}async function _F(){if(!process.stdin.isTTY)console.error(`${D.red}lodestar-setup: stdin 不是 TTY,无法交互式输入。${D.reset}`),console.error("请直接在 cmd / PowerShell / Terminal 里跑,不要 pipe 或重定向 stdin。"),process.exit(1);if(ZZ(c0)){if(console.log(`${D.yellow}发现已有配置: ${c0}${D.reset}`),(await W2("覆盖? (y/N)",{default:"n"})).toLowerCase()!=="y"){console.log("已取消"),x9.close();return}}GF("Lodestar 安装向导"),console.log("Lodestar 把 Feishu (飞书) 群聊接到 AI agent。"),console.log("默认后端是 Claude Code; Codex 是可选第二后端, 群里发 model 一键切换。"),console.log("每个群对应一个项目目录, agent 在那里跑、能读写文件。"),console.log(),console.log("支持本机已登录的 Claude Code 订阅,也可配置 GLM Coding Plan 或 Anthropic API key。"),console.log("Claude Code 订阅与第三方来源可在 model 面板中分别选择。"),console.log(),console.log("本向导依次做 4 件事:"),console.log(` ${D.dim}1) 确保 Claude Code CLI 已装好${D.reset}`),console.log(` ${D.dim}2) GLM Coding Plan API key (推荐, 可选) + Codex (可选)${D.reset}`),console.log(` ${D.dim}3) Feishu 自建应用 (含权限 / 事件 / 发版 + 凭据测试)${D.reset}`),console.log(` ${D.dim}4) 工作目录, 自动启动 daemon${D.reset}`),console.log(),await x9.question(`${D.dim}按 Enter 开始 (Ctrl+C 退出)...${D.reset}`),S3(1,4,"准备 Claude Code CLI"),await E3("claude",{report:(W)=>console.log(W)}),console.log(`${D.green}✓ Claude Code / SDK 已更新${D.reset}: ${D.dim}${C9("claude","claude")}${D.reset}`),console.log(),console.log(`${D.dim}下一步可选配 GLM Coding Plan 自动写入路由; 不配则用本机 Claude Code 现有配置。${D.reset}`),console.log(`${D.dim}使用 Claude 订阅时,在本机运行 \`claude auth login\`;完成后在 model 面板选择 Claude Code 订阅。${D.reset}`),S3(2,4,"GLM Coding Plan (推荐, 可选)"),console.log("GLM Coding Plan 给 Claude Code 接 GLM 系列模型 (支持 1M token 上下文, 中文友好)。"),console.log("订阅后在智谱开放平台拿一个 API key, 粘到下面 —— 向导自动写进 ~/.claude/settings.json。"),console.log(` ${D.dim}拿 key: https://open.bigmodel.cn → 控制台 → API Keys${D.reset}`),console.log(` ${D.dim}此项可选,直接回车跳过;以后可在群内发送 glm-setup <api_key> 补配。${D.reset}`),console.log(` ${D.dim}使用本机 Claude Code 或 Codex 订阅不需要 GLM Key。此处填写智谱国内站 Key;Z.ai 请之后用 glm-setup 指定对应地址。${D.reset}`),console.log();while(!0){let W=await W2("GLM API key (直接回车跳过)",{});if(!W){console.log(`${D.dim}已跳过 GLM, 以本机 Claude Code 现有配置启动。${D.reset}`);break}let K=await Yz(W);if("path"in K){console.log(`${D.green}✓ GLM 路由已写入${D.reset}: ${D.dim}${K.path}${D.reset}`),console.log(`${D.dim}模型 slots 按端点当前列表自动选取(最新一代 opus/sonnet, 1M ctx)${D.reset}`);break}else console.log(`${D.red}✗ GLM 配置失败:${D.reset} ${K.error}`),console.log(`${D.dim}请按错误提示处理后重新输入;直接回车可跳过,之后用群命令补配。${D.reset}`)}if(console.log(),console.log(`${D.bold}Codex (可选第二后端)${D.reset}`),console.log(` ${D.dim}想用 Codex 的话, 登录 ChatGPT 订阅即可, 模型/effort 走 ~/.codex/config.toml, 群里发 model 切换。${D.reset}`),(await W2("现在顺便配置 Codex 后端吗?",{default:"n"})).toLowerCase()==="y"){await E3("codex",{report:(K)=>console.log(K)});let W=C9("codex","codex");if(Jz(W))console.log(`${D.green}✓ Codex 已登录 ChatGPT${D.reset}`);else if(console.log(`${D.dim}启动 \`codex login\`...${D.reset}`),await WF(W)&&Jz(W))console.log(`${D.green}✓ Codex 已登录 ChatGPT${D.reset}`);else console.log(`${D.yellow}Codex 登录未完成 — 不影响默认 Claude 后端; 需要时随时跑 codex login。${D.reset}`)}else console.log(`${D.dim}已跳过 Codex (需要时随时跑 codex login, 群里发 model 切)。${D.reset}`);S3(3,4,"Feishu 自建应用");let Z="https://open.feishu.cn/app";console.log("打开飞书开放平台 (浏览器):"),console.log(` ${D.cyan}${Z}${D.reset}`),jF(Z),console.log(`${D.dim}(如果浏览器没自动开, 复制上面 URL 粘到浏览器)${D.reset}`),console.log(),console.log(`${D.bold}详细操作步骤:${D.reset}`),console.log(),console.log(` ${D.bold}① 创建应用${D.reset}`),console.log(` 点 "创建企业自建应用", 填名字 (如 ${D.dim}Lodestar${D.reset}), logo 随意。`),console.log(),console.log(` ${D.bold}② 添加机器人能力${D.reset}`),console.log(` 左侧菜单 "${D.cyan}添加应用能力${D.reset}" → 找到 "机器人" → 点 "${D.bold}添加${D.reset}" 按钮。`),console.log(),console.log(` ${D.bold}③ 申请权限 (左侧 "${D.cyan}权限管理${D.reset}" → "${D.bold}批量导入/导出权限${D.reset}")${D.reset}`),console.log(` ${D.yellow}选择应用身份权限,复制下方完整 JSON 批量导入,一次开齐账号信息、消息、卡片和云空间能力。${D.reset}`),console.log(JSON.stringify(Zz,null,2)),console.log(` ${D.dim}无需用户身份权限或飞书 CLI 登录。权限申请后须完成审批,并在步骤 ⑤ 发布飞书应用版本。${D.reset}`),console.log(` ${D.dim}清单包含以下用途;也可按名称逐项开通:${D.reset}`),console.log(` ${D.dim}账号与认证信息 (排障):${D.reset}`),console.log(` • ${D.bold}verification:verification_information:readonly${D.reset} ${D.dim}# 查看账号主体认证状态${D.reset}`),console.log(` • ${D.bold}tenant:tenant:readonly${D.reset} ${D.dim}# 查看租户基本信息${D.reset}`),console.log(` ${D.dim}消息类:${D.reset}`),console.log(` • ${D.bold}im:message:send_as_bot${D.reset} ${D.dim}# 以机器人身份发消息${D.reset}`),console.log(` • ${D.bold}im:message${D.reset} ${D.dim}# 接收/操作消息 (核心)${D.reset}`),console.log(` • ${D.bold}im:chat${D.reset} ${D.dim}# 读/写群信息 (匹配群名 ↔ 项目目录)${D.reset}`),console.log(` • ${D.bold}im:chat:create${D.reset} ${D.dim}# wt: 自动创建 worktree 群${D.reset}`),console.log(` • ${D.bold}im:chat:delete${D.reset} ${D.dim}# wt: 解散 worktree 群${D.reset}`),console.log(` • ${D.bold}im:chat.members:read${D.reset} ${D.dim}# wt: 判断发起人是否已在群内${D.reset}`),console.log(` • ${D.bold}im:chat.members:write_only${D.reset} ${D.dim}# wt: 把发起人拉进已有 worktree 群${D.reset}`),console.log(` • ${D.bold}im:resource${D.reset} ${D.dim}# 上传/下载附件 (图文双向)${D.reset}`),console.log(` • ${D.bold}im:message.urgent${D.reset} ${D.dim}# 加急推送 (锁屏通知 / Ask)${D.reset}`),console.log(` • ${D.bold}im:message.group_msg${D.reset} ${D.dim}# 敏感: 接收群里所有消息${D.reset}`),console.log(` ${D.dim}└ 关键: 没它机器人只收 @ 自己的消息, 拿不到群里其他对话, 一定要开${D.reset}`),console.log(` ${D.dim}└ 敏感权限要走审批: 申请时填用途, 个人开发者通常秒过${D.reset}`),console.log(` • ${D.bold}im:message.group_at_msg:readonly${D.reset} ${D.dim}# 读 @ 机器人消息 (兜底)${D.reset}`),console.log(` ${D.dim}卡片类 (Card Kit):${D.reset}`),console.log(` • ${D.bold}cardkit:card:read${D.reset} ${D.dim}# 读卡片状态${D.reset}`),console.log(` • ${D.bold}cardkit:card:write${D.reset} ${D.dim}# 创建/更新卡片 (流式渲染核心)${D.reset}`),console.log(` ${D.dim}云空间交付 (权限预先开通,功能仍按群开启):${D.reset}`),console.log(` • ${D.bold}drive:drive${D.reset} ${D.dim}# 上传、创建目录、协作者授权、关闭并核对文件链接分享${D.reset}`),console.log(` • ${D.bold}drive:file:upload${D.reset} ${D.dim}# 文件夹改名接口单独要求此权限${D.reset}`),console.log(` ${D.dim}默认仍直接发聊天附件;在指定群发送 files on 开启云空间,files off 恢复附件。${D.reset}`),console.log(` ${D.yellow}只取得 tenant_access_token 不代表以上权限已生效;缺少权限时群内命令会明确报错。${D.reset}`),console.log(),console.log(` ${D.bold}④ 订阅事件 (左侧 "${D.cyan}事件与回调${D.reset}", 拆两个子页:)${D.reset}`),console.log(` ${D.dim}a)${D.reset} ${D.bold}事件配置${D.reset} 页:`),console.log(` ${D.yellow}• "订阅方式" → 选 "长连接" → 点保存${D.reset}`),console.log(` • 添加事件: ${D.bold}im.message.receive_v1${D.reset} ${D.dim}# 收群消息${D.reset}`),console.log(` ${D.dim}b)${D.reset} ${D.bold}回调配置${D.reset} 页:`),console.log(` ${D.yellow}• "订阅方式" → 选 "长连接" → 点保存${D.reset}`),console.log(` • 添加事件: ${D.bold}card.action.trigger${D.reset} ${D.dim}# 卡片按钮点击回调${D.reset}`),console.log(),console.log(` ${D.bold}⑤ 发布版本${D.reset}`),console.log(` 页面顶部 "${D.bold}创建版本${D.reset}" → 滚到底点 "${D.bold}保存${D.reset}" → 弹框点 "${D.bold}发布${D.reset}"。`),console.log(` ${D.yellow}没发版的应用收不到任何事件 — 这步九成新手会忘!${D.reset}`),console.log(),console.log(` ${D.bold}⑥ 拿凭据${D.reset}`),console.log(` 左侧 "凭证与基础信息" → 顶部 ${D.bold}App ID${D.reset} (${D.dim}cli_...${D.reset}) 和 ${D.bold}App Secret${D.reset}, 待会粘到下面。`),console.log(),console.log(` ${D.bold}⑦ 把机器人拉进群${D.reset}`),console.log(" 想用的飞书群 → 群设置 → 群机器人 → 添加机器人 → 选你的应用。"),console.log(` ${D.yellow}群名要等于 projects_root 下的项目目录名${D.reset} (下一步设, 默认是用户主目录)。`),console.log();let J="",Q="";while(!0){J=await W2("App ID (以 cli_ 开头)",{required:!0}),Q=await W2("App Secret",{required:!0}),console.log(`${D.dim}测试中... (调 tenant_access_token endpoint)${D.reset}`);let W=await Vz(J,Q);if(W.ok){console.log(`${D.green}✓ Feishu 凭据测试通过${D.reset}`);break}if(console.log(`${D.red}✗ 测试失败:${D.reset} ${W.error}`),console.log(`${D.dim}最常见原因: app_id / app_secret 抄错, 或应用还没 "发布上线" (步骤 ⑤)。${D.reset}`),console.log(),(await W2("重新填? (Y/n)",{default:"y"})).toLowerCase()==="n")console.log(`${D.yellow}已取消, 配置未写盘。${D.reset}`),x9.close(),process.exit(1)}S3(4,4,"工作目录 + 启动"),console.log("每个 Feishu 群对应 projects_root 下同名的目录。"),console.log();let Y=process.platform==="win32"?process.env.USERPROFILE??"C:\\Users\\Default":process.env.HOME??"/root",V=await W2("projects_root",{default:Y});Qz(C5,{recursive:!0});let X=["# Lodestar config — generated by `lodestar-setup`","# Edit by hand or re-run setup to overwrite.","","[feishu]",`app_id = "${$Z(J)}"`,`app_secret = "${$Z(Q)}"`,"","[runtime]",`projects_root = "${$Z(V)}"`,"","[runtime.agent_auto_update]","codex = false","claude = false","dsh = false",""];Q$(c0,X.join(`
60
60
  `)),console.log(`
61
- ${F.green}${F.bold}✓ 配置已写入${F.reset}`),console.log(` ${F.cyan}${c0}${F.reset}`),console.log(`
62
- ${F.bold}启动 daemon...${F.reset}`);let z=await Xz(),H=process.platform==="win32"?"\\":"/",G=process.platform==="win32"?`${process.env.LOCALAPPDATA??"%LOCALAPPDATA%"}\\Lodestar\\daemon-YYYY-MM-DD.log`:`${process.env.HOME??"~"}/.local/share/lodestar/daemon-YYYY-MM-DD.log`;if("pid"in z)console.log(`${F.green}✓ daemon 已在后台启动${F.reset} (pid ${z.pid})`),console.log(),console.log(`${F.bold}最后一步: 在 Feishu 验证${F.reset}`),console.log(" ① 把机器人拉进任意飞书群"),console.log(` ② 群名 = ${F.cyan}${V}${H}<群名>${F.reset} 下的目录名 (新群第一条消息会自动建)`),console.log(" ③ 在群里发任意一条消息, 默认由 Claude 接管"),console.log(` ${F.dim}(群里发 model 可选择已配置账号、动态模型和 effort)${F.reset}`),console.log(),console.log("日志 (按日滚动, 保留近 7 天):"),console.log(` ${F.cyan}${G}${F.reset}`),console.log(),console.log(`${F.dim}若长期跑后台, Linux 配 systemd --user,macOS 配 launchd,Windows 配任务计划程序。${F.reset}`);else console.log(`${F.yellow}启动失败: ${z.error}${F.reset}`),console.log(`手动运行: ${F.cyan}lodestar-daemon${F.reset}`);console.log(),x9.close()}var F,x9;var Hz=R(()=>{u0();j4();E9();H0();b0();F4();$z();F={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m"},x9=VD({input:process.stdin,output:process.stdout})});class b3{label;interval;load;pending;timer;dueAt;failures=0;retired=!1;constructor($,Z,J,Q=0){this.label=$;this.interval=Z;this.load=J;this.dueAt=Q,x3.add(this),this.schedule()}get nextRefreshAt(){return this.dueAt}refresh(){if(this.retired)return Promise.resolve();if(this.pending)return this.pending;clearTimeout(this.timer);let $=Promise.resolve().then(()=>this.retired?void 0:this.load()).then(()=>{this.failures=0,this.dueAt=Date.now()+this.interval},(Z)=>{this.failures++;let J=Number(Z?.retryAfterMs);throw this.dueAt=Date.now()+Math.max(Math.min(300000,60000*2**Math.min(this.failures-1,3)),Number.isFinite(J)?J:0),j(`${this.label} refresh MISS: ${Z instanceof Error?Z.message:String(Z)}`),Z}).finally(()=>{if(this.pending===$)this.pending=void 0;this.schedule()});return this.pending=$,$}schedule(){if(clearTimeout(this.timer),!QZ||this.retired||this.pending)return;this.timer=setTimeout(()=>{this.refresh().catch(()=>{})},Math.max(0,this.dueAt-Date.now())),this.timer.unref?.()}dispose(){this.retired=!0,clearTimeout(this.timer),x3.delete(this)}}function Gz(){QZ=!0;for(let $ of x3)$.schedule()}function Wz(){QZ=!1;for(let $ of x3)$.schedule()}var x3,QZ=!1;var YZ=R(()=>{I();x3=new Set});import{createHash as PD,randomUUID as VZ}from"node:crypto";import{existsSync as k3,lstatSync as w3,mkdirSync as XZ,readFileSync as Kz,readdirSync as LD,realpathSync as M4,rmSync as qD,symlinkSync as DD,writeFileSync as FD}from"node:fs";import{homedir as MD}from"node:os";import{isAbsolute as UD,join as G1,relative as OD,resolve as AD,sep as ND}from"node:path";class Bz{defaultHome;root;stateFile;defaultLoginRevision;constructor($=AD(process.env.CODEX_HOME||G1(MD(),".codex")),Z=BX,J=jX){this.defaultHome=$;this.root=Z;this.stateFile=J}read(){if(!k3(this.stateFile))return{version:1,accounts:[],selections:{}};let $=JSON.parse(Kz(this.stateFile,"utf8"));if(!$||$.version!==1||!Array.isArray($.accounts)||!$.selections||typeof $.selections!=="object"||Array.isArray($.selections))throw Error("Codex 账号记录格式无效");let Z=new Set,J=new Set;for(let Q of $.accounts){if(!Q||!/^[a-f0-9-]{36}$/.test(Q.id)||typeof Q.name!=="string"||Z.has(Q.id)||J.has(this.nameKey(Q.name)))throw Error("Codex 账号记录重复或无效");this.validateName(Q.name),Z.add(Q.id),J.add(this.nameKey(Q.name))}for(let Q of Object.values($.selections))if(Q!==d&&!Z.has(Q))throw Error("Codex 账号选择指向不存在的账号");return $}nameKey($){return $.normalize("NFC").trim().toLowerCase()}validateName($){if(!$.trim()||$.length>80||/[\x00-\x1f\x7f/\\]/.test($)||["default","默认",".",".."].includes(this.nameKey($)))throw Error("备注名须为 1–80 个字符,不能包含换行或路径分隔符;default/默认为保留名称")}list(){return[{id:d,name:"默认",...this.defaultLoginRevision?{revision:this.defaultLoginRevision}:{}},...this.read().accounts.map(($)=>({...$}))]}get($){let Z=this.list().find((J)=>J.id===$);if(!Z)throw Error(`Codex 账号不存在:${$}`);return Z}find($=""){if(!$.trim()||["default","默认"].includes(this.nameKey($)))return this.get(d);let Z=this.list().find((J)=>this.nameKey(J.name)===this.nameKey($));if(!Z)throw Error(`Codex 账号不存在:${$};先发送 codex-login ${$}`);return Z}ensure($=""){if(!$.trim()||["default","默认"].includes(this.nameKey($)))return this.get(d);this.validateName($);let Z=this.read(),J=Z.accounts.find((Y)=>this.nameKey(Y.name)===this.nameKey($));if(J)return{...J};let Q={id:VZ(),name:$.normalize("NFC").trim()};return Z.accounts.push(Q),r(this.stateFile,Z),Q}remove($){let Z=this.get($);if($===d)throw Error("默认账号由设备原生 Codex 管理,不能用此命令删除");if(k1($))throw Error(`账号正在登录;先发送 codex-login-cancel ${Z.name}`);if(f3($,!0))throw Error("账号正在使用中;请先结束使用该账号的会话或委派任务,额度及模型查询结束后重试");let J=this.read(),Q=this.home($),Y;try{Y=w3(Q)}catch(X){if(X.code!=="ENOENT")throw X}if(Y){if(Y.isSymbolicLink()||!Y.isDirectory())throw Error("额外账号目录不是独立目录,拒绝删除");if(k3(this.defaultHome)){let X=OD(M4(Q),M4(this.defaultHome));if(!X||!UD(X)&&X!==".."&&!X.startsWith(`..${ND}`))throw Error("额外账号目录包含默认认证目录,拒绝删除")}try{qD(Q,{recursive:!0})}catch(X){throw Error(`账号文件删除失败,账号记录已保留;${X}`)}}J.accounts=J.accounts.filter((X)=>X.id!==$);let V=0;for(let[X,z]of Object.entries(J.selections)){if(z!==$)continue;delete J.selections[X],V++}try{r(this.stateFile,J)}catch(X){throw Error(`账号文件已移除,但账号记录保存失败;请重试 codex-account-delete ${Z.name};${X}`)}return{account:Z,clearedSelections:V}}selected($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:d}preferred($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:null}selectAuto($){let Z=this.read();delete Z.selections[$],r(this.stateFile,Z)}select($,Z){this.get(Z);let J=this.read();Object.defineProperty(J.selections,$,{value:Z,enumerable:!0,writable:!0,configurable:!0}),r(this.stateFile,J)}recordLogin($,Z){let J=this.read();if($===d){this.defaultLoginRevision=VZ();return}let Q=J.accounts.find((Y)=>Y.id===$);if(!Q)throw Error("登录完成时账号记录已不存在");Object.assign(Q,{email:Z.email,planType:Z.planType,revision:VZ()}),r(this.stateFile,J)}home($=d){return $===d?this.defaultHome:G1(this.root,this.get($).id)}revision($){let Z=this.get($);return JSON.stringify([this.home($),Z.revision??null])}prepareHome($){let Z=this.home($);if($===d)return Z;let J;try{J=w3(Z)}catch(V){if(V.code!=="ENOENT")throw V}if(J?.isSymbolicLink())throw Error("额外账号目录不能是软链接");if(XZ(Z,{recursive:!0,mode:448}),XZ(this.defaultHome,{recursive:!0,mode:448}),M4(Z)===M4(this.defaultHome))throw Error("额外账号不能使用默认认证目录");let Q;try{Q=w3(G1(Z,"auth.json"))}catch(V){if(V.code!=="ENOENT")throw V}if(Q?.isSymbolicLink()||Q&&!Q.isFile())throw Error("额外账号的 auth.json 必须为独立文件");try{FD(G1(this.defaultHome,"config.toml"),"",{flag:"wx",mode:384})}catch(V){if(V.code!=="EEXIST")throw V}for(let V of RD){let X=G1(this.defaultHome,V);XZ(X,{recursive:!0,mode:448}),this.link(X,G1(Z,V),!0)}let Y=new Set([...TD,...LD(this.defaultHome).filter((V)=>V.endsWith(".config.toml"))]);for(let V of Y){let X=G1(this.defaultHome,V);if(k3(X))this.link(X,G1(Z,V),!1)}return Z}link($,Z,J){let Q;try{Q=w3(Z)}catch(Y){if(Y.code!=="ENOENT")throw Y}if(Q){if(!Q.isSymbolicLink()||M4(Z)!==M4($))throw Error(`Codex 共享路径已被替换或指向其他位置:${Z}`);return}DD($,Z,J&&process.platform==="win32"?"junction":J?"dir":"file")}env($,Z,J=!0,Q=!1){if(!Q&&k1($))throw Error("该 Codex 账号正在登录,请等待授权完成");let Y=J?this.prepareHome($):this.home($),V={...Z,CODEX_HOME:Y};if($!==d){V.CODEX_SQLITE_HOME=Z.CODEX_SQLITE_HOME||this.defaultHome;for(let X of["CODEX_API_KEY","OPENAI_API_KEY","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete V[X]}return V}cliArgs($){return this.get($),$===d?[]:["-c",'cli_auth_credentials_store="file"',"-c",'forced_login_method="chatgpt"']}fingerprint($){let Z=G1(this.home($),"auth.json");if(!k3(Z))return null;let Q=JSON.parse(Kz(Z,"utf8"))?.tokens;if(!Q?.account_id||typeof Q.id_token!=="string")return null;let Y=Q.id_token.split(".")[1];if(!Y)throw Error("Codex 身份 Token 格式无效");let V=JSON.parse(Buffer.from(Y,"base64url").toString("utf8"));if(typeof V.sub!=="string"||!V.sub)return null;return PD("sha256").update(JSON.stringify([Q.account_id,V.sub])).digest("hex")}}function w1($,Z,J=!0){if(jz.set($,Z),!v3.has($))$.once("exit",()=>v3.delete($));v3.set($,{id:Z,ownsNativeProcess:J})}function f3($,Z=!1){return[...v3].some(([J,Q])=>Q.id===$&&(Q.ownsNativeProcess||Z)&&J.isAlive())}function k1($){return b9.has($)}function _z($){if(b9.has($))throw Error("该账号已有登录任务");if(f3($))throw Error("该 Codex 账号正在使用中");let Z=Symbol($);return b9.set($,Z),()=>{if(b9.get($)===Z)b9.delete($)}}function M$($){return $?jz.get($)??d:d}var d="default",RD,TD,v,jz,v3,b9;var F0=R(()=>{H0();b0();RD=["sessions","archived_sessions","skills","rules","prompts","plugins","memories","generated_images","thread-writer-locks"],TD=["config.toml","AGENTS.md","AGENTS.override.md","hooks.json","history.jsonl","session_index.jsonl","installation_id"];v=new Bz,jz=new WeakMap,v3=new Map;b9=new Map});import{readFileSync as ED}from"node:fs";import{homedir as Lz}from"node:os";function Pz($){return $.replace(/^~(?=\/|$)/,Lz())}function SD($){let Z={_:{}},J="_";for(let Q of $.split(`
63
- `)){let Y=CD(Q).trim();if(!Y)continue;let V=Y.match(/^\[([^\]]+)\]$/);if(V){if(J=V[1].trim(),J.startsWith("claude.safe_mode."))throw Error("lodestar: use [claude.safe_mode] with Token Source keys, not nested tables");Z[J]??={};continue}if(/^\[+\s*claude\.safe_mode(?:[.\]\s]|$)/.test(Y))throw Error("lodestar: invalid [claude.safe_mode] table header");let X=Y.match(/^([\w.-]+)\s*=\s*(.+)$/);if(X){let z=X[2].trim();if(J==="claude.safe_mode"){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(X[1]))throw Error(`lodestar: invalid [claude.safe_mode] Token Source key "${X[1]}"`);if(!/^(?:"(?:[^"\\]|\\[\\"])*"|'[^']*')$/.test(z))throw Error(`lodestar: [claude.safe_mode].${X[1]} must be a quoted string of model IDs, "*", or ""`);if(Object.hasOwn(Z[J],X[1]))throw Error(`lodestar: duplicate [claude.safe_mode].${X[1]}`)}let H=z.startsWith('"')&&z.endsWith('"'),G=z.startsWith("'")&&z.endsWith("'");if(H||G){if(z=z.slice(1,-1),H)z=z.replace(/\\([\\"])/g,"$1")}Z[J][X[1]]=z}else if(J==="claude.safe_mode"||J==="claude"&&/^safe_mode(?:\s|=|$)/.test(Y))throw Error('lodestar: invalid entry in [claude.safe_mode]; expected Token Source = "model IDs"')}return Z}function CD($){let Z=null,J=!1;for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Z==="double"){if(J){J=!1;continue}if(Y==="\\"){J=!0;continue}if(Y==='"')Z=null;continue}if(Z==="single"){if(Y==="'")Z=null;continue}if(Y==='"')Z="double";else if(Y==="'")Z="single";else if(Y==="#")return $.slice(0,Q)}return $}function k9(){let $;try{$=ED(c0,"utf8")}catch(O){throw process.stderr.write(`lodestar: cannot read config at ${c0}
61
+ ${D.green}${D.bold}✓ 配置已写入${D.reset}`),console.log(` ${D.cyan}${c0}${D.reset}`),console.log(`
62
+ ${D.bold}启动 daemon...${D.reset}`);let z=await Xz(),H=process.platform==="win32"?"\\":"/",G=process.platform==="win32"?`${process.env.LOCALAPPDATA??"%LOCALAPPDATA%"}\\Lodestar\\daemon-YYYY-MM-DD.log`:`${process.env.HOME??"~"}/.local/share/lodestar/daemon-YYYY-MM-DD.log`;if("pid"in z)console.log(`${D.green}✓ daemon 已在后台启动${D.reset} (pid ${z.pid})`),console.log(),console.log(`${D.bold}最后一步: 在 Feishu 验证${D.reset}`),console.log(" ① 把机器人拉进任意飞书群"),console.log(` ② 群名 = ${D.cyan}${V}${H}<群名>${D.reset} 下的目录名 (新群第一条消息会自动建)`),console.log(" ③ 在群里发任意一条消息, 默认由 Claude 接管"),console.log(` ${D.dim}(群里发 model 可选择已配置账号、动态模型和 effort)${D.reset}`),console.log(),console.log("日志 (按日滚动, 保留近 7 天):"),console.log(` ${D.cyan}${G}${D.reset}`),console.log(),console.log(`${D.dim}若长期跑后台, Linux 配 systemd --user,macOS 配 launchd,Windows 配任务计划程序。${D.reset}`);else console.log(`${D.yellow}启动失败: ${z.error}${D.reset}`),console.log(`手动运行: ${D.cyan}lodestar-daemon${D.reset}`);console.log(),x9.close()}var D,x9;var Hz=R(()=>{u0();j4();E9();H0();b0();D4();$z();D={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m"},x9=VF({input:process.stdin,output:process.stdout})});class b3{label;interval;load;pending;timer;dueAt;failures=0;retired=!1;constructor($,Z,J,Q=0){this.label=$;this.interval=Z;this.load=J;this.dueAt=Q,x3.add(this),this.schedule()}get nextRefreshAt(){return this.dueAt}refresh(){if(this.retired)return Promise.resolve();if(this.pending)return this.pending;clearTimeout(this.timer);let $=Promise.resolve().then(()=>this.retired?void 0:this.load()).then(()=>{this.failures=0,this.dueAt=Date.now()+this.interval},(Z)=>{this.failures++;let J=Number(Z?.retryAfterMs);throw this.dueAt=Date.now()+Math.max(Math.min(300000,60000*2**Math.min(this.failures-1,3)),Number.isFinite(J)?J:0),j(`${this.label} refresh MISS: ${Z instanceof Error?Z.message:String(Z)}`),Z}).finally(()=>{if(this.pending===$)this.pending=void 0;this.schedule()});return this.pending=$,$}schedule(){if(clearTimeout(this.timer),!QZ||this.retired||this.pending)return;this.timer=setTimeout(()=>{this.refresh().catch(()=>{})},Math.max(0,this.dueAt-Date.now())),this.timer.unref?.()}dispose(){this.retired=!0,clearTimeout(this.timer),x3.delete(this)}}function Gz(){QZ=!0;for(let $ of x3)$.schedule()}function Wz(){QZ=!1;for(let $ of x3)$.schedule()}var x3,QZ=!1;var YZ=R(()=>{I();x3=new Set});import{createHash as PF,randomUUID as VZ}from"node:crypto";import{existsSync as k3,lstatSync as w3,mkdirSync as XZ,readFileSync as Kz,readdirSync as LF,realpathSync as M4,rmSync as qF,symlinkSync as FF,writeFileSync as DF}from"node:fs";import{homedir as MF}from"node:os";import{isAbsolute as UF,join as G1,relative as OF,resolve as AF,sep as NF}from"node:path";class Bz{defaultHome;root;stateFile;defaultLoginRevision;constructor($=AF(process.env.CODEX_HOME||G1(MF(),".codex")),Z=BX,J=jX){this.defaultHome=$;this.root=Z;this.stateFile=J}read(){if(!k3(this.stateFile))return{version:1,accounts:[],selections:{}};let $=JSON.parse(Kz(this.stateFile,"utf8"));if(!$||$.version!==1||!Array.isArray($.accounts)||!$.selections||typeof $.selections!=="object"||Array.isArray($.selections))throw Error("Codex 账号记录格式无效");let Z=new Set,J=new Set;for(let Q of $.accounts){if(!Q||!/^[a-f0-9-]{36}$/.test(Q.id)||typeof Q.name!=="string"||Z.has(Q.id)||J.has(this.nameKey(Q.name)))throw Error("Codex 账号记录重复或无效");this.validateName(Q.name),Z.add(Q.id),J.add(this.nameKey(Q.name))}for(let Q of Object.values($.selections))if(Q!==d&&!Z.has(Q))throw Error("Codex 账号选择指向不存在的账号");return $}nameKey($){return $.normalize("NFC").trim().toLowerCase()}validateName($){if(!$.trim()||$.length>80||/[\x00-\x1f\x7f/\\]/.test($)||["default","默认",".",".."].includes(this.nameKey($)))throw Error("备注名须为 1–80 个字符,不能包含换行或路径分隔符;default/默认为保留名称")}list(){return[{id:d,name:"默认",...this.defaultLoginRevision?{revision:this.defaultLoginRevision}:{}},...this.read().accounts.map(($)=>({...$}))]}get($){let Z=this.list().find((J)=>J.id===$);if(!Z)throw Error(`Codex 账号不存在:${$}`);return Z}find($=""){if(!$.trim()||["default","默认"].includes(this.nameKey($)))return this.get(d);let Z=this.list().find((J)=>this.nameKey(J.name)===this.nameKey($));if(!Z)throw Error(`Codex 账号不存在:${$};先发送 codex-login ${$}`);return Z}ensure($=""){if(!$.trim()||["default","默认"].includes(this.nameKey($)))return this.get(d);this.validateName($);let Z=this.read(),J=Z.accounts.find((Y)=>this.nameKey(Y.name)===this.nameKey($));if(J)return{...J};let Q={id:VZ(),name:$.normalize("NFC").trim()};return Z.accounts.push(Q),r(this.stateFile,Z),Q}remove($){let Z=this.get($);if($===d)throw Error("默认账号由设备原生 Codex 管理,不能用此命令删除");if(k1($))throw Error(`账号正在登录;先发送 codex-login-cancel ${Z.name}`);if(y3($,!0))throw Error("账号正在使用中;请先结束使用该账号的会话或委派任务,额度及模型查询结束后重试");let J=this.read(),Q=this.home($),Y;try{Y=w3(Q)}catch(X){if(X.code!=="ENOENT")throw X}if(Y){if(Y.isSymbolicLink()||!Y.isDirectory())throw Error("额外账号目录不是独立目录,拒绝删除");if(k3(this.defaultHome)){let X=OF(M4(Q),M4(this.defaultHome));if(!X||!UF(X)&&X!==".."&&!X.startsWith(`..${NF}`))throw Error("额外账号目录包含默认认证目录,拒绝删除")}try{qF(Q,{recursive:!0})}catch(X){throw Error(`账号文件删除失败,账号记录已保留;${X}`)}}J.accounts=J.accounts.filter((X)=>X.id!==$);let V=0;for(let[X,z]of Object.entries(J.selections)){if(z!==$)continue;delete J.selections[X],V++}try{r(this.stateFile,J)}catch(X){throw Error(`账号文件已移除,但账号记录保存失败;请重试 codex-account-delete ${Z.name};${X}`)}return{account:Z,clearedSelections:V}}selected($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:d}preferred($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:null}selectAuto($){let Z=this.read();delete Z.selections[$],r(this.stateFile,Z)}select($,Z){this.get(Z);let J=this.read();Object.defineProperty(J.selections,$,{value:Z,enumerable:!0,writable:!0,configurable:!0}),r(this.stateFile,J)}recordLogin($,Z){let J=this.read();if($===d){this.defaultLoginRevision=VZ();return}let Q=J.accounts.find((Y)=>Y.id===$);if(!Q)throw Error("登录完成时账号记录已不存在");Object.assign(Q,{email:Z.email,planType:Z.planType,revision:VZ()}),r(this.stateFile,J)}home($=d){return $===d?this.defaultHome:G1(this.root,this.get($).id)}revision($){let Z=this.get($);return JSON.stringify([this.home($),Z.revision??null])}prepareHome($){let Z=this.home($);if($===d)return Z;let J;try{J=w3(Z)}catch(V){if(V.code!=="ENOENT")throw V}if(J?.isSymbolicLink())throw Error("额外账号目录不能是软链接");if(XZ(Z,{recursive:!0,mode:448}),XZ(this.defaultHome,{recursive:!0,mode:448}),M4(Z)===M4(this.defaultHome))throw Error("额外账号不能使用默认认证目录");let Q;try{Q=w3(G1(Z,"auth.json"))}catch(V){if(V.code!=="ENOENT")throw V}if(Q?.isSymbolicLink()||Q&&!Q.isFile())throw Error("额外账号的 auth.json 必须为独立文件");try{DF(G1(this.defaultHome,"config.toml"),"",{flag:"wx",mode:384})}catch(V){if(V.code!=="EEXIST")throw V}for(let V of RF){let X=G1(this.defaultHome,V);XZ(X,{recursive:!0,mode:448}),this.link(X,G1(Z,V),!0)}let Y=new Set([...TF,...LF(this.defaultHome).filter((V)=>V.endsWith(".config.toml"))]);for(let V of Y){let X=G1(this.defaultHome,V);if(k3(X))this.link(X,G1(Z,V),!1)}return Z}link($,Z,J){let Q;try{Q=w3(Z)}catch(Y){if(Y.code!=="ENOENT")throw Y}if(Q){if(!Q.isSymbolicLink()||M4(Z)!==M4($))throw Error(`Codex 共享路径已被替换或指向其他位置:${Z}`);return}FF($,Z,J&&process.platform==="win32"?"junction":J?"dir":"file")}env($,Z,J=!0,Q=!1){if(!Q&&k1($))throw Error("该 Codex 账号正在登录,请等待授权完成");let Y=J?this.prepareHome($):this.home($),V={...Z,CODEX_HOME:Y};if($!==d){V.CODEX_SQLITE_HOME=Z.CODEX_SQLITE_HOME||this.defaultHome;for(let X of["CODEX_API_KEY","OPENAI_API_KEY","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete V[X]}return V}cliArgs($){return this.get($),$===d?[]:["-c",'cli_auth_credentials_store="file"',"-c",'forced_login_method="chatgpt"']}fingerprint($){let Z=G1(this.home($),"auth.json");if(!k3(Z))return null;let Q=JSON.parse(Kz(Z,"utf8"))?.tokens;if(!Q?.account_id||typeof Q.id_token!=="string")return null;let Y=Q.id_token.split(".")[1];if(!Y)throw Error("Codex 身份 Token 格式无效");let V=JSON.parse(Buffer.from(Y,"base64url").toString("utf8"));if(typeof V.sub!=="string"||!V.sub)return null;return PF("sha256").update(JSON.stringify([Q.account_id,V.sub])).digest("hex")}}function w1($,Z,J=!0){if(jz.set($,Z),!v3.has($))$.once("exit",()=>v3.delete($));v3.set($,{id:Z,ownsNativeProcess:J})}function y3($,Z=!1){return[...v3].some(([J,Q])=>Q.id===$&&(Q.ownsNativeProcess||Z)&&J.isAlive())}function k1($){return b9.has($)}function _z($){if(b9.has($))throw Error("该账号已有登录任务");if(y3($))throw Error("该 Codex 账号正在使用中");let Z=Symbol($);return b9.set($,Z),()=>{if(b9.get($)===Z)b9.delete($)}}function M$($){return $?jz.get($)??d:d}var d="default",RF,TF,v,jz,v3,b9;var D0=R(()=>{H0();b0();RF=["sessions","archived_sessions","skills","rules","prompts","plugins","memories","generated_images","thread-writer-locks"],TF=["config.toml","AGENTS.md","AGENTS.override.md","hooks.json","history.jsonl","session_index.jsonl","installation_id"];v=new Bz,jz=new WeakMap,v3=new Map;b9=new Map});import{readFileSync as EF}from"node:fs";import{homedir as Lz}from"node:os";function Pz($){return $.replace(/^~(?=\/|$)/,Lz())}function SF($){let Z={_:{}},J="_";for(let Q of $.split(`
63
+ `)){let Y=CF(Q).trim();if(!Y)continue;let V=Y.match(/^\[([^\]]+)\]$/);if(V){if(J=V[1].trim(),J.startsWith("claude.safe_mode."))throw Error("lodestar: use [claude.safe_mode] with Token Source keys, not nested tables");Z[J]??={};continue}if(/^\[+\s*claude\.safe_mode(?:[.\]\s]|$)/.test(Y))throw Error("lodestar: invalid [claude.safe_mode] table header");let X=Y.match(/^([\w.-]+)\s*=\s*(.+)$/);if(X){let z=X[2].trim();if(J==="claude.safe_mode"){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(X[1]))throw Error(`lodestar: invalid [claude.safe_mode] Token Source key "${X[1]}"`);if(!/^(?:"(?:[^"\\]|\\[\\"])*"|'[^']*')$/.test(z))throw Error(`lodestar: [claude.safe_mode].${X[1]} must be a quoted string of model IDs, "*", or ""`);if(Object.hasOwn(Z[J],X[1]))throw Error(`lodestar: duplicate [claude.safe_mode].${X[1]}`)}let H=z.startsWith('"')&&z.endsWith('"'),G=z.startsWith("'")&&z.endsWith("'");if(H||G){if(z=z.slice(1,-1),H)z=z.replace(/\\([\\"])/g,"$1")}Z[J][X[1]]=z}else if(J==="claude.safe_mode"||J==="claude"&&/^safe_mode(?:\s|=|$)/.test(Y))throw Error('lodestar: invalid entry in [claude.safe_mode]; expected Token Source = "model IDs"')}return Z}function CF($){let Z=null,J=!1;for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Z==="double"){if(J){J=!1;continue}if(Y==="\\"){J=!0;continue}if(Y==='"')Z=null;continue}if(Z==="single"){if(Y==="'")Z=null;continue}if(Y==='"')Z="double";else if(Y==="'")Z="single";else if(Y==="#")return $.slice(0,Q)}return $}function k9(){let $;try{$=EF(c0,"utf8")}catch(O){throw process.stderr.write(`lodestar: cannot read config at ${c0}
64
64
  `+" → 运行 `lodestar-setup` 走交互式向导生成 (Feishu / Codex / 工作目录)\n"+` → 或手写: 设 LODESTAR_CONFIG=/path/to/config.toml 覆盖默认路径
65
65
  `+` [feishu]
66
66
  app_id = "cli_xxx"
67
67
  app_secret = "xxx"
68
68
 
69
- `),O}let Z=SD($),J=Z.feishu?.app_id,Q=Z.feishu?.app_secret;if(!J||!Q)throw Error(`lodestar: ${c0} is missing [feishu].app_id / [feishu].app_secret`);let Y=Pz(Z.runtime?.projects_root??Lz()),V={codex:!1,claude:!1,dsh:!1},X=Z["runtime.agent_auto_update"],z=Z.runtime?.agent_auto_update;if(z!==void 0){if(X)throw Error("lodestar: legacy [runtime].agent_auto_update cannot be combined with [runtime.agent_auto_update]");if(z!=="true"&&z!=="false")throw Error(`lodestar: [runtime].agent_auto_update must be true or false, got "${z}"`);for(let O of["codex","claude","dsh"])V[O]=z==="true";process.stderr.write(`lodestar: 旧 agent_auto_update 总开关已按原值映射为三个开关;请改用 [runtime.agent_auto_update] 的 codex、claude、dsh 配置。
70
- `)}else if(X)for(let[O,N]of Object.entries(X)){if(O!=="codex"&&O!=="claude"&&O!=="dsh")throw Error(`lodestar: unknown [runtime.agent_auto_update] Agent "${O}"`);if(N!=="true"&&N!=="false")throw Error(`lodestar: [runtime.agent_auto_update].${O} must be true or false, got "${N}"`);V[O]=N==="true"}let H=(Z.runtime?.live_elapsed??"bucket").trim().toLowerCase();if(H!=="bucket"&&H!=="second")throw Error(`lodestar: [runtime].live_elapsed must be "bucket" or "second", got "${Z.runtime?.live_elapsed}"`);let G=H,W=Z.notify?.bind??"127.0.0.1",K=Z.notify?.port??"9876";if(!/^\d+$/.test(K.trim()))throw Error(`lodestar: [notify].port must be an integer, got "${K}"`);let B=Number.parseInt(K,10);if(!Number.isFinite(B)||B<=0||B>65535)throw Error(`lodestar: [notify].port must be 1..65535, got "${K}"`);let _=(O)=>{let N=Z[O]??{},S={};for(let[T,y]of Object.entries(N))if(typeof y==="string"&&y.length>0)S[T]=y;return S},P=()=>{let O={};for(let[N,S]of Object.entries(Z)){if(!N.startsWith("claude.models."))continue;let y=N.slice(14).trim();if(!y)continue;let m={};for(let[b,p]of Object.entries(S)){if(typeof p!=="string"||p.length===0)continue;if(b.trim()==="model")m.model=p}O[y]=m}return O},L=()=>{let O={},N="projects.";for(let[S,T]of Object.entries(Z)){if(!S.startsWith("projects."))continue;let y=S.slice(9).trim();if(!y)continue;let m={};for(let[b,p]of Object.entries(T)){if(typeof p!=="string"||p.length===0)continue;switch(b.trim()){case"cwd":m.cwd=p;break;case"setting_sources":m.settingSources=p;break;case"strict_mcp":m.strictMcp=p==="true";break;case"tools":m.tools=p;break;case"load_project_mcp":m.loadProjectMcp=p==="true";break}}O[y]=m}return O},q=()=>{let O={},N="token_source.";for(let[S,T]of Object.entries(Z)){if(!S.startsWith("token_source."))continue;let y=S.slice(13).trim();if(!y)continue;let m={};for(let[b,p]of Object.entries(T)){if(typeof p!=="string")continue;let c=b.trim();if(c==="enabled"){if(p!=="true"&&p!=="false")throw Error(`[${S}].enabled 必须为 true 或 false`);m.enabled=p==="true"}else if(c==="default")m.default=p==="true";else if(c==="agent"||c==="display"||c==="auth"||c==="base_url"||c==="auth_token"||c==="api_key"||c==="management_token"||c==="management_user_id"||c==="management_url"||c==="billing_source"||c==="bin"||c==="model"||c==="effort"||c==="models"||c==="hidden_models"||c==="shown_models"||c==="custom_models"||c==="slots"||c==="usage")m[c]=p}O[y]=m}return O},D=_("codex.env"),M=_("claude.env"),U=Z.claude?.bin?Pz(Z.claude.bin):void 0;if(Z.claude?.safe_mode!==void 0)throw Error("lodestar: safe_mode must use the [claude.safe_mode] table");let A={};for(let[O,N]of Object.entries(Z["claude.safe_mode"]??{})){let S=N.trim(),T=S===""?[]:S.split(",").map((y)=>y.trim());if(T.some((y)=>!y||/[\s,"']/.test(y))||T.some((y)=>y.includes("*"))&&(T.length!==1||T[0]!=="*"))throw Error(`lodestar: [claude.safe_mode].${O} must be comma-separated exact model IDs, "*", or ""`);A[O]=T}return{feishu:{app_id:J,app_secret:Q},runtime:{projects_root:Y,live_elapsed:G,agent_auto_update:V},notify:{bind:W,port:B},codex:{env:D},claude:{bin:U,env:M,models:P(),safe_mode:A,...Z.claude?.translation_validation_rules!==void 0?{translation_validation_rules:Z.claude.translation_validation_rules}:{}},projects:L(),token_sources:q()}}function qz(){g.token_sources=k9().token_sources}var g;var k0=R(()=>{H0();g=k9()});import{spawn as xD}from"cross-spawn";import{mkdtemp as bD,rm as Dz,writeFile as kD}from"node:fs/promises";import{tmpdir as wD}from"node:os";import{join as Fz}from"node:path";function fD($){if(!$||typeof $!=="object"||Array.isArray($))throw Error("Codex raw model catalog is not an object");let Z=structuredClone($);if(!Array.isArray(Z.models)||!Z.models.length)throw Error("Codex raw model catalog has no models");for(let J of Z.models){if(!J||typeof J!=="object"||typeof J.slug!=="string"||!J.slug)throw Error("Codex raw model catalog contains an invalid model");if(!Array.isArray(J.experimental_supported_tools)||J.experimental_supported_tools.some((Q)=>typeof Q!=="string"))throw Error(`Codex raw model ${J.slug} has invalid experimental_supported_tools`);J.experimental_supported_tools=J.experimental_supported_tools.filter((Q)=>!vD.has(Q))}return Z}function yD($){let Z=[],J=$.trim().split(`
71
- `);for(let Q of J){let Y=/^([a-z0-9_.]+)\s+(.+?)\s+(true|false)\s*$/.exec(Q);if(!Y)throw Error("Codex feature catalog returned an invalid row");if(Y[2]!=="removed"&&["send_message_to_user_async","send_async_message"].includes(Y[1]))Z.push(Y[1])}return Z}async function Mz($,Z){$.signal.throwIfAborted();let J=`Codex ${Z.join(" ")}`,Q=xD($.binary,[...Z,...$.configArgs],{cwd:$.workDir,env:$.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y=[],V=[],X=0,z,H,G=(L)=>{if(z)return;if(z??=L,Q.pid)Q.kill("SIGTERM"),H=setTimeout(()=>{Q.kill("SIGKILL")},3000)},W=()=>G($.signal.reason instanceof Error?$.signal.reason:Error("Codex model catalog preparation cancelled"));$.signal.addEventListener("abort",W,{once:!0});let K=setTimeout(()=>G(Error(`${J} exceeded 30 seconds`)),30000),B=new Promise((L)=>{Q.on("error",(q)=>{z??=q}),Q.stdout.on("data",(q)=>{if(X+=q.length,X>33554432)G(Error("Codex raw model catalog exceeds 32 MiB"));else Y.push(q)}),Q.stderr.on("data",(q)=>{V.push(q)}),Q.once("close",(q)=>L(q))});if($.signal.aborted)W();let _;try{_=await B}finally{if(clearTimeout(K),H)clearTimeout(H);$.signal.removeEventListener("abort",W)}let P=Buffer.concat(V).toString("utf8").trim();if(P)j(`${J}[stderr]: ${P}`);if(z)throw z;if(_!==0)throw Error(`${J} failed (exit ${_}): ${P||"no diagnostic"}`);if(/ERROR[^\n]*(?:models_manager|model_catalog)|(?:models_manager|model_catalog)[^\n]*(?:failed|error)/i.test(P))throw Error(`Codex model catalog export reported an upstream failure: ${P}`);return $.signal.throwIfAborted(),Buffer.concat(Y).toString("utf8")}async function Uz($){let Z=await Promise.allSettled([Mz($,["debug","models"]),Mz($,["features","list"])]),J=Z.filter((G)=>G.status==="rejected");if(J.length)throw AggregateError(J.map((G)=>G.reason),J.map((G)=>String(G.reason)).join("; "));let[Q,Y]=Z.map((G)=>G.value),V=fD(JSON.parse(Q)),X=yD(Y),z=await bD(Fz(wD(),"lodestar-codex-input-policy-")),H=Fz(z,"models.json");try{return await kD(H,JSON.stringify(V),{mode:384}),$.signal.throwIfAborted(),{path:H,disabledFeatures:X,dispose:()=>Dz(z,{recursive:!0,force:!0})}}catch(G){throw await Dz(z,{recursive:!0,force:!0}),G}}var vD;var Oz=R(()=>{I();vD=new Set(["request_user_input","request_user_input_async","send_user_message_async","send_message_to_user_async"])});function A0($){return typeof $==="string"&&$?$:void 0}function Z0($){return $!=null&&typeof $==="object"?$:null}function W1($){if($==null||$==="")return"-";return String($).replace(/\s+/g," ").slice(0,300)}function y3($){if(!$)return"[]";let Z=Object.keys($),J=Z.slice(0,80),Q=Z.length>J.length?`,...+${Z.length-J.length}`:"";return`[${J.join(",")}${Q}]`}function ID($){let Z=$.slice(0,GZ),J=$.length>Z.length?`,...+${$.length-Z.length}`:"";return`[${Z.join(",")}${J}]`}function gD($){let Z=Z0($);if(!Z)return null;let J=Z0(Z.event),Q=Z0(Z.payload);return Z0(Z.item)??Z0(Z.responseItem)??Z0(Z.rawItem)??Z0(J?.item)??Z0(J?.responseItem)??Z0(J?.rawItem)??Z0(Q?.item)??Z0(Q?.responseItem)??Z0(Q?.rawItem)??(w9(Z.type)?Z:null)??(J&&w9(J.type)?J:null)??(Q&&w9(Q.type)?Q:null)}function mD($){let Z=[],J=new WeakSet,Q=(Y,V,X)=>{if(Z.length>=GZ||X>6)return;if(Array.isArray(Y)){if(V)Z.push(`${V}[]`);if(Y.length>0)Q(Y[0],V?`${V}[]`:"[]",X+1);return}if(Y==null||typeof Y!=="object")return;if(J.has(Y))return;J.add(Y);for(let z of Object.keys(Y)){if(Z.length>=GZ)return;let H=V?`${V}.${z}`:z;Z.push(H),Q(Y[z],H,X+1)}};return Q($,"",0),Z}function WZ($){let Z=new WeakSet,J;try{J=JSON.stringify($,(Q,Y)=>{if(typeof Y==="bigint")return`${Y.toString()}n`;if(typeof Y==="string"&&Y.length>HZ)return`${Y.slice(0,HZ)}...<truncated ${Y.length-HZ} chars>`;if(Y!=null&&typeof Y==="object"){if(Z.has(Y))return"[Circular]";Z.add(Y)}return Y})??String($)}catch(Q){J=`<unserializable: ${Q}>`}if(J.length>zZ)return`${J.slice(0,zZ)}...<truncated ${J.length-zZ} chars>`;return J}function V$($,Z){let J=Z0(Z),Q=J?Z0(J.params):null,Y=J?Z0(J.item)??Z0(Q?.item):null,V=J?A0(J.method)??"-":"-";j([`codex-process: APP_SERVER_UNHANDLED_${$}`,`method=${W1(V)}`,`rootKeys=${y3(J)}`,`itemKeys=${y3(Y)}`,`payload=${WZ(Z)}`].join(" "))}function KZ($,Z,J){let Q=Z0(Z),Y=gD(Z),V=[`phase=${W1(J.phase??"event")}`,`method=${W1($)}`,`sourceMethod=${W1(J.sourceMethod)}`,`sourceType=${W1(J.sourceType)}`,`sessionId=${W1(J.sessionId)}`,`threadId=${W1(J.threadId)}`,`turnId=${W1(J.turnId)}`,`itemId=${W1(J.itemId)}`].join(" ");if(j(`codex-process: CONTEXT_COMPACTION_EVENT ${V} rootKeys=${y3(Q)} itemKeys=${y3(Y)}`),j(`codex-process: CONTEXT_COMPACTION_PATHS ${V} paths=${ID(mD(Z))}`),Y)j(`codex-process: CONTEXT_COMPACTION_ITEM ${V} item=${WZ(Y)}`);j(`codex-process: CONTEXT_COMPACTION_PAYLOAD ${V} payload=${WZ(Z)}`)}function w9($){if(typeof $!=="string")return null;return hD.has($)?$:null}function pD($,Z){if(Z==="item/started")return"start";if(Z==="item/completed"||Z==="rawResponseItem/completed")return"end";if($==="compacted")return"start";if($==="context_compacted"||Az.has(Z))return"end";return"event"}function BZ($,Z){return Nz($,Z0(Z)??{})}function jZ($){let Z=Z0($);if(!Z)return null;let J=A0(Z.method)??A0(Z.type)??"raw_message";return Nz(J,Z)}function Nz($,Z){let J=Z0(Z.payload),Q=[Z,Z0(Z.event),J,Z0(Z.item),Z0(Z.responseItem),Z0(Z.rawItem)].filter((H)=>H!=null),Y=null;for(let H of Q)if(Y=w9(H.type),Y)break;if(!Az.has($)&&!Y)return null;let V=Z0(Z.item)??Z0(Z.responseItem)??Z0(Z.rawItem),X=Y==="compacted"&&J?J:V&&w9(V.type)?V:Z,z=Z0(X.item)??Z0(X.responseItem)??Z0(X.rawItem)??V??{};return{...X,threadId:A0(X.threadId)??A0(X.thread_id)??A0(Z.threadId)??A0(Z.thread_id),turnId:A0(X.turnId)??A0(X.turn_id)??A0(Z.turnId)??A0(Z.turn_id),itemId:A0(X.itemId)??A0(X.item_id)??A0(z.id)??A0(z.itemId)??A0(z.item_id),timestamp:A0(Z.timestamp)??A0(X.timestamp),recordType:A0(Z.type),phase:pD(Y,$),sourceMethod:$,sourceType:Y??$}}var Az,hD,zZ=200000,HZ=50000,GZ=400;var _Z=R(()=>{I();Az=new Set(["thread/compacted","context/compacted","context_compacted","contextCompacted"]),hD=new Set(["compacted","compaction","compaction_trigger","context_compacted","context_compaction","contextCompaction","ContextCompaction"])});function v9($){return $!=null&&typeof $==="object"?$:null}function K1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Rz($){return Object.values($).some((Z)=>typeof Z==="number"&&Number.isFinite(Z))}function h3($,Z){return $?K1($[Z]):void 0}function U4($){let Z=v9($);if(!Z)return null;let J=v9(Z.inputTokensDetails)??v9(Z.input_tokens_details),Q=v9(Z.outputTokensDetails)??v9(Z.output_tokens_details),Y={total_tokens:K1(Z.totalTokens??Z.total_tokens),input_tokens:K1(Z.inputTokens??Z.input_tokens),output_tokens:K1(Z.outputTokens??Z.output_tokens),reasoning_output_tokens:K1(Z.reasoningOutputTokens??Z.reasoning_output_tokens??h3(Q,"reasoningTokens")??h3(Q,"reasoning_tokens")),cache_creation_input_tokens:K1(Z.cacheCreationInputTokens??Z.cache_creation_input_tokens),cache_read_input_tokens:K1(Z.cachedInputTokens??Z.cached_input_tokens??Z.cacheReadInputTokens??Z.cache_read_input_tokens??h3(J,"cachedTokens")??h3(J,"cached_tokens"))};return Rz(Y)?Y:null}function PZ($,Z){let J=(Y)=>{let V=K1($?.[Y]),X=K1(Z?.[Y]);if(V===void 0&&X===void 0)return;return Math.max(0,(V??0)-(X??0))},Q={total_tokens:J("total_tokens"),input_tokens:J("input_tokens"),output_tokens:J("output_tokens"),reasoning_output_tokens:J("reasoning_output_tokens"),cache_creation_input_tokens:J("cache_creation_input_tokens"),cache_read_input_tokens:J("cache_read_input_tokens")};return Rz(Q)?Q:null}function LZ($){if(!$)return null;if(typeof $.input_tokens==="number"||typeof $.cache_creation_input_tokens==="number"||typeof $.output_tokens==="number")return($.input_tokens??0)+($.cache_creation_input_tokens??0)+($.output_tokens??0);return typeof $.total_tokens==="number"&&Number.isFinite($.total_tokens)?$.total_tokens:null}function Tz($){let Z=$.trim();if(Z.length<2)return Z;let J=I3[Z[0]];if(!J||!Z.endsWith(J))return Z;let Q=Z.slice(1,-1);if(Z[0]==="'")return Q.replace(/''/g,"'");if(Z[0]==='"')return Q.replace(/\\"/g,'"');return Q}function B1($){let Z=uD(String($??"")),J=Z.split(`
69
+ `),O}let Z=SF($),J=Z.feishu?.app_id,Q=Z.feishu?.app_secret;if(!J||!Q)throw Error(`lodestar: ${c0} is missing [feishu].app_id / [feishu].app_secret`);let Y=Pz(Z.runtime?.projects_root??Lz()),V={codex:!1,claude:!1,dsh:!1},X=Z["runtime.agent_auto_update"],z=Z.runtime?.agent_auto_update;if(z!==void 0){if(X)throw Error("lodestar: legacy [runtime].agent_auto_update cannot be combined with [runtime.agent_auto_update]");if(z!=="true"&&z!=="false")throw Error(`lodestar: [runtime].agent_auto_update must be true or false, got "${z}"`);for(let O of["codex","claude","dsh"])V[O]=z==="true";process.stderr.write(`lodestar: 旧 agent_auto_update 总开关已按原值映射为三个开关;请改用 [runtime.agent_auto_update] 的 codex、claude、dsh 配置。
70
+ `)}else if(X)for(let[O,N]of Object.entries(X)){if(O!=="codex"&&O!=="claude"&&O!=="dsh")throw Error(`lodestar: unknown [runtime.agent_auto_update] Agent "${O}"`);if(N!=="true"&&N!=="false")throw Error(`lodestar: [runtime.agent_auto_update].${O} must be true or false, got "${N}"`);V[O]=N==="true"}let H=(Z.runtime?.live_elapsed??"bucket").trim().toLowerCase();if(H!=="bucket"&&H!=="second")throw Error(`lodestar: [runtime].live_elapsed must be "bucket" or "second", got "${Z.runtime?.live_elapsed}"`);let G=H,W=Z.notify?.bind??"127.0.0.1",K=Z.notify?.port??"9876";if(!/^\d+$/.test(K.trim()))throw Error(`lodestar: [notify].port must be an integer, got "${K}"`);let B=Number.parseInt(K,10);if(!Number.isFinite(B)||B<=0||B>65535)throw Error(`lodestar: [notify].port must be 1..65535, got "${K}"`);let _=(O)=>{let N=Z[O]??{},S={};for(let[T,f]of Object.entries(N))if(typeof f==="string"&&f.length>0)S[T]=f;return S},P=()=>{let O={};for(let[N,S]of Object.entries(Z)){if(!N.startsWith("claude.models."))continue;let f=N.slice(14).trim();if(!f)continue;let m={};for(let[b,p]of Object.entries(S)){if(typeof p!=="string"||p.length===0)continue;if(b.trim()==="model")m.model=p}O[f]=m}return O},L=()=>{let O={},N="projects.";for(let[S,T]of Object.entries(Z)){if(!S.startsWith("projects."))continue;let f=S.slice(9).trim();if(!f)continue;let m={};for(let[b,p]of Object.entries(T)){if(typeof p!=="string"||p.length===0)continue;switch(b.trim()){case"cwd":m.cwd=p;break;case"setting_sources":m.settingSources=p;break;case"strict_mcp":m.strictMcp=p==="true";break;case"tools":m.tools=p;break;case"load_project_mcp":m.loadProjectMcp=p==="true";break}}O[f]=m}return O},q=()=>{let O={},N="token_source.";for(let[S,T]of Object.entries(Z)){if(!S.startsWith("token_source."))continue;let f=S.slice(13).trim();if(!f)continue;let m={};for(let[b,p]of Object.entries(T)){if(typeof p!=="string")continue;let c=b.trim();if(c==="enabled"){if(p!=="true"&&p!=="false")throw Error(`[${S}].enabled 必须为 true 或 false`);m.enabled=p==="true"}else if(c==="default")m.default=p==="true";else if(c==="agent"||c==="display"||c==="auth"||c==="base_url"||c==="auth_token"||c==="api_key"||c==="management_token"||c==="management_user_id"||c==="management_url"||c==="billing_source"||c==="bin"||c==="model"||c==="effort"||c==="models"||c==="hidden_models"||c==="shown_models"||c==="custom_models"||c==="slots"||c==="usage")m[c]=p}O[f]=m}return O},F=_("codex.env"),M=_("claude.env"),U=Z.claude?.bin?Pz(Z.claude.bin):void 0;if(Z.claude?.safe_mode!==void 0)throw Error("lodestar: safe_mode must use the [claude.safe_mode] table");let A={};for(let[O,N]of Object.entries(Z["claude.safe_mode"]??{})){let S=N.trim(),T=S===""?[]:S.split(",").map((f)=>f.trim());if(T.some((f)=>!f||/[\s,"']/.test(f))||T.some((f)=>f.includes("*"))&&(T.length!==1||T[0]!=="*"))throw Error(`lodestar: [claude.safe_mode].${O} must be comma-separated exact model IDs, "*", or ""`);A[O]=T}return{feishu:{app_id:J,app_secret:Q},runtime:{projects_root:Y,live_elapsed:G,agent_auto_update:V},notify:{bind:W,port:B},codex:{env:F},claude:{bin:U,env:M,models:P(),safe_mode:A,...Z.claude?.translation_validation_rules!==void 0?{translation_validation_rules:Z.claude.translation_validation_rules}:{}},projects:L(),token_sources:q()}}function qz(){g.token_sources=k9().token_sources}var g;var k0=R(()=>{H0();g=k9()});import{spawn as xF}from"cross-spawn";import{mkdtemp as bF,rm as Fz,writeFile as kF}from"node:fs/promises";import{tmpdir as wF}from"node:os";import{join as Dz}from"node:path";function yF($){if(!$||typeof $!=="object"||Array.isArray($))throw Error("Codex raw model catalog is not an object");let Z=structuredClone($);if(!Array.isArray(Z.models)||!Z.models.length)throw Error("Codex raw model catalog has no models");for(let J of Z.models){if(!J||typeof J!=="object"||typeof J.slug!=="string"||!J.slug)throw Error("Codex raw model catalog contains an invalid model");if(!Array.isArray(J.experimental_supported_tools)||J.experimental_supported_tools.some((Q)=>typeof Q!=="string"))throw Error(`Codex raw model ${J.slug} has invalid experimental_supported_tools`);J.experimental_supported_tools=J.experimental_supported_tools.filter((Q)=>!vF.has(Q))}return Z}function fF($){let Z=[],J=$.trim().split(`
71
+ `);for(let Q of J){let Y=/^([a-z0-9_.]+)\s+(.+?)\s+(true|false)\s*$/.exec(Q);if(!Y)throw Error("Codex feature catalog returned an invalid row");if(Y[2]!=="removed"&&["send_message_to_user_async","send_async_message"].includes(Y[1]))Z.push(Y[1])}return Z}async function Mz($,Z){$.signal.throwIfAborted();let J=`Codex ${Z.join(" ")}`,Q=xF($.binary,[...Z,...$.configArgs],{cwd:$.workDir,env:$.env,shell:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y=[],V=[],X=0,z,H,G=(L)=>{if(z)return;if(z??=L,Q.pid)Q.kill("SIGTERM"),H=setTimeout(()=>{Q.kill("SIGKILL")},3000)},W=()=>G($.signal.reason instanceof Error?$.signal.reason:Error("Codex model catalog preparation cancelled"));$.signal.addEventListener("abort",W,{once:!0});let K=setTimeout(()=>G(Error(`${J} exceeded 30 seconds`)),30000),B=new Promise((L)=>{Q.on("error",(q)=>{z??=q}),Q.stdout.on("data",(q)=>{if(X+=q.length,X>33554432)G(Error("Codex raw model catalog exceeds 32 MiB"));else Y.push(q)}),Q.stderr.on("data",(q)=>{V.push(q)}),Q.once("close",(q)=>L(q))});if($.signal.aborted)W();let _;try{_=await B}finally{if(clearTimeout(K),H)clearTimeout(H);$.signal.removeEventListener("abort",W)}let P=Buffer.concat(V).toString("utf8").trim();if(P)j(`${J}[stderr]: ${P}`);if(z)throw z;if(_!==0)throw Error(`${J} failed (exit ${_}): ${P||"no diagnostic"}`);if(/ERROR[^\n]*(?:models_manager|model_catalog)|(?:models_manager|model_catalog)[^\n]*(?:failed|error)/i.test(P))throw Error(`Codex model catalog export reported an upstream failure: ${P}`);return $.signal.throwIfAborted(),Buffer.concat(Y).toString("utf8")}async function Uz($){let Z=await Promise.allSettled([Mz($,["debug","models"]),Mz($,["features","list"])]),J=Z.filter((G)=>G.status==="rejected");if(J.length)throw AggregateError(J.map((G)=>G.reason),J.map((G)=>String(G.reason)).join("; "));let[Q,Y]=Z.map((G)=>G.value),V=yF(JSON.parse(Q)),X=fF(Y),z=await bF(Dz(wF(),"lodestar-codex-input-policy-")),H=Dz(z,"models.json");try{return await kF(H,JSON.stringify(V),{mode:384}),$.signal.throwIfAborted(),{path:H,disabledFeatures:X,dispose:()=>Fz(z,{recursive:!0,force:!0})}}catch(G){throw await Fz(z,{recursive:!0,force:!0}),G}}var vF;var Oz=R(()=>{I();vF=new Set(["request_user_input","request_user_input_async","send_user_message_async","send_message_to_user_async"])});function A0($){return typeof $==="string"&&$?$:void 0}function Z0($){return $!=null&&typeof $==="object"?$:null}function W1($){if($==null||$==="")return"-";return String($).replace(/\s+/g," ").slice(0,300)}function f3($){if(!$)return"[]";let Z=Object.keys($),J=Z.slice(0,80),Q=Z.length>J.length?`,...+${Z.length-J.length}`:"";return`[${J.join(",")}${Q}]`}function IF($){let Z=$.slice(0,GZ),J=$.length>Z.length?`,...+${$.length-Z.length}`:"";return`[${Z.join(",")}${J}]`}function gF($){let Z=Z0($);if(!Z)return null;let J=Z0(Z.event),Q=Z0(Z.payload);return Z0(Z.item)??Z0(Z.responseItem)??Z0(Z.rawItem)??Z0(J?.item)??Z0(J?.responseItem)??Z0(J?.rawItem)??Z0(Q?.item)??Z0(Q?.responseItem)??Z0(Q?.rawItem)??(w9(Z.type)?Z:null)??(J&&w9(J.type)?J:null)??(Q&&w9(Q.type)?Q:null)}function mF($){let Z=[],J=new WeakSet,Q=(Y,V,X)=>{if(Z.length>=GZ||X>6)return;if(Array.isArray(Y)){if(V)Z.push(`${V}[]`);if(Y.length>0)Q(Y[0],V?`${V}[]`:"[]",X+1);return}if(Y==null||typeof Y!=="object")return;if(J.has(Y))return;J.add(Y);for(let z of Object.keys(Y)){if(Z.length>=GZ)return;let H=V?`${V}.${z}`:z;Z.push(H),Q(Y[z],H,X+1)}};return Q($,"",0),Z}function WZ($){let Z=new WeakSet,J;try{J=JSON.stringify($,(Q,Y)=>{if(typeof Y==="bigint")return`${Y.toString()}n`;if(typeof Y==="string"&&Y.length>HZ)return`${Y.slice(0,HZ)}...<truncated ${Y.length-HZ} chars>`;if(Y!=null&&typeof Y==="object"){if(Z.has(Y))return"[Circular]";Z.add(Y)}return Y})??String($)}catch(Q){J=`<unserializable: ${Q}>`}if(J.length>zZ)return`${J.slice(0,zZ)}...<truncated ${J.length-zZ} chars>`;return J}function V$($,Z){let J=Z0(Z),Q=J?Z0(J.params):null,Y=J?Z0(J.item)??Z0(Q?.item):null,V=J?A0(J.method)??"-":"-";j([`codex-process: APP_SERVER_UNHANDLED_${$}`,`method=${W1(V)}`,`rootKeys=${f3(J)}`,`itemKeys=${f3(Y)}`,`payload=${WZ(Z)}`].join(" "))}function KZ($,Z,J){let Q=Z0(Z),Y=gF(Z),V=[`phase=${W1(J.phase??"event")}`,`method=${W1($)}`,`sourceMethod=${W1(J.sourceMethod)}`,`sourceType=${W1(J.sourceType)}`,`sessionId=${W1(J.sessionId)}`,`threadId=${W1(J.threadId)}`,`turnId=${W1(J.turnId)}`,`itemId=${W1(J.itemId)}`].join(" ");if(j(`codex-process: CONTEXT_COMPACTION_EVENT ${V} rootKeys=${f3(Q)} itemKeys=${f3(Y)}`),j(`codex-process: CONTEXT_COMPACTION_PATHS ${V} paths=${IF(mF(Z))}`),Y)j(`codex-process: CONTEXT_COMPACTION_ITEM ${V} item=${WZ(Y)}`);j(`codex-process: CONTEXT_COMPACTION_PAYLOAD ${V} payload=${WZ(Z)}`)}function w9($){if(typeof $!=="string")return null;return hF.has($)?$:null}function pF($,Z){if(Z==="item/started")return"start";if(Z==="item/completed"||Z==="rawResponseItem/completed")return"end";if($==="compacted")return"start";if($==="context_compacted"||Az.has(Z))return"end";return"event"}function BZ($,Z){return Nz($,Z0(Z)??{})}function jZ($){let Z=Z0($);if(!Z)return null;let J=A0(Z.method)??A0(Z.type)??"raw_message";return Nz(J,Z)}function Nz($,Z){let J=Z0(Z.payload),Q=[Z,Z0(Z.event),J,Z0(Z.item),Z0(Z.responseItem),Z0(Z.rawItem)].filter((H)=>H!=null),Y=null;for(let H of Q)if(Y=w9(H.type),Y)break;if(!Az.has($)&&!Y)return null;let V=Z0(Z.item)??Z0(Z.responseItem)??Z0(Z.rawItem),X=Y==="compacted"&&J?J:V&&w9(V.type)?V:Z,z=Z0(X.item)??Z0(X.responseItem)??Z0(X.rawItem)??V??{};return{...X,threadId:A0(X.threadId)??A0(X.thread_id)??A0(Z.threadId)??A0(Z.thread_id),turnId:A0(X.turnId)??A0(X.turn_id)??A0(Z.turnId)??A0(Z.turn_id),itemId:A0(X.itemId)??A0(X.item_id)??A0(z.id)??A0(z.itemId)??A0(z.item_id),timestamp:A0(Z.timestamp)??A0(X.timestamp),recordType:A0(Z.type),phase:pF(Y,$),sourceMethod:$,sourceType:Y??$}}var Az,hF,zZ=200000,HZ=50000,GZ=400;var _Z=R(()=>{I();Az=new Set(["thread/compacted","context/compacted","context_compacted","contextCompacted"]),hF=new Set(["compacted","compaction","compaction_trigger","context_compacted","context_compaction","contextCompaction","ContextCompaction"])});function v9($){return $!=null&&typeof $==="object"?$:null}function K1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Rz($){return Object.values($).some((Z)=>typeof Z==="number"&&Number.isFinite(Z))}function h3($,Z){return $?K1($[Z]):void 0}function U4($){let Z=v9($);if(!Z)return null;let J=v9(Z.inputTokensDetails)??v9(Z.input_tokens_details),Q=v9(Z.outputTokensDetails)??v9(Z.output_tokens_details),Y={total_tokens:K1(Z.totalTokens??Z.total_tokens),input_tokens:K1(Z.inputTokens??Z.input_tokens),output_tokens:K1(Z.outputTokens??Z.output_tokens),reasoning_output_tokens:K1(Z.reasoningOutputTokens??Z.reasoning_output_tokens??h3(Q,"reasoningTokens")??h3(Q,"reasoning_tokens")),cache_creation_input_tokens:K1(Z.cacheCreationInputTokens??Z.cache_creation_input_tokens),cache_read_input_tokens:K1(Z.cachedInputTokens??Z.cached_input_tokens??Z.cacheReadInputTokens??Z.cache_read_input_tokens??h3(J,"cachedTokens")??h3(J,"cached_tokens"))};return Rz(Y)?Y:null}function PZ($,Z){let J=(Y)=>{let V=K1($?.[Y]),X=K1(Z?.[Y]);if(V===void 0&&X===void 0)return;return Math.max(0,(V??0)-(X??0))},Q={total_tokens:J("total_tokens"),input_tokens:J("input_tokens"),output_tokens:J("output_tokens"),reasoning_output_tokens:J("reasoning_output_tokens"),cache_creation_input_tokens:J("cache_creation_input_tokens"),cache_read_input_tokens:J("cache_read_input_tokens")};return Rz(Q)?Q:null}function LZ($){if(!$)return null;if(typeof $.input_tokens==="number"||typeof $.cache_creation_input_tokens==="number"||typeof $.output_tokens==="number")return($.input_tokens??0)+($.cache_creation_input_tokens??0)+($.output_tokens??0);return typeof $.total_tokens==="number"&&Number.isFinite($.total_tokens)?$.total_tokens:null}function Tz($){let Z=$.trim();if(Z.length<2)return Z;let J=I3[Z[0]];if(!J||!Z.endsWith(J))return Z;let Q=Z.slice(1,-1);if(Z[0]==="'")return Q.replace(/''/g,"'");if(Z[0]==='"')return Q.replace(/\\"/g,'"');return Q}function B1($){let Z=uF(String($??"")),J=Z.split(`
72
72
  `,1)[0]?.trim()??"",Y=(J.startsWith("#")&&!J.startsWith("#!")?J.replace(/^#\s*/,"").trim():"").replace(/^(?:desc|dec|description|说明|目的|用途)\s*[::]\s*/i,"").trim(),V=Y?Z.split(`
73
73
  `).slice(1).join(`
74
- `).trimStart():Z;return{description:Y,command:V||Z}}function O4($,Z=60){let{description:J,command:Q}=B1($);if(J)return J;return cD(Q).replace(/\s+/g," ").trim().slice(0,Z)}function cD($){let Z=$.split(/\r?\n/).map((J)=>J.trim()).filter(Boolean);return Z.find((J)=>!J.startsWith("#")&&!/^set\s+-/.test(J)&&!/^cd\s+/.test(J)&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(J)&&!/^cat\s+<<['"]?\w+['"]?/.test(J))??Z[Z.length-1]??""}function uD($){let Z=$.replace(/\r\n/g,`
75
- `).trim(),J=Z.match(/^(?:\/usr\/bin\/env\s+)?(?:\/[\w./-]+\/)?(?:ba|z|fi)?sh\s+-[A-Za-z]*c[A-Za-z]*\s+([\s\S]+)$/);if(J){let Y=dD(J[1]);return qZ(Y||Z)}let Q=lD(Z);if(Q)return Q;return qZ(Z)}function lD($){let Z=$.match(/^("[^"]*"|'[^']*'|“[^”]*”|\S+)\s+([\s\S]*)$/);if(!Z)return null;let J=Tz(Z[1]).replace(/\.exe$/i,"");if(!/(?:^|[\\/])(?:powershell|pwsh)$/i.test(J))return null;let Q=Z[2];for(;;){let Y=Q.match(/^(-[A-Za-z][\w-]*)\s+([\s\S]*)$/);if(!Y)break;let V=Y[1].toLowerCase();if(V==="-command"||V==="-c")return qZ(Tz(Y[2]));if(Q=Y[2],V==="-executionpolicy"||V==="-inputformat"||V==="-outputformat")Q=Q.replace(/^(?:"[^"]*"|'[^']*'|\S+)\s+/,"")}return null}function dD($){let Z=$.trim();if(Z.length<2)return Z;let J=I3[Z[0]];if(!J||!Z.endsWith(J))return Z;let Q=Z.slice(1,-1);if(Z[0]==="'")return Q.replace(/'\\''/g,"'");return Q.replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
76
- `)}function qZ($){let Z=$.trim(),J=Z[0];if(!I3[J])return Z;let Q=Z.slice(1);if(!/^#\s*(?:desc|dec|description|说明|目的|用途)\s*[::]/i.test(Q)&&!iD(Q,J))return Z;if(J!=='"')return Q.replace(/'\s*$/,"");return Q.replace(/\s*[”"]\s*$/,"").replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
77
- `).replace(/\s*"\s*'\$\(([^)]*)\)'/g,(X,z)=>` $(${z})`)}function iD($,Z){let J=I3[Z];for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Z==='"'&&Y==="\\"&&Q+1<$.length){Q++;continue}if(Y===J)return/^[\s]*$/.test($.slice(Q+1))}return!1}var I3;var A4=R(()=>{I3={'"':'"',"'":"'","“":"”"}});function Ez($,Z){return $?.then(async(J)=>{return await Z(J),J.ok?"complete":"retry"})??null}function E($){return $ instanceof Error?$.message:String($)}function h0($){return $.length<=16?$:`${$.slice(0,8)}…${$.slice(-4)}`}import{isAbsolute as Sz}from"node:path";function nD($){return $.kind==="fresh"?null:$.source.provider}function E0($,Z,J){let Q=nD($);if(Q&&Q!==Z)throw Error(`conversation launch provider mismatch: source=${Q} target=${Z}`);if($.kind!=="fresh"&&!$.source.sessionId.trim())throw Error("conversation launch source session id is empty");if($.kind!=="fresh"&&$.source.cwd!==null&&(typeof $.source.cwd!=="string"||!Sz($.source.cwd)))throw Error(`conversation launch source cwd is not absolute: ${String($.source.cwd)}`);if($.kind!=="fresh"&&J!==void 0){if(!Sz(J))throw Error(`expected conversation cwd is not absolute: ${J}`);if($.source.cwd===null)throw Error("conversation launch source cwd is missing");if($.source.cwd!==J)throw Error(`conversation launch cwd mismatch: source=${$.source.cwd} target=${J}`)}if($.kind!=="fork"||!$.through)return;if($.through.provider!==Z||$.through.source.provider!==Z)throw Error(`conversation checkpoint provider mismatch: checkpoint=${$.through.provider} target=${Z}`);if($.through.source.sessionId!==$.source.sessionId)throw Error("conversation checkpoint source does not match fork source");if($.through.source.cwd!==$.source.cwd)throw Error("conversation checkpoint cwd does not match fork source");if(!$.through.id.trim())throw Error("conversation checkpoint id is empty");if(Z==="dsh"&&(!/^\d+$/.test($.through.id)||!Number.isSafeInteger(Number($.through.id))))throw Error("DSH checkpoint must be a non-negative event sequence")}var K2=()=>{};import{existsSync as aD,readFileSync as oD}from"node:fs";function Cz($,Z){return`${$}:${Z}`}function sD(){if(!aD(B3))return;try{let $=JSON.parse(oD(B3,"utf8"));if($?.version!==1||!Array.isArray($.ids)||$.ids.some((Z)=>typeof Z!=="string"||!Z))throw Error("invalid delegated-agent session registry");f9=new Set($.ids)}catch($){DZ=$ instanceof Error?$:Error(String($))}}function xz(){if(DZ)throw Error(`delegated-agent session registry is unavailable: ${DZ.message}`)}function bz($,Z){xz();let J=Z.trim();if(!J)throw Error("delegated-agent session id is empty");let Q=Cz($,J);if(f9.has(Q))return;let Y=new Set(f9);Y.add(Q),r(B3,{version:1,ids:[...Y].sort()}),f9=Y}function N4($,Z){return xz(),f9.has(Cz($,Z))}var f9,DZ=null;var y9=R(()=>{H0();b0();f9=new Set;sD()});function g3($){if(!$||typeof $!=="object"||Array.isArray($))return null;let Z=$;if(typeof Z.hasCredits!=="boolean"||typeof Z.unlimited!=="boolean")return null;let J=null;if(Z.balance!=null){if(typeof Z.balance!=="number"&&!(typeof Z.balance==="string"&&/^\d+(?:\.\d+)?$/.test(Z.balance.trim())))return null;if(J=Number(Z.balance),!Number.isFinite(J)||J<0||J>Number.MAX_SAFE_INTEGER)return null}if(!Z.unlimited&&J!==null&&Z.hasCredits!==J>0)return null;return{hasCredits:Z.hasCredits,unlimited:Z.unlimited,balance:J}}function B2($){return $==null?"unknown":$.hasCredits||$.unlimited?"available":"empty"}function kz($,Z){if(!$||!Z||B2(Z)!=="available")return!1;return B2($)==="empty"||!$.unlimited&&Z.unlimited||!$.unlimited&&$.balance!==null&&Z.balance!==null&&Z.balance>$.balance}function eD($){switch($){case"plus":return 1;case"prolite":return 5;case"pro":return 20;default:return null}}function j2($,Z){let J=$.buckets?.find((Y)=>Y.limitName?.toLowerCase()===Z.toLowerCase()||Y.normalModelSlug===Z)??$,Q=!("limitId"in J)||J.limitId===$.defaultLimitId?$.ordinaryUsageAllowed:void 0;return{...J,ordinaryUsageAllowed:Q}}function MZ($){if($.spendControlReached===!0)return{state:"exhausted",reason:"已达到上游消费限制"};if($.rateLimitReachedType&&$.rateLimitReachedType!=="rate_limit_reached")return{state:"exhausted",reason:`上游额度限制:${$.rateLimitReachedType}`};let Z=[$.fiveHour,$.weekly].filter((V)=>V!==null),J=Z.some((V)=>V.percent!==null&&V.percent>=100),Q=J||$.ordinaryUsageAllowed===!1||$.rateLimitReachedType==="rate_limit_reached",Y=B2($.credits);if(Q&&Y==="empty")return{state:"exhausted",reason:J?"额度耗尽":"套餐内额度暂不可用,且无可用积分"};if(Z.some((V)=>V.percent===null||!Number.isFinite(V.percent)||V.percent<0||V.percent>100))return{state:"miss",reason:"额度百分比 MISS"};if(Q)return Y==="available"?{state:"credits"}:{state:"miss",reason:`${J?"订阅额度已用完":"套餐内额度暂不可用"},积分 MISS`};return{state:"subscription"}}function _2($,Z){if($.state!=="ok")throw Error("额度计量桶 MISS");let J=j2($,Z);return"limitId"in J?J.limitId:$.defaultLimitId??"codex"}function vz($,Z){let J=j2($,Z).weekly,Q=$.readStartedAt??$.fetchedAt,Y=J?.resetsAt?.getTime();return J?.percent===0&&J.durationMins===10080&&Number.isFinite(Q)&&Number.isFinite($.fetchedAt)&&Q<=$.fetchedAt&&Y!=null&&Y>=Math.floor(Q/1000)*1000+FZ&&Y<=Math.floor($.fetchedAt/1000)*1000+FZ}function fz($,Z,J){let Q=j2($,Z).weekly?.resetsAt?.getTime();return Q!=null&&Q-FZ<=J}function m3($,Z){let J=Number($.funding==="credits")-Number(Z.funding==="credits");if(J)return J;if($.funding==="credits"&&Z.funding==="credits"){let Y=$.credits,V=Z.credits;return Number(V.unlimited)-Number(Y.unlimited)||Number(Y.balance===null)-Number(V.balance===null)||(Y.balance!==null&&V.balance!==null?V.balance-Y.balance:0)||$.account.id.localeCompare(Z.account.id)}let Q=(Y)=>Y.priority==="expiring"?1:0;return Q(Z)-Q($)||($.priority==="expiring"?$.hours-Z.hours:Z.score-$.score)||(Z.availableNow??0)-($.availableNow??0)||$.account.id.localeCompare(Z.account.id)}function h9($,Z,J=Date.now(),Q){let Y={state:"miss",score:null,shares:null,remaining:null,hours:null};if($.state!=="ok")return{...Y,reason:$.state==="network"?$.reason??"额度读取失败":$.state};let V=eD($.subscriptionType);if(V===null)return{...Y,reason:`未知周额度套餐:${$.subscriptionType??"MISS"}`};Y.shares=V;let X=j2($,Z),z=MZ(X);if(z.state==="miss")return{...Y,reason:z.reason};if(z.state==="exhausted"){let q=[X.fiveHour,X.weekly].filter((M)=>M!==null&&M.percent!==null&&M.percent>=100),D=q.map((M)=>M.resetsAt?.getTime()).filter((M)=>M!=null&&Number.isFinite(M)&&M>J);return{...Y,state:"exhausted",reason:z.reason,...D.length===q.length&&D.length?{retryAt:Math.max(...D)}:{}}}let H=B2(X.credits);if(Q==="ultra"&&$.subscriptionType==="plus"&&X.fiveHour!==null&&H!=="available")return H==="unknown"?{...Y,reason:"Ultra 自动选择有短窗的 Plus,积分 MISS"}:{...Y,state:"excluded",reason:"Ultra 自动选择有短窗的 Plus 需要可用积分"};if(z.state==="credits")return{...Y,state:"ready",funding:"credits",credits:X.credits};let G=X.weekly;if(!G||G.percent===null)return{...Y,reason:"周额度 MISS"};if(G.durationMins!=null&&G.durationMins!==10080)return{...Y,reason:`周额度窗口时长不匹配:${G.durationMins} 分钟(需要 10080 分钟)`};let W=G.resetsAt?.getTime();if(W==null||!Number.isFinite(W)||W<=J)return{...Y,reason:"周重置时间 MISS 或已过期"};let K=V*(100-G.percent)/100,B=(W-J)/3600000,_=B-rD,P=_>0?K/_:null;if(Q==="ultra"&&$.subscriptionType!=="plus"&&K<wz&&H!=="available"){if(H==="unknown")return{...Y,remaining:K,hours:B,weeklyScore:P,reason:"Ultra 周余量不足,积分 MISS"};return{...Y,state:"waiting",remaining:K,hours:B,weeklyScore:P,reason:`Ultra 至少需要 ${wz} 份周余量`,retryAt:W}}let L=_<=0?"expiring":void 0;if($.subscriptionType==="plus"&&X.fiveHour!==null){let q=X.fiveHour,D=tD*(100-q.percent)/100,M=((q.resetsAt?.getTime()??NaN)-J)/3600000;if(!Number.isFinite(M)||M<=0)return{...Y,reason:"5h 重置时间 MISS 或已过期"};return{state:"ready",shares:V,remaining:K,hours:B,priority:L,weeklyScore:P,fiveHourRemaining:D,fiveHourHours:M,availableNow:Math.min(K,D),score:P===null?null:Math.min(P,D/M)}}return{state:"ready",shares:V,remaining:K,hours:B,priority:L,weeklyScore:P,availableNow:K,score:P}}function R4($){if(!$||typeof $!=="object")return!1;let Z=$;if(Z.codexErrorInfo==="usageLimitExceeded"||Z.type==="usage_limit_reached"||Z.code==="usage_limit_reached")return!0;return typeof Z.message==="string"&&/^You(?:'|’)ve hit your usage limit\b/i.test(Z.message)}var tD=0.15,wz=0.5,FZ=604800000,rD=5;var T4=()=>{};import{closeSync as $F,existsSync as ZF,mkdirSync as JF,openSync as QF,readdirSync as YF,readSync as VF,statSync as c3,writeFileSync as XF}from"node:fs";import{homedir as UZ}from"node:os";import{delimiter as yz,isAbsolute as hz,join as v1}from"node:path";import{EventEmitter as zF}from"node:events";import{randomUUID as HF}from"node:crypto";import{StringDecoder as Iz}from"node:string_decoder";import{spawn as GF}from"cross-spawn";function I9(){return C9("codex","codex")}function WF(){if(process.platform==="win32")return process.env.PATH??"";return[...new Set([v1(UZ(),".local","npm-global","bin"),v1(UZ(),".local","bin"),v1(UZ(),".bun","bin"),...(process.env.PATH??"").split(yz),"/usr/local/bin","/usr/bin","/bin"].filter(Boolean))].join(yz)}function AZ($,Z=!1){if(!$||typeof $!=="object")return null;let{message:J,codexErrorInfo:Q,additionalDetails:Y}=$;if(typeof J!=="string")return null;if(R4($))return null;let V=null;if(typeof Q==="string")V=Q;else if(Q!=null){if(typeof Q!=="object"||Array.isArray(Q))return null;let K=Object.entries(Q);if(K.length!==1)return null;let[B,_]=K[0];if(V=B,!OZ.has(V)||!_||typeof _!=="object"||Array.isArray(_))return null;let P=_.httpStatusCode;if(P!=null&&(typeof P!=="number"||!pz.has(P)))return null}if(V!==null&&V!=="other"&&V!=="serverOverloaded"&&!OZ.has(V))return null;let X=/^(?:Codex\s+)?Error running remote compact task:\s*/i.test(J),z=J.replace(/^(?:Codex\s+)?Error running remote compact task:\s*/i,"").replace(/^Codex\s+/i,"").trim();for(let K of[z,Y]){if(typeof K!=="string")continue;if(R4({message:K})||/(?:^|:\s*)(?:unauthorized\b|forbidden\b|authentication failed\b|invalid (?:api key|request|argument)\b|(?:usage|rate|session budget) limit exceeded\b|context window exceeded\b)/i.test(K))return null;let B=/(?:^|:\s*)unexpected status (\d{3})\b/i.exec(K);if(B&&!pz.has(Number(B[1])))return null}let H=/(?:^|:\s*)unexpected status (\d{3})\b/i.exec(z);if(/\bselected\s+model\s+is\s+at\s+capacity\b/i.test(z))return"capacity";let G=/^Connection failed:\s*error sending request(?: for url \([^\r\n]+\))?\s*$/i.test(z)||/^(?:request timed out|workspace routing discovery timed out)$/i.test(z)||Z&&/^workspace routing discovery failed$/i.test(z),W=/^stream disconnected before completion\s*:/i.test(z);if(OZ.has(V??"")||V==="serverOverloaded"||G||W||H){if(X)return"compact_connection_failed";if(V==="responseStreamDisconnected"||W)return"stream_disconnected";return"transient_error"}return null}function qF($){if(!/^[a-z][a-z0-9_-]*$/.test($.id)||["openai","ollama","lmstudio"].includes($.id))throw Error("Codex API provider id 无效或属于保留名称");if(!/^[A-Z][A-Z0-9_]*$/.test($.envKey))throw Error("Codex API key 环境变量名无效");let Z=`model_providers.${$.id}`,J={name:$.name,base_url:$.baseUrl,env_key:$.envKey,wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},Q=`{${Object.entries(J).map(([Y,V])=>`${Y}=${JSON.stringify(V)}`).join(",")}}`;return["-c",`model_provider=${JSON.stringify($.id)}`,"-c",`${Z}=${Q}`,"-c","features.apps=false"]}function DF(){return["app-server","--listen","stdio://"]}function FF($,Z){return{cwd:$,stdio:["pipe","pipe","pipe"],shell:!1,env:Z}}function U$($){return typeof $==="string"&&L2.includes($)}function MF($){if(!Array.isArray($))return[];let Z=new Set,J=[];for(let Q of $){let Y=typeof Q==="string"?Q:typeof Q==="object"&&Q?Q.reasoningEffort:null;if(!U$(Y)||Z.has(Y))continue;Z.add(Y);let V=typeof Q==="object"&&Q&&typeof Q.description==="string"?Q.description:"";J.push({reasoningEffort:Y,description:V})}return J}function NZ($,Z){switch($.type){case"commandExecution":return{name:"Bash",input:{command:$.command,cwd:$.cwd,source:$.source}};case"fileChange":return{name:"FileChange",input:{changes:$.changes,status:$.status,cwd:Z}};case"mcpToolCall":return{name:"MCP",input:{server:$.server,tool:$.tool,arguments:$.arguments}};case"dynamicToolCall":return{name:$.namespace?`${$.namespace}.${$.tool}`:$.tool,input:$.arguments};case"webSearch":return{name:"WebSearch",input:{query:$.query,action:$.action}};case"imageGeneration":return{name:"ImageGeneration",input:RZ($)}}return null}function UF($){let Z=$?.revisedPrompt??$?.revised_prompt;return typeof Z==="string"&&Z?Z:void 0}function RZ($){return{status:$.status,revisedPrompt:UF($),...typeof $?.prompt==="string"&&$.prompt?{prompt:$.prompt}:{}}}function cz($){if(!$||!ZF(gz))return null;let Z=null,J=[gz];while(J.length){let Q=J.pop(),Y;try{Y=YF(Q,{withFileTypes:!0})}catch(V){j(`codex-process: cannot scan Codex session dir ${Q}: ${V instanceof Error?V.message:V}`);continue}for(let V of Y){let X=v1(Q,V.name);if(V.isDirectory()){J.push(X);continue}if(!V.isFile())continue;if(!V.name.startsWith("rollout-")||!V.name.endsWith(`${$}.jsonl`))continue;try{let z=c3(X).mtimeMs;if(!Z||z>Z.mtimeMs)Z={path:X,mtimeMs:z}}catch(z){j(`codex-process: cannot stat Codex rollout ${X}: ${z instanceof Error?z.message:z}`)}}}return Z?.path??null}function iz($,Z,J=KF){let Q=$?.savedPath??$?.saved_path;if(typeof Q==="string"&&Q)return Q;let Y=$?.result;if(typeof Y==="string"){let V=OF($,Z,J);if(V)return V;if(Y.length>2048){let X=nz($);return j(`codex-process: image generation inline result could not be decoded id=${X} length=${Y.length}`),`Image generation returned ${Y.length} chars of inline data, but Lodestar could not materialize it as an image file.`}return Y}if(Y&&typeof Y==="object"){let V=Y.savedPath??Y.saved_path??Y.path;if(typeof V==="string"&&V)return V;return JSON.stringify(Y,null,2)}return""}function OF($,Z,J){let Q=$?.result;if(typeof Q!=="string")return null;let Y=AF(Q);if(!Y)return null;let V=uz(Z??"unknown-thread"),X=uz(nz($)),z=v1(J,V),H=v1(z,`${X}.${Y.ext}`);try{return JF(z,{recursive:!0}),XF(H,Y.buffer),H}catch(G){return j(`codex-process: failed to write image generation result ${H}: ${G instanceof Error?G.message:G}`),null}}function nz($){let Z=$?.callId??$?.call_id??$?.id;return typeof Z==="string"&&Z?Z:`image-${Date.now()}`}function uz($){let Z=$.trim().replace(/[^a-zA-Z0-9_.-]/g,"_").replace(/^_+|_+$/g,"");return Z?Z.slice(0,140):"unknown"}function AF($){let Z=$.trim(),J=Z,Q=null,Y=Z.match(/^data:image\/([a-zA-Z0-9.+-]+);base64,(.*)$/s);if(Y)Q=RF(Y[1]),J=Y[2];else{if(Z.length<64)return null;if(!/^[a-zA-Z0-9+/=_\-\s]+$/.test(Z))return null}if(J=J.replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),!J||J.length%4===1)return null;let V=J.padEnd(Math.ceil(J.length/4)*4,"="),X;try{X=Buffer.from(V,"base64")}catch{return null}if(X.length<12)return null;let z=NF(X)??Q;if(!z)return null;return{buffer:X,ext:z}}function NF($){if($[0]===137&&$[1]===80&&$[2]===78&&$[3]===71&&$[4]===13&&$[5]===10&&$[6]===26&&$[7]===10)return"png";if($[0]===255&&$[1]===216&&$[2]===255)return"jpg";let Z=$.subarray(0,6).toString("ascii");if(Z==="GIF87a"||Z==="GIF89a")return"gif";if($.subarray(0,4).toString("ascii")==="RIFF"&&$.subarray(8,12).toString("ascii")==="WEBP")return"webp";return null}function RF($){let Z=$.toLowerCase();if(Z==="jpeg"||Z==="jpg")return"jpg";if(Z==="png")return"png";if(Z==="gif")return"gif";if(Z==="webp")return"webp";return null}function lz($,Z,J){let Q=NZ($,Z);if(!Q)return null;switch($.type){case"commandExecution":return{...Q,output:$.aggregatedOutput??"",isError:$.exitCode!=null&&$.exitCode!==0};case"fileChange":return{...Q,output:JSON.stringify($.changes??[],null,2),isError:$.status==="failed"};case"mcpToolCall":return{...Q,output:$.error?JSON.stringify($.error,null,2):JSON.stringify($.result??null,null,2),isError:!!$.error};case"dynamicToolCall":return{...Q,output:JSON.stringify($.contentItems??[],null,2),isError:$.success===!1};case"webSearch":return{...Q,output:JSON.stringify($.action??{},null,2),isError:!1};case"imageGeneration":return{...Q,output:iz($,J),isError:$.status==="failed"}}return null}function p3($,Z){if(typeof $==="string"&&$){let J=$.split("/").filter(Boolean).pop();if(J)return J}return h0(Z)}function dz($){if(typeof $!=="string"||!$)return;if($.startsWith("gAAAA")&&!/[一-鿿]/.test($))return"(继承主线程历史的密文任务书)";return $}function TF($,Z,J){let Q=(Y)=>typeof Y==="string"?Y:"";switch($){case"Bash":{if(J!=null){let Y=J.replace(/\s+/g," ").trim();return Y?`→ ${Y.slice(0,60)}`:""}return O4(Q(Z?.command))||"(空命令)"}case"FileChange":{let Y=Array.isArray(Z?.changes)?Z.changes.length:0;if(J!=null)return"";return Y>0?`改 ${Y} 个文件`:"文件变更"}case"MCP":return`${Q(Z?.server)}/${Q(Z?.tool)}`.slice(0,60);case"WebSearch":return`"${Q(Z?.query).slice(0,50)}"`;default:{if(J!=null){let Y=J.replace(/\s+/g," ").trim();return Y?`→ ${Y.slice(0,60)}`:""}return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}}function az($){return(Array.isArray($.receiverThreadIds)?$.receiverThreadIds:[]).filter((J)=>typeof J==="string"&&!!J)}function EF($){let Z=az($);return Z.length>0?`派生 ${Z.length} 个子 agent`:"派生子 agent"}function SF($){let Z=$.agentsStates;if(!Z||typeof Z!=="object")return"";let J=[];for(let[Q,Y]of Object.entries(Z)){let V=Y,X=typeof V?.status==="string"?V.status:"unknown";J.push(`${h0(Q)}: ${X}`)}return J.join(`
78
- `)}var gz,KF,BF=30000,jF=600000,_F=5000,PF=60000,mz=10,LF,OZ,pz,L2,g9="xhigh",P2,E4;var j1=R(()=>{k0();I();F4();Oz();_Z();A4();K2();y9();F0();T4();_Z();gz=v1(v.defaultHome,"sessions"),KF=v1(v.defaultHome,"generated_images"),LF={capacity:"上一轮因模型暂时满载而中断。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",stream_disconnected:"上一轮因响应流连接中断而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",compact_connection_failed:"上一轮因远程压缩时连接失败而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",transient_error:"上一轮因临时连接或服务错误而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。"},OZ=new Set(["httpConnectionFailed","responseStreamConnectionFailed","responseStreamDisconnected","responseTooManyFailedAttempts"]),pz=new Set([408,500,502,503,504]);L2=["none","minimal","low","medium","high","xhigh","max","ultra"];P2=class P2 extends Error{method;requestId;serverCode;serverMessage;serverData;constructor($,Z,J,Q,Y){super(`codex app-server ${$} failed (id=${Z}, code=${J??"MISS"}): ${Q}`);this.method=$;this.requestId=Z;this.serverCode=J;this.serverMessage=Q;this.serverData=Y;this.name="CodexRpcResponseError"}};E4=class E4 extends zF{provider="codex";tokenSourceId;launchKind;proc=null;startupPromise=null;inputPolicyAbort=new AbortController;inputPolicyCatalog=null;stdoutBuf="";stderrBuf="";requestCounter=0;pending=new Map;serverRequests=new Map;alive=!0;expectedExit=!1;exitEventEmitted=!1;childExitCode=null;childExitSignal=null;exitPromise;resolveExit;opts;usesCustomDefaultModeInstructions=!1;readyPromise=null;initializePromise=null;conversationResumable=!1;conversationRolloutPath=null;conversationMaterializationVerification=null;conversationMaterializationRetrySource=null;lastConversationMaterializationFailure=null;currentTurnId=null;steeringInputs=new Map;inputConsumptionOpen=!1;turnStartGeneration=0;turnStartOwner=null;turnStartOwnersByTurnId=new Map;finishedTurnIds=new Set;turnRetryTimer=null;turnRetryCount=0;transientRetryCount=0;turnRetryHasStarted=!1;turnRetryEnabled=!0;turnError=null;routingTimeoutTurnId=null;rolloutFilePath=null;rolloutReadOffset=0;rolloutLineRemainder="";rolloutDecoder=new Iz("utf8");emittedImageGenerationIds=new Set;collabAgentNames=new Map;collabAgentSettled=new Set;collabAgentWasActive=new Set;collabAgentSummaries=new Map;sessionId=null;lastAssistantUuid=null;lastCompletedTurnId=null;lastModel=null;lastEffort=null;lastUsage=null;lastTotalUsage=null;lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1};lastContextWindow=null;lastContextTokens=null;turnRetry=null;constructor($){super();this.on("error",()=>{}),this.exitPromise=new Promise((z)=>{this.resolveExit=z}),this.opts=$,this.tokenSourceId=$.tokenSourceId??null,this.launchKind=($.launch??{kind:"fresh"}).kind;let Z=I9(),J=$.apiProvider?qF($.apiProvider):[...$.tokenSourceId==="codex-sub"?["-c",'model_provider="openai"']:[],...v.cliArgs($.codexAccountId??d)],Q={...process.env,NPM_CONFIG_LOGLEVEL:"error",PATH:WF(),...g.codex.env,...$.hostEnv??{}},Y=$.transformEnv?$.transformEnv(Q):Q,V=$.apiProvider?{...Y,CODEX_HOME:v.defaultHome}:v.env($.codexAccountId??d,Y),X=(z)=>{if(this.expectedExit)throw Error("Codex startup cancelled");this.inputPolicyCatalog=z??null,this.spawnNative(Z,[...DF(),...J,...z?["-c",`model_catalog_json=${JSON.stringify(z.path)}`,...z.disabledFeatures.flatMap((H)=>["--disable",H])]:[]],V)};if($.allowUserInput===!1)this.startupPromise=Uz({binary:Z,configArgs:J,env:V,workDir:$.workDir,signal:this.inputPolicyAbort.signal}).then(async(z)=>{if(this.expectedExit)throw await z.dispose(),Error("Codex startup cancelled");X(z)}).catch((z)=>{throw this.alive=!1,this.emit("error",z instanceof Error?z:Error(String(z))),this.emitProcessExit(this.expectedExit?null:1,this.expectedExit?"SIGTERM":null),z}),this.startupPromise.catch(()=>{});else X();if(!$.apiProvider)w1(this,$.codexAccountId??d)}spawnNative($,Z,J){j(`codex-process: spawn ${$} app-server (cwd=${this.opts.workDir})`),this.proc=GF($,Z,FF(this.opts.workDir,J)),this.proc.stdout.on("data",(Q)=>this.onStdout(Q)),this.proc.stderr.on("data",(Q)=>this.onStderr(Q)),this.proc.stdin.on("error",(Q)=>this.handleStdinError(Q)),this.proc.on("exit",(Q,Y)=>this.handleChildExit(Q,Y)),this.proc.on("close",(Q,Y)=>this.handleChildClose(Q,Y)),this.proc.on("error",(Q)=>this.handleChildProcessError(Q))}handleStdinError($){let Z=$ instanceof Error?$:Error(String($));if(j(`codex-process: stdin failed: ${Z.message}`),!this.expectedExit)this.emit("error",Z)}handleChildExit($,Z){if(!this.alive){j(`codex-process: duplicate exit ignored code=${$} signal=${Z}`);return}this.alive=!1,this.cancelTurnRetry(),this.childExitCode=$,this.childExitSignal=Z,j(`codex-process: OS exit code=${$} signal=${Z}; awaiting stdio close`)}handleChildClose($,Z){this.alive=!1,this.cancelTurnRetry(),this.flushStdoutTail(),this.flushStderrTail(),this.rejectPendingRequests((V,X)=>Error(`codex app-server closed before ${X.method} response (id=${V})`)),this.serverRequests.clear();let J=$??this.childExitCode,Q=Z??this.childExitSignal,Y=this.conversationMaterializationBarrier();if(Y){Y.then(()=>this.emitProcessExit(J,Q),()=>this.emitProcessExit(J,Q));return}this.emitProcessExit(J,Q)}handleChildProcessError($){j(`codex-process: child process error: ${$}`),this.rejectPendingRequests((Q,Y)=>Error(`codex app-server process failed before ${Y.method} response (id=${Q}): ${$.message}`,{cause:$}));let Z=typeof this.proc?.pid!=="number",J=!1;if(Z&&this.alive)this.alive=!1,this.cancelTurnRetry(),this.serverRequests.clear(),J=!0;if(this.emit("error",$),J)j(`codex-process: spawn failed before pid assignment expected=${this.expectedExit}`),this.emitProcessExit(null,null)}emitProcessExit($,Z){if(this.exitEventEmitted)return;this.exitEventEmitted=!0,this.resolveExit(),j(`codex-process: exited code=${$} signal=${Z} expected=${this.expectedExit}`),this.emit("exit",{code:$,signal:Z,expected:this.expectedExit})}onStdout($){this.stdoutBuf+=$.toString();let Z;while((Z=this.stdoutBuf.indexOf(`
74
+ `).trimStart():Z;return{description:Y,command:V||Z}}function O4($,Z=60){let{description:J,command:Q}=B1($);if(J)return J;return cF(Q).replace(/\s+/g," ").trim().slice(0,Z)}function cF($){let Z=$.split(/\r?\n/).map((J)=>J.trim()).filter(Boolean);return Z.find((J)=>!J.startsWith("#")&&!/^set\s+-/.test(J)&&!/^cd\s+/.test(J)&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(J)&&!/^cat\s+<<['"]?\w+['"]?/.test(J))??Z[Z.length-1]??""}function uF($){let Z=$.replace(/\r\n/g,`
75
+ `).trim(),J=Z.match(/^(?:\/usr\/bin\/env\s+)?(?:\/[\w./-]+\/)?(?:ba|z|fi)?sh\s+-[A-Za-z]*c[A-Za-z]*\s+([\s\S]+)$/);if(J){let Y=dF(J[1]);return qZ(Y||Z)}let Q=lF(Z);if(Q)return Q;return qZ(Z)}function lF($){let Z=$.match(/^("[^"]*"|'[^']*'|“[^”]*”|\S+)\s+([\s\S]*)$/);if(!Z)return null;let J=Tz(Z[1]).replace(/\.exe$/i,"");if(!/(?:^|[\\/])(?:powershell|pwsh)$/i.test(J))return null;let Q=Z[2];for(;;){let Y=Q.match(/^(-[A-Za-z][\w-]*)\s+([\s\S]*)$/);if(!Y)break;let V=Y[1].toLowerCase();if(V==="-command"||V==="-c")return qZ(Tz(Y[2]));if(Q=Y[2],V==="-executionpolicy"||V==="-inputformat"||V==="-outputformat")Q=Q.replace(/^(?:"[^"]*"|'[^']*'|\S+)\s+/,"")}return null}function dF($){let Z=$.trim();if(Z.length<2)return Z;let J=I3[Z[0]];if(!J||!Z.endsWith(J))return Z;let Q=Z.slice(1,-1);if(Z[0]==="'")return Q.replace(/'\\''/g,"'");return Q.replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
76
+ `)}function qZ($){let Z=$.trim(),J=Z[0];if(!I3[J])return Z;let Q=Z.slice(1);if(!/^#\s*(?:desc|dec|description|说明|目的|用途)\s*[::]/i.test(Q)&&!iF(Q,J))return Z;if(J!=='"')return Q.replace(/'\s*$/,"");return Q.replace(/\s*[”"]\s*$/,"").replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
77
+ `).replace(/\s*"\s*'\$\(([^)]*)\)'/g,(X,z)=>` $(${z})`)}function iF($,Z){let J=I3[Z];for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Z==='"'&&Y==="\\"&&Q+1<$.length){Q++;continue}if(Y===J)return/^[\s]*$/.test($.slice(Q+1))}return!1}var I3;var A4=R(()=>{I3={'"':'"',"'":"'","“":"”"}});function Ez($,Z){return $?.then(async(J)=>{return await Z(J),J.ok?"complete":"retry"})??null}function E($){return $ instanceof Error?$.message:String($)}function h0($){return $.length<=16?$:`${$.slice(0,8)}…${$.slice(-4)}`}import{isAbsolute as Sz}from"node:path";function nF($){return $.kind==="fresh"?null:$.source.provider}function E0($,Z,J){let Q=nF($);if(Q&&Q!==Z)throw Error(`conversation launch provider mismatch: source=${Q} target=${Z}`);if($.kind!=="fresh"&&!$.source.sessionId.trim())throw Error("conversation launch source session id is empty");if($.kind!=="fresh"&&$.source.cwd!==null&&(typeof $.source.cwd!=="string"||!Sz($.source.cwd)))throw Error(`conversation launch source cwd is not absolute: ${String($.source.cwd)}`);if($.kind!=="fresh"&&J!==void 0){if(!Sz(J))throw Error(`expected conversation cwd is not absolute: ${J}`);if($.source.cwd===null)throw Error("conversation launch source cwd is missing");if($.source.cwd!==J)throw Error(`conversation launch cwd mismatch: source=${$.source.cwd} target=${J}`)}if($.kind!=="fork"||!$.through)return;if($.through.provider!==Z||$.through.source.provider!==Z)throw Error(`conversation checkpoint provider mismatch: checkpoint=${$.through.provider} target=${Z}`);if($.through.source.sessionId!==$.source.sessionId)throw Error("conversation checkpoint source does not match fork source");if($.through.source.cwd!==$.source.cwd)throw Error("conversation checkpoint cwd does not match fork source");if(!$.through.id.trim())throw Error("conversation checkpoint id is empty");if(Z==="dsh"&&(!/^\d+$/.test($.through.id)||!Number.isSafeInteger(Number($.through.id))))throw Error("DSH checkpoint must be a non-negative event sequence")}var K2=()=>{};import{existsSync as aF,readFileSync as oF}from"node:fs";function Cz($,Z){return`${$}:${Z}`}function sF(){if(!aF(B3))return;try{let $=JSON.parse(oF(B3,"utf8"));if($?.version!==1||!Array.isArray($.ids)||$.ids.some((Z)=>typeof Z!=="string"||!Z))throw Error("invalid delegated-agent session registry");y9=new Set($.ids)}catch($){FZ=$ instanceof Error?$:Error(String($))}}function xz(){if(FZ)throw Error(`delegated-agent session registry is unavailable: ${FZ.message}`)}function bz($,Z){xz();let J=Z.trim();if(!J)throw Error("delegated-agent session id is empty");let Q=Cz($,J);if(y9.has(Q))return;let Y=new Set(y9);Y.add(Q),r(B3,{version:1,ids:[...Y].sort()}),y9=Y}function N4($,Z){return xz(),y9.has(Cz($,Z))}var y9,FZ=null;var f9=R(()=>{H0();b0();y9=new Set;sF()});function g3($){if(!$||typeof $!=="object"||Array.isArray($))return null;let Z=$;if(typeof Z.hasCredits!=="boolean"||typeof Z.unlimited!=="boolean")return null;let J=null;if(Z.balance!=null){if(typeof Z.balance!=="number"&&!(typeof Z.balance==="string"&&/^\d+(?:\.\d+)?$/.test(Z.balance.trim())))return null;if(J=Number(Z.balance),!Number.isFinite(J)||J<0||J>Number.MAX_SAFE_INTEGER)return null}if(!Z.unlimited&&J!==null&&Z.hasCredits!==J>0)return null;return{hasCredits:Z.hasCredits,unlimited:Z.unlimited,balance:J}}function B2($){return $==null?"unknown":$.hasCredits||$.unlimited?"available":"empty"}function kz($,Z){if(!$||!Z||B2(Z)!=="available")return!1;return B2($)==="empty"||!$.unlimited&&Z.unlimited||!$.unlimited&&$.balance!==null&&Z.balance!==null&&Z.balance>$.balance}function eF($){switch($){case"plus":return 1;case"prolite":return 5;case"pro":return 20;default:return null}}function j2($,Z){let J=$.buckets?.find((Y)=>Y.limitName?.toLowerCase()===Z.toLowerCase()||Y.normalModelSlug===Z)??$,Q=!("limitId"in J)||J.limitId===$.defaultLimitId?$.ordinaryUsageAllowed:void 0;return{...J,ordinaryUsageAllowed:Q}}function MZ($){if($.spendControlReached===!0)return{state:"exhausted",reason:"已达到上游消费限制"};if($.rateLimitReachedType&&$.rateLimitReachedType!=="rate_limit_reached")return{state:"exhausted",reason:`上游额度限制:${$.rateLimitReachedType}`};let Z=[$.fiveHour,$.weekly].filter((V)=>V!==null),J=Z.some((V)=>V.percent!==null&&V.percent>=100),Q=J||$.ordinaryUsageAllowed===!1||$.rateLimitReachedType==="rate_limit_reached",Y=B2($.credits);if(Q&&Y==="empty")return{state:"exhausted",reason:J?"额度耗尽":"套餐内额度暂不可用,且无可用积分"};if(Z.some((V)=>V.percent===null||!Number.isFinite(V.percent)||V.percent<0||V.percent>100))return{state:"miss",reason:"额度百分比 MISS"};if(Q)return Y==="available"?{state:"credits"}:{state:"miss",reason:`${J?"订阅额度已用完":"套餐内额度暂不可用"},积分 MISS`};return{state:"subscription"}}function _2($,Z){if($.state!=="ok")throw Error("额度计量桶 MISS");let J=j2($,Z);return"limitId"in J?J.limitId:$.defaultLimitId??"codex"}function vz($,Z){let J=j2($,Z).weekly,Q=$.readStartedAt??$.fetchedAt,Y=J?.resetsAt?.getTime();return J?.percent===0&&J.durationMins===10080&&Number.isFinite(Q)&&Number.isFinite($.fetchedAt)&&Q<=$.fetchedAt&&Y!=null&&Y>=Math.floor(Q/1000)*1000+DZ&&Y<=Math.floor($.fetchedAt/1000)*1000+DZ}function yz($,Z,J){let Q=j2($,Z).weekly?.resetsAt?.getTime();return Q!=null&&Q-DZ<=J}function m3($,Z){let J=Number($.funding==="credits")-Number(Z.funding==="credits");if(J)return J;if($.funding==="credits"&&Z.funding==="credits"){let Y=$.credits,V=Z.credits;return Number(V.unlimited)-Number(Y.unlimited)||Number(Y.balance===null)-Number(V.balance===null)||(Y.balance!==null&&V.balance!==null?V.balance-Y.balance:0)||$.account.id.localeCompare(Z.account.id)}let Q=(Y)=>Y.priority==="expiring"?1:0;return Q(Z)-Q($)||($.priority==="expiring"?$.hours-Z.hours:Z.score-$.score)||(Z.availableNow??0)-($.availableNow??0)||$.account.id.localeCompare(Z.account.id)}function h9($,Z,J=Date.now(),Q){let Y={state:"miss",score:null,shares:null,remaining:null,hours:null};if($.state!=="ok")return{...Y,reason:$.state==="network"?$.reason??"额度读取失败":$.state};let V=eF($.subscriptionType);if(V===null)return{...Y,reason:`未知周额度套餐:${$.subscriptionType??"MISS"}`};Y.shares=V;let X=j2($,Z),z=MZ(X);if(z.state==="miss")return{...Y,reason:z.reason};if(z.state==="exhausted"){let q=[X.fiveHour,X.weekly].filter((M)=>M!==null&&M.percent!==null&&M.percent>=100),F=q.map((M)=>M.resetsAt?.getTime()).filter((M)=>M!=null&&Number.isFinite(M)&&M>J);return{...Y,state:"exhausted",reason:z.reason,...F.length===q.length&&F.length?{retryAt:Math.max(...F)}:{}}}let H=B2(X.credits);if(Q==="ultra"&&$.subscriptionType==="plus"&&X.fiveHour!==null&&H!=="available")return H==="unknown"?{...Y,reason:"Ultra 自动选择有短窗的 Plus,积分 MISS"}:{...Y,state:"excluded",reason:"Ultra 自动选择有短窗的 Plus 需要可用积分"};if(z.state==="credits")return{...Y,state:"ready",funding:"credits",credits:X.credits};let G=X.weekly;if(!G||G.percent===null)return{...Y,reason:"周额度 MISS"};if(G.durationMins!=null&&G.durationMins!==10080)return{...Y,reason:`周额度窗口时长不匹配:${G.durationMins} 分钟(需要 10080 分钟)`};let W=G.resetsAt?.getTime();if(W==null||!Number.isFinite(W)||W<=J)return{...Y,reason:"周重置时间 MISS 或已过期"};let K=V*(100-G.percent)/100,B=(W-J)/3600000,_=B-rF,P=_>0?K/_:null;if(Q==="ultra"&&$.subscriptionType!=="plus"&&K<wz&&H!=="available"){if(H==="unknown")return{...Y,remaining:K,hours:B,weeklyScore:P,reason:"Ultra 周余量不足,积分 MISS"};return{...Y,state:"waiting",remaining:K,hours:B,weeklyScore:P,reason:`Ultra 至少需要 ${wz} 份周余量`,retryAt:W}}let L=_<=0?"expiring":void 0;if($.subscriptionType==="plus"&&X.fiveHour!==null){let q=X.fiveHour,F=tF*(100-q.percent)/100,M=((q.resetsAt?.getTime()??NaN)-J)/3600000;if(!Number.isFinite(M)||M<=0)return{...Y,reason:"5h 重置时间 MISS 或已过期"};return{state:"ready",shares:V,remaining:K,hours:B,priority:L,weeklyScore:P,fiveHourRemaining:F,fiveHourHours:M,availableNow:Math.min(K,F),score:P===null?null:Math.min(P,F/M)}}return{state:"ready",shares:V,remaining:K,hours:B,priority:L,weeklyScore:P,availableNow:K,score:P}}function R4($){if(!$||typeof $!=="object")return!1;let Z=$;if(Z.codexErrorInfo==="usageLimitExceeded"||Z.type==="usage_limit_reached"||Z.code==="usage_limit_reached")return!0;return typeof Z.message==="string"&&/^You(?:'|’)ve hit your usage limit\b/i.test(Z.message)}var tF=0.15,wz=0.5,DZ=604800000,rF=5;var T4=()=>{};import{closeSync as $D,existsSync as ZD,mkdirSync as JD,openSync as QD,readdirSync as YD,readSync as VD,statSync as c3,writeFileSync as XD}from"node:fs";import{homedir as UZ}from"node:os";import{delimiter as fz,isAbsolute as hz,join as v1}from"node:path";import{EventEmitter as zD}from"node:events";import{randomUUID as HD}from"node:crypto";import{StringDecoder as Iz}from"node:string_decoder";import{spawn as GD}from"cross-spawn";function I9(){return C9("codex","codex")}function WD(){if(process.platform==="win32")return process.env.PATH??"";return[...new Set([v1(UZ(),".local","npm-global","bin"),v1(UZ(),".local","bin"),v1(UZ(),".bun","bin"),...(process.env.PATH??"").split(fz),"/usr/local/bin","/usr/bin","/bin"].filter(Boolean))].join(fz)}function AZ($,Z=!1){if(!$||typeof $!=="object")return null;let{message:J,codexErrorInfo:Q,additionalDetails:Y}=$;if(typeof J!=="string")return null;if(R4($))return null;let V=null;if(typeof Q==="string")V=Q;else if(Q!=null){if(typeof Q!=="object"||Array.isArray(Q))return null;let K=Object.entries(Q);if(K.length!==1)return null;let[B,_]=K[0];if(V=B,!OZ.has(V)||!_||typeof _!=="object"||Array.isArray(_))return null;let P=_.httpStatusCode;if(P!=null&&(typeof P!=="number"||!pz.has(P)))return null}if(V!==null&&V!=="other"&&V!=="serverOverloaded"&&!OZ.has(V))return null;let X=/^(?:Codex\s+)?Error running remote compact task:\s*/i.test(J),z=J.replace(/^(?:Codex\s+)?Error running remote compact task:\s*/i,"").replace(/^Codex\s+/i,"").trim();for(let K of[z,Y]){if(typeof K!=="string")continue;if(R4({message:K})||/(?:^|:\s*)(?:unauthorized\b|forbidden\b|authentication failed\b|invalid (?:api key|request|argument)\b|(?:usage|rate|session budget) limit exceeded\b|context window exceeded\b)/i.test(K))return null;let B=/(?:^|:\s*)unexpected status (\d{3})\b/i.exec(K);if(B&&!pz.has(Number(B[1])))return null}let H=/(?:^|:\s*)unexpected status (\d{3})\b/i.exec(z);if(/\bselected\s+model\s+is\s+at\s+capacity\b/i.test(z))return"capacity";let G=/^Connection failed:\s*error sending request(?: for url \([^\r\n]+\))?\s*$/i.test(z)||/^(?:request timed out|workspace routing discovery timed out)$/i.test(z)||Z&&/^workspace routing discovery failed$/i.test(z),W=/^stream disconnected before completion\s*:/i.test(z);if(OZ.has(V??"")||V==="serverOverloaded"||G||W||H){if(X)return"compact_connection_failed";if(V==="responseStreamDisconnected"||W)return"stream_disconnected";return"transient_error"}return null}function qD($){if(!/^[a-z][a-z0-9_-]*$/.test($.id)||["openai","ollama","lmstudio"].includes($.id))throw Error("Codex API provider id 无效或属于保留名称");if(!/^[A-Z][A-Z0-9_]*$/.test($.envKey))throw Error("Codex API key 环境变量名无效");let Z=`model_providers.${$.id}`,J={name:$.name,base_url:$.baseUrl,env_key:$.envKey,wire_api:"responses",requires_openai_auth:!1,supports_websockets:!1},Q=`{${Object.entries(J).map(([Y,V])=>`${Y}=${JSON.stringify(V)}`).join(",")}}`;return["-c",`model_provider=${JSON.stringify($.id)}`,"-c",`${Z}=${Q}`,"-c","features.apps=false"]}function FD(){return["app-server","--listen","stdio://"]}function DD($,Z){return{cwd:$,stdio:["pipe","pipe","pipe"],shell:!1,env:Z}}function U$($){return typeof $==="string"&&L2.includes($)}function MD($){if(!Array.isArray($))return[];let Z=new Set,J=[];for(let Q of $){let Y=typeof Q==="string"?Q:typeof Q==="object"&&Q?Q.reasoningEffort:null;if(!U$(Y)||Z.has(Y))continue;Z.add(Y);let V=typeof Q==="object"&&Q&&typeof Q.description==="string"?Q.description:"";J.push({reasoningEffort:Y,description:V})}return J}function NZ($,Z){switch($.type){case"commandExecution":return{name:"Bash",input:{command:$.command,cwd:$.cwd,source:$.source}};case"fileChange":return{name:"FileChange",input:{changes:$.changes,status:$.status,cwd:Z}};case"mcpToolCall":return{name:"MCP",input:{server:$.server,tool:$.tool,arguments:$.arguments}};case"dynamicToolCall":return{name:$.namespace?`${$.namespace}.${$.tool}`:$.tool,input:$.arguments};case"webSearch":return{name:"WebSearch",input:{query:$.query,action:$.action}};case"imageGeneration":return{name:"ImageGeneration",input:RZ($)}}return null}function UD($){let Z=$?.revisedPrompt??$?.revised_prompt;return typeof Z==="string"&&Z?Z:void 0}function RZ($){return{status:$.status,revisedPrompt:UD($),...typeof $?.prompt==="string"&&$.prompt?{prompt:$.prompt}:{}}}function cz($){if(!$||!ZD(gz))return null;let Z=null,J=[gz];while(J.length){let Q=J.pop(),Y;try{Y=YD(Q,{withFileTypes:!0})}catch(V){j(`codex-process: cannot scan Codex session dir ${Q}: ${V instanceof Error?V.message:V}`);continue}for(let V of Y){let X=v1(Q,V.name);if(V.isDirectory()){J.push(X);continue}if(!V.isFile())continue;if(!V.name.startsWith("rollout-")||!V.name.endsWith(`${$}.jsonl`))continue;try{let z=c3(X).mtimeMs;if(!Z||z>Z.mtimeMs)Z={path:X,mtimeMs:z}}catch(z){j(`codex-process: cannot stat Codex rollout ${X}: ${z instanceof Error?z.message:z}`)}}}return Z?.path??null}function iz($,Z,J=KD){let Q=$?.savedPath??$?.saved_path;if(typeof Q==="string"&&Q)return Q;let Y=$?.result;if(typeof Y==="string"){let V=OD($,Z,J);if(V)return V;if(Y.length>2048){let X=nz($);return j(`codex-process: image generation inline result could not be decoded id=${X} length=${Y.length}`),`Image generation returned ${Y.length} chars of inline data, but Lodestar could not materialize it as an image file.`}return Y}if(Y&&typeof Y==="object"){let V=Y.savedPath??Y.saved_path??Y.path;if(typeof V==="string"&&V)return V;return JSON.stringify(Y,null,2)}return""}function OD($,Z,J){let Q=$?.result;if(typeof Q!=="string")return null;let Y=AD(Q);if(!Y)return null;let V=uz(Z??"unknown-thread"),X=uz(nz($)),z=v1(J,V),H=v1(z,`${X}.${Y.ext}`);try{return JD(z,{recursive:!0}),XD(H,Y.buffer),H}catch(G){return j(`codex-process: failed to write image generation result ${H}: ${G instanceof Error?G.message:G}`),null}}function nz($){let Z=$?.callId??$?.call_id??$?.id;return typeof Z==="string"&&Z?Z:`image-${Date.now()}`}function uz($){let Z=$.trim().replace(/[^a-zA-Z0-9_.-]/g,"_").replace(/^_+|_+$/g,"");return Z?Z.slice(0,140):"unknown"}function AD($){let Z=$.trim(),J=Z,Q=null,Y=Z.match(/^data:image\/([a-zA-Z0-9.+-]+);base64,(.*)$/s);if(Y)Q=RD(Y[1]),J=Y[2];else{if(Z.length<64)return null;if(!/^[a-zA-Z0-9+/=_\-\s]+$/.test(Z))return null}if(J=J.replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),!J||J.length%4===1)return null;let V=J.padEnd(Math.ceil(J.length/4)*4,"="),X;try{X=Buffer.from(V,"base64")}catch{return null}if(X.length<12)return null;let z=ND(X)??Q;if(!z)return null;return{buffer:X,ext:z}}function ND($){if($[0]===137&&$[1]===80&&$[2]===78&&$[3]===71&&$[4]===13&&$[5]===10&&$[6]===26&&$[7]===10)return"png";if($[0]===255&&$[1]===216&&$[2]===255)return"jpg";let Z=$.subarray(0,6).toString("ascii");if(Z==="GIF87a"||Z==="GIF89a")return"gif";if($.subarray(0,4).toString("ascii")==="RIFF"&&$.subarray(8,12).toString("ascii")==="WEBP")return"webp";return null}function RD($){let Z=$.toLowerCase();if(Z==="jpeg"||Z==="jpg")return"jpg";if(Z==="png")return"png";if(Z==="gif")return"gif";if(Z==="webp")return"webp";return null}function lz($,Z,J){let Q=NZ($,Z);if(!Q)return null;switch($.type){case"commandExecution":return{...Q,output:$.aggregatedOutput??"",isError:$.exitCode!=null&&$.exitCode!==0};case"fileChange":return{...Q,output:JSON.stringify($.changes??[],null,2),isError:$.status==="failed"};case"mcpToolCall":return{...Q,output:$.error?JSON.stringify($.error,null,2):JSON.stringify($.result??null,null,2),isError:!!$.error};case"dynamicToolCall":return{...Q,output:JSON.stringify($.contentItems??[],null,2),isError:$.success===!1};case"webSearch":return{...Q,output:JSON.stringify($.action??{},null,2),isError:!1};case"imageGeneration":return{...Q,output:iz($,J),isError:$.status==="failed"}}return null}function p3($,Z){if(typeof $==="string"&&$){let J=$.split("/").filter(Boolean).pop();if(J)return J}return h0(Z)}function dz($){if(typeof $!=="string"||!$)return;if($.startsWith("gAAAA")&&!/[一-鿿]/.test($))return"(继承主线程历史的密文任务书)";return $}function TD($,Z,J){let Q=(Y)=>typeof Y==="string"?Y:"";switch($){case"Bash":{if(J!=null){let Y=J.replace(/\s+/g," ").trim();return Y?`→ ${Y.slice(0,60)}`:""}return O4(Q(Z?.command))||"(空命令)"}case"FileChange":{let Y=Array.isArray(Z?.changes)?Z.changes.length:0;if(J!=null)return"";return Y>0?`改 ${Y} 个文件`:"文件变更"}case"MCP":return`${Q(Z?.server)}/${Q(Z?.tool)}`.slice(0,60);case"WebSearch":return`"${Q(Z?.query).slice(0,50)}"`;default:{if(J!=null){let Y=J.replace(/\s+/g," ").trim();return Y?`→ ${Y.slice(0,60)}`:""}return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}}function az($){return(Array.isArray($.receiverThreadIds)?$.receiverThreadIds:[]).filter((J)=>typeof J==="string"&&!!J)}function ED($){let Z=az($);return Z.length>0?`派生 ${Z.length} 个子 agent`:"派生子 agent"}function SD($){let Z=$.agentsStates;if(!Z||typeof Z!=="object")return"";let J=[];for(let[Q,Y]of Object.entries(Z)){let V=Y,X=typeof V?.status==="string"?V.status:"unknown";J.push(`${h0(Q)}: ${X}`)}return J.join(`
78
+ `)}var gz,KD,BD=30000,jD=600000,_D=5000,PD=60000,mz=10,LD,OZ,pz,L2,g9="xhigh",P2,E4;var j1=R(()=>{k0();I();D4();Oz();_Z();A4();K2();f9();D0();T4();_Z();gz=v1(v.defaultHome,"sessions"),KD=v1(v.defaultHome,"generated_images"),LD={capacity:"上一轮因模型暂时满载而中断。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",stream_disconnected:"上一轮因响应流连接中断而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",compact_connection_failed:"上一轮因远程压缩时连接失败而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",transient_error:"上一轮因临时连接或服务错误而未完成。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。"},OZ=new Set(["httpConnectionFailed","responseStreamConnectionFailed","responseStreamDisconnected","responseTooManyFailedAttempts"]),pz=new Set([408,500,502,503,504]);L2=["none","minimal","low","medium","high","xhigh","max","ultra"];P2=class P2 extends Error{method;requestId;serverCode;serverMessage;serverData;constructor($,Z,J,Q,Y){super(`codex app-server ${$} failed (id=${Z}, code=${J??"MISS"}): ${Q}`);this.method=$;this.requestId=Z;this.serverCode=J;this.serverMessage=Q;this.serverData=Y;this.name="CodexRpcResponseError"}};E4=class E4 extends zD{provider="codex";tokenSourceId;launchKind;proc=null;startupPromise=null;inputPolicyAbort=new AbortController;inputPolicyCatalog=null;stdoutBuf="";stderrBuf="";requestCounter=0;pending=new Map;serverRequests=new Map;alive=!0;expectedExit=!1;exitEventEmitted=!1;childExitCode=null;childExitSignal=null;exitPromise;resolveExit;opts;usesCustomDefaultModeInstructions=!1;readyPromise=null;initializePromise=null;conversationResumable=!1;conversationRolloutPath=null;conversationMaterializationVerification=null;conversationMaterializationRetrySource=null;lastConversationMaterializationFailure=null;currentTurnId=null;steeringInputs=new Map;inputConsumptionOpen=!1;turnStartGeneration=0;turnStartOwner=null;turnStartOwnersByTurnId=new Map;finishedTurnIds=new Set;turnRetryTimer=null;turnRetryCount=0;transientRetryCount=0;turnRetryHasStarted=!1;turnRetryEnabled=!0;turnError=null;routingTimeoutTurnId=null;rolloutFilePath=null;rolloutReadOffset=0;rolloutLineRemainder="";rolloutDecoder=new Iz("utf8");emittedImageGenerationIds=new Set;collabAgentNames=new Map;collabAgentSettled=new Set;collabAgentWasActive=new Set;collabAgentSummaries=new Map;sessionId=null;lastAssistantUuid=null;lastCompletedTurnId=null;lastModel=null;lastEffort=null;lastUsage=null;lastTotalUsage=null;lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1};lastContextWindow=null;lastContextTokens=null;turnRetry=null;constructor($){super();this.on("error",()=>{}),this.exitPromise=new Promise((z)=>{this.resolveExit=z}),this.opts=$,this.tokenSourceId=$.tokenSourceId??null,this.launchKind=($.launch??{kind:"fresh"}).kind;let Z=I9(),J=$.apiProvider?qD($.apiProvider):[...$.tokenSourceId==="codex-sub"?["-c",'model_provider="openai"']:[],...v.cliArgs($.codexAccountId??d)],Q={...process.env,NPM_CONFIG_LOGLEVEL:"error",PATH:WD(),...g.codex.env,...$.hostEnv??{}},Y=$.transformEnv?$.transformEnv(Q):Q,V=$.apiProvider?{...Y,CODEX_HOME:v.defaultHome}:v.env($.codexAccountId??d,Y),X=(z)=>{if(this.expectedExit)throw Error("Codex startup cancelled");this.inputPolicyCatalog=z??null,this.spawnNative(Z,[...FD(),...J,...z?["-c",`model_catalog_json=${JSON.stringify(z.path)}`,...z.disabledFeatures.flatMap((H)=>["--disable",H])]:[]],V)};if($.allowUserInput===!1)this.startupPromise=Uz({binary:Z,configArgs:J,env:V,workDir:$.workDir,signal:this.inputPolicyAbort.signal}).then(async(z)=>{if(this.expectedExit)throw await z.dispose(),Error("Codex startup cancelled");X(z)}).catch((z)=>{throw this.alive=!1,this.emit("error",z instanceof Error?z:Error(String(z))),this.emitProcessExit(this.expectedExit?null:1,this.expectedExit?"SIGTERM":null),z}),this.startupPromise.catch(()=>{});else X();if(!$.apiProvider)w1(this,$.codexAccountId??d)}spawnNative($,Z,J){j(`codex-process: spawn ${$} app-server (cwd=${this.opts.workDir})`),this.proc=GD($,Z,DD(this.opts.workDir,J)),this.proc.stdout.on("data",(Q)=>this.onStdout(Q)),this.proc.stderr.on("data",(Q)=>this.onStderr(Q)),this.proc.stdin.on("error",(Q)=>this.handleStdinError(Q)),this.proc.on("exit",(Q,Y)=>this.handleChildExit(Q,Y)),this.proc.on("close",(Q,Y)=>this.handleChildClose(Q,Y)),this.proc.on("error",(Q)=>this.handleChildProcessError(Q))}handleStdinError($){let Z=$ instanceof Error?$:Error(String($));if(j(`codex-process: stdin failed: ${Z.message}`),!this.expectedExit)this.emit("error",Z)}handleChildExit($,Z){if(!this.alive){j(`codex-process: duplicate exit ignored code=${$} signal=${Z}`);return}this.alive=!1,this.cancelTurnRetry(),this.childExitCode=$,this.childExitSignal=Z,j(`codex-process: OS exit code=${$} signal=${Z}; awaiting stdio close`)}handleChildClose($,Z){this.alive=!1,this.cancelTurnRetry(),this.flushStdoutTail(),this.flushStderrTail(),this.rejectPendingRequests((V,X)=>Error(`codex app-server closed before ${X.method} response (id=${V})`)),this.serverRequests.clear();let J=$??this.childExitCode,Q=Z??this.childExitSignal,Y=this.conversationMaterializationBarrier();if(Y){Y.then(()=>this.emitProcessExit(J,Q),()=>this.emitProcessExit(J,Q));return}this.emitProcessExit(J,Q)}handleChildProcessError($){j(`codex-process: child process error: ${$}`),this.rejectPendingRequests((Q,Y)=>Error(`codex app-server process failed before ${Y.method} response (id=${Q}): ${$.message}`,{cause:$}));let Z=typeof this.proc?.pid!=="number",J=!1;if(Z&&this.alive)this.alive=!1,this.cancelTurnRetry(),this.serverRequests.clear(),J=!0;if(this.emit("error",$),J)j(`codex-process: spawn failed before pid assignment expected=${this.expectedExit}`),this.emitProcessExit(null,null)}emitProcessExit($,Z){if(this.exitEventEmitted)return;this.exitEventEmitted=!0,this.resolveExit(),j(`codex-process: exited code=${$} signal=${Z} expected=${this.expectedExit}`),this.emit("exit",{code:$,signal:Z,expected:this.expectedExit})}onStdout($){this.stdoutBuf+=$.toString();let Z;while((Z=this.stdoutBuf.indexOf(`
79
79
  `))>=0){let J=this.stdoutBuf.slice(0,Z).trim();if(this.stdoutBuf=this.stdoutBuf.slice(Z+1),!J)continue;let Q;try{Q=JSON.parse(J)}catch(Y){j(`codex-process: bad json: ${J.slice(0,200)} (${Y})`);continue}try{this.handleMessage(Q)}catch(Y){j(`codex-process: dispatch error: ${JSON.stringify(Q).slice(0,200)} (${Y})`)}}}flushStdoutTail(){if(!this.stdoutBuf)return;this.onStdout(Buffer.from(`
80
80
  `))}onStderr($){this.stderrBuf+=$.toString();let Z;while((Z=this.stderrBuf.indexOf(`
81
- `))>=0){let J=this.stderrBuf.slice(0,Z);if(this.stderrBuf=this.stderrBuf.slice(Z+1),J.trim())j(`codex-process[stderr]: ${J}`)}}flushStderrTail(){let $=this.stderrBuf;if(this.stderrBuf="",$.trim())j(`codex-process[stderr]: ${$}`)}handleMessage($){if(Object.prototype.hasOwnProperty.call($,"id")&&!$.method){let J=this.pending.get($.id);if(!J){j(`codex-process: response for unknown id=${$.id}`);return}if(this.pending.delete($.id),clearTimeout(J.timeout),$.error){let Q=typeof $.error?.code==="number"?$.error.code:null,Y=typeof $.error==="string"?$.error:typeof $.error?.message==="string"?$.error.message:JSON.stringify($.error);J.reject(new P2(J.method,$.id,Q,Y,$.error?.data))}else J.resolve($.result);return}if(Object.prototype.hasOwnProperty.call($,"id")&&$.method){this.handleServerRequest($);return}if($.method){this.handleNotification($.method,$.params??{});return}let Z=jZ($);if(Z){let J=this.withSessionId(Z);KZ(Z.sourceMethod??"raw_message",$,J),this.emit("context_compacted",J);return}V$("RAW_MESSAGE",$),this.emit("raw",$)}handleNotification($,Z){if(this.isSubagentThread(Z)){if($==="thread/status/changed")this.handleThreadStatusChanged(Z);else if($==="item/started")this.handleSubagentItemStarted(Z);else if($==="item/completed")this.handleSubagentItemCompleted(Z);return}let J=BZ($,Z);if(J){let Q=this.withSessionId(J);KZ($,Z,Q),this.emit("context_compacted",Q);return}switch($){case"thread/started":{let Q=Z.thread;if(Q?.id)this.sessionId=Q.id;return}case"thread/settings/updated":{let Q=Z.threadSettings;if(typeof Q?.model==="string")this.lastModel=Q.model;if(U$(Q?.effort))this.lastEffort=Q.effort;if(Q?.collaborationMode)this.usesCustomDefaultModeInstructions=Q.collaborationMode.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string";return}case"thread/tokenUsage/updated":{let Q=U4(Z.tokenUsage?.last);if(Q)this.lastUsage=Q,this.lastResult.usage=this.lastUsage;else j("codex-process: tokenUsage notification missing last breakdown");this.lastTotalUsage=U4(Z.tokenUsage?.total);let Y=Z.tokenUsage?.modelContextWindow;if(typeof Y==="number"&&Y>0)this.lastContextWindow=Y;this.emit("token_usage",{usage:this.lastUsage,totalUsage:this.lastTotalUsage,contextWindow:this.lastContextWindow,threadId:Z.threadId,turnId:Z.turnId});return}case"turn/started":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_STARTED_THREAD_MISMATCH",{method:$,params:Z});return}this.recordTurnStarted(Z.turn,Z.threadId,"turn/started notification"),this.markConversationMaterialized("turn/started notification");return}case"turn/completed":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_COMPLETED_THREAD_MISMATCH",{method:$,params:Z});return}let Q=Z.turn??{},Y=typeof Q.id==="string"&&Q.id?Q.id:null;if(Y){if(this.finishedTurnIds?.has(Y)){j(`codex-process: duplicate turn/completed ignored turn=${Y}`);return}if(this.currentTurnId&&this.currentTurnId!==Y){this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y),j(`codex-process: stale turn/completed ignored turn=${Y} current=${this.currentTurnId}`);return}this.flushRolloutImageGenerations(),this.markConversationMaterialized("turn/completed notification"),this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y)}else V$("TURN_COMPLETED_MISSING_ID",{method:$,params:Z});let V=Q.status,X=V==="failed"&&this.turnError&&this.turnError.turnId===Y?this.turnError.error:null,z=Q.error&&X&&typeof Q.error.message==="string"&&Q.error.message===X.message?{...X,...Q.error,codexErrorInfo:Q.error.codexErrorInfo??X.codexErrorInfo,additionalDetails:Q.error.additionalDetails??X.additionalDetails}:Q.error??X;this.turnError=null;let H=V==="failed"||!!z,G=V==="completed"&&!H&&!!Y;this.lastCompletedTurnId=G?Y:null,this.currentTurnId=null,this.inputConsumptionOpen=!1;let W=AZ(z,!!Y&&this.routingTimeoutTurnId===Y);if(this.routingTimeoutTurnId=null,V==="failed"&&Y&&W&&this.scheduleTurnRetry(z.message,LF[W],W))return;this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1;let K=H?z?.type??z?.message??"failed":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof Q.durationMs==="number"?Q.durationMs:null,num_turns:1,usage:this.lastUsage,subtype:K,is_error:H};for(let[B,_]of this.steeringInputs??[])if(_===Y)this.steeringInputs.delete(B);this.emit("result",{subtype:K,is_error:H,...H&&typeof z?.message==="string"?{error:z.message}:{},...V==="failed"&&Y&&R4(z)?{codexQuotaFailure:{accepted:!0}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,turn_id:Y,checkpoint:G&&this.sessionId?{provider:"codex",kind:"turn",id:Y,source:{provider:"codex",sessionId:this.sessionId,cwd:this.opts.workDir}}:null});return}case"turn/plan/updated":{this.emit("turn_plan_updated",Z);return}case"item/plan/delta":{this.emit("plan_delta",Z);return}case"thread/goal/updated":{if(Z.goal)this.emit("thread_goal_updated",Z.goal);else j("codex-process: thread/goal/updated missing goal");return}case"thread/goal/cleared":{this.emit("thread_goal_cleared",Z);return}case"thread/status/changed":{this.handleThreadStatusChanged(Z);return}case"item/agentMessage/delta":{if(typeof Z.delta==="string"&&Z.delta.length>0)this.emit("assistant_text",{uuid:Z.itemId,text:Z.delta,parentToolUseId:null});else V$("AGENT_MESSAGE_DELTA_EMPTY",{method:$,params:Z});return}case"item/started":{this.handleItemStarted(Z);return}case"item/completed":{this.handleItemCompleted(Z);return}case"mcpServer/startupStatus/updated":{j(`codex-process: mcp ${Z.name} ${Z.status}${Z.error?`: ${Z.error}`:""}`);return}case"account/rateLimits/updated":{this.emit("rate_limits_updated",Z.rateLimits);return}case"configWarning":case"warning":case"guardianWarning":case"deprecationNotice":{j(`codex-process: ${$}: ${Z.summary??Z.message??JSON.stringify(Z).slice(0,200)}`);return}case"error":{j(`codex-process: server error: ${JSON.stringify(Z).slice(0,500)}`);let Q=Z.error??Z;if(typeof Z.turnId==="string"&&Z.threadId===this.sessionId&&!this.finishedTurnIds?.has(Z.turnId)&&(!this.currentTurnId||this.currentTurnId===Z.turnId)){if(this.turnError={turnId:Z.turnId,error:Q},Z.willRetry===!0&&[Q.message,Q.additionalDetails].some((Y)=>typeof Y==="string"&&/^workspace routing discovery timed out$/i.test(Y.trim())&&AZ({...Q,message:Y,additionalDetails:Y===Q.additionalDetails?Q.message:Q.additionalDetails})!==null))this.routingTimeoutTurnId=Z.turnId}this.emit("error",Error(Q.message??Q.summary??"codex app-server error"));return}}V$("NOTIFICATION",{method:$,params:Z}),this.emit("raw",{method:$,params:Z})}handleItemStarted($){let Z=$?.item;if(!Z?.id){V$("ITEM_STARTED_MISSING_ID",{method:"item/started",params:$});return}if(Z.type==="userMessage"){let Q=Z.clientId;if(typeof Q==="string"&&$.threadId===this.sessionId&&this.steeringInputs?.get(Q)===$.turnId)this.steeringInputs.delete(Q),this.inputConsumptionOpen=!0,this.emit("user_input_consumed",{inputId:Q});return}if(this.inputConsumptionOpen&&$.turnId===this.currentTurnId)this.inputConsumptionOpen=!1,this.emit("input_batch_end",{itemId:Z.id});if(this.feedCollabItem(Z,"started"))return;let J=NZ(Z,this.opts.workDir);if(!J){V$("ITEM_STARTED_UNMAPPED",{method:"item/started",params:$});return}this.emit("tool_use",{id:Z.id,name:J.name,input:J.input})}handleSubagentItemStarted($){let Z=$?.item;if(!Z?.id)return;if(this.feedCollabItem(Z,"started"))return;this.emitSubagentStep(Z,"started",$)}handleSubagentItemCompleted($){let Z=$?.item;if(!Z?.id)return;if(Z.type==="agentMessage"){let J=typeof Z.text==="string"?Z.text:"";if(J){let Q=typeof $?.threadId==="string"?$.threadId:"";this.collabAgentSummaries.set(Q,J)}return}if(this.feedCollabItem(Z,"completed"))return;this.emitSubagentStep(Z,"completed",$)}handleItemCompleted($){let Z=$?.item;if(!Z?.id){V$("ITEM_COMPLETED_MISSING_ID",{method:"item/completed",params:$});return}if(Z.type==="userMessage")return;if(Z.type==="agentMessage"){this.lastAssistantUuid=Z.id,this.emit("assistant_block_stop",{index:Z.id,parentToolUseId:null});return}if(this.feedCollabItem(Z,"completed"))return;let J=lz(Z,this.opts.workDir,this.sessionId??void 0);if(!J){V$("ITEM_COMPLETED_UNMAPPED",{method:"item/completed",params:$});return}if(this.emit("tool_result",{tool_use_id:Z.id,content:J.output,is_error:J.isError,...Z.type==="imageGeneration"?{input:RZ(Z)}:{}}),Z.type==="imageGeneration")this.emittedImageGenerationIds.add(Z.id)}isSubagentThread($){let Z=typeof $?.threadId==="string"?$.threadId:"";return!!this.sessionId&&!!Z&&Z!==this.sessionId}handleThreadStatusChanged($){let Z=typeof $?.threadId==="string"?$.threadId:"",J=$?.status?.type;if(!Z||typeof J!=="string")return;if(!this.collabAgentNames?.has(Z))return;if(J==="active"){if(this.collabAgentWasActive.add(Z),this.collabAgentSettled.has(Z))this.collabAgentSettled.delete(Z),this.emit("bg_task_started",{task_id:Z,task_type:"local_agent",description:this.collabAgentNames.get(Z)??h0(Z)}),this.emit("bg_task_updated",{task_id:Z,patch:{is_backgrounded:!0}});this.emit("bg_task_updated",{task_id:Z,patch:{status:"running"}});return}if(J==="idle"||J==="systemError"){if(!this.collabAgentWasActive.has(Z))return;if(this.collabAgentSettled.has(Z))return;this.collabAgentSettled.add(Z),this.emit("bg_task_settled",{task_id:Z,status:J==="systemError"?"failed":"completed",summary:this.collabAgentSummaries.get(Z)??void 0})}}emitSubagentStep($,Z,J){let Q=typeof J?.threadId==="string"?J.threadId:"",Y=Z==="started"?NZ($,this.opts.workDir):lz($,this.opts.workDir,this.sessionId??void 0);if(!Y)return;let V="output"in Y&&typeof Y.output==="string"?Y.output:void 0;this.emit("subagent_step",{thread_id:Q,item_id:$.id,tool:Y.name,phase:Z,brief:TF(Y.name,Y.input,V)})}feedCollabItem($,Z){if($.type==="subAgentActivity"){let J=typeof $.agentThreadId==="string"?$.agentThreadId:"";if(!J)return!0;if($.kind==="started"&&!this.collabAgentNames.has(J)){let Q=p3($.agentPath,J);this.collabAgentNames.set(J,Q),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Q}),this.emit("bg_task_updated",{task_id:J,patch:{is_backgrounded:!0}})}else if($.kind==="started"){let Q=this.collabAgentNames.get(J),Y=p3($.agentPath,J);if(Q!==Y&&!this.collabAgentSettled.has(J))this.collabAgentNames.set(J,Y),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Y})}else if($.kind==="interrupted")this.emit("bg_task_updated",{task_id:J,patch:{status:"paused"}});return!0}if($.type==="collabAgentToolCall"){let J=$.agentsStates;if(J&&typeof J==="object")for(let[Q,Y]of Object.entries(J))this.translateAgentState(Q,Y,$);if($.tool==="closeAgent"&&Z==="completed"&&$.status!=="failed"){let Q=az($);for(let Y of Q){if(this.collabAgentSettled.has(Y))continue;if(this.collabAgentSettled.add(Y),!this.collabAgentNames.has(Y))this.collabAgentNames.set(Y,p3(null,Y));this.emit("bg_task_settled",{task_id:Y,status:"stopped"})}}if($.tool==="spawnAgent"){if(Z==="started")this.emit("tool_use",{id:$.id,name:"Agent",input:{tool:"spawnAgent",prompt:dz($.prompt),description:EF($),model:typeof $.model==="string"?$.model:void 0}});else if($.status!=="inProgress")this.emit("tool_result",{tool_use_id:$.id,content:SF($),is_error:$.status==="failed"})}return!0}return!1}translateAgentState($,Z,J){let Q=Z?.status;if(typeof Q!=="string")return;if(this.collabAgentSettled.has($)){if(Q!=="running"&&Q!=="pendingInit"){if(Q==="errored"||Q==="shutdown"||Q==="notFound"||Q==="interrupted")this.emit("bg_task_updated",{task_id:$,patch:{status:Q==="errored"?"failed":"killed",error:typeof Z?.message==="string"&&Z.message?Z.message:void 0}});return}this.collabAgentSettled.delete($);let V=this.collabAgentNames.get($)??p3(null,$);this.emit("bg_task_started",{task_id:$,task_type:"local_agent",description:V}),this.emit("bg_task_updated",{task_id:$,patch:{is_backgrounded:!0}})}if(!this.collabAgentNames.has($)){this.collabAgentNames.set($,"子 agent");let X={task_id:$,task_type:"local_agent",description:"子 agent",prompt:dz(J.prompt)};this.emit("bg_task_started",X);let z={task_id:$,patch:{is_backgrounded:!0}};this.emit("bg_task_updated",z)}if(Q==="running"||Q==="pendingInit"||Q==="interrupted"){let V={task_id:$,patch:{status:Q==="pendingInit"?"pending":Q==="interrupted"?"paused":"running"}};this.emit("bg_task_updated",V);return}if(this.collabAgentSettled.size>=5000)this.collabAgentSettled.clear();this.collabAgentSettled.add($);let Y={task_id:$,status:Q==="completed"?"completed":Q==="errored"?"failed":"stopped",summary:typeof Z?.message==="string"&&Z.message?Z.message:void 0};this.emit("bg_task_settled",Y)}primeRolloutImageGenerationScan(){if(this.rolloutFilePath=null,this.rolloutReadOffset=0,this.rolloutLineRemainder="",this.rolloutDecoder=new Iz("utf8"),this.emittedImageGenerationIds.clear(),!this.sessionId)return;let $=cz(this.sessionId);if(!$)return;this.rolloutFilePath=$;try{this.rolloutReadOffset=c3($).size,j(`codex-process: image generation rollout scan primed ${$} offset=${this.rolloutReadOffset}`)}catch(Z){j(`codex-process: image generation rollout stat failed ${$}: ${Z instanceof Error?Z.message:Z}`),this.rolloutFilePath=null,this.rolloutReadOffset=0}}flushRolloutImageGenerations(){if(!this.sessionId)return;let $=this.rolloutFilePath??cz(this.sessionId);if(!$){j(`codex-process: image generation rollout file not found for thread=${this.sessionId}`);return}this.rolloutFilePath=$;let Z;try{let Y=c3($).size;if(Y<=this.rolloutReadOffset)return;let V=Y-this.rolloutReadOffset;Z=Buffer.allocUnsafe(V);let X=QF($,"r"),z=0;try{while(z<V){let H=VF(X,Z,z,V-z,this.rolloutReadOffset+z);if(H===0)break;z+=H}}finally{$F(X)}Z=Z.subarray(0,z),this.rolloutReadOffset+=z}catch(Y){j(`codex-process: image generation rollout read failed ${$}: ${Y instanceof Error?Y.message:Y}`);return}let J=this.rolloutLineRemainder+this.rolloutDecoder.write(Z),Q=J.split(/\r?\n/);this.rolloutLineRemainder=J.endsWith(`
81
+ `))>=0){let J=this.stderrBuf.slice(0,Z);if(this.stderrBuf=this.stderrBuf.slice(Z+1),J.trim())j(`codex-process[stderr]: ${J}`)}}flushStderrTail(){let $=this.stderrBuf;if(this.stderrBuf="",$.trim())j(`codex-process[stderr]: ${$}`)}handleMessage($){if(Object.prototype.hasOwnProperty.call($,"id")&&!$.method){let J=this.pending.get($.id);if(!J){j(`codex-process: response for unknown id=${$.id}`);return}if(this.pending.delete($.id),clearTimeout(J.timeout),$.error){let Q=typeof $.error?.code==="number"?$.error.code:null,Y=typeof $.error==="string"?$.error:typeof $.error?.message==="string"?$.error.message:JSON.stringify($.error);J.reject(new P2(J.method,$.id,Q,Y,$.error?.data))}else J.resolve($.result);return}if(Object.prototype.hasOwnProperty.call($,"id")&&$.method){this.handleServerRequest($);return}if($.method){this.handleNotification($.method,$.params??{});return}let Z=jZ($);if(Z){let J=this.withSessionId(Z);KZ(Z.sourceMethod??"raw_message",$,J),this.emit("context_compacted",J);return}V$("RAW_MESSAGE",$),this.emit("raw",$)}handleNotification($,Z){if(this.isSubagentThread(Z)){if($==="thread/status/changed")this.handleThreadStatusChanged(Z);else if($==="item/started")this.handleSubagentItemStarted(Z);else if($==="item/completed")this.handleSubagentItemCompleted(Z);return}let J=BZ($,Z);if(J){let Q=this.withSessionId(J);KZ($,Z,Q),this.emit("context_compacted",Q);return}switch($){case"thread/started":{let Q=Z.thread;if(Q?.id)this.sessionId=Q.id;return}case"thread/settings/updated":{let Q=Z.threadSettings;if(typeof Q?.model==="string")this.lastModel=Q.model;if(U$(Q?.effort))this.lastEffort=Q.effort;if(Q?.collaborationMode)this.usesCustomDefaultModeInstructions=Q.collaborationMode.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string";return}case"thread/tokenUsage/updated":{let Q=U4(Z.tokenUsage?.last);if(Q)this.lastUsage=Q,this.lastResult.usage=this.lastUsage;else j("codex-process: tokenUsage notification missing last breakdown");this.lastTotalUsage=U4(Z.tokenUsage?.total);let Y=Z.tokenUsage?.modelContextWindow;if(typeof Y==="number"&&Y>0)this.lastContextWindow=Y;this.emit("token_usage",{usage:this.lastUsage,totalUsage:this.lastTotalUsage,contextWindow:this.lastContextWindow,threadId:Z.threadId,turnId:Z.turnId});return}case"turn/started":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_STARTED_THREAD_MISMATCH",{method:$,params:Z});return}this.recordTurnStarted(Z.turn,Z.threadId,"turn/started notification"),this.markConversationMaterialized("turn/started notification");return}case"turn/completed":{if(typeof Z.threadId!=="string"||Z.threadId!==this.sessionId){V$("TURN_COMPLETED_THREAD_MISMATCH",{method:$,params:Z});return}let Q=Z.turn??{},Y=typeof Q.id==="string"&&Q.id?Q.id:null;if(Y){if(this.finishedTurnIds?.has(Y)){j(`codex-process: duplicate turn/completed ignored turn=${Y}`);return}if(this.currentTurnId&&this.currentTurnId!==Y){this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y),j(`codex-process: stale turn/completed ignored turn=${Y} current=${this.currentTurnId}`);return}this.flushRolloutImageGenerations(),this.markConversationMaterialized("turn/completed notification"),this.markTurnStartTerminal(Y),this.rememberFinishedTurn(Y)}else V$("TURN_COMPLETED_MISSING_ID",{method:$,params:Z});let V=Q.status,X=V==="failed"&&this.turnError&&this.turnError.turnId===Y?this.turnError.error:null,z=Q.error&&X&&typeof Q.error.message==="string"&&Q.error.message===X.message?{...X,...Q.error,codexErrorInfo:Q.error.codexErrorInfo??X.codexErrorInfo,additionalDetails:Q.error.additionalDetails??X.additionalDetails}:Q.error??X;this.turnError=null;let H=V==="failed"||!!z,G=V==="completed"&&!H&&!!Y;this.lastCompletedTurnId=G?Y:null,this.currentTurnId=null,this.inputConsumptionOpen=!1;let W=AZ(z,!!Y&&this.routingTimeoutTurnId===Y);if(this.routingTimeoutTurnId=null,V==="failed"&&Y&&W&&this.scheduleTurnRetry(z.message,LD[W],W))return;this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1;let K=H?z?.type??z?.message??"failed":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof Q.durationMs==="number"?Q.durationMs:null,num_turns:1,usage:this.lastUsage,subtype:K,is_error:H};for(let[B,_]of this.steeringInputs??[])if(_===Y)this.steeringInputs.delete(B);this.emit("result",{subtype:K,is_error:H,...H&&typeof z?.message==="string"?{error:z.message}:{},...V==="failed"&&Y&&R4(z)?{codexQuotaFailure:{accepted:!0}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,turn_id:Y,checkpoint:G&&this.sessionId?{provider:"codex",kind:"turn",id:Y,source:{provider:"codex",sessionId:this.sessionId,cwd:this.opts.workDir}}:null});return}case"turn/plan/updated":{this.emit("turn_plan_updated",Z);return}case"item/plan/delta":{this.emit("plan_delta",Z);return}case"thread/goal/updated":{if(Z.goal)this.emit("thread_goal_updated",Z.goal);else j("codex-process: thread/goal/updated missing goal");return}case"thread/goal/cleared":{this.emit("thread_goal_cleared",Z);return}case"thread/status/changed":{this.handleThreadStatusChanged(Z);return}case"item/agentMessage/delta":{if(typeof Z.delta==="string"&&Z.delta.length>0)this.emit("assistant_text",{uuid:Z.itemId,text:Z.delta,parentToolUseId:null});else V$("AGENT_MESSAGE_DELTA_EMPTY",{method:$,params:Z});return}case"item/started":{this.handleItemStarted(Z);return}case"item/completed":{this.handleItemCompleted(Z);return}case"mcpServer/startupStatus/updated":{j(`codex-process: mcp ${Z.name} ${Z.status}${Z.error?`: ${Z.error}`:""}`);return}case"account/rateLimits/updated":{this.emit("rate_limits_updated",Z.rateLimits);return}case"configWarning":case"warning":case"guardianWarning":case"deprecationNotice":{j(`codex-process: ${$}: ${Z.summary??Z.message??JSON.stringify(Z).slice(0,200)}`);return}case"error":{j(`codex-process: server error: ${JSON.stringify(Z).slice(0,500)}`);let Q=Z.error??Z;if(typeof Z.turnId==="string"&&Z.threadId===this.sessionId&&!this.finishedTurnIds?.has(Z.turnId)&&(!this.currentTurnId||this.currentTurnId===Z.turnId)){if(this.turnError={turnId:Z.turnId,error:Q},Z.willRetry===!0&&[Q.message,Q.additionalDetails].some((Y)=>typeof Y==="string"&&/^workspace routing discovery timed out$/i.test(Y.trim())&&AZ({...Q,message:Y,additionalDetails:Y===Q.additionalDetails?Q.message:Q.additionalDetails})!==null))this.routingTimeoutTurnId=Z.turnId}this.emit("error",Error(Q.message??Q.summary??"codex app-server error"));return}}V$("NOTIFICATION",{method:$,params:Z}),this.emit("raw",{method:$,params:Z})}handleItemStarted($){let Z=$?.item;if(!Z?.id){V$("ITEM_STARTED_MISSING_ID",{method:"item/started",params:$});return}if(Z.type==="userMessage"){let Q=Z.clientId;if(typeof Q==="string"&&$.threadId===this.sessionId&&this.steeringInputs?.get(Q)===$.turnId)this.steeringInputs.delete(Q),this.inputConsumptionOpen=!0,this.emit("user_input_consumed",{inputId:Q});return}if(this.inputConsumptionOpen&&$.turnId===this.currentTurnId)this.inputConsumptionOpen=!1,this.emit("input_batch_end",{itemId:Z.id});if(this.feedCollabItem(Z,"started"))return;let J=NZ(Z,this.opts.workDir);if(!J){V$("ITEM_STARTED_UNMAPPED",{method:"item/started",params:$});return}this.emit("tool_use",{id:Z.id,name:J.name,input:J.input})}handleSubagentItemStarted($){let Z=$?.item;if(!Z?.id)return;if(this.feedCollabItem(Z,"started"))return;this.emitSubagentStep(Z,"started",$)}handleSubagentItemCompleted($){let Z=$?.item;if(!Z?.id)return;if(Z.type==="agentMessage"){let J=typeof Z.text==="string"?Z.text:"";if(J){let Q=typeof $?.threadId==="string"?$.threadId:"";this.collabAgentSummaries.set(Q,J)}return}if(this.feedCollabItem(Z,"completed"))return;this.emitSubagentStep(Z,"completed",$)}handleItemCompleted($){let Z=$?.item;if(!Z?.id){V$("ITEM_COMPLETED_MISSING_ID",{method:"item/completed",params:$});return}if(Z.type==="userMessage")return;if(Z.type==="agentMessage"){this.lastAssistantUuid=Z.id,this.emit("assistant_block_stop",{index:Z.id,parentToolUseId:null});return}if(this.feedCollabItem(Z,"completed"))return;let J=lz(Z,this.opts.workDir,this.sessionId??void 0);if(!J){V$("ITEM_COMPLETED_UNMAPPED",{method:"item/completed",params:$});return}if(this.emit("tool_result",{tool_use_id:Z.id,content:J.output,is_error:J.isError,...Z.type==="imageGeneration"?{input:RZ(Z)}:{}}),Z.type==="imageGeneration")this.emittedImageGenerationIds.add(Z.id)}isSubagentThread($){let Z=typeof $?.threadId==="string"?$.threadId:"";return!!this.sessionId&&!!Z&&Z!==this.sessionId}handleThreadStatusChanged($){let Z=typeof $?.threadId==="string"?$.threadId:"",J=$?.status?.type;if(!Z||typeof J!=="string")return;if(!this.collabAgentNames?.has(Z))return;if(J==="active"){if(this.collabAgentWasActive.add(Z),this.collabAgentSettled.has(Z))this.collabAgentSettled.delete(Z),this.emit("bg_task_started",{task_id:Z,task_type:"local_agent",description:this.collabAgentNames.get(Z)??h0(Z)}),this.emit("bg_task_updated",{task_id:Z,patch:{is_backgrounded:!0}});this.emit("bg_task_updated",{task_id:Z,patch:{status:"running"}});return}if(J==="idle"||J==="systemError"){if(!this.collabAgentWasActive.has(Z))return;if(this.collabAgentSettled.has(Z))return;this.collabAgentSettled.add(Z),this.emit("bg_task_settled",{task_id:Z,status:J==="systemError"?"failed":"completed",summary:this.collabAgentSummaries.get(Z)??void 0})}}emitSubagentStep($,Z,J){let Q=typeof J?.threadId==="string"?J.threadId:"",Y=Z==="started"?NZ($,this.opts.workDir):lz($,this.opts.workDir,this.sessionId??void 0);if(!Y)return;let V="output"in Y&&typeof Y.output==="string"?Y.output:void 0;this.emit("subagent_step",{thread_id:Q,item_id:$.id,tool:Y.name,phase:Z,brief:TD(Y.name,Y.input,V)})}feedCollabItem($,Z){if($.type==="subAgentActivity"){let J=typeof $.agentThreadId==="string"?$.agentThreadId:"";if(!J)return!0;if($.kind==="started"&&!this.collabAgentNames.has(J)){let Q=p3($.agentPath,J);this.collabAgentNames.set(J,Q),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Q}),this.emit("bg_task_updated",{task_id:J,patch:{is_backgrounded:!0}})}else if($.kind==="started"){let Q=this.collabAgentNames.get(J),Y=p3($.agentPath,J);if(Q!==Y&&!this.collabAgentSettled.has(J))this.collabAgentNames.set(J,Y),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Y})}else if($.kind==="interrupted")this.emit("bg_task_updated",{task_id:J,patch:{status:"paused"}});return!0}if($.type==="collabAgentToolCall"){let J=$.agentsStates;if(J&&typeof J==="object")for(let[Q,Y]of Object.entries(J))this.translateAgentState(Q,Y,$);if($.tool==="closeAgent"&&Z==="completed"&&$.status!=="failed"){let Q=az($);for(let Y of Q){if(this.collabAgentSettled.has(Y))continue;if(this.collabAgentSettled.add(Y),!this.collabAgentNames.has(Y))this.collabAgentNames.set(Y,p3(null,Y));this.emit("bg_task_settled",{task_id:Y,status:"stopped"})}}if($.tool==="spawnAgent"){if(Z==="started")this.emit("tool_use",{id:$.id,name:"Agent",input:{tool:"spawnAgent",prompt:dz($.prompt),description:ED($),model:typeof $.model==="string"?$.model:void 0}});else if($.status!=="inProgress")this.emit("tool_result",{tool_use_id:$.id,content:SD($),is_error:$.status==="failed"})}return!0}return!1}translateAgentState($,Z,J){let Q=Z?.status;if(typeof Q!=="string")return;if(this.collabAgentSettled.has($)){if(Q!=="running"&&Q!=="pendingInit"){if(Q==="errored"||Q==="shutdown"||Q==="notFound"||Q==="interrupted")this.emit("bg_task_updated",{task_id:$,patch:{status:Q==="errored"?"failed":"killed",error:typeof Z?.message==="string"&&Z.message?Z.message:void 0}});return}this.collabAgentSettled.delete($);let V=this.collabAgentNames.get($)??p3(null,$);this.emit("bg_task_started",{task_id:$,task_type:"local_agent",description:V}),this.emit("bg_task_updated",{task_id:$,patch:{is_backgrounded:!0}})}if(!this.collabAgentNames.has($)){this.collabAgentNames.set($,"子 agent");let X={task_id:$,task_type:"local_agent",description:"子 agent",prompt:dz(J.prompt)};this.emit("bg_task_started",X);let z={task_id:$,patch:{is_backgrounded:!0}};this.emit("bg_task_updated",z)}if(Q==="running"||Q==="pendingInit"||Q==="interrupted"){let V={task_id:$,patch:{status:Q==="pendingInit"?"pending":Q==="interrupted"?"paused":"running"}};this.emit("bg_task_updated",V);return}if(this.collabAgentSettled.size>=5000)this.collabAgentSettled.clear();this.collabAgentSettled.add($);let Y={task_id:$,status:Q==="completed"?"completed":Q==="errored"?"failed":"stopped",summary:typeof Z?.message==="string"&&Z.message?Z.message:void 0};this.emit("bg_task_settled",Y)}primeRolloutImageGenerationScan(){if(this.rolloutFilePath=null,this.rolloutReadOffset=0,this.rolloutLineRemainder="",this.rolloutDecoder=new Iz("utf8"),this.emittedImageGenerationIds.clear(),!this.sessionId)return;let $=cz(this.sessionId);if(!$)return;this.rolloutFilePath=$;try{this.rolloutReadOffset=c3($).size,j(`codex-process: image generation rollout scan primed ${$} offset=${this.rolloutReadOffset}`)}catch(Z){j(`codex-process: image generation rollout stat failed ${$}: ${Z instanceof Error?Z.message:Z}`),this.rolloutFilePath=null,this.rolloutReadOffset=0}}flushRolloutImageGenerations(){if(!this.sessionId)return;let $=this.rolloutFilePath??cz(this.sessionId);if(!$){j(`codex-process: image generation rollout file not found for thread=${this.sessionId}`);return}this.rolloutFilePath=$;let Z;try{let Y=c3($).size;if(Y<=this.rolloutReadOffset)return;let V=Y-this.rolloutReadOffset;Z=Buffer.allocUnsafe(V);let X=QD($,"r"),z=0;try{while(z<V){let H=VD(X,Z,z,V-z,this.rolloutReadOffset+z);if(H===0)break;z+=H}}finally{$D(X)}Z=Z.subarray(0,z),this.rolloutReadOffset+=z}catch(Y){j(`codex-process: image generation rollout read failed ${$}: ${Y instanceof Error?Y.message:Y}`);return}let J=this.rolloutLineRemainder+this.rolloutDecoder.write(Z),Q=J.split(/\r?\n/);this.rolloutLineRemainder=J.endsWith(`
82
82
  `)?"":Q.pop()??"";for(let Y of Q){if(!Y.trim())continue;let V;try{V=JSON.parse(Y)}catch(H){j(`codex-process: image generation rollout JSON parse failed ${$}: ${H instanceof Error?H.message:H}`);continue}let X=V?.payload,z=X?.type;if(z!=="image_generation_end"&&z!=="image_generation_call")continue;this.emitRolloutImageGeneration(X)}}emitRolloutImageGeneration($){let Z=typeof $?.call_id==="string"?$.call_id:typeof $?.id==="string"?$.id:"";if(!Z||this.emittedImageGenerationIds.has(Z))return;let J=iz($,this.sessionId??void 0);if(!J)return;let Q=$?.status==="failed",Y=$?.status==="generating"&&hz(J)?"completed":$?.status;this.emittedImageGenerationIds.add(Z),this.emit("tool_use",{id:Z,name:"ImageGeneration",input:RZ({...$,status:Y})}),this.emit("tool_result",{tool_use_id:Z,content:J,is_error:Q})}withSessionId($){let Z=$.sessionId??this.sessionId??void 0;return Z?{...$,sessionId:Z}:$}handleServerRequest($){let Z=String($.id);switch(this.serverRequests.set(Z,{id:$.id,method:$.method,params:$.params}),$.method){case"item/commandExecution/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"Bash",input:{command:J.command,cwd:J.cwd,reason:J.reason},tool_use_id:J.itemId});return}case"item/fileChange/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"FileChange",input:{reason:J.reason,grantRoot:J.grantRoot},tool_use_id:J.itemId});return}case"item/tool/requestUserInput":{let J=$.params??{},Q={questions:(J.questions??[]).map((Y)=>({id:Y.id,header:Y.header,question:Y.question,options:Array.isArray(Y.options)&&Y.options.length?Y.options.map((V)=>({label:V.label,description:V.description})):[{label:"自定义回答",description:Y.isSecret?"请直接在群里回复":"可直接在群里回复"}]}))};this.emit("tool_use",{id:J.itemId,name:"AskUserQuestion",input:Q}),this.emit("can_use_tool",{request_id:Z,tool_name:"AskUserQuestion",input:Q,tool_use_id:J.itemId});return}case"item/permissions/requestApproval":{let J=$.params??{};this.emit("can_use_tool",{request_id:Z,tool_name:"PermissionProfile",input:{cwd:J.cwd,reason:J.reason,permissions:J.permissions},tool_use_id:J.itemId});return}case"item/tool/call":{let J=$.params??{};this.emit("tool_use",{id:J.callId,name:J.namespace?`${J.namespace}.${J.tool}`:J.tool,input:J.arguments}),this.respond(Z,{contentItems:[{type:"inputText",text:"Lodestar does not implement this dynamic tool."}],success:!1});return}case"account/chatgptAuthTokens/refresh":case"attestation/generate":case"applyPatchApproval":case"execCommandApproval":default:V$("SERVER_REQUEST_UNSUPPORTED",$),this.respondError(Z,`unsupported server request: ${$.method}`)}}write($,Z){let J=(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));return j(`codex-process: stdin write failed: ${Y.message}`),Z?.(Y),!1};if(!this.alive)return J(Error(`write to dead process: ${JSON.stringify($).slice(0,200)}`));if(!this.proc||this.proc.stdin.destroyed||this.proc.stdin.writableEnded||!this.proc.stdin.writable)return J(Error("stdin is not writable"));try{return this.proc.stdin.write(JSON.stringify($)+`
83
- `,(Q)=>{if(Q)J(Q)}),!0}catch(Q){return J(Q)}}request($,Z,J=BF){let Q=++this.requestCounter;return new Promise((Y,V)=>{let X=setTimeout(()=>{let H=this.pending.get(Q);if(!H)return;this.pending.delete(Q),H.reject(Error(`codex app-server ${$} request timed out after ${J}ms (id=${Q})`))},Math.max(0,J)),z={resolve:Y,reject:V,method:$,timeout:X};this.pending.set(Q,z),this.write({id:Q,method:$,params:Z},(H)=>{if(this.pending.get(Q)!==z)return;this.pending.delete(Q),clearTimeout(X),V(Error(`codex app-server ${$} request write failed (id=${Q}): ${H.message}`,{cause:H}))})})}rejectPendingRequests($){for(let[Z,J]of this.pending)clearTimeout(J.timeout),J.reject($(Z,J));this.pending.clear()}respond($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,result:Z})}respondError($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,error:{code:-32601,message:Z}})}sendInitialize(){if(!this.readyPromise)this.readyPromise=this.initializeAndStartThread(),this.readyPromise.catch(($)=>{j(`codex-process: initialize failed: ${$}`),this.emit("error",$)})}initializationPromise(){if(!this.readyPromise)this.sendInitialize();return this.readyPromise}isConversationResumable(){return this.conversationResumable}conversationMaterializationBarrier(){return this.conversationMaterializationVerification?this.drainConversationMaterialization():null}conversationMaterializationFailure(){return this.lastConversationMaterializationFailure}async drainConversationMaterialization(){while(this.conversationMaterializationVerification){let $=this.conversationMaterializationVerification;try{await $}catch{}await Promise.resolve()}if(!this.conversationResumable&&this.lastConversationMaterializationFailure)throw this.lastConversationMaterializationFailure}async readRateLimits(){return await this.ensureInitialized(),this.request("account/rateLimits/read",{})}initializeParams(){return{clientInfo:{name:"lodestar",version:"0.0.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}}async ensureInitialized(){if(this.startupPromise)await this.startupPromise;if(!this.initializePromise)this.initializePromise=this.request("initialize",this.initializeParams()).then(()=>{if(!this.write({method:"initialized"}))throw Error("codex app-server initialized notification write failed")});await this.initializePromise}async initializeAndStartThread(){let $=this.conversationLaunch();await this.ensureInitialized();let Z=this.threadParams(),J,Q;if($.kind==="resume")J="thread/resume",Q=await this.request(J,{threadId:$.source.sessionId,...Z,excludeTurns:!0,persistExtendedHistory:!1});else if($.kind==="fork")J="thread/fork",Q=await this.request(J,{threadId:$.source.sessionId,...$.through?{lastTurnId:$.through.id}:{},...Z,excludeTurns:!0});else J="thread/start",Q=await this.request(J,{...Z,experimentalRawEvents:!1,persistExtendedHistory:!1});let Y=Q?.thread;if(typeof Y?.id!=="string"||!Y.id)throw Error(`codex app-server ${J} returned no thread.id`);let V=typeof Y.cwd==="string"?Y.cwd:typeof Q?.cwd==="string"?Q.cwd:null;if(V!==this.opts.workDir)throw Error(`codex app-server ${J} returned cwd=${V??"MISS"}, expected ${this.opts.workDir}`);if($.kind==="fork"&&Y.id===$.source.sessionId)throw Error(`codex app-server thread/fork returned source thread id ${Y.id}`);if($.kind==="resume"&&Y.id!==$.source.sessionId)throw Error(`codex app-server thread/resume returned thread id ${Y.id}, expected ${$.source.sessionId}`);let X=typeof Y.path==="string"&&Y.path?Y.path:null;if(!X||!hz(X)||!X.endsWith(`${Y.id}.jsonl`))throw Error(`codex app-server ${J} returned invalid thread.path=${X??"MISS"}`);if(this.sessionId=Y.id,this.conversationRolloutPath=X,this.conversationResumable=!1,$.kind!=="fresh")await this.verifyConversationMaterialized(`${J} response`),this.conversationResumable=!0;if(Q?.model)this.lastModel=Q.model;if(this.usesCustomDefaultModeInstructions=Q?.collaborationMode?.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string",U$(Q?.reasoningEffort))this.lastEffort=Q.reasoningEffort;else this.lastEffort=this.opts.effort??null;j(`codex-process: thread=${this.sessionId}`),this.primeRolloutImageGenerationScan(),this.emit("init",{session_id:this.sessionId,thread:Y})}markConversationMaterialized($){if(this.conversationResumable)return;if(!this.sessionId)throw Error(`codex ${$} arrived before thread initialization`);if(this.conversationMaterializationVerification){this.conversationMaterializationRetrySource=$;return}let Z=this.sessionId,J=this.verifyConversationMaterialized($);this.conversationMaterializationVerification=J,J.then(()=>{if(this.sessionId!==Z||this.conversationResumable)return;this.lastConversationMaterializationFailure=null,this.conversationResumable=!0,j(`codex-process: conversation materialized thread=${Z} source=${$}`),this.emit("conversation_materialized",{session_id:Z,source:$})},(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));this.lastConversationMaterializationFailure=Y,j(`codex-process: conversation materialization check failed thread=${Z} source=${$}: ${Y.message}`),this.emit("conversation_materialization_failed",{session_id:Z,path:this.conversationRolloutPath,source:$,error:Y})}).finally(()=>{if(this.conversationMaterializationVerification===J)this.conversationMaterializationVerification=null;let Q=this.conversationMaterializationRetrySource;if(this.conversationMaterializationRetrySource=null,!this.conversationResumable&&Q)this.markConversationMaterialized(Q)})}async verifyConversationMaterialized($){let Z=this.sessionId,J=this.conversationRolloutPath;if(!Z||!J)throw Error(`codex ${$} has no initialized rollout identity`);let Y=(await this.request("thread/read",{threadId:Z,includeTurns:!0},jF))?.thread;if(Y?.id!==Z||Y.cwd!==this.opts.workDir||Y.path!==J||!Array.isArray(Y.turns))throw Error(`codex ${$} thread/read returned an invalid materialized thread`);this.assertConversationRolloutMaterialized($)}assertConversationRolloutMaterialized($){let Z=this.conversationRolloutPath;if(!Z)throw Error(`codex ${$} has no authoritative rollout path`);let J;try{J=c3(Z)}catch(Q){throw Error(`codex ${$} rollout is not readable at ${Z}: ${Q instanceof Error?Q.message:Q}`,{cause:Q})}if(!J.isFile())throw Error(`codex ${$} rollout path is not a file: ${Z}`)}conversationLaunch(){let $=this.opts.launch??{kind:"fresh"};if(E0($,"codex",this.opts.workDir),$.kind!=="fresh"&&(typeof $.source.sessionId!=="string"||!$.source.sessionId))throw Error(`codex ${$.kind} launch requires a source session id`);if($.kind==="fork"&&$.through){if($.through.provider!=="codex"||$.through.kind!=="turn")throw Error("codex fork through checkpoint must be a codex turn checkpoint");if(typeof $.through.id!=="string"||!$.through.id)throw Error("codex fork through checkpoint requires a turn id")}return $}threadParams(){return{cwd:this.opts.workDir,runtimeWorkspaceRoots:[this.opts.workDir],approvalPolicy:"never",sandbox:"danger-full-access",config:{"tools.experimental_request_user_input.enabled":this.opts.allowUserInput!==!1,"features.default_mode_request_user_input":this.opts.allowUserInput!==!1,...this.opts.effort?{model_reasoning_effort:this.opts.effort}:{}},...this.opts.model?{model:this.opts.model}:{},...this.opts.apiProvider?{modelProvider:this.opts.apiProvider.id}:this.opts.tokenSourceId==="codex-sub"?{modelProvider:"openai"}:{},...this.opts.appendSystemPrompt?{developerInstructions:this.opts.appendSystemPrompt}:{},serviceName:this.opts.serviceName??"lodestar"}}sendUserText($,Z=[]){let J=Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
83
+ `,(Q)=>{if(Q)J(Q)}),!0}catch(Q){return J(Q)}}request($,Z,J=BD){let Q=++this.requestCounter;return new Promise((Y,V)=>{let X=setTimeout(()=>{let H=this.pending.get(Q);if(!H)return;this.pending.delete(Q),H.reject(Error(`codex app-server ${$} request timed out after ${J}ms (id=${Q})`))},Math.max(0,J)),z={resolve:Y,reject:V,method:$,timeout:X};this.pending.set(Q,z),this.write({id:Q,method:$,params:Z},(H)=>{if(this.pending.get(Q)!==z)return;this.pending.delete(Q),clearTimeout(X),V(Error(`codex app-server ${$} request write failed (id=${Q}): ${H.message}`,{cause:H}))})})}rejectPendingRequests($){for(let[Z,J]of this.pending)clearTimeout(J.timeout),J.reject($(Z,J));this.pending.clear()}respond($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,result:Z})}respondError($,Z){let J=String($),Q=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Q?.id??$,error:{code:-32601,message:Z}})}sendInitialize(){if(!this.readyPromise)this.readyPromise=this.initializeAndStartThread(),this.readyPromise.catch(($)=>{j(`codex-process: initialize failed: ${$}`),this.emit("error",$)})}initializationPromise(){if(!this.readyPromise)this.sendInitialize();return this.readyPromise}isConversationResumable(){return this.conversationResumable}conversationMaterializationBarrier(){return this.conversationMaterializationVerification?this.drainConversationMaterialization():null}conversationMaterializationFailure(){return this.lastConversationMaterializationFailure}async drainConversationMaterialization(){while(this.conversationMaterializationVerification){let $=this.conversationMaterializationVerification;try{await $}catch{}await Promise.resolve()}if(!this.conversationResumable&&this.lastConversationMaterializationFailure)throw this.lastConversationMaterializationFailure}async readRateLimits(){return await this.ensureInitialized(),this.request("account/rateLimits/read",{})}initializeParams(){return{clientInfo:{name:"lodestar",version:"0.0.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}}async ensureInitialized(){if(this.startupPromise)await this.startupPromise;if(!this.initializePromise)this.initializePromise=this.request("initialize",this.initializeParams()).then(()=>{if(!this.write({method:"initialized"}))throw Error("codex app-server initialized notification write failed")});await this.initializePromise}async initializeAndStartThread(){let $=this.conversationLaunch();await this.ensureInitialized();let Z=this.threadParams(),J,Q;if($.kind==="resume")J="thread/resume",Q=await this.request(J,{threadId:$.source.sessionId,...Z,excludeTurns:!0,persistExtendedHistory:!1});else if($.kind==="fork")J="thread/fork",Q=await this.request(J,{threadId:$.source.sessionId,...$.through?{lastTurnId:$.through.id}:{},...Z,excludeTurns:!0});else J="thread/start",Q=await this.request(J,{...Z,experimentalRawEvents:!1,persistExtendedHistory:!1});let Y=Q?.thread;if(typeof Y?.id!=="string"||!Y.id)throw Error(`codex app-server ${J} returned no thread.id`);let V=typeof Y.cwd==="string"?Y.cwd:typeof Q?.cwd==="string"?Q.cwd:null;if(V!==this.opts.workDir)throw Error(`codex app-server ${J} returned cwd=${V??"MISS"}, expected ${this.opts.workDir}`);if($.kind==="fork"&&Y.id===$.source.sessionId)throw Error(`codex app-server thread/fork returned source thread id ${Y.id}`);if($.kind==="resume"&&Y.id!==$.source.sessionId)throw Error(`codex app-server thread/resume returned thread id ${Y.id}, expected ${$.source.sessionId}`);let X=typeof Y.path==="string"&&Y.path?Y.path:null;if(!X||!hz(X)||!X.endsWith(`${Y.id}.jsonl`))throw Error(`codex app-server ${J} returned invalid thread.path=${X??"MISS"}`);if(this.sessionId=Y.id,this.conversationRolloutPath=X,this.conversationResumable=!1,$.kind!=="fresh")await this.verifyConversationMaterialized(`${J} response`),this.conversationResumable=!0;if(Q?.model)this.lastModel=Q.model;if(this.usesCustomDefaultModeInstructions=Q?.collaborationMode?.mode==="default"&&typeof Q.collaborationMode.settings?.developer_instructions==="string",U$(Q?.reasoningEffort))this.lastEffort=Q.reasoningEffort;else this.lastEffort=this.opts.effort??null;j(`codex-process: thread=${this.sessionId}`),this.primeRolloutImageGenerationScan(),this.emit("init",{session_id:this.sessionId,thread:Y})}markConversationMaterialized($){if(this.conversationResumable)return;if(!this.sessionId)throw Error(`codex ${$} arrived before thread initialization`);if(this.conversationMaterializationVerification){this.conversationMaterializationRetrySource=$;return}let Z=this.sessionId,J=this.verifyConversationMaterialized($);this.conversationMaterializationVerification=J,J.then(()=>{if(this.sessionId!==Z||this.conversationResumable)return;this.lastConversationMaterializationFailure=null,this.conversationResumable=!0,j(`codex-process: conversation materialized thread=${Z} source=${$}`),this.emit("conversation_materialized",{session_id:Z,source:$})},(Q)=>{let Y=Q instanceof Error?Q:Error(String(Q));this.lastConversationMaterializationFailure=Y,j(`codex-process: conversation materialization check failed thread=${Z} source=${$}: ${Y.message}`),this.emit("conversation_materialization_failed",{session_id:Z,path:this.conversationRolloutPath,source:$,error:Y})}).finally(()=>{if(this.conversationMaterializationVerification===J)this.conversationMaterializationVerification=null;let Q=this.conversationMaterializationRetrySource;if(this.conversationMaterializationRetrySource=null,!this.conversationResumable&&Q)this.markConversationMaterialized(Q)})}async verifyConversationMaterialized($){let Z=this.sessionId,J=this.conversationRolloutPath;if(!Z||!J)throw Error(`codex ${$} has no initialized rollout identity`);let Y=(await this.request("thread/read",{threadId:Z,includeTurns:!0},jD))?.thread;if(Y?.id!==Z||Y.cwd!==this.opts.workDir||Y.path!==J||!Array.isArray(Y.turns))throw Error(`codex ${$} thread/read returned an invalid materialized thread`);this.assertConversationRolloutMaterialized($)}assertConversationRolloutMaterialized($){let Z=this.conversationRolloutPath;if(!Z)throw Error(`codex ${$} has no authoritative rollout path`);let J;try{J=c3(Z)}catch(Q){throw Error(`codex ${$} rollout is not readable at ${Z}: ${Q instanceof Error?Q.message:Q}`,{cause:Q})}if(!J.isFile())throw Error(`codex ${$} rollout path is not a file: ${Z}`)}conversationLaunch(){let $=this.opts.launch??{kind:"fresh"};if(E0($,"codex",this.opts.workDir),$.kind!=="fresh"&&(typeof $.source.sessionId!=="string"||!$.source.sessionId))throw Error(`codex ${$.kind} launch requires a source session id`);if($.kind==="fork"&&$.through){if($.through.provider!=="codex"||$.through.kind!=="turn")throw Error("codex fork through checkpoint must be a codex turn checkpoint");if(typeof $.through.id!=="string"||!$.through.id)throw Error("codex fork through checkpoint requires a turn id")}return $}threadParams(){return{cwd:this.opts.workDir,runtimeWorkspaceRoots:[this.opts.workDir],approvalPolicy:"never",sandbox:"danger-full-access",config:{"tools.experimental_request_user_input.enabled":this.opts.allowUserInput!==!1,"features.default_mode_request_user_input":this.opts.allowUserInput!==!1,...this.opts.effort?{model_reasoning_effort:this.opts.effort}:{}},...this.opts.model?{model:this.opts.model}:{},...this.opts.apiProvider?{modelProvider:this.opts.apiProvider.id}:this.opts.tokenSourceId==="codex-sub"?{modelProvider:"openai"}:{},...this.opts.appendSystemPrompt?{developerInstructions:this.opts.appendSystemPrompt}:{},serviceName:this.opts.serviceName??"lodestar"}}sendUserText($,Z=[]){let J=Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
84
84
 
85
- `:"";this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1,this.turnRetryEnabled=!0,this.turnError=null,this.routingTimeoutTurnId=null;let Q=this.beginTurnStart(J+$);this.startTurn(J+$,Q).catch((Y)=>this.failTurnStart(Y,Q))}async steerUserText($,Z=[],J=HF()){if(!this.alive||this.expectedExit)throw Error("Codex 进程已关闭");let Q=this.currentTurnId;if(!Q)return!1;let Y=Z.length?Z.map((X)=>`[file: ${X}]`).join(" ")+`
85
+ `:"";this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1,this.turnRetryEnabled=!0,this.turnError=null,this.routingTimeoutTurnId=null;let Q=this.beginTurnStart(J+$);this.startTurn(J+$,Q).catch((Y)=>this.failTurnStart(Y,Q))}async steerUserText($,Z=[],J=HD()){if(!this.alive||this.expectedExit)throw Error("Codex 进程已关闭");let Q=this.currentTurnId;if(!Q)return!1;let Y=Z.length?Z.map((X)=>`[file: ${X}]`).join(" ")+`
86
86
 
87
- `:"";this.steeringInputs??=new Map,this.steeringInputs.set(J,Q);let V;try{V=await this.request("turn/steer",{threadId:this.sessionId,expectedTurnId:Q,clientUserMessageId:J,input:[{type:"text",text:Y+$,text_elements:[]}]})}catch(X){if(X instanceof P2)this.steeringInputs.delete(J);throw X}if(V?.turnId!==Q)throw Error("Codex turn/steer 未确认目标回合,追加消息的接收状态未知");return!0}async listModels(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Q=await this.request("model/list",{cursor:J,limit:100,includeHidden:!1});if(!Array.isArray(Q?.data))throw Error("model/list returned no data array");for(let V of Q.data){if(typeof V?.model!=="string"||!V.model)continue;$.push({id:typeof V.id==="string"&&V.id?V.id:V.model,model:V.model,displayName:typeof V.displayName==="string"&&V.displayName?V.displayName:V.model,description:typeof V.description==="string"?V.description:"",hidden:V.hidden===!0,isDefault:V.isDefault===!0,supportedReasoningEfforts:MF(V.supportedReasoningEfforts),defaultReasoningEffort:U$(V.defaultReasoningEffort)?V.defaultReasoningEffort:null})}let Y=Q?.nextCursor;if(Y!==null&&typeof Y!=="string")throw Error("model/list returned an invalid nextCursor");if(J=Y||null,J){if(Z.has(J))throw Error("model/list returned a repeated nextCursor");Z.add(J)}}while(J);return $}async listConversations(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Q=await this.request("thread/list",{cursor:J,limit:100,sortKey:"updated_at",sortDirection:"desc",cwd:this.opts.workDir});if(!Array.isArray(Q?.data))throw Error("thread/list returned no data array");for(let V of Q.data){if(typeof V?.id!=="string"||!V.id||typeof V.preview!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt)||typeof V.cwd!=="string"||V.cwd!==this.opts.workDir)throw Error("thread/list returned an invalid thread summary");let X=typeof V.status==="string"?V.status:typeof V.status?.type==="string"?V.status.type:void 0;if(N4("codex",V.id))continue;$.push({provider:"codex",sessionId:V.id,cwd:V.cwd,preview:V.preview,ts:V.updatedAt*1000,...X?{status:X}:{}})}let Y=Q?.nextCursor;if(Y!==null&&typeof Y!=="string")throw Error("thread/list returned an invalid nextCursor");if(Y&&Z.has(Y))throw Error(`thread/list repeated pagination cursor ${Y}`);if(Y)Z.add(Y);J=Y}while(J);return $}async readConversationRef($){if(!$.trim())throw Error("thread/read requires a session id");await this.ensureInitialized();let J=(await this.request("thread/read",{threadId:$,includeTurns:!1}))?.thread;if(J?.id!==$||typeof J.cwd!=="string")throw Error("thread/read returned an invalid conversation reference");return{provider:"codex",sessionId:$,cwd:J.cwd}}async setModelSettings($,Z){j("codex-process: model settings require a process restart")}async compactThread(){if(!this.readyPromise)throw Error("codex thread not initialized");if(await this.readyPromise,!this.sessionId)throw Error("codex thread not initialized");if(this.currentTurnId||this.turnRetry||this.turnStartOwner&&!this.turnStartOwner.terminal)throw Error("codex cannot manually compact while a task is active");this.turnRetryEnabled=!1,await this.request("thread/compact/start",{threadId:this.sessionId})}failTurnStart($,Z){if(!this.ownsTurnStartFailure(Z)){j(`codex-process: ignored stale turn/start failure generation=${Z.generation}`);return}this.turnStartOwner=null,Z.terminal=!0;let J=$ instanceof Error?$.message:String($);if(j(`codex-process: turn/start failed: ${J}`),$ instanceof P2&&$.method==="turn/start"&&Z.inputText!==void 0){let Q=AZ({...$.serverData&&typeof $.serverData==="object"?$.serverData:{},message:$.serverMessage});if(Q&&this.scheduleTurnRetry($.serverMessage,Z.inputText,Q))return}this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"codex_turn_start_failed",is_error:!0},this.currentTurnId=null,this.lastCompletedTurnId=null,this.emit("result",{subtype:this.lastResult.subtype,is_error:!0,duration_ms:null,usage:this.lastUsage,error:J,...$ instanceof P2&&$.method==="turn/start"&&Z.inputText!==void 0&&(R4($.serverData)||R4({message:$.serverMessage}))?{codexQuotaFailure:{accepted:!1,rejectedInput:Z.inputText}}:{}})}recordTurnStarted($,Z,J,Q){let Y=typeof $?.id==="string"&&$.id?$.id:null;if(!Y)throw Error(`codex app-server ${J} returned no turn.id`);if(this.finishedTurnIds?.has(Y))return;let V=Q??this.turnStartOwner;if(V?.interrupted){if(this.rememberFinishedTurn(Y),this.turnStartOwner===V)this.turnStartOwner=null;this.interruptTurn(Y);return}this.confirmTurnStart(Y,Q);let X=this.currentTurnId!==Y;if(this.currentTurnId=Y,!X)return;let z=this.turnRetryHasStarted&&(this.turnRetryCount??0)>0;if(this.turnRetryHasStarted=!0,this.turnRetryTimer&&this.turnRetry){let H={...this.turnRetry,phase:"retrying",delayMs:0};this.cancelTurnRetry(),this.emit("turn_retry",H)}this.turnRetry=null,this.lastCompletedTurnId=null,this.emit("turn_started",{turn_id:Y,thread_id:typeof Z==="string"&&Z?Z:this.sessionId,...z?{retry:!0}:{}})}beginTurnStart($){let Z={generation:(this.turnStartGeneration??0)+1,turnId:null,confirmed:!1,terminal:!1,inputText:$};return this.turnStartGeneration=Z.generation,this.turnStartOwner=Z,Z}confirmTurnStart($,Z){if(!this.turnStartOwnersByTurnId)this.turnStartOwnersByTurnId=new Map;let J=Z??this.turnStartOwnersByTurnId.get($)??this.turnStartOwner;if(!J)return;if(J.turnId&&J.turnId!==$)throw Error(`codex turn/start generation=${J.generation} changed turn id from ${J.turnId} to ${$}`);if(J.terminal)return;J.turnId=$,J.confirmed=!0,this.turnStartOwnersByTurnId.set($,J)}markTurnStartTerminal($){if(!this.turnStartOwnersByTurnId)this.turnStartOwnersByTurnId=new Map;let Z=this.turnStartOwnersByTurnId.get($);if(!Z&&this.turnStartOwner&&(!this.currentTurnId||this.currentTurnId===$))Z=this.turnStartOwner,this.confirmTurnStart($,Z);if(!Z)return;if(Z.confirmed=!0,Z.terminal=!0,this.turnStartOwnersByTurnId.delete($),this.turnStartOwner===Z)this.turnStartOwner=null}ownsTurnStartFailure($){return this.turnStartOwner===$&&!$.confirmed&&!$.terminal}rememberFinishedTurn($){if(!this.finishedTurnIds)this.finishedTurnIds=new Set;if(this.finishedTurnIds.add($),this.finishedTurnIds.size<=64)return;let Z=this.finishedTurnIds.values().next().value;if(typeof Z==="string")this.finishedTurnIds.delete(Z)}async startTurn($,Z){let J=Z??this.beginTurnStart($);this.lastCompletedTurnId=null;try{if(!this.readyPromise)this.sendInitialize();if(await this.readyPromise,J.interrupted||this.expectedExit||!this.alive)return;if(!this.sessionId)throw Error("codex thread not initialized");let Q=this.opts.allowUserInput===!1||this.usesCustomDefaultModeInstructions&&!!this.opts.appendSystemPrompt,Y=this.opts.model??this.lastModel;if(Q&&!Y)throw Error("Codex model is missing while applying the current invocation policy");let V=await this.request("turn/start",{threadId:this.sessionId,input:[{type:"text",text:$,text_elements:[]}],cwd:this.opts.workDir,runtimeWorkspaceRoots:[this.opts.workDir],approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"},...Q?{collaborationMode:{mode:"default",settings:{model:Y,reasoning_effort:this.opts.effort??this.lastEffort??null,developer_instructions:this.opts.appendSystemPrompt??null}}}:{}});this.recordTurnStarted(V?.turn,this.sessionId,"turn/start response",J)}catch(Q){if(!this.ownsTurnStartFailure(J)){j(`codex-process: ignored stale turn/start rejection generation=${J.generation}`);return}throw Q}}sendInterrupt(){this.inputConsumptionOpen=!1,this.steeringInputs?.clear(),this.turnRetryEnabled=!1;let $=!!this.turnRetry&&!this.currentTurnId;this.cancelTurnRetry();let Z=this.turnStartOwner,J=Z&&!Z.confirmed&&!Z.terminal;if(J)Z.interrupted=!0,Z.terminal=!0;if(this.currentTurnId)this.interruptTurn(this.currentTurnId);else if($||J)this.lastCompletedTurnId=null,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"interrupted",is_error:!1},this.emit("result",{...this.lastResult,checkpoint:null})}interruptTurn($){if(!this.sessionId)return;this.request("turn/interrupt",{threadId:this.sessionId,turnId:$}).catch((Z)=>j(`codex-process: interrupt failed: ${Z}`))}cancelTurnRetry(){if(this.turnRetryTimer)clearTimeout(this.turnRetryTimer);this.turnRetryTimer=null,this.turnRetry=null}scheduleTurnRetry($,Z,J){if(!this.alive||this.expectedExit||!this.turnRetryEnabled)return!1;if(this.turnRetryTimer)return!0;if(J!=="capacity"){if((this.transientRetryCount??0)>=mz)return j(`codex-process: transient retry limit reached (${mz}): ${$}`),!1;this.transientRetryCount=(this.transientRetryCount??0)+1}let Q=(this.turnRetryCount??0)+1;this.turnRetryCount=Q;let Y=J==="capacity"?Q:this.transientRetryCount,V=Math.min(_F*2**Math.min(Y-1,4),PF),X=this.turnStartGeneration??0,z={phase:"waiting",attempt:Q,delayMs:V,message:$,reason:J};this.turnRetry=z,j(`codex-process: ${J} retry #${Q} in ${V}ms: ${$}`);let H=setTimeout(()=>{if(this.turnRetryTimer!==H)return;if(this.turnRetryTimer=null,!this.alive||this.expectedExit||!this.turnRetryEnabled||this.currentTurnId||X!==(this.turnStartGeneration??0))return;if(this.turnRetry={...z,phase:"retrying",delayMs:0},this.emit("turn_retry",this.turnRetry),!this.alive||this.expectedExit||!this.turnRetryEnabled||X!==(this.turnStartGeneration??0))return;let G=this.beginTurnStart(Z);this.startTurn(Z,G).catch((W)=>this.failTurnStart(W,G))},V);return this.turnRetryTimer=H,this.emit("turn_retry",z),!0}sendPermissionResponse($,Z,J){let Q=this.serverRequests.get(String($));if(!Q){j(`codex-process: permission response for unknown request ${$}`);return}let Y=Z==="allow";switch(Q.method){case"item/commandExecution/requestApproval":this.respond($,{decision:Y?"accept":"decline"});return;case"item/fileChange/requestApproval":this.respond($,{decision:Y?"accept":"decline"});return;case"item/permissions/requestApproval":if(Y)this.respond($,{permissions:Q.params?.permissions??{},scope:"session"});else this.respondError($,J?.denyMessage??"denied by user");return;case"item/tool/requestUserInput":{if(!Y){this.respondError($,J?.denyMessage??"denied by user");return}let V=J?.updatedInput?.answers??{},X={};for(let z of Q.params?.questions??[]){let H=V[z.question]??V[z.id];if(H!==void 0)X[z.id]={answers:[String(H)]}}this.respond($,{answers:X});return}default:V$("APPROVAL_RESPONSE_UNSUPPORTED",{requestId:$,method:Q.method,params:Q.params,decision:Z,payload:J}),this.respondError($,J?.denyMessage??"unsupported approval request")}}sendHookResponse($,Z={}){this.respond($,Z)}isAlive(){return!this.exitEventEmitted}async kill($=5000){if(this.turnRetryEnabled=!1,this.cancelTurnRetry(),this.inputPolicyAbort?.abort(Error("Codex process cancelled")),this.startupPromise){this.expectedExit=!0;let Y;try{await Promise.race([this.startupPromise.catch(()=>{}),new Promise((V,X)=>{Y=setTimeout(()=>X(Error(`Codex model catalog preparation did not exit within ${$*2}ms`)),$*2)})])}finally{if(Y)clearTimeout(Y)}}if(!this.alive){if(await this.waitForExit($)){await this.disposeInputPolicy();return}throw Error(`codex app-server exited but stdio did not close within ${$}ms`)}this.expectedExit=!0,j(`codex-process: SIGTERM (timeout=${$}ms)`);let Z=[];if(this.sendSignal("SIGTERM",Z),await this.waitForExit($)){await this.disposeInputPolicy();return}if(j(`codex-process: SIGKILL (lifecycle not closed after ${$}ms)`),this.alive)this.sendSignal("SIGKILL",Z);if(await this.waitForExit($)){await this.disposeInputPolicy();return}let J=Z.length?`; ${Z.join("; ")}`:"",Q=Error(`codex app-server did not exit after SIGTERM and SIGKILL (${$}ms each)${J}`);throw j(`codex-process: kill failed: ${Q.message}`),Q}async disposeInputPolicy(){if(!this.inputPolicyCatalog)return;await this.inputPolicyCatalog.dispose(),this.inputPolicyCatalog=null}sendSignal($,Z){try{if(!this.proc?.kill($)&&this.alive)Z.push(`${$} was not delivered`)}catch(J){Z.push(`${$} failed: ${J instanceof Error?J.message:String(J)}`)}}async waitForExit($){if(this.exitEventEmitted)return!0;return new Promise((Z)=>{let J=!1,Q=(V)=>{if(J)return;J=!0,clearTimeout(Y),Z(V)},Y=setTimeout(()=>Q(!1),Math.max(0,$));this.exitPromise.then(()=>Q(!0))})}}});import{createHash as CF}from"node:crypto";class X${now;entries=new Map;constructor($=()=>Date.now()){this.now=$}read($,Z){let J=this.entries.get($);if(J?.pending)return J.pending;if(J&&this.now()<J.retryAt)return J.failed?Promise.reject(J.error):Promise.resolve(J.value);J??={failed:!1,failures:0,retryAt:0},this.entries.set($,J);let Q=J,Y=(X,z=0)=>{Q.failures=X?0:Q.failures+1;let H=X?u3:Math.min(xF,u3*2**Math.min(Q.failures-1,3));Q.retryAt=this.now()+Math.max(H,Number.isFinite(z)?z:0)},V=Promise.resolve().then(Z).then((X)=>{if(this.entries.get($)===Q){if(Q.value=X,X.state==="ok")Q.successfulValue=X;else if(X.state==="no_credentials"||X.state==="auth_failed"||a0(X.reason))Q.successfulValue=void 0;Q.failed=!1,Q.error=void 0,Y(X.state==="ok"||X.state==="not_applicable",X.retryAfterMs)}return X},(X)=>{if(this.entries.get($)===Q){if(Q.value=void 0,a0(X))Q.successfulValue=void 0;Q.failed=!0,Q.error=X,Y(!1,Number(X?.retryAfterMs))}throw X}).finally(()=>{if(Q.pending===V)Q.pending=void 0});return Q.pending=V,V}readStale($,Z){return this.read($,Z).then((J)=>{if(J.state==="ok")return J;let Q=this.peekSuccessful($);return Q&&(J.state==="network"||J.state==="rate_limited")&&!a0(J.reason)?Q:J}).catch((J)=>{let Q=this.peekSuccessful($);if(Q&&bF(J))return Q;throw J})}peekSuccessful($){return this.entries.get($)?.successfulValue}prime($,Z){this.entries.set($,{value:Z,...Z.state==="ok"?{successfulValue:Z}:{},failed:!1,failures:0,retryAt:this.now()+u3})}invalidate($){this.entries.delete($)}clear(){this.entries.clear()}}function bF($){let Z=$ instanceof Error?$.message:String($);return/abort|timed? ?out|timeout|fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:408|429|500|502|503|504)\b/i.test(Z)}function a0($){let Z=$ instanceof Error?$.message:String($??"");return/\b(?:401|403)\b|unauthori[sz]ed|authentication (?:failed|required)|not authenticated|not logged in|未登录|not (?:a )?first[- ]party|subscription (?:expired|missing)|(?:invalid|expired|revoked).*(?:key|token)|(?:key|token).*(?:invalid|expired|revoked)|认证(?:失败|失效|不是)|(?:不是|非).*(?:第一方|订阅)/i.test(Z)}function O$($,Z,J){return CF("sha256").update(JSON.stringify([$,Z,J])).digest("hex")}function l$($,Z=Date.now()){let J=$.get("retry-after");if(!J)return;let Q=Number(J),Y=Number.isFinite(Q)?Q*1000:Date.parse(J)-Z;return Number.isFinite(Y)&&Y>=0?Y:void 0}function q2($){let Z=$ instanceof Error?$.message:String($);return/\b429\b|too many requests|\brate[ _-]?limit(?:ed|[ _-](?:exceeded|reached))\b/i.test(Z)}var u3=60000,xF=300000;var _1=()=>{};function l3($,Z,J){if(!v.list().some((Y)=>Y.id===$)||v.revision($)!==J)return;let Q=Z?.type==="chatgpt"&&typeof Z.email==="string"?Z.email.trim():"";oz.set($,{revision:J,email:Q||null,...!Q?{error:Z?.type==="chatgpt"?"原生账号未提供邮箱":"该账号未登录 ChatGPT"}:{}})}function sz($){let Z=oz.get($);return Z?.revision===v.revision($)?Z:void 0}var oz;var d3=R(()=>{F0();oz=new Map});import{spawn as kF}from"cross-spawn";import{EventEmitter as wF}from"node:events";import{StringDecoder as vF}from"node:string_decoder";import{createHash as fF}from"node:crypto";function EZ($,Z){if(Z.state==="ok"){f1.set($,Z),D2.set($,Z);return}if(Z.state==="no_credentials"||Z.state==="auth_failed")f1.set($,Z),D2.delete($);else if(!D2.has($))f1.set($,Z)}function rz($,Z,J=(Q)=>new w$({accountId:Q})){if(!$||!Z.trim())return Promise.reject(Error("重置卡请求缺少账号或幂等标识"));let Q=i3.get($);if(Q)return Q.key===Z?Q.promise:Promise.reject(Error("该账号正在使用重置卡,请等待结果后再操作"));let Y=Promise.resolve().then(async()=>{let V=J($),X,z;try{await V.initialize("lodestar-codex-reset");let H=(await V.request("account/read",{}))?.account;if(!H||H.type!=="chatgpt")throw Error("该账号未登录 ChatGPT 订阅,不能使用重置卡");d$($);let G;try{G=await i$(()=>V.request("account/rateLimitResetCredit/consume",{idempotencyKey:Z}),"重置卡请求")}catch(B){throw Error(`重置卡请求未确认结果:${B instanceof Error?B.message:String(B)};请用 codex-accounts 核对额度与重置卡次数`,{cause:B})}finally{d$($)}if(!["reset","alreadyRedeemed","nothingToReset","noCredit"].includes(G?.outcome))throw Error(`Codex 重置卡返回未知结果:${JSON.stringify(G)};请用 codex-accounts 核对后再操作`);let W=A$.get($),K;try{K=await a3.read($,async()=>m9(await CZ(()=>V.request("account/rateLimits/read",{})),H.planType))}catch(B){K={state:"network",reason:B instanceof Error?B.message:String(B)}}if(A$.get($)!==W)K={state:"auth_failed"};else EZ($,K);if(K.state!=="ok")j(`codex-reset: ${$} quota refresh failed: ${K.state==="network"?K.reason:K.state}`);X={outcome:G.outcome,usage:K}}catch(H){z=H,j(`codex-reset: ${$}: ${H}`)}try{await V.close()}catch(H){let G=`控制连接关闭失败:${H instanceof Error?H.message:String(H)}`;if(j(`codex-reset: ${$}: ${G}`),X)X.cleanupError=G;else throw AggregateError([z,H],`${String(z)};${G}`)}if(!X)throw z;return X}).finally(()=>{if(i3.get($)?.promise===Y)i3.delete($)});return i3.set($,{key:Z,promise:Y}),Y}function ez($,Z){return new Promise((J,Q)=>{let Y=setTimeout(()=>Q(Error(`timeout after ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Y),J(V)},(V)=>{clearTimeout(Y),Q(V)})})}function yF($){return typeof $==="number"&&Number.isFinite($)&&$>=0&&$<=100?$:null}function n3($){if(!$)return null;return{percent:yF($.usedPercent),resetsAt:typeof $.resetsAt==="number"?new Date($.resetsAt*1000):null,durationMins:typeof $.windowDurationMins==="number"?$.windowDurationMins:null}}function hF($){let Z=n3($?.primary),J=n3($?.secondary),Q=(V)=>V?.durationMins!=null&&V.durationMins>0&&V.durationMins<=720,Y=(V)=>V?.durationMins!=null&&V.durationMins>720;if(Q(Z)&&Y(J))return{fiveHour:Z,weekly:J};if(Q(J)&&Y(Z))return{fiveHour:J,weekly:Z};if(Q(J)&&!Z)return{fiveHour:J,weekly:null};if(Y(Z)&&!J)return{fiveHour:null,weekly:Z};if(Y(J)&&!Z)return{fiveHour:null,weekly:J};return{fiveHour:Z,weekly:J}}function IF($){let Z=$?.rateLimitsByLimitId,J=Z&&typeof Z==="object"?Object.entries(Z):$?.rateLimits?[[$.rateLimits.limitId??"codex",$.rateLimits]]:[],Q=[];for(let[Y,V]of J){let{fiveHour:X,weekly:z}=hF(V);if(!X&&!z)continue;Q.push({limitId:Y,limitName:V?.limitName??null,fiveHour:X,weekly:z,normalModelSlug:V?.normalModelSlug??null,rateLimitReachedType:V?.rateLimitReachedType??null,spendControlReached:V?.spendControlReached??null,credits:g3(V?.credits)})}return{buckets:Q,defaultLimitId:$?.rateLimits?.limitId??void 0}}function gF($){if(!$)return"empty";let Z=(J)=>J?`${J.usedPercent??"?"}%/${J.windowDurationMins??"?"}m`:"null";return`limitId=${$.limitId??"null"} name=${$.limitName??"null"} primary=${Z($.primary)} secondary=${Z($.secondary)}`}function $H($,Z=d){let J=gF($),Q=f1.get(Z),Y=Q?.state==="ok"?Q.buckets??[]:[],V=Y.filter((X)=>tz(X.fiveHour,n3($?.primary))&&tz(X.weekly,n3($?.secondary)));if(Y.length>0&&V.length===0)j(`usage: rate-limit notification matches NO known bucket — possible relabel or new bucket, will resolve on next read. (${J})`);else if($?.limitId&&V.length===1&&V[0].limitId!==$.limitId)j(`usage: rate-limit notification labeled limitId=${$.limitId} but content matches bucket ${V[0].limitId} (known codex parser fallback relabels; ignoring notification payload)`)}function tz($,Z){if(!$||!Z)return!$&&!Z;return $.percent===Z.percent&&$.durationMins===Z.durationMins&&$.resetsAt?.getTime()===Z.resetsAt?.getTime()}async function mF($){let Z=v.revision($),J=new w$({accountId:$});try{await J.initialize("lodestar-usage");let Y=(await ez(J.request("account/read",{}),TZ))?.account;if(l3($,Y,Z),!Y)return{state:"no_credentials"};if(Y.type!=="chatgpt")return{state:"auth_failed"};let V,X=await CZ(()=>{return V=Date.now(),J.request("account/rateLimits/read",{})});return m9(X,Y.planType,V)}catch(Q){if(j(`usage: codex app-server usage failed: ${Q?.message??Q}`),a0(Q))return{state:"auth_failed"};if(q2(Q))return{state:"rate_limited"};return{state:"network",reason:Q?.message??String(Q)}}finally{await J.close()}}function m9($,Z,J){let{buckets:Q,defaultLimitId:Y}=IF($),V=Q.find((G)=>G.limitId===Y)??Q[0];if(!V)return{state:"network",reason:"empty rate limit response"};let X=$?.rateLimits?.planType,z=X??Z??void 0,H=typeof $?.accountId==="string"&&$.accountId?fF("sha256").update($.accountId).digest("hex"):void 0;if(X!=null&&Z!=null&&X!==Z)j(`usage: codex plan mismatch account=${H??"MISS"} account/read=${JSON.stringify(Z)} account/rateLimits/read=${JSON.stringify(X)}; using quota plan`);return{state:"ok",subscriptionType:z,...H?{accountFingerprint:H}:{},...typeof $?.ordinaryUsageAllowed==="boolean"?{ordinaryUsageAllowed:$.ordinaryUsageAllowed}:{},rateLimitReachedType:V.rateLimitReachedType,spendControlReached:V.spendControlReached,credits:V.credits,fiveHour:V.fiveHour,weekly:V.weekly,buckets:Q,defaultLimitId:V.limitId,resetCredits:Number.isInteger($?.rateLimitResetCredits?.availableCount)&&$.rateLimitResetCredits.availableCount>=0?$.rateLimitResetCredits.availableCount:null,...J!==void 0?{readStartedAt:J}:{},fetchedAt:Date.now()}}function F2($=d){return f1.get($)??null}function M2($=d){return D2.get($)??null}function SZ($=d){let Z=A$.get($)??0;return{accountId:$,read:()=>(A$.get($)??0)===Z?M2($):null}}function ZH($=d){let Z=A$.get($)??0;return a3.read($,async()=>{try{return await mF($)}catch(J){throw j(`usage: ${$} fetch failed: ${J}`),J}}).catch((J)=>{if(a0(J))return{state:"auth_failed"};if(q2(J))return{state:"rate_limited"};return{state:"network",reason:String(J)}}).then((J)=>{if((A$.get($)??0)!==Z)return{state:"auth_failed"};return EZ($,J),J})}async function JH($=d){return F2($)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"}}function QH($,Z=d){let J=A$.get(Z)??0;return a3.read(Z,async()=>{try{let Q,Y=await CZ(()=>{return Q=Date.now(),$("account/rateLimits/read",{})}),V=m9(Y,void 0,Q);if(V.state!=="ok")j(`usage: refresh from connection: ${V.state==="network"?V.reason:V.state}`);return V}catch(Q){throw j(`usage: refresh from connection failed: ${Q instanceof Error?Q.message:String(Q)}`),Q}}).then((Q)=>{if((A$.get(Z)??0)!==J)return null;if((A$.get(Z)??0)===J)EZ(Z,Q);return Q}).catch((Q)=>{if((A$.get(Z)??0)===J){if(a0(Q))f1.set(Z,{state:"auth_failed"}),D2.delete(Z);else if(!D2.has(Z))f1.set(Z,{state:q2(Q)?"rate_limited":"network",reason:String(Q)})}return null})}function VH(){return YH}function d$($){YH++,A$.set($,(A$.get($)??0)+1),f1.delete($),D2.delete($),a3.invalidate($)}function CZ($){return i$($,"额度查询",{retryRateLimits:!1})}async function i$($,Z="额度查询",J={}){let Q=[1000,4000];for(let Y=0;;Y++)try{return await ez($(),TZ)}catch(V){let X=V instanceof Error?V.message:String(V);if(a0(V))throw V;if(q2(V))throw V;if(!/error sending request|timed? ?out|timeout|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:429|502|503|504)\b/i.test(X))throw V;if(Y>=Q.length)throw Error(`Codex ${Z}失败(已尝试 ${Y+1} 次):${X}`,{cause:V});j(`usage: ${Z} retry ${Y+1}/${Q.length} in ${Q[Y]}ms: ${X}`),await new Promise((H)=>setTimeout(H,Q[Y]))}}var TZ=1e4,f1,D2,a3,i3,w$,A$,YH=0;var z$=R(()=>{j1();I();k0();F0();_1();d3();f1=new Map,D2=new Map,a3=new X$;i3=new Map;w$=class w$ extends wF{proc;buf="";decoder=new vF("utf8");nextId=1;alive=!0;exitPromise;resolveExit;pending=new Map;constructor($={}){super();let Z=$.accountId??d;this.proc=kF($.bin??I9(),["app-server","--listen","stdio://",...$.args??v.cliArgs(Z)],{stdio:["pipe","pipe","pipe"],shell:!1,cwd:$.cwd,env:$.env??v.env(Z,{...process.env,...g.codex.env},!0,$.login)}),this.exitPromise=new Promise((Q)=>{this.resolveExit=Q}),this.proc.stdout.on("data",(Q)=>this.onStdout(Q)),this.proc.stderr.on("data",(Q)=>{let Y=Q.toString().trim();if(Y)j(`usage[codex stderr]: ${Y}`)});let J=(Q)=>{if(!this.alive)return;this.alive=!1;for(let[Y,V]of this.pending)clearTimeout(V.timer),V.reject(Error(`${Q.message}; pending ${V.method} id=${Y}`));this.pending.clear(),this.resolveExit(),this.emit("exit"),this.emit("closed",Q)};this.proc.on("error",(Q)=>J(Error(`codex app-server spawn failed: ${Q.message}`))),this.proc.stdin.on("error",(Q)=>{j(`usage: codex stdin failed: ${Q.message}`),this.emit("protocolError",Q)}),this.proc.on("close",(Q,Y)=>{J(Error(`codex app-server exited code=${Q} signal=${Y}`))}),w1(this,Z)}onStdout($){this.buf+=this.decoder.write($);let Z;while((Z=this.buf.indexOf(`
87
+ `:"";this.steeringInputs??=new Map,this.steeringInputs.set(J,Q);let V;try{V=await this.request("turn/steer",{threadId:this.sessionId,expectedTurnId:Q,clientUserMessageId:J,input:[{type:"text",text:Y+$,text_elements:[]}]})}catch(X){if(X instanceof P2)this.steeringInputs.delete(J);throw X}if(V?.turnId!==Q)throw Error("Codex turn/steer 未确认目标回合,追加消息的接收状态未知");return!0}async listModels(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Q=await this.request("model/list",{cursor:J,limit:100,includeHidden:!1});if(!Array.isArray(Q?.data))throw Error("model/list returned no data array");for(let V of Q.data){if(typeof V?.model!=="string"||!V.model)continue;$.push({id:typeof V.id==="string"&&V.id?V.id:V.model,model:V.model,displayName:typeof V.displayName==="string"&&V.displayName?V.displayName:V.model,description:typeof V.description==="string"?V.description:"",hidden:V.hidden===!0,isDefault:V.isDefault===!0,supportedReasoningEfforts:MD(V.supportedReasoningEfforts),defaultReasoningEffort:U$(V.defaultReasoningEffort)?V.defaultReasoningEffort:null})}let Y=Q?.nextCursor;if(Y!==null&&typeof Y!=="string")throw Error("model/list returned an invalid nextCursor");if(J=Y||null,J){if(Z.has(J))throw Error("model/list returned a repeated nextCursor");Z.add(J)}}while(J);return $}async listConversations(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Q=await this.request("thread/list",{cursor:J,limit:100,sortKey:"updated_at",sortDirection:"desc",cwd:this.opts.workDir});if(!Array.isArray(Q?.data))throw Error("thread/list returned no data array");for(let V of Q.data){if(typeof V?.id!=="string"||!V.id||typeof V.preview!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt)||typeof V.cwd!=="string"||V.cwd!==this.opts.workDir)throw Error("thread/list returned an invalid thread summary");let X=typeof V.status==="string"?V.status:typeof V.status?.type==="string"?V.status.type:void 0;if(N4("codex",V.id))continue;$.push({provider:"codex",sessionId:V.id,cwd:V.cwd,preview:V.preview,ts:V.updatedAt*1000,...X?{status:X}:{}})}let Y=Q?.nextCursor;if(Y!==null&&typeof Y!=="string")throw Error("thread/list returned an invalid nextCursor");if(Y&&Z.has(Y))throw Error(`thread/list repeated pagination cursor ${Y}`);if(Y)Z.add(Y);J=Y}while(J);return $}async readConversationRef($){if(!$.trim())throw Error("thread/read requires a session id");await this.ensureInitialized();let J=(await this.request("thread/read",{threadId:$,includeTurns:!1}))?.thread;if(J?.id!==$||typeof J.cwd!=="string")throw Error("thread/read returned an invalid conversation reference");return{provider:"codex",sessionId:$,cwd:J.cwd}}async setModelSettings($,Z){j("codex-process: model settings require a process restart")}async compactThread(){if(!this.readyPromise)throw Error("codex thread not initialized");if(await this.readyPromise,!this.sessionId)throw Error("codex thread not initialized");if(this.currentTurnId||this.turnRetry||this.turnStartOwner&&!this.turnStartOwner.terminal)throw Error("codex cannot manually compact while a task is active");this.turnRetryEnabled=!1,await this.request("thread/compact/start",{threadId:this.sessionId})}failTurnStart($,Z){if(!this.ownsTurnStartFailure(Z)){j(`codex-process: ignored stale turn/start failure generation=${Z.generation}`);return}this.turnStartOwner=null,Z.terminal=!0;let J=$ instanceof Error?$.message:String($);if(j(`codex-process: turn/start failed: ${J}`),$ instanceof P2&&$.method==="turn/start"&&Z.inputText!==void 0){let Q=AZ({...$.serverData&&typeof $.serverData==="object"?$.serverData:{},message:$.serverMessage});if(Q&&this.scheduleTurnRetry($.serverMessage,Z.inputText,Q))return}this.cancelTurnRetry(),this.turnRetryCount=0,this.transientRetryCount=0,this.turnRetryHasStarted=!1,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"codex_turn_start_failed",is_error:!0},this.currentTurnId=null,this.lastCompletedTurnId=null,this.emit("result",{subtype:this.lastResult.subtype,is_error:!0,duration_ms:null,usage:this.lastUsage,error:J,...$ instanceof P2&&$.method==="turn/start"&&Z.inputText!==void 0&&(R4($.serverData)||R4({message:$.serverMessage}))?{codexQuotaFailure:{accepted:!1,rejectedInput:Z.inputText}}:{}})}recordTurnStarted($,Z,J,Q){let Y=typeof $?.id==="string"&&$.id?$.id:null;if(!Y)throw Error(`codex app-server ${J} returned no turn.id`);if(this.finishedTurnIds?.has(Y))return;let V=Q??this.turnStartOwner;if(V?.interrupted){if(this.rememberFinishedTurn(Y),this.turnStartOwner===V)this.turnStartOwner=null;this.interruptTurn(Y);return}this.confirmTurnStart(Y,Q);let X=this.currentTurnId!==Y;if(this.currentTurnId=Y,!X)return;let z=this.turnRetryHasStarted&&(this.turnRetryCount??0)>0;if(this.turnRetryHasStarted=!0,this.turnRetryTimer&&this.turnRetry){let H={...this.turnRetry,phase:"retrying",delayMs:0};this.cancelTurnRetry(),this.emit("turn_retry",H)}this.turnRetry=null,this.lastCompletedTurnId=null,this.emit("turn_started",{turn_id:Y,thread_id:typeof Z==="string"&&Z?Z:this.sessionId,...z?{retry:!0}:{}})}beginTurnStart($){let Z={generation:(this.turnStartGeneration??0)+1,turnId:null,confirmed:!1,terminal:!1,inputText:$};return this.turnStartGeneration=Z.generation,this.turnStartOwner=Z,Z}confirmTurnStart($,Z){if(!this.turnStartOwnersByTurnId)this.turnStartOwnersByTurnId=new Map;let J=Z??this.turnStartOwnersByTurnId.get($)??this.turnStartOwner;if(!J)return;if(J.turnId&&J.turnId!==$)throw Error(`codex turn/start generation=${J.generation} changed turn id from ${J.turnId} to ${$}`);if(J.terminal)return;J.turnId=$,J.confirmed=!0,this.turnStartOwnersByTurnId.set($,J)}markTurnStartTerminal($){if(!this.turnStartOwnersByTurnId)this.turnStartOwnersByTurnId=new Map;let Z=this.turnStartOwnersByTurnId.get($);if(!Z&&this.turnStartOwner&&(!this.currentTurnId||this.currentTurnId===$))Z=this.turnStartOwner,this.confirmTurnStart($,Z);if(!Z)return;if(Z.confirmed=!0,Z.terminal=!0,this.turnStartOwnersByTurnId.delete($),this.turnStartOwner===Z)this.turnStartOwner=null}ownsTurnStartFailure($){return this.turnStartOwner===$&&!$.confirmed&&!$.terminal}rememberFinishedTurn($){if(!this.finishedTurnIds)this.finishedTurnIds=new Set;if(this.finishedTurnIds.add($),this.finishedTurnIds.size<=64)return;let Z=this.finishedTurnIds.values().next().value;if(typeof Z==="string")this.finishedTurnIds.delete(Z)}async startTurn($,Z){let J=Z??this.beginTurnStart($);this.lastCompletedTurnId=null;try{if(!this.readyPromise)this.sendInitialize();if(await this.readyPromise,J.interrupted||this.expectedExit||!this.alive)return;if(!this.sessionId)throw Error("codex thread not initialized");let Q=this.opts.allowUserInput===!1||this.usesCustomDefaultModeInstructions&&!!this.opts.appendSystemPrompt,Y=this.opts.model??this.lastModel;if(Q&&!Y)throw Error("Codex model is missing while applying the current invocation policy");let V=await this.request("turn/start",{threadId:this.sessionId,input:[{type:"text",text:$,text_elements:[]}],cwd:this.opts.workDir,runtimeWorkspaceRoots:[this.opts.workDir],approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"},...Q?{collaborationMode:{mode:"default",settings:{model:Y,reasoning_effort:this.opts.effort??this.lastEffort??null,developer_instructions:this.opts.appendSystemPrompt??null}}}:{}});this.recordTurnStarted(V?.turn,this.sessionId,"turn/start response",J)}catch(Q){if(!this.ownsTurnStartFailure(J)){j(`codex-process: ignored stale turn/start rejection generation=${J.generation}`);return}throw Q}}sendInterrupt(){this.inputConsumptionOpen=!1,this.steeringInputs?.clear(),this.turnRetryEnabled=!1;let $=!!this.turnRetry&&!this.currentTurnId;this.cancelTurnRetry();let Z=this.turnStartOwner,J=Z&&!Z.confirmed&&!Z.terminal;if(J)Z.interrupted=!0,Z.terminal=!0;if(this.currentTurnId)this.interruptTurn(this.currentTurnId);else if($||J)this.lastCompletedTurnId=null,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"interrupted",is_error:!1},this.emit("result",{...this.lastResult,checkpoint:null})}interruptTurn($){if(!this.sessionId)return;this.request("turn/interrupt",{threadId:this.sessionId,turnId:$}).catch((Z)=>j(`codex-process: interrupt failed: ${Z}`))}cancelTurnRetry(){if(this.turnRetryTimer)clearTimeout(this.turnRetryTimer);this.turnRetryTimer=null,this.turnRetry=null}scheduleTurnRetry($,Z,J){if(!this.alive||this.expectedExit||!this.turnRetryEnabled)return!1;if(this.turnRetryTimer)return!0;if(J!=="capacity"){if((this.transientRetryCount??0)>=mz)return j(`codex-process: transient retry limit reached (${mz}): ${$}`),!1;this.transientRetryCount=(this.transientRetryCount??0)+1}let Q=(this.turnRetryCount??0)+1;this.turnRetryCount=Q;let Y=J==="capacity"?Q:this.transientRetryCount,V=Math.min(_D*2**Math.min(Y-1,4),PD),X=this.turnStartGeneration??0,z={phase:"waiting",attempt:Q,delayMs:V,message:$,reason:J};this.turnRetry=z,j(`codex-process: ${J} retry #${Q} in ${V}ms: ${$}`);let H=setTimeout(()=>{if(this.turnRetryTimer!==H)return;if(this.turnRetryTimer=null,!this.alive||this.expectedExit||!this.turnRetryEnabled||this.currentTurnId||X!==(this.turnStartGeneration??0))return;if(this.turnRetry={...z,phase:"retrying",delayMs:0},this.emit("turn_retry",this.turnRetry),!this.alive||this.expectedExit||!this.turnRetryEnabled||X!==(this.turnStartGeneration??0))return;let G=this.beginTurnStart(Z);this.startTurn(Z,G).catch((W)=>this.failTurnStart(W,G))},V);return this.turnRetryTimer=H,this.emit("turn_retry",z),!0}sendPermissionResponse($,Z,J){let Q=this.serverRequests.get(String($));if(!Q){j(`codex-process: permission response for unknown request ${$}`);return}let Y=Z==="allow";switch(Q.method){case"item/commandExecution/requestApproval":this.respond($,{decision:Y?"accept":"decline"});return;case"item/fileChange/requestApproval":this.respond($,{decision:Y?"accept":"decline"});return;case"item/permissions/requestApproval":if(Y)this.respond($,{permissions:Q.params?.permissions??{},scope:"session"});else this.respondError($,J?.denyMessage??"denied by user");return;case"item/tool/requestUserInput":{if(!Y){this.respondError($,J?.denyMessage??"denied by user");return}let V=J?.updatedInput?.answers??{},X={};for(let z of Q.params?.questions??[]){let H=V[z.question]??V[z.id];if(H!==void 0)X[z.id]={answers:[String(H)]}}this.respond($,{answers:X});return}default:V$("APPROVAL_RESPONSE_UNSUPPORTED",{requestId:$,method:Q.method,params:Q.params,decision:Z,payload:J}),this.respondError($,J?.denyMessage??"unsupported approval request")}}sendHookResponse($,Z={}){this.respond($,Z)}isAlive(){return!this.exitEventEmitted}async kill($=5000){if(this.turnRetryEnabled=!1,this.cancelTurnRetry(),this.inputPolicyAbort?.abort(Error("Codex process cancelled")),this.startupPromise){this.expectedExit=!0;let Y;try{await Promise.race([this.startupPromise.catch(()=>{}),new Promise((V,X)=>{Y=setTimeout(()=>X(Error(`Codex model catalog preparation did not exit within ${$*2}ms`)),$*2)})])}finally{if(Y)clearTimeout(Y)}}if(!this.alive){if(await this.waitForExit($)){await this.disposeInputPolicy();return}throw Error(`codex app-server exited but stdio did not close within ${$}ms`)}this.expectedExit=!0,j(`codex-process: SIGTERM (timeout=${$}ms)`);let Z=[];if(this.sendSignal("SIGTERM",Z),await this.waitForExit($)){await this.disposeInputPolicy();return}if(j(`codex-process: SIGKILL (lifecycle not closed after ${$}ms)`),this.alive)this.sendSignal("SIGKILL",Z);if(await this.waitForExit($)){await this.disposeInputPolicy();return}let J=Z.length?`; ${Z.join("; ")}`:"",Q=Error(`codex app-server did not exit after SIGTERM and SIGKILL (${$}ms each)${J}`);throw j(`codex-process: kill failed: ${Q.message}`),Q}async disposeInputPolicy(){if(!this.inputPolicyCatalog)return;await this.inputPolicyCatalog.dispose(),this.inputPolicyCatalog=null}sendSignal($,Z){try{if(!this.proc?.kill($)&&this.alive)Z.push(`${$} was not delivered`)}catch(J){Z.push(`${$} failed: ${J instanceof Error?J.message:String(J)}`)}}async waitForExit($){if(this.exitEventEmitted)return!0;return new Promise((Z)=>{let J=!1,Q=(V)=>{if(J)return;J=!0,clearTimeout(Y),Z(V)},Y=setTimeout(()=>Q(!1),Math.max(0,$));this.exitPromise.then(()=>Q(!0))})}}});import{createHash as CD}from"node:crypto";class X${now;entries=new Map;constructor($=()=>Date.now()){this.now=$}read($,Z){let J=this.entries.get($);if(J?.pending)return J.pending;if(J&&this.now()<J.retryAt)return J.failed?Promise.reject(J.error):Promise.resolve(J.value);J??={failed:!1,failures:0,retryAt:0},this.entries.set($,J);let Q=J,Y=(X,z=0)=>{Q.failures=X?0:Q.failures+1;let H=X?u3:Math.min(xD,u3*2**Math.min(Q.failures-1,3));Q.retryAt=this.now()+Math.max(H,Number.isFinite(z)?z:0)},V=Promise.resolve().then(Z).then((X)=>{if(this.entries.get($)===Q){if(Q.value=X,X.state==="ok")Q.successfulValue=X;else if(X.state==="no_credentials"||X.state==="auth_failed"||a0(X.reason))Q.successfulValue=void 0;Q.failed=!1,Q.error=void 0,Y(X.state==="ok"||X.state==="not_applicable",X.retryAfterMs)}return X},(X)=>{if(this.entries.get($)===Q){if(Q.value=void 0,a0(X))Q.successfulValue=void 0;Q.failed=!0,Q.error=X,Y(!1,Number(X?.retryAfterMs))}throw X}).finally(()=>{if(Q.pending===V)Q.pending=void 0});return Q.pending=V,V}readStale($,Z){return this.read($,Z).then((J)=>{if(J.state==="ok")return J;let Q=this.peekSuccessful($);return Q&&(J.state==="network"||J.state==="rate_limited")&&!a0(J.reason)?Q:J}).catch((J)=>{let Q=this.peekSuccessful($);if(Q&&bD(J))return Q;throw J})}peekSuccessful($){return this.entries.get($)?.successfulValue}prime($,Z){this.entries.set($,{value:Z,...Z.state==="ok"?{successfulValue:Z}:{},failed:!1,failures:0,retryAt:this.now()+u3})}invalidate($){this.entries.delete($)}clear(){this.entries.clear()}}function bD($){let Z=$ instanceof Error?$.message:String($);return/abort|timed? ?out|timeout|fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:408|429|500|502|503|504)\b/i.test(Z)}function a0($){let Z=$ instanceof Error?$.message:String($??"");return/\b(?:401|403)\b|unauthori[sz]ed|authentication (?:failed|required)|not authenticated|not logged in|未登录|not (?:a )?first[- ]party|subscription (?:expired|missing)|(?:invalid|expired|revoked).*(?:key|token)|(?:key|token).*(?:invalid|expired|revoked)|认证(?:失败|失效|不是)|(?:不是|非).*(?:第一方|订阅)/i.test(Z)}function O$($,Z,J){return CD("sha256").update(JSON.stringify([$,Z,J])).digest("hex")}function l$($,Z=Date.now()){let J=$.get("retry-after");if(!J)return;let Q=Number(J),Y=Number.isFinite(Q)?Q*1000:Date.parse(J)-Z;return Number.isFinite(Y)&&Y>=0?Y:void 0}function q2($){let Z=$ instanceof Error?$.message:String($);return/\b429\b|too many requests|\brate[ _-]?limit(?:ed|[ _-](?:exceeded|reached))\b/i.test(Z)}var u3=60000,xD=300000;var _1=()=>{};function l3($,Z,J){if(!v.list().some((Y)=>Y.id===$)||v.revision($)!==J)return;let Q=Z?.type==="chatgpt"&&typeof Z.email==="string"?Z.email.trim():"";oz.set($,{revision:J,email:Q||null,...!Q?{error:Z?.type==="chatgpt"?"原生账号未提供邮箱":"该账号未登录 ChatGPT"}:{}})}function sz($){let Z=oz.get($);return Z?.revision===v.revision($)?Z:void 0}var oz;var d3=R(()=>{D0();oz=new Map});import{spawn as kD}from"cross-spawn";import{EventEmitter as wD}from"node:events";import{StringDecoder as vD}from"node:string_decoder";import{createHash as yD}from"node:crypto";function EZ($,Z){if(Z.state==="ok"){y1.set($,Z),F2.set($,Z);return}if(Z.state==="no_credentials"||Z.state==="auth_failed")y1.set($,Z),F2.delete($);else if(!F2.has($))y1.set($,Z)}function rz($,Z,J=(Q)=>new w$({accountId:Q})){if(!$||!Z.trim())return Promise.reject(Error("重置卡请求缺少账号或幂等标识"));let Q=i3.get($);if(Q)return Q.key===Z?Q.promise:Promise.reject(Error("该账号正在使用重置卡,请等待结果后再操作"));let Y=Promise.resolve().then(async()=>{let V=J($),X,z;try{await V.initialize("lodestar-codex-reset");let H=(await V.request("account/read",{}))?.account;if(!H||H.type!=="chatgpt")throw Error("该账号未登录 ChatGPT 订阅,不能使用重置卡");d$($);let G;try{G=await i$(()=>V.request("account/rateLimitResetCredit/consume",{idempotencyKey:Z}),"重置卡请求")}catch(B){throw Error(`重置卡请求未确认结果:${B instanceof Error?B.message:String(B)};请用 codex-accounts 核对额度与重置卡次数`,{cause:B})}finally{d$($)}if(!["reset","alreadyRedeemed","nothingToReset","noCredit"].includes(G?.outcome))throw Error(`Codex 重置卡返回未知结果:${JSON.stringify(G)};请用 codex-accounts 核对后再操作`);let W=A$.get($),K;try{K=await a3.read($,async()=>m9(await CZ(()=>V.request("account/rateLimits/read",{})),H.planType))}catch(B){K={state:"network",reason:B instanceof Error?B.message:String(B)}}if(A$.get($)!==W)K={state:"auth_failed"};else EZ($,K);if(K.state!=="ok")j(`codex-reset: ${$} quota refresh failed: ${K.state==="network"?K.reason:K.state}`);X={outcome:G.outcome,usage:K}}catch(H){z=H,j(`codex-reset: ${$}: ${H}`)}try{await V.close()}catch(H){let G=`控制连接关闭失败:${H instanceof Error?H.message:String(H)}`;if(j(`codex-reset: ${$}: ${G}`),X)X.cleanupError=G;else throw AggregateError([z,H],`${String(z)};${G}`)}if(!X)throw z;return X}).finally(()=>{if(i3.get($)?.promise===Y)i3.delete($)});return i3.set($,{key:Z,promise:Y}),Y}function ez($,Z){return new Promise((J,Q)=>{let Y=setTimeout(()=>Q(Error(`timeout after ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Y),J(V)},(V)=>{clearTimeout(Y),Q(V)})})}function fD($){return typeof $==="number"&&Number.isFinite($)&&$>=0&&$<=100?$:null}function n3($){if(!$)return null;return{percent:fD($.usedPercent),resetsAt:typeof $.resetsAt==="number"?new Date($.resetsAt*1000):null,durationMins:typeof $.windowDurationMins==="number"?$.windowDurationMins:null}}function hD($){let Z=n3($?.primary),J=n3($?.secondary),Q=(V)=>V?.durationMins!=null&&V.durationMins>0&&V.durationMins<=720,Y=(V)=>V?.durationMins!=null&&V.durationMins>720;if(Q(Z)&&Y(J))return{fiveHour:Z,weekly:J};if(Q(J)&&Y(Z))return{fiveHour:J,weekly:Z};if(Q(J)&&!Z)return{fiveHour:J,weekly:null};if(Y(Z)&&!J)return{fiveHour:null,weekly:Z};if(Y(J)&&!Z)return{fiveHour:null,weekly:J};return{fiveHour:Z,weekly:J}}function ID($){let Z=$?.rateLimitsByLimitId,J=Z&&typeof Z==="object"?Object.entries(Z):$?.rateLimits?[[$.rateLimits.limitId??"codex",$.rateLimits]]:[],Q=[];for(let[Y,V]of J){let{fiveHour:X,weekly:z}=hD(V);if(!X&&!z)continue;Q.push({limitId:Y,limitName:V?.limitName??null,fiveHour:X,weekly:z,normalModelSlug:V?.normalModelSlug??null,rateLimitReachedType:V?.rateLimitReachedType??null,spendControlReached:V?.spendControlReached??null,credits:g3(V?.credits)})}return{buckets:Q,defaultLimitId:$?.rateLimits?.limitId??void 0}}function gD($){if(!$)return"empty";let Z=(J)=>J?`${J.usedPercent??"?"}%/${J.windowDurationMins??"?"}m`:"null";return`limitId=${$.limitId??"null"} name=${$.limitName??"null"} primary=${Z($.primary)} secondary=${Z($.secondary)}`}function $H($,Z=d){let J=gD($),Q=y1.get(Z),Y=Q?.state==="ok"?Q.buckets??[]:[],V=Y.filter((X)=>tz(X.fiveHour,n3($?.primary))&&tz(X.weekly,n3($?.secondary)));if(Y.length>0&&V.length===0)j(`usage: rate-limit notification matches NO known bucket — possible relabel or new bucket, will resolve on next read. (${J})`);else if($?.limitId&&V.length===1&&V[0].limitId!==$.limitId)j(`usage: rate-limit notification labeled limitId=${$.limitId} but content matches bucket ${V[0].limitId} (known codex parser fallback relabels; ignoring notification payload)`)}function tz($,Z){if(!$||!Z)return!$&&!Z;return $.percent===Z.percent&&$.durationMins===Z.durationMins&&$.resetsAt?.getTime()===Z.resetsAt?.getTime()}async function mD($){let Z=v.revision($),J=new w$({accountId:$});try{await J.initialize("lodestar-usage");let Y=(await ez(J.request("account/read",{}),TZ))?.account;if(l3($,Y,Z),!Y)return{state:"no_credentials"};if(Y.type!=="chatgpt")return{state:"auth_failed"};let V,X=await CZ(()=>{return V=Date.now(),J.request("account/rateLimits/read",{})});return m9(X,Y.planType,V)}catch(Q){if(j(`usage: codex app-server usage failed: ${Q?.message??Q}`),a0(Q))return{state:"auth_failed"};if(q2(Q))return{state:"rate_limited"};return{state:"network",reason:Q?.message??String(Q)}}finally{await J.close()}}function m9($,Z,J){let{buckets:Q,defaultLimitId:Y}=ID($),V=Q.find((G)=>G.limitId===Y)??Q[0];if(!V)return{state:"network",reason:"empty rate limit response"};let X=$?.rateLimits?.planType,z=X??Z??void 0,H=typeof $?.accountId==="string"&&$.accountId?yD("sha256").update($.accountId).digest("hex"):void 0;if(X!=null&&Z!=null&&X!==Z)j(`usage: codex plan mismatch account=${H??"MISS"} account/read=${JSON.stringify(Z)} account/rateLimits/read=${JSON.stringify(X)}; using quota plan`);return{state:"ok",subscriptionType:z,...H?{accountFingerprint:H}:{},...typeof $?.ordinaryUsageAllowed==="boolean"?{ordinaryUsageAllowed:$.ordinaryUsageAllowed}:{},rateLimitReachedType:V.rateLimitReachedType,spendControlReached:V.spendControlReached,credits:V.credits,fiveHour:V.fiveHour,weekly:V.weekly,buckets:Q,defaultLimitId:V.limitId,resetCredits:Number.isInteger($?.rateLimitResetCredits?.availableCount)&&$.rateLimitResetCredits.availableCount>=0?$.rateLimitResetCredits.availableCount:null,...J!==void 0?{readStartedAt:J}:{},fetchedAt:Date.now()}}function D2($=d){return y1.get($)??null}function M2($=d){return F2.get($)??null}function SZ($=d){let Z=A$.get($)??0;return{accountId:$,read:()=>(A$.get($)??0)===Z?M2($):null}}function ZH($=d){let Z=A$.get($)??0;return a3.read($,async()=>{try{return await mD($)}catch(J){throw j(`usage: ${$} fetch failed: ${J}`),J}}).catch((J)=>{if(a0(J))return{state:"auth_failed"};if(q2(J))return{state:"rate_limited"};return{state:"network",reason:String(J)}}).then((J)=>{if((A$.get($)??0)!==Z)return{state:"auth_failed"};return EZ($,J),J})}async function JH($=d){return D2($)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"}}function QH($,Z=d){let J=A$.get(Z)??0;return a3.read(Z,async()=>{try{let Q,Y=await CZ(()=>{return Q=Date.now(),$("account/rateLimits/read",{})}),V=m9(Y,void 0,Q);if(V.state!=="ok")j(`usage: refresh from connection: ${V.state==="network"?V.reason:V.state}`);return V}catch(Q){throw j(`usage: refresh from connection failed: ${Q instanceof Error?Q.message:String(Q)}`),Q}}).then((Q)=>{if((A$.get(Z)??0)!==J)return null;if((A$.get(Z)??0)===J)EZ(Z,Q);return Q}).catch((Q)=>{if((A$.get(Z)??0)===J){if(a0(Q))y1.set(Z,{state:"auth_failed"}),F2.delete(Z);else if(!F2.has(Z))y1.set(Z,{state:q2(Q)?"rate_limited":"network",reason:String(Q)})}return null})}function VH(){return YH}function d$($){YH++,A$.set($,(A$.get($)??0)+1),y1.delete($),F2.delete($),a3.invalidate($)}function CZ($){return i$($,"额度查询",{retryRateLimits:!1})}async function i$($,Z="额度查询",J={}){let Q=[1000,4000];for(let Y=0;;Y++)try{return await ez($(),TZ)}catch(V){let X=V instanceof Error?V.message:String(V);if(a0(V))throw V;if(q2(V))throw V;if(!/error sending request|timed? ?out|timeout|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:429|502|503|504)\b/i.test(X))throw V;if(Y>=Q.length)throw Error(`Codex ${Z}失败(已尝试 ${Y+1} 次):${X}`,{cause:V});j(`usage: ${Z} retry ${Y+1}/${Q.length} in ${Q[Y]}ms: ${X}`),await new Promise((H)=>setTimeout(H,Q[Y]))}}var TZ=1e4,y1,F2,a3,i3,w$,A$,YH=0;var z$=R(()=>{j1();I();k0();D0();_1();d3();y1=new Map,F2=new Map,a3=new X$;i3=new Map;w$=class w$ extends wD{proc;buf="";decoder=new vD("utf8");nextId=1;alive=!0;exitPromise;resolveExit;pending=new Map;constructor($={}){super();let Z=$.accountId??d;this.proc=kD($.bin??I9(),["app-server","--listen","stdio://",...$.args??v.cliArgs(Z)],{stdio:["pipe","pipe","pipe"],shell:!1,cwd:$.cwd,env:$.env??v.env(Z,{...process.env,...g.codex.env},!0,$.login)}),this.exitPromise=new Promise((Q)=>{this.resolveExit=Q}),this.proc.stdout.on("data",(Q)=>this.onStdout(Q)),this.proc.stderr.on("data",(Q)=>{let Y=Q.toString().trim();if(Y)j(`usage[codex stderr]: ${Y}`)});let J=(Q)=>{if(!this.alive)return;this.alive=!1;for(let[Y,V]of this.pending)clearTimeout(V.timer),V.reject(Error(`${Q.message}; pending ${V.method} id=${Y}`));this.pending.clear(),this.resolveExit(),this.emit("exit"),this.emit("closed",Q)};this.proc.on("error",(Q)=>J(Error(`codex app-server spawn failed: ${Q.message}`))),this.proc.stdin.on("error",(Q)=>{j(`usage: codex stdin failed: ${Q.message}`),this.emit("protocolError",Q)}),this.proc.on("close",(Q,Y)=>{J(Error(`codex app-server exited code=${Q} signal=${Y}`))}),w1(this,Z)}onStdout($){this.buf+=this.decoder.write($);let Z;while((Z=this.buf.indexOf(`
88
88
  `))>=0){let J=this.buf.slice(0,Z).trim();if(this.buf=this.buf.slice(Z+1),!J)continue;let Q;try{Q=JSON.parse(J)}catch{this.emit("protocolError",Error("Codex app-server returned invalid JSON"));continue}if(!Q||typeof Q!=="object"||Array.isArray(Q)){this.emit("protocolError",Error("Codex app-server returned invalid RPC object"));continue}let Y=Object.prototype.hasOwnProperty.call(Q,"id");if(typeof Q.method==="string"){if(!Y)this.emit("notification",Q.method,Q.params);else j(`usage: unsupported Codex server request: ${Q.method}`),this.proc.stdin.write(JSON.stringify({id:Q.id,error:{code:-32601,message:`Unsupported server request: ${Q.method}`}})+`
89
89
  `);continue}if(!Y||!Object.prototype.hasOwnProperty.call(Q,"result")&&!Object.prototype.hasOwnProperty.call(Q,"error")){this.emit("protocolError",Error("Codex app-server returned an incomplete RPC response"));continue}let V=this.pending.get(Q.id);if(!V)continue;if(this.pending.delete(Q.id),clearTimeout(V.timer),Q.error)V.reject(Error(JSON.stringify(Q.error)));else V.resolve(Q.result)}}async initialize($){await this.request("initialize",{clientInfo:{name:$,version:"0.0.0"},capabilities:{experimentalApi:!0,requestAttestation:!1}}),await new Promise((Z,J)=>{this.proc.stdin.write(JSON.stringify({method:"initialized"})+`
90
90
  `,(Q)=>Q?J(Q):Z())})}isAlive(){return this.alive}request($,Z,J=TZ){let Q=this.nextId++;return new Promise((Y,V)=>{if(!this.alive){V(Error(`codex app-server is not alive; cannot request ${$}`));return}let X=setTimeout(()=>{if(!this.pending.delete(Q))return;V(Error(`codex app-server ${$} timed out after ${J}ms`))},J);this.pending.set(Q,{resolve:Y,reject:V,method:$,timer:X});try{this.proc.stdin.write(JSON.stringify({id:Q,method:$,params:Z})+`
91
- `,(z)=>{if(!z)return;let H=this.pending.get(Q);if(!H)return;this.pending.delete(Q),clearTimeout(H.timer),H.reject(Error(`codex app-server write failed for ${$}: ${z.message}`))})}catch(z){this.pending.delete(Q),clearTimeout(X),V(z instanceof Error?z:Error(String(z)))}})}async close($=2000){if(!this.alive)return;if(this.proc.exitCode!==null||this.proc.signalCode!==null){if(!await this.waitForExit($))throw Error("codex app-server stdio did not close after exit");return}if(!this.proc.kill("SIGTERM"))throw Error("codex app-server rejected SIGTERM");if(await this.waitForExit($))return;if(!this.proc.kill("SIGKILL"))throw Error("codex app-server rejected SIGKILL");if(!await this.waitForExit($))throw Error(`codex app-server did not exit after SIGKILL (${$}ms)`)}async waitForExit($){let Z;try{return await Promise.race([this.exitPromise.then(()=>!0),new Promise((J)=>{Z=setTimeout(()=>J(!1),$)})])}finally{if(Z!==void 0)clearTimeout(Z)}}};A$=new Map});var WH={};H1(WH,{waitForTokenSourceModelRefresh:()=>cF,tokenSourceRuntimeModels:()=>y1,tokenSourceRuntimeModel:()=>n$,tokenSourceRegistryRevision:()=>bZ,tokenSourceProcessRevision:()=>C4,tokenSourceFactories:()=>U2,setDefaultTokenSource:()=>vZ,scrubDshEnv:()=>p9,scrubAnthropicEnv:()=>o0,resetTokenSourceRegistry:()=>fZ,registerTokenSourceFactory:()=>N0,registerTokenSource:()=>kZ,refreshAllTokenSourceModels:()=>pF,pendingTokenSourceModelRefresh:()=>GH,listTokenSourcesByAgent:()=>zH,listTokenSources:()=>s0,listTokenSourceAccounts:()=>HH,listEnabledTokenSourcesByAgent:()=>wZ,getTokenSourceForAccount:()=>j0,getTokenSource:()=>M0,ANTHROPIC_ENV_KEYS:()=>s3});function o0($){let Z={...$};for(let J of s3)delete Z[J];return delete Z.LODESTAR_PACKY_API_KEY,Z}function p9($){let Z=o0($);for(let J of Object.keys(Z))if(/^(DSH_|DEEPSEEK_|LODESTAR_DSH_|ZAI_|ZHIPU_)/.test(J))delete Z[J];return Z}function y1($){return $.modelSelection?[...$.models,...$.modelSelection.availableModels.filter((Z)=>!$.models.some((J)=>J.model===Z.model))]:$.models}function n$($,Z){let J=(Q)=>$.agent==="claude"?Q?.replace(/\[1m\]$/,""):Q;return y1($).find((Q)=>J(Q.model)===J(Z))}function C4($,Z){let J=$?.spawnRevision??null,Q=$?.modelEnvironmentRevision?.(Z??$.defaultModel);return Q===void 0?J:JSON.stringify([J,Q])}function N0($){XH.set($.kind,$)}function U2(){return[...XH.values()]}function bZ(){return xZ}function kZ($,Z){if(c9.set($.id,$),Z?.default||o3===null)o3=$.id}function M0($){return $?c9.get($):void 0}function j0($,Z="default"){let J=M0($);return J?.forAccount?J.forAccount(Z):J}function s0(){return[...c9.values()]}function zH($){return s0().filter((Z)=>Z.agent===$)}function wZ($){return zH($).filter((Z)=>Z.enabled)}function vZ($){if(c9.has($))o3=$}function fZ(){c9.clear(),o3=null,xZ++}function pF(){let $=xZ;if(S4?.generation===$)return S4.promise;let Z=Promise.allSettled(HH().map(async(J)=>{await J.refreshModels(),j(`token-source ${J.id}: ${J.models.length} models loaded`)})).then(()=>{}).finally(()=>{if(S4?.promise===Z)S4=null});return S4={generation:$,promise:Z},Z}function HH(){return s0().flatMap(($)=>$.forAccount?v.list().map((Z)=>$.forAccount(Z.id)):[$])}function GH(){return S4?.promise??null}async function cF(){let $;while($=GH())await $}var s3,XH,c9,o3=null,xZ=0,S4=null;var X0=R(()=>{I();F0();s3=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","CLAUDE_CODE_SUBAGENT_MODEL","ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_EFFORT_LEVEL"];XH=new Map;c9=new Map});import{existsSync as uF,readFileSync as lF}from"node:fs";class KH{deps;lastUses=new Map;constructor($){this.deps=$}recordUsage($,Z,J){let Q=J??this.deps.cachedUsage($);if(Q?.state!=="ok")return;let Y=Q.accountFingerprint??this.deps.identity($);if(!Y)return;this.lastUses.set(JSON.stringify([Y,_2(Q,Z)]),this.deps.now())}weekWasUsed($,Z,J){let Q=this.lastUses.get(JSON.stringify([$,_2(Z,J)]));return Q!==void 0&&fz(Z,J,Q)}blocks(){if(!uF(this.deps.stateFile))return[];let $=JSON.parse(lF(this.deps.stateFile,"utf8"));if($?.version!==1||!Array.isArray($.blocks)||$.blocks.some((Z)=>typeof Z?.key!=="string"||typeof Z?.identity!=="string"||typeof Z?.meter!=="string"||!Array.isArray(Z?.windows)||Z.credits!=null&&(!g3(Z.credits)||Z.credits.balance!==null&&!Number.isFinite(Z.credits.balance))||Z.creditsObservedAt!==void 0&&!Number.isFinite(Z.creditsObservedAt)||Z.windows.some((J)=>!["fiveHour","weekly"].includes(J?.kind)||J.percent!==null&&!Number.isFinite(J.percent)||J.reset!==null&&!Number.isFinite(J.reset))))throw Error("Codex 额度耗尽记录格式无效");return $.blocks}block($,Z){if(!$.usage)throw Error("未读取额度,不能记录耗尽窗口");let J=$.usage.state==="ok"?j2($.usage,Z):null,Q=["fiveHour","weekly"].flatMap((z)=>{let H=J?.[z];return H?[{kind:z,percent:H.percent,reset:H.resetsAt?.getTime()??null}]:[]}),Y=_2($.usage,Z),V=JSON.stringify([$.identity,Y]),X=this.blocks().filter((z)=>z.key!==V);X.push({key:V,identity:$.identity,meter:Y,windows:Q,credits:J?.credits??null,blockedAt:this.deps.now()}),r(this.deps.stateFile,{version:1,blocks:X})}async choose($){$.signal?.throwIfAborted();let Z=this.deps.accounts();if($.preferred){let Q=Z.find((Y)=>Y.id===$.preferred);if(!Q)throw Error(`指定 Codex 账号不存在:${$.preferred}`);return{selected:{account:Q,identity:`record:${Q.id}`,usage:null,state:"manual",score:null,shares:null,remaining:null,hours:null},candidates:[]}}let J=new Map;if($.preferCachedUsage){let Q=await this.chooseAutomatic(Z,$,!0,J);if(Q.selected)return Q}return this.chooseAutomatic(Z,$,!1,J)}async chooseAutomatic($,Z,J,Q){Z.signal?.throwIfAborted();let Y=await Promise.all($.map(async(q)=>{let D,M=null,U=`record:${q.id}`;if(this.deps.pendingLogin(q.id))D={state:"network",reason:"正在登录"};else try{D=J?this.deps.cachedUsage(q.id):await this.deps.usage(q.id);let A=D?.state==="ok"?D.accountFingerprint??this.deps.identity(q.id):null;if(A)U=A;else if(D?.state==="ok")M="账号身份 MISS";if(D?.state==="ok"&&!M){let O=Q.get(q.id);if(!O)O=this.deps.compatible(q.id,Z.model,Z.effort),Q.set(q.id,O);M=await O}}catch(A){D={state:"network",reason:String(A)}}return{account:q,usage:D,identity:U,reason:M}}));Z.signal?.throwIfAborted();let V=Z.failedAccountId&&Y.find((q)=>q.account.id===Z.failedAccountId);if(V&&V.usage?.state==="ok")this.block({account:V.account,usage:V.usage,identity:V.identity,...h9(V.usage,Z.model,this.deps.now(),Z.effort)},Z.model);let X=this.blocks(),z=this.deps.now(),H=new Set,G=new Map,W=new Map,K=Y.map(({account:q,usage:D,identity:M,reason:U})=>{let A=h9(D??{state:"network",reason:"尚无额度缓存"},Z.model,z,Z.effort);if(U)A={...A,state:"miss",score:null,reason:U};let O=W.get(M);if(W.set(M,O??q.name),O)A={...A,state:"miss",score:null,reason:`重复账号:${O}`};let N=D?.state==="ok"?_2(D,Z.model):null,S=X.find((T)=>(T.identity===M||T.identity===`record:${q.id}`)&&T.meter===N);if(S&&D?.state==="ok"&&!O){let T=j2(D,Z.model),y=D.readStartedAt??D.fetchedAt,m=y>(S.blockedAt??0),b=m&&y>(S.creditsObservedAt??0),p=b&&kz(S.credits,T.credits),c=m&&A.funding!=="credits"&&S.windows.some((J0)=>{let l=T[J0.kind];if(l===null)return!0;return l&&l.percent!==null&&(J0.percent!==null&&l.percent<J0.percent||J0.reset!==null&&J0.reset<=z&&(l.resetsAt?.getTime()??0)>J0.reset)});if(A.state==="ready")if(c||p)H.add(S.key);else A={...A,state:"exhausted",score:null,reason:"上次请求已确认额度耗尽,等待接口确认恢复"};if(!H.has(S.key)&&b&&!p&&T.credits!=null)G.set(S.key,{...S,credits:T.credits,creditsObservedAt:y})}return{account:q,usage:D,identity:M,...A,...O?{duplicateOf:O}:{}}});if(H.size||G.size)r(this.deps.stateFile,{version:1,blocks:X.filter((q)=>!H.has(q.key)).map((q)=>G.get(q.key)??q)});let B=K.filter((q)=>q.state==="ready");B.sort(m3);let _=B[0]??null,P=K.filter((q)=>q.state==="exhausted"||q.state==="waiting"),L=P.length?Math.min(...P.map((q)=>q.retryAt??z+60000)):void 0;for(let q of K)j(`codex scheduler${J?" [cache]":""}: ${q.account.name} ${q.state} priority=${q.funding??q.priority??"score"} score=${q.score??(q.funding==="credits"||q.priority==="expiring"?"N/A":"MISS")}${q.reason?` (${q.reason})`:""}`);return{selected:_,candidates:K,...L!==void 0?{retryAt:L}:{}}}}function dF($,Z,J){let Q=n$($,Z);if(!Q)return`模型目录缺少 ${Z}`;if(Q.unavailableReason)return`${Z} 不可用:${Q.unavailableReason}`;if(J&&!Q.efforts.includes(J))return`${Z} 缺少推理档位 ${J}(目录档位:${Q.efforts.join("、")||"MISS"})`;return null}async function iF($,Z,J,Q=Date.now()){if(!$.enabled||$.modelCatalogState?.status!=="ready")return`模型目录查询失败:${$.modelCatalogState?.error??($.enabled?"模型目录 MISS":"订阅来源未启用")}`;return dF($,Z,J)}var O2;var t3=R(()=>{F0();z$();T4();X0();H0();b0();I();O2=new KH({accounts:()=>v.list(),usage:async($)=>F2($)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"},cachedUsage:M2,identity:($)=>v.fingerprint($),pendingLogin:k1,now:Date.now,stateFile:_X,compatible:async($,Z,J)=>{let Q=j0("codex-sub",$);if(!Q)return"订阅来源 MISS";return iF(Q,Z,J)}})});import{createHash as nF}from"node:crypto";import{readFile as aF}from"node:fs/promises";import{join as oF}from"node:path";function BH($){if(!$?.enabled||$.kind!=="codex-subscription"||$.modelCatalogState?.status!=="ready")throw Error(`后台激活模型目录 MISS:${$?.modelCatalogState?.error??"订阅目录未就绪"}`);let Z=($.modelSelection?.availableModels??$.models).find((Q)=>Q.model===P1&&Q.origin!=="custom");if(!Z||Z.unavailableReason)throw Error(`后台激活需要 ${P1}:${Z?.unavailableReason??"原生目录未提供"}`);let J=L2.find((Q)=>Z.efforts.includes(Q));if(!J)throw Error(`${P1} 推理档位 MISS`);return J}function sF($){return{model:P1,instructions:"",store:!1,stream:!0,input:[{role:"user",content:[{type:"input_text",text:"你好,只回复“你好”。"}]}],tools:[],tool_choice:"none",parallel_tool_calls:!1,reasoning:{effort:$},text:{verbosity:"low"},service_tier:"default"}}function yZ($){let Z=h9($,"");return!!$.defaultLimitId&&($.fiveHour===null||$.fiveHour.percent===0)&&vz($,"")&&Z.state==="ready"&&Z.funding!=="credits"}async function tF($){let Z;try{Z=await aF(oF(v.home($),"auth.json"),"utf8")}catch(Q){throw Error(`后台激活无法读取原生 auth.json:${Q.code??"读取失败"}`)}let J;try{J=JSON.parse(Z)}catch{throw Error("后台激活的原生 auth.json 不是有效 JSON")}if(J?.auth_mode!=="chatgpt"||typeof J.tokens?.access_token!=="string"||!J.tokens.access_token||typeof J.tokens.account_id!=="string"||!J.tokens.account_id)throw Error("后台激活的原生 ChatGPT 文件登录态无效");return{accessToken:J.tokens.access_token,accountId:J.tokens.account_id}}function rF($){if(typeof $!=="string"||!$)throw Error("原生 chatgpt_base_url MISS");let Z=new URL($);if(!["http:","https:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("原生 chatgpt_base_url 格式无效");let J=Z.pathname.replace(/\/+$/,"");return Z.pathname=J.endsWith("/codex/responses")?J:J.endsWith("/codex")?`${J}/responses`:`${J}/codex/responses`,Z.href}async function eF($,Z){if(!$.ok)throw Error(`后台激活 HTTP ${$.status}:${await $.text()}`);if(!$.body)throw Error("后台激活响应缺少事件流");let J=$.body.getReader(),Q=new TextDecoder,Y="",V="",X,z=()=>{let H=V;if(V="",!H||H.trim()==="[DONE]")return;let G;try{G=JSON.parse(H)}catch{throw Error("后台激活返回无效 JSON 事件")}if(G.type==="error"||["response.failed","response.incomplete"].includes(G.type))throw Error(`后台激活失败:${G.error?.message??G.response?.error?.message??G.message??G.type}`);if(!["response.completed","response.done"].includes(G.type))return;if(G.response?.status!=="completed")throw Error(`后台激活终态异常:${G.response?.status??"MISS"}`);let W=G.response?.usage?.total_tokens;if(!Number.isFinite(W)||W<=0)throw Error("后台激活已结束,但真实 token 用量 MISS");return W};try{while(!0){let{value:H,done:G}=await J.read();if(Y+=G?Q.decode():Q.decode(H,{stream:!0}),Y.length+V.length>1e6)throw Error("后台激活响应事件超过大小限制");let W;while((W=Y.indexOf(`
91
+ `,(z)=>{if(!z)return;let H=this.pending.get(Q);if(!H)return;this.pending.delete(Q),clearTimeout(H.timer),H.reject(Error(`codex app-server write failed for ${$}: ${z.message}`))})}catch(z){this.pending.delete(Q),clearTimeout(X),V(z instanceof Error?z:Error(String(z)))}})}async close($=2000){if(!this.alive)return;if(this.proc.exitCode!==null||this.proc.signalCode!==null){if(!await this.waitForExit($))throw Error("codex app-server stdio did not close after exit");return}if(!this.proc.kill("SIGTERM"))throw Error("codex app-server rejected SIGTERM");if(await this.waitForExit($))return;if(!this.proc.kill("SIGKILL"))throw Error("codex app-server rejected SIGKILL");if(!await this.waitForExit($))throw Error(`codex app-server did not exit after SIGKILL (${$}ms)`)}async waitForExit($){let Z;try{return await Promise.race([this.exitPromise.then(()=>!0),new Promise((J)=>{Z=setTimeout(()=>J(!1),$)})])}finally{if(Z!==void 0)clearTimeout(Z)}}};A$=new Map});var WH={};H1(WH,{waitForTokenSourceModelRefresh:()=>cD,tokenSourceRuntimeModels:()=>f1,tokenSourceRuntimeModel:()=>n$,tokenSourceRegistryRevision:()=>bZ,tokenSourceProcessRevision:()=>C4,tokenSourceFactories:()=>U2,setDefaultTokenSource:()=>vZ,scrubDshEnv:()=>p9,scrubAnthropicEnv:()=>o0,resetTokenSourceRegistry:()=>yZ,registerTokenSourceFactory:()=>N0,registerTokenSource:()=>kZ,refreshAllTokenSourceModels:()=>pD,pendingTokenSourceModelRefresh:()=>GH,listTokenSourcesByAgent:()=>zH,listTokenSources:()=>s0,listTokenSourceAccounts:()=>HH,listEnabledTokenSourcesByAgent:()=>wZ,getTokenSourceForAccount:()=>j0,getTokenSource:()=>M0,ANTHROPIC_ENV_KEYS:()=>s3});function o0($){let Z={...$};for(let J of s3)delete Z[J];return delete Z.LODESTAR_PACKY_API_KEY,Z}function p9($){let Z=o0($);for(let J of Object.keys(Z))if(/^(DSH_|DEEPSEEK_|LODESTAR_DSH_|ZAI_|ZHIPU_)/.test(J))delete Z[J];return Z}function f1($){return $.modelSelection?[...$.models,...$.modelSelection.availableModels.filter((Z)=>!$.models.some((J)=>J.model===Z.model))]:$.models}function n$($,Z){let J=(Q)=>$.agent==="claude"?Q?.replace(/\[1m\]$/,""):Q;return f1($).find((Q)=>J(Q.model)===J(Z))}function C4($,Z){let J=$?.spawnRevision??null,Q=$?.modelEnvironmentRevision?.(Z??$.defaultModel);return Q===void 0?J:JSON.stringify([J,Q])}function N0($){XH.set($.kind,$)}function U2(){return[...XH.values()]}function bZ(){return xZ}function kZ($,Z){if(c9.set($.id,$),Z?.default||o3===null)o3=$.id}function M0($){return $?c9.get($):void 0}function j0($,Z="default"){let J=M0($);return J?.forAccount?J.forAccount(Z):J}function s0(){return[...c9.values()]}function zH($){return s0().filter((Z)=>Z.agent===$)}function wZ($){return zH($).filter((Z)=>Z.enabled)}function vZ($){if(c9.has($))o3=$}function yZ(){c9.clear(),o3=null,xZ++}function pD(){let $=xZ;if(S4?.generation===$)return S4.promise;let Z=Promise.allSettled(HH().map(async(J)=>{await J.refreshModels(),j(`token-source ${J.id}: ${J.models.length} models loaded`)})).then(()=>{}).finally(()=>{if(S4?.promise===Z)S4=null});return S4={generation:$,promise:Z},Z}function HH(){return s0().flatMap(($)=>$.forAccount?v.list().map((Z)=>$.forAccount(Z.id)):[$])}function GH(){return S4?.promise??null}async function cD(){let $;while($=GH())await $}var s3,XH,c9,o3=null,xZ=0,S4=null;var X0=R(()=>{I();D0();s3=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","CLAUDE_CODE_SUBAGENT_MODEL","ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_EFFORT_LEVEL"];XH=new Map;c9=new Map});import{existsSync as uD,readFileSync as lD}from"node:fs";class KH{deps;lastUses=new Map;constructor($){this.deps=$}recordUsage($,Z,J){let Q=J??this.deps.cachedUsage($);if(Q?.state!=="ok")return;let Y=Q.accountFingerprint??this.deps.identity($);if(!Y)return;this.lastUses.set(JSON.stringify([Y,_2(Q,Z)]),this.deps.now())}weekWasUsed($,Z,J){let Q=this.lastUses.get(JSON.stringify([$,_2(Z,J)]));return Q!==void 0&&yz(Z,J,Q)}blocks(){if(!uD(this.deps.stateFile))return[];let $=JSON.parse(lD(this.deps.stateFile,"utf8"));if($?.version!==1||!Array.isArray($.blocks)||$.blocks.some((Z)=>typeof Z?.key!=="string"||typeof Z?.identity!=="string"||typeof Z?.meter!=="string"||!Array.isArray(Z?.windows)||Z.credits!=null&&(!g3(Z.credits)||Z.credits.balance!==null&&!Number.isFinite(Z.credits.balance))||Z.creditsObservedAt!==void 0&&!Number.isFinite(Z.creditsObservedAt)||Z.windows.some((J)=>!["fiveHour","weekly"].includes(J?.kind)||J.percent!==null&&!Number.isFinite(J.percent)||J.reset!==null&&!Number.isFinite(J.reset))))throw Error("Codex 额度耗尽记录格式无效");return $.blocks}block($,Z){if(!$.usage)throw Error("未读取额度,不能记录耗尽窗口");let J=$.usage.state==="ok"?j2($.usage,Z):null,Q=["fiveHour","weekly"].flatMap((z)=>{let H=J?.[z];return H?[{kind:z,percent:H.percent,reset:H.resetsAt?.getTime()??null}]:[]}),Y=_2($.usage,Z),V=JSON.stringify([$.identity,Y]),X=this.blocks().filter((z)=>z.key!==V);X.push({key:V,identity:$.identity,meter:Y,windows:Q,credits:J?.credits??null,blockedAt:this.deps.now()}),r(this.deps.stateFile,{version:1,blocks:X})}async choose($){$.signal?.throwIfAborted();let Z=this.deps.accounts();if($.preferred){let Q=Z.find((Y)=>Y.id===$.preferred);if(!Q)throw Error(`指定 Codex 账号不存在:${$.preferred}`);return{selected:{account:Q,identity:`record:${Q.id}`,usage:null,state:"manual",score:null,shares:null,remaining:null,hours:null},candidates:[]}}let J=new Map;if($.preferCachedUsage){let Q=await this.chooseAutomatic(Z,$,!0,J);if(Q.selected)return Q}return this.chooseAutomatic(Z,$,!1,J)}async chooseAutomatic($,Z,J,Q){Z.signal?.throwIfAborted();let Y=await Promise.all($.map(async(q)=>{let F,M=null,U=`record:${q.id}`;if(this.deps.pendingLogin(q.id))F={state:"network",reason:"正在登录"};else try{F=J?this.deps.cachedUsage(q.id):await this.deps.usage(q.id);let A=F?.state==="ok"?F.accountFingerprint??this.deps.identity(q.id):null;if(A)U=A;else if(F?.state==="ok")M="账号身份 MISS";if(F?.state==="ok"&&!M){let O=Q.get(q.id);if(!O)O=this.deps.compatible(q.id,Z.model,Z.effort),Q.set(q.id,O);M=await O}}catch(A){F={state:"network",reason:String(A)}}return{account:q,usage:F,identity:U,reason:M}}));Z.signal?.throwIfAborted();let V=Z.failedAccountId&&Y.find((q)=>q.account.id===Z.failedAccountId);if(V&&V.usage?.state==="ok")this.block({account:V.account,usage:V.usage,identity:V.identity,...h9(V.usage,Z.model,this.deps.now(),Z.effort)},Z.model);let X=this.blocks(),z=this.deps.now(),H=new Set,G=new Map,W=new Map,K=Y.map(({account:q,usage:F,identity:M,reason:U})=>{let A=h9(F??{state:"network",reason:"尚无额度缓存"},Z.model,z,Z.effort);if(U)A={...A,state:"miss",score:null,reason:U};let O=W.get(M);if(W.set(M,O??q.name),O)A={...A,state:"miss",score:null,reason:`重复账号:${O}`};let N=F?.state==="ok"?_2(F,Z.model):null,S=X.find((T)=>(T.identity===M||T.identity===`record:${q.id}`)&&T.meter===N);if(S&&F?.state==="ok"&&!O){let T=j2(F,Z.model),f=F.readStartedAt??F.fetchedAt,m=f>(S.blockedAt??0),b=m&&f>(S.creditsObservedAt??0),p=b&&kz(S.credits,T.credits),c=m&&A.funding!=="credits"&&S.windows.some((J0)=>{let l=T[J0.kind];if(l===null)return!0;return l&&l.percent!==null&&(J0.percent!==null&&l.percent<J0.percent||J0.reset!==null&&J0.reset<=z&&(l.resetsAt?.getTime()??0)>J0.reset)});if(A.state==="ready")if(c||p)H.add(S.key);else A={...A,state:"exhausted",score:null,reason:"上次请求已确认额度耗尽,等待接口确认恢复"};if(!H.has(S.key)&&b&&!p&&T.credits!=null)G.set(S.key,{...S,credits:T.credits,creditsObservedAt:f})}return{account:q,usage:F,identity:M,...A,...O?{duplicateOf:O}:{}}});if(H.size||G.size)r(this.deps.stateFile,{version:1,blocks:X.filter((q)=>!H.has(q.key)).map((q)=>G.get(q.key)??q)});let B=K.filter((q)=>q.state==="ready");B.sort(m3);let _=B[0]??null,P=K.filter((q)=>q.state==="exhausted"||q.state==="waiting"),L=P.length?Math.min(...P.map((q)=>q.retryAt??z+60000)):void 0;for(let q of K)j(`codex scheduler${J?" [cache]":""}: ${q.account.name} ${q.state} priority=${q.funding??q.priority??"score"} score=${q.score??(q.funding==="credits"||q.priority==="expiring"?"N/A":"MISS")}${q.reason?` (${q.reason})`:""}`);return{selected:_,candidates:K,...L!==void 0?{retryAt:L}:{}}}}function dD($,Z,J){let Q=n$($,Z);if(!Q)return`模型目录缺少 ${Z}`;if(Q.unavailableReason)return`${Z} 不可用:${Q.unavailableReason}`;if(J&&!Q.efforts.includes(J))return`${Z} 缺少推理档位 ${J}(目录档位:${Q.efforts.join("、")||"MISS"})`;return null}async function iD($,Z,J,Q=Date.now()){if(!$.enabled||$.modelCatalogState?.status!=="ready")return`模型目录查询失败:${$.modelCatalogState?.error??($.enabled?"模型目录 MISS":"订阅来源未启用")}`;return dD($,Z,J)}var O2;var t3=R(()=>{D0();z$();T4();X0();H0();b0();I();O2=new KH({accounts:()=>v.list(),usage:async($)=>D2($)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"},cachedUsage:M2,identity:($)=>v.fingerprint($),pendingLogin:k1,now:Date.now,stateFile:_X,compatible:async($,Z,J)=>{let Q=j0("codex-sub",$);if(!Q)return"订阅来源 MISS";return iD(Q,Z,J)}})});import{createHash as nD}from"node:crypto";import{readFile as aD}from"node:fs/promises";import{join as oD}from"node:path";function BH($){if(!$?.enabled||$.kind!=="codex-subscription"||$.modelCatalogState?.status!=="ready")throw Error(`后台激活模型目录 MISS:${$?.modelCatalogState?.error??"订阅目录未就绪"}`);let Z=($.modelSelection?.availableModels??$.models).find((Q)=>Q.model===P1&&Q.origin!=="custom");if(!Z||Z.unavailableReason)throw Error(`后台激活需要 ${P1}:${Z?.unavailableReason??"原生目录未提供"}`);let J=L2.find((Q)=>Z.efforts.includes(Q));if(!J)throw Error(`${P1} 推理档位 MISS`);return J}function sD($){return{model:P1,instructions:"",store:!1,stream:!0,input:[{role:"user",content:[{type:"input_text",text:"你好,只回复“你好”。"}]}],tools:[],tool_choice:"none",parallel_tool_calls:!1,reasoning:{effort:$},text:{verbosity:"low"},service_tier:"default"}}function fZ($){let Z=h9($,"");return!!$.defaultLimitId&&($.fiveHour===null||$.fiveHour.percent===0)&&vz($,"")&&Z.state==="ready"&&Z.funding!=="credits"}async function tD($){let Z;try{Z=await aD(oD(v.home($),"auth.json"),"utf8")}catch(Q){throw Error(`后台激活无法读取原生 auth.json:${Q.code??"读取失败"}`)}let J;try{J=JSON.parse(Z)}catch{throw Error("后台激活的原生 auth.json 不是有效 JSON")}if(J?.auth_mode!=="chatgpt"||typeof J.tokens?.access_token!=="string"||!J.tokens.access_token||typeof J.tokens.account_id!=="string"||!J.tokens.account_id)throw Error("后台激活的原生 ChatGPT 文件登录态无效");return{accessToken:J.tokens.access_token,accountId:J.tokens.account_id}}function rD($){if(typeof $!=="string"||!$)throw Error("原生 chatgpt_base_url MISS");let Z=new URL($);if(!["http:","https:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("原生 chatgpt_base_url 格式无效");let J=Z.pathname.replace(/\/+$/,"");return Z.pathname=J.endsWith("/codex/responses")?J:J.endsWith("/codex")?`${J}/responses`:`${J}/codex/responses`,Z.href}async function eD($,Z){if(!$.ok)throw Error(`后台激活 HTTP ${$.status}:${await $.text()}`);if(!$.body)throw Error("后台激活响应缺少事件流");let J=$.body.getReader(),Q=new TextDecoder,Y="",V="",X,z=()=>{let H=V;if(V="",!H||H.trim()==="[DONE]")return;let G;try{G=JSON.parse(H)}catch{throw Error("后台激活返回无效 JSON 事件")}if(G.type==="error"||["response.failed","response.incomplete"].includes(G.type))throw Error(`后台激活失败:${G.error?.message??G.response?.error?.message??G.message??G.type}`);if(!["response.completed","response.done"].includes(G.type))return;if(G.response?.status!=="completed")throw Error(`后台激活终态异常:${G.response?.status??"MISS"}`);let W=G.response?.usage?.total_tokens;if(!Number.isFinite(W)||W<=0)throw Error("后台激活已结束,但真实 token 用量 MISS");return W};try{while(!0){let{value:H,done:G}=await J.read();if(Y+=G?Q.decode():Q.decode(H,{stream:!0}),Y.length+V.length>1e6)throw Error("后台激活响应事件超过大小限制");let W;while((W=Y.indexOf(`
92
92
  `))>=0){let K=Y.slice(0,W).replace(/\r$/,"");if(Y=Y.slice(W+1),K.startsWith("data:"))V+=`${K.slice(5).trimStart()}
93
- `;else if(!K){let B=z();if(B!==void 0)return Z?.(B),B}}if(G)throw Error("后台激活连接在确认成功前结束")}}catch(H){throw X=H,H}finally{try{await J.cancel()}catch(H){if(X)throw AggregateError([X,H],`${String(X)};响应流关闭失败:${H}`);throw H}finally{J.releaseLock()}}}async function jH(){let Z=(await Promise.allSettled([...u9.values()].map((J)=>J.close()))).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,`后台激活连接未全部退出:${Z.map(String).join(";")}`)}async function _H($,Z=$M){$.signal.throwIfAborted();let J=Z.createClient($.accountId),Q=new AbortController,Y=()=>Q.abort($.signal.reason);$.signal.addEventListener("abort",Y,{once:!0});let V=setTimeout(()=>Q.abort(Error("后台激活请求超过 60 秒")),60000),X,z,H=!1;try{await J.initialize("lodestar-codex-activation");let G=(await J.request("config/read",{}))?.config;if(G?.cli_auth_credentials_store!=="file")throw Error("零上下文后台激活需要原生文件登录态;当前凭据存储不支持,普通 Codex 会话仍可使用");let W=rF(G.chatgpt_base_url),K=(await J.request("account/read",{refreshToken:!0}))?.account;if(K?.type!=="chatgpt")throw Error("后台激活账号未登录 ChatGPT 订阅");let B=await Z.credentials($.accountId);X=B.accessToken,Q.signal.throwIfAborted();let _=0,P=await i$(()=>{return Q.signal.throwIfAborted(),_=Date.now(),J.request("account/rateLimits/read",{})},"激活前额度确认"),L=m9(P,K.planType,_);if(L.state!=="ok")throw Error(`激活前额度 MISS:${L.state==="network"?L.reason:L.state}`);let q=nF("sha256").update(B.accountId).digest("hex");if(!L.accountFingerprint||L.accountFingerprint!==$.identity||L.accountFingerprint!==q)throw Error("后台激活账号身份与最新额度不一致");if(Q.signal.throwIfAborted(),yZ(L)&&$.eligible(L)){if(_2(L,P1)!==L.defaultLimitId)throw Error(`${P1} 被分配到独立额度,不能用于激活主额度`);let D=await Z.fetch(W,{method:"POST",redirect:"error",signal:Q.signal,headers:{authorization:`Bearer ${X}`,"chatgpt-account-id":B.accountId,"content-type":"application/json",accept:"text/event-stream","OpenAI-Beta":"responses=experimental",originator:"lodestar","user-agent":"lodestar-codex-activation"},body:JSON.stringify(sF($.effort))});await eF(D,(U)=>{H=!0,$.used(L,U)}),Q.signal.throwIfAborted();let M=await Z.refresh(J,$.accountId);if(M?.state!=="ok")throw Error(`额度复核 MISS:${M?.state==="network"?M.reason:M?.state??"读取失败"}`)}}catch(G){let W=G instanceof Error?G.message:String(G),K=X?W.split(X).join("[REDACTED]"):W;z=Error(`${H?"后台激活请求已成功;":""}${K.slice(0,2000)}`)}clearTimeout(V),$.signal.removeEventListener("abort",Y);try{await J.close()}catch(G){z=AggregateError(z?[z,G]:[G],`${z?`${String(z)};`:H?"后台激活请求已成功;":""}后台激活控制连接关闭失败:${G}`)}if(z)throw z;return H?"sent":"skipped"}var P1="gpt-6-luna",u9,$M;var PH=R(()=>{F0();j1();T4();u0();z$();u9=new Map;$M={createClient:($)=>{if(u9.has($))throw Error("该账号上次后台激活连接尚未退出");let Z=new w$({accountId:$});return u9.set($,Z),Z.once("exit",()=>{if(u9.get($)===Z)u9.delete($)}),Z},credentials:tF,fetch:V0,refresh:($,Z)=>{return d$(Z),QH((J,Q)=>$.request(J,Q),Z)}}});class qH{deps;entries=new Map;controller;timer;pending;constructor($){this.deps=$}start(){if(this.controller)return;this.controller=new AbortController,this.schedule(0)}async stop(){clearTimeout(this.timer),this.controller?.abort(Error("服务退出,取消后台激活")),this.controller=void 0;let $=[];try{await this.pending}catch(Z){$.push(Z)}this.entries.clear();try{await this.deps.close?.()}catch(Z){$.push(Z)}if($.length)throw AggregateError($,`后台激活停止失败:${$.map(String).join(";")}`)}error($){return[...this.entries.values()].find((Z)=>Z.accountId===$)?.error}schedule($){if(clearTimeout(this.timer),!this.controller)return;$??=Math.min(JM,...[...this.entries.values()].filter((Z)=>!Z.completed).map((Z)=>Math.max(0,Z.dueAt-this.deps.now()))),this.timer=setTimeout(()=>{this.check().catch((Z)=>this.deps.log(`codex activation scan MISS: ${Z}`)).finally(()=>this.schedule())},$),this.timer.unref?.()}dueAt(){let $=this.deps.random();if(!Number.isFinite($)||$<0||$>=1)throw Error("后台激活随机间隔无效");return this.deps.now()+LH+Math.floor($*(ZM-LH))}check(){if(this.pending)return this.pending;let $=this.controller?.signal;if(!$||$.aborted)return Promise.resolve();let Z=this.scan($).finally(()=>{if(this.pending===Z)this.pending=void 0});return this.pending=Z,Z}async scan($){let Z=this.deps.accounts(),J=new Set(Z.flatMap((Y)=>Y.usage?.accountFingerprint?[Y.usage.accountFingerprint]:[]));for(let Y of this.entries.keys())if(!J.has(Y))this.entries.delete(Y);let Q=new Set;for(let Y of Z){if($.aborted)return;let V=Y.usage,X=V?.accountFingerprint;if(!V||!X||Q.has(X))continue;Q.add(X);let z=this.entries.get(X);if(!yZ(V)||this.deps.used(X,V)){if(!z?.completed||!z.error||z.revision!==Y.revision)this.entries.delete(X);continue}if(z?.completed)z=void 0;if(!z||z.revision!==Y.revision||z.accountId!==Y.id)z={accountId:Y.id,revision:Y.revision,dueAt:this.dueAt(),completed:!1},this.entries.set(X,z);if(z.completed||this.deps.now()<z.dueAt)continue;z.dueAt=this.dueAt();try{let H=Y.revision;if(this.deps.loginPending(Y.id))throw Error("账号正在登录,后台激活延后");let G=BH(this.deps.source(Y.id)),W=await this.deps.activate({accountId:Y.id,identity:X,effort:G,signal:$,eligible:(K)=>!$.aborted&&this.deps.accounts().some((B)=>B.id===Y.id&&B.revision===H&&B.usage?.accountFingerprint===X)&&!this.deps.loginPending(Y.id)&&!this.deps.used(X,K),used:(K,B)=>{z.completed=!0,this.deps.recordUsage(Y.id,K),this.deps.log(`codex activation: ${Y.name} ${P1}/${G} completed tokens=${B}`)}});if(z.error=void 0,W==="skipped")this.deps.log(`codex activation: ${Y.name} skipped after fresh quota/account check`)}catch(H){z.error=H instanceof Error?H.message:String(H),this.deps.log(`codex activation: ${Y.name} MISS: ${z.error}`)}}}}var LH=1800000,ZM=3600000,JM=60000,l9;var hZ=R(()=>{F0();t3();PH();I();X0();z$();l9=new qH({accounts:()=>v.list().map(($)=>({id:$.id,name:$.name,revision:v.revision($.id),usage:M2($.id)})),source:($)=>j0("codex-sub",$),loginPending:k1,used:($,Z)=>O2.weekWasUsed($,Z,""),recordUsage:($,Z)=>O2.recordUsage($,P1,Z),activate:_H,now:Date.now,random:Math.random,log:j,close:jH})});function a$($){return typeof $==="string"&&IZ.includes($)}function S0($){return typeof $==="string"&&["off","minimal","low","medium","high","xhigh","max"].includes($)}function w0($){return typeof $==="string"&&d9.includes($)}function x4($){if($?.startsWith("dsh:"))return"dsh";return $?.startsWith("claude:")?"claude":"codex"}function t0($){return{claude:"Claude",codex:"Codex",dsh:"DeepSeek Harness"}[$]}function v$($){return $.translationEnabled===!0}var IZ,d9,h1="max",A2,b4;var P0=R(()=>{IZ=["codex","claude","dsh"];d9=["low","medium","high","xhigh","max","default"];A2=class A2 extends Error{constructor($="上下文窗口充足,无需压缩"){super($);this.name="NothingToCompactError"}};b4=class b4 extends Error{confirmedModel;constructor($,Z,J){super($,J);this.confirmedModel=Z;this.name="ModelSettingsUpdateError"}}});function s($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function N2($,Z){let J=$.agent==="claude"?d9.filter((Y)=>Y!=="default"):$.agent==="codex"?[...L2]:["off","minimal","low","medium","high","xhigh","max"],Q=Z.effort?.trim();return{efforts:J,defaultEffort:Q&&J.includes(Q)?Q:$.agent==="claude"?"max":$.agent==="codex"?"xhigh":"high"}}function r3($,Z){let J=$.modelSelection,Q=new Set(s(Z.hidden_models)),Y=J?.visibilityKey??((H)=>H),V=[...new Set([...s(Z.custom_models),...J?[]:s(Z.models)])],X=$.modelSelection=J??{mode:"catalog",modelIds:[],availableModels:[]},z=$.refreshModels.bind($);return $.refreshModels=async()=>{if($.models=[],X.availableModels=[],!J)X.modelIds=[];try{await z()}catch(_){throw $.models=[],$.modelCatalogState={status:"failed",updatedAt:Date.now(),error:_ instanceof Error?_.message:String(_)},_}if($.modelCatalogState?.status!=="ready")return;let H=$.models,G=(J?X.availableModels:H).map((_)=>({..._,origin:_.origin??"upstream"}));for(let _ of V){if(G.some((P)=>P.model.toLowerCase()===_.toLowerCase()))continue;G.push({model:_,display:_,origin:"custom",...N2($,Z)})}X.availableModels=G;let W=J?H.map((_)=>G.find((P)=>P.model===_.model)??{..._,origin:"upstream"}):G,K=new Set(J?.selectDefaults?.(G)??[]),B=new Set(s(Z.shown_models));$.models=[...W.filter((_)=>_.origin==="custom"||!Q.has(_.model)&&(!K.has(_.model)||B.has(_.model)||!Q.has(Y(_.model)))),...G.filter((_)=>_.origin==="custom"&&!W.some((P)=>P.model===_.model))],X.modelIds=$.models.map((_)=>_.model)},$}var L1=R(()=>{P0();j1()});function I1($){return $.startsWith("claude:")?$:`claude:${$}`}function i9($){if(!$||$==="default"||$==="claude:default")return"opus";if(!$.startsWith("claude:"))return $;let Z=$.slice(7);if(Z==="glm"||Object.hasOwn(g.claude.models,Z))return g.claude.models[Z]?.model?.trim()||"opus";return Z}var gZ=R(()=>{k0()});import{existsSync as QM,readFileSync as YM}from"node:fs";function mZ(){return process.env.LODESTAR_DATA_DIR?`${process.env.LODESTAR_DATA_DIR.replace(/\/+$/,"")}/context-window-cache.json`:PX}function a9(){if(n9!==null)return n9;try{n9=QM(mZ())?JSON.parse(YM(mZ(),"utf8")):{}}catch($){j(`context-window-observe: cache read MISS (${$?.message??$}), starting fresh`),n9={}}return n9??{}}function XM(){try{r(mZ(),a9())}catch($){j(`context-window-observe: cache write MISS (${$?.message??$})`)}}function pZ($,Z){return`${$}:${Z.replace(/\[1m\]$/,"")}`}function DH($,Z,J){if(!Number.isFinite(J)||J<=0)return;let Q=pZ($,Z),Y=a9()[Q];if(Y===J)return;a9()[Q]=J,XM(),j(`context-window-observe: ${Q} → ${J} (prev ${Y??"-"})`)}function e3($,Z){if(!Z)return;if(Z.endsWith("[1m]"))return Z;let J=a9()[pZ($,Z)];return J!=null&&J<VM?Z:`${Z}[1m]`}function k4($,Z){return a9()[pZ($,Z)]}var VM=1e6,n9=null;var o9=R(()=>{H0();I();b0()});function zM($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s9($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Q=0;while(Q<$.length){J.lastIndex=Q;let Y=J.exec($);if(!Y)break;let V=Y[1];if(V[0]==="`"&&Y[0].trimStart().slice(V.length).includes("`")){Q=Y.index+Y[0].length;continue}let X=new RegExp(`^(?: {0,3})${zM(V[0])}{${V.length},}[ \\t]*(?:\\n|$)`,"gm");X.lastIndex=Y.index+Y[0].length;let z=X.exec($),H=z?z.index+z[0].length:$.length;Z.push({start:Y.index,end:H}),Q=H}return Z}function cZ($){let Z=s9($),J=[...Z],Q=[],Y=0;for(let V of Z){if(Y<V.start)Q.push({start:Y,end:V.start});Y=V.end}if(Y<$.length)Q.push({start:Y,end:$.length});for(let V of Q){let X=$.slice(V.start,V.end),z=V.start;for(let H of X.split(/(\r?\n[ \t]*\r?\n)/)){let G=z;z+=H.length;let W=[...H.matchAll(/`+/g)],K=new Map,B=[];for(let _=W.length-1;_>=0;_--){let P=W[_][0].length;B[_]=K.get(P),K.set(P,_)}for(let _=0;_<W.length;_++){let P=B[_];if(P===void 0)continue;let L=W[_],q=W[P];J.push({start:G+L.index,end:G+q.index+q[0].length}),_=P}}}return J.sort((V,X)=>V.start-X.start)}import{createHash as HM}from"node:crypto";import{lstatSync as GM,mkdirSync as WM,readFileSync as KM,realpathSync as BM}from"node:fs";import{join as FH,resolve as MH}from"node:path";function t9($){switch($){case"user":return i.legacyUserMessage;case"user/answer":return i.legacyUserAnswer;case"assistant/question":return i.question;case"assistant/command-description":return i.commandExplanation;case"assistant/task-text":return i.taskText;case"assistant/tool-result":return i.toolResult;case"assistant/error":return i.error;case"assistant/background":return i.backgroundUpdate;case"assistant/scheduled":return i.scheduledPrompt;default:return $==="assistant"||$.startsWith("assistant/")?i.legacyVisibleOutput:i.legacyUnknown}}function $7($){return!!$&&typeof $==="object"&&!Array.isArray($)}function L0($){return typeof $==="string"&&!!$.trim()}function UH($){return HM("sha256").update($).digest("hex")}function T2($){let Z="",J=0;for(let Q of s9($))Z+=$.slice(J,Q.start),J=Q.end;return(Z+$.slice(J)).replace(/\[\[send:\s*[^\]\n]+\]\]|\[file:\s*[^\]\n]+\]/g,"").trim()}function jM($,Z,J){let Q=()=>{throw Error(`Claude translation context legacy pair is malformed or ambiguous: ${J}`)},Y,V;if($==="user")Y=`Original user text:
93
+ `;else if(!K){let B=z();if(B!==void 0)return Z?.(B),B}}if(G)throw Error("后台激活连接在确认成功前结束")}}catch(H){throw X=H,H}finally{try{await J.cancel()}catch(H){if(X)throw AggregateError([X,H],`${String(X)};响应流关闭失败:${H}`);throw H}finally{J.releaseLock()}}}async function jH(){let Z=(await Promise.allSettled([...u9.values()].map((J)=>J.close()))).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,`后台激活连接未全部退出:${Z.map(String).join(";")}`)}async function _H($,Z=$M){$.signal.throwIfAborted();let J=Z.createClient($.accountId),Q=new AbortController,Y=()=>Q.abort($.signal.reason);$.signal.addEventListener("abort",Y,{once:!0});let V=setTimeout(()=>Q.abort(Error("后台激活请求超过 60 秒")),60000),X,z,H=!1;try{await J.initialize("lodestar-codex-activation");let G=(await J.request("config/read",{}))?.config;if(G?.cli_auth_credentials_store!=="file")throw Error("零上下文后台激活需要原生文件登录态;当前凭据存储不支持,普通 Codex 会话仍可使用");let W=rD(G.chatgpt_base_url),K=(await J.request("account/read",{refreshToken:!0}))?.account;if(K?.type!=="chatgpt")throw Error("后台激活账号未登录 ChatGPT 订阅");let B=await Z.credentials($.accountId);X=B.accessToken,Q.signal.throwIfAborted();let _=0,P=await i$(()=>{return Q.signal.throwIfAborted(),_=Date.now(),J.request("account/rateLimits/read",{})},"激活前额度确认"),L=m9(P,K.planType,_);if(L.state!=="ok")throw Error(`激活前额度 MISS:${L.state==="network"?L.reason:L.state}`);let q=nD("sha256").update(B.accountId).digest("hex");if(!L.accountFingerprint||L.accountFingerprint!==$.identity||L.accountFingerprint!==q)throw Error("后台激活账号身份与最新额度不一致");if(Q.signal.throwIfAborted(),fZ(L)&&$.eligible(L)){if(_2(L,P1)!==L.defaultLimitId)throw Error(`${P1} 被分配到独立额度,不能用于激活主额度`);let F=await Z.fetch(W,{method:"POST",redirect:"error",signal:Q.signal,headers:{authorization:`Bearer ${X}`,"chatgpt-account-id":B.accountId,"content-type":"application/json",accept:"text/event-stream","OpenAI-Beta":"responses=experimental",originator:"lodestar","user-agent":"lodestar-codex-activation"},body:JSON.stringify(sD($.effort))});await eD(F,(U)=>{H=!0,$.used(L,U)}),Q.signal.throwIfAborted();let M=await Z.refresh(J,$.accountId);if(M?.state!=="ok")throw Error(`额度复核 MISS:${M?.state==="network"?M.reason:M?.state??"读取失败"}`)}}catch(G){let W=G instanceof Error?G.message:String(G),K=X?W.split(X).join("[REDACTED]"):W;z=Error(`${H?"后台激活请求已成功;":""}${K.slice(0,2000)}`)}clearTimeout(V),$.signal.removeEventListener("abort",Y);try{await J.close()}catch(G){z=AggregateError(z?[z,G]:[G],`${z?`${String(z)};`:H?"后台激活请求已成功;":""}后台激活控制连接关闭失败:${G}`)}if(z)throw z;return H?"sent":"skipped"}var P1="gpt-6-luna",u9,$M;var PH=R(()=>{D0();j1();T4();u0();z$();u9=new Map;$M={createClient:($)=>{if(u9.has($))throw Error("该账号上次后台激活连接尚未退出");let Z=new w$({accountId:$});return u9.set($,Z),Z.once("exit",()=>{if(u9.get($)===Z)u9.delete($)}),Z},credentials:tD,fetch:V0,refresh:($,Z)=>{return d$(Z),QH((J,Q)=>$.request(J,Q),Z)}}});class qH{deps;entries=new Map;controller;timer;pending;constructor($){this.deps=$}start(){if(this.controller)return;this.controller=new AbortController,this.schedule(0)}async stop(){clearTimeout(this.timer),this.controller?.abort(Error("服务退出,取消后台激活")),this.controller=void 0;let $=[];try{await this.pending}catch(Z){$.push(Z)}this.entries.clear();try{await this.deps.close?.()}catch(Z){$.push(Z)}if($.length)throw AggregateError($,`后台激活停止失败:${$.map(String).join(";")}`)}error($){return[...this.entries.values()].find((Z)=>Z.accountId===$)?.error}schedule($){if(clearTimeout(this.timer),!this.controller)return;$??=Math.min(JM,...[...this.entries.values()].filter((Z)=>!Z.completed).map((Z)=>Math.max(0,Z.dueAt-this.deps.now()))),this.timer=setTimeout(()=>{this.check().catch((Z)=>this.deps.log(`codex activation scan MISS: ${Z}`)).finally(()=>this.schedule())},$),this.timer.unref?.()}dueAt(){let $=this.deps.random();if(!Number.isFinite($)||$<0||$>=1)throw Error("后台激活随机间隔无效");return this.deps.now()+LH+Math.floor($*(ZM-LH))}check(){if(this.pending)return this.pending;let $=this.controller?.signal;if(!$||$.aborted)return Promise.resolve();let Z=this.scan($).finally(()=>{if(this.pending===Z)this.pending=void 0});return this.pending=Z,Z}async scan($){let Z=this.deps.accounts(),J=new Set(Z.flatMap((Y)=>Y.usage?.accountFingerprint?[Y.usage.accountFingerprint]:[]));for(let Y of this.entries.keys())if(!J.has(Y))this.entries.delete(Y);let Q=new Set;for(let Y of Z){if($.aborted)return;let V=Y.usage,X=V?.accountFingerprint;if(!V||!X||Q.has(X))continue;Q.add(X);let z=this.entries.get(X);if(!fZ(V)||this.deps.used(X,V)){if(!z?.completed||!z.error||z.revision!==Y.revision)this.entries.delete(X);continue}if(z?.completed)z=void 0;if(!z||z.revision!==Y.revision||z.accountId!==Y.id)z={accountId:Y.id,revision:Y.revision,dueAt:this.dueAt(),completed:!1},this.entries.set(X,z);if(z.completed||this.deps.now()<z.dueAt)continue;z.dueAt=this.dueAt();try{let H=Y.revision;if(this.deps.loginPending(Y.id))throw Error("账号正在登录,后台激活延后");let G=BH(this.deps.source(Y.id)),W=await this.deps.activate({accountId:Y.id,identity:X,effort:G,signal:$,eligible:(K)=>!$.aborted&&this.deps.accounts().some((B)=>B.id===Y.id&&B.revision===H&&B.usage?.accountFingerprint===X)&&!this.deps.loginPending(Y.id)&&!this.deps.used(X,K),used:(K,B)=>{z.completed=!0,this.deps.recordUsage(Y.id,K),this.deps.log(`codex activation: ${Y.name} ${P1}/${G} completed tokens=${B}`)}});if(z.error=void 0,W==="skipped")this.deps.log(`codex activation: ${Y.name} skipped after fresh quota/account check`)}catch(H){z.error=H instanceof Error?H.message:String(H),this.deps.log(`codex activation: ${Y.name} MISS: ${z.error}`)}}}}var LH=1800000,ZM=3600000,JM=60000,l9;var hZ=R(()=>{D0();t3();PH();I();X0();z$();l9=new qH({accounts:()=>v.list().map(($)=>({id:$.id,name:$.name,revision:v.revision($.id),usage:M2($.id)})),source:($)=>j0("codex-sub",$),loginPending:k1,used:($,Z)=>O2.weekWasUsed($,Z,""),recordUsage:($,Z)=>O2.recordUsage($,P1,Z),activate:_H,now:Date.now,random:Math.random,log:j,close:jH})});function a$($){return typeof $==="string"&&IZ.includes($)}function S0($){return typeof $==="string"&&["off","minimal","low","medium","high","xhigh","max"].includes($)}function w0($){return typeof $==="string"&&d9.includes($)}function x4($){if($?.startsWith("dsh:"))return"dsh";return $?.startsWith("claude:")?"claude":"codex"}function t0($){return{claude:"Claude",codex:"Codex",dsh:"DeepSeek Harness"}[$]}function v$($){return $.translationEnabled===!0}var IZ,d9,h1="max",A2,b4;var P0=R(()=>{IZ=["codex","claude","dsh"];d9=["low","medium","high","xhigh","max","default"];A2=class A2 extends Error{constructor($="上下文窗口充足,无需压缩"){super($);this.name="NothingToCompactError"}};b4=class b4 extends Error{confirmedModel;constructor($,Z,J){super($,J);this.confirmedModel=Z;this.name="ModelSettingsUpdateError"}}});function s($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function N2($,Z){let J=$.agent==="claude"?d9.filter((Y)=>Y!=="default"):$.agent==="codex"?[...L2]:["off","minimal","low","medium","high","xhigh","max"],Q=Z.effort?.trim();return{efforts:J,defaultEffort:Q&&J.includes(Q)?Q:$.agent==="claude"?"max":$.agent==="codex"?"xhigh":"high"}}function r3($,Z){let J=$.modelSelection,Q=new Set(s(Z.hidden_models)),Y=J?.visibilityKey??((H)=>H),V=[...new Set([...s(Z.custom_models),...J?[]:s(Z.models)])],X=$.modelSelection=J??{mode:"catalog",modelIds:[],availableModels:[]},z=$.refreshModels.bind($);return $.refreshModels=async()=>{if($.models=[],X.availableModels=[],!J)X.modelIds=[];try{await z()}catch(_){throw $.models=[],$.modelCatalogState={status:"failed",updatedAt:Date.now(),error:_ instanceof Error?_.message:String(_)},_}if($.modelCatalogState?.status!=="ready")return;let H=$.models,G=(J?X.availableModels:H).map((_)=>({..._,origin:_.origin??"upstream"}));for(let _ of V){if(G.some((P)=>P.model.toLowerCase()===_.toLowerCase()))continue;G.push({model:_,display:_,origin:"custom",...N2($,Z)})}X.availableModels=G;let W=J?H.map((_)=>G.find((P)=>P.model===_.model)??{..._,origin:"upstream"}):G,K=new Set(J?.selectDefaults?.(G)??[]),B=new Set(s(Z.shown_models));$.models=[...W.filter((_)=>_.origin==="custom"||!Q.has(_.model)&&(!K.has(_.model)||B.has(_.model)||!Q.has(Y(_.model)))),...G.filter((_)=>_.origin==="custom"&&!W.some((P)=>P.model===_.model))],X.modelIds=$.models.map((_)=>_.model)},$}var L1=R(()=>{P0();j1()});function I1($){return $.startsWith("claude:")?$:`claude:${$}`}function i9($){if(!$||$==="default"||$==="claude:default")return"opus";if(!$.startsWith("claude:"))return $;let Z=$.slice(7);if(Z==="glm"||Object.hasOwn(g.claude.models,Z))return g.claude.models[Z]?.model?.trim()||"opus";return Z}var gZ=R(()=>{k0()});import{existsSync as QM,readFileSync as YM}from"node:fs";function mZ(){return process.env.LODESTAR_DATA_DIR?`${process.env.LODESTAR_DATA_DIR.replace(/\/+$/,"")}/context-window-cache.json`:PX}function a9(){if(n9!==null)return n9;try{n9=QM(mZ())?JSON.parse(YM(mZ(),"utf8")):{}}catch($){j(`context-window-observe: cache read MISS (${$?.message??$}), starting fresh`),n9={}}return n9??{}}function XM(){try{r(mZ(),a9())}catch($){j(`context-window-observe: cache write MISS (${$?.message??$})`)}}function pZ($,Z){return`${$}:${Z.replace(/\[1m\]$/,"")}`}function FH($,Z,J){if(!Number.isFinite(J)||J<=0)return;let Q=pZ($,Z),Y=a9()[Q];if(Y===J)return;a9()[Q]=J,XM(),j(`context-window-observe: ${Q} → ${J} (prev ${Y??"-"})`)}function e3($,Z){if(!Z)return;if(Z.endsWith("[1m]"))return Z;let J=a9()[pZ($,Z)];return J!=null&&J<VM?Z:`${Z}[1m]`}function k4($,Z){return a9()[pZ($,Z)]}var VM=1e6,n9=null;var o9=R(()=>{H0();I();b0()});function zM($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s9($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Q=0;while(Q<$.length){J.lastIndex=Q;let Y=J.exec($);if(!Y)break;let V=Y[1];if(V[0]==="`"&&Y[0].trimStart().slice(V.length).includes("`")){Q=Y.index+Y[0].length;continue}let X=new RegExp(`^(?: {0,3})${zM(V[0])}{${V.length},}[ \\t]*(?:\\n|$)`,"gm");X.lastIndex=Y.index+Y[0].length;let z=X.exec($),H=z?z.index+z[0].length:$.length;Z.push({start:Y.index,end:H}),Q=H}return Z}function cZ($){let Z=s9($),J=[...Z],Q=[],Y=0;for(let V of Z){if(Y<V.start)Q.push({start:Y,end:V.start});Y=V.end}if(Y<$.length)Q.push({start:Y,end:$.length});for(let V of Q){let X=$.slice(V.start,V.end),z=V.start;for(let H of X.split(/(\r?\n[ \t]*\r?\n)/)){let G=z;z+=H.length;let W=[...H.matchAll(/`+/g)],K=new Map,B=[];for(let _=W.length-1;_>=0;_--){let P=W[_][0].length;B[_]=K.get(P),K.set(P,_)}for(let _=0;_<W.length;_++){let P=B[_];if(P===void 0)continue;let L=W[_],q=W[P];J.push({start:G+L.index,end:G+q.index+q[0].length}),_=P}}}return J.sort((V,X)=>V.start-X.start)}import{createHash as HM}from"node:crypto";import{lstatSync as GM,mkdirSync as WM,readFileSync as KM,realpathSync as BM}from"node:fs";import{join as DH,resolve as MH}from"node:path";function t9($){switch($){case"user":return i.legacyUserMessage;case"user/answer":return i.legacyUserAnswer;case"assistant/question":return i.question;case"assistant/command-description":return i.commandExplanation;case"assistant/task-text":return i.taskText;case"assistant/tool-result":return i.toolResult;case"assistant/error":return i.error;case"assistant/background":return i.backgroundUpdate;case"assistant/scheduled":return i.scheduledPrompt;default:return $==="assistant"||$.startsWith("assistant/")?i.legacyVisibleOutput:i.legacyUnknown}}function $7($){return!!$&&typeof $==="object"&&!Array.isArray($)}function L0($){return typeof $==="string"&&!!$.trim()}function UH($){return HM("sha256").update($).digest("hex")}function T2($){let Z="",J=0;for(let Q of s9($))Z+=$.slice(J,Q.start),J=Q.end;return(Z+$.slice(J)).replace(/\[\[send:\s*[^\]\n]+\]\]|\[file:\s*[^\]\n]+\]/g,"").trim()}function jM($,Z,J){let Q=()=>{throw Error(`Claude translation context legacy pair is malformed or ambiguous: ${J}`)},Y,V;if($==="user")Y=`Original user text:
94
94
  `,V=`
95
95
  English submitted text:
96
96
  `;else if($==="user/answer")Y=`Original user answer:
@@ -99,10 +99,10 @@ Submitted answer:
99
99
  `;else if($.startsWith("assistant/"))Y=`Original Claude output:
100
100
  `,V=`
101
101
  Verified display text:
102
- `;else return Q();if(!Z.startsWith(Y))return Q();let X=Z.slice(Y.length).split(V);if(X.length!==2)return Q();let z=(H)=>T2(H.replaceAll("[Code omitted from translation context.]",""));return{original:z(X[0]),translated:z(X[1])}}function R2($,Z){let J;try{J=GM($)}catch(Y){if(Y.code==="ENOENT")return!1;throw Y}if(J.isSymbolicLink()||(Z?!J.isDirectory():!J.isFile()))throw Error(`Claude translation context path is not a regular ${Z?"directory":"file"}: ${$}`);let Q=Z?448:384;if(process.platform!=="win32"&&(J.mode&511)!==Q)throw Error(`Claude translation context permissions must be ${Q.toString(8)}: ${$}`);return!0}function _M($,Z,J){let Q=()=>{throw Error(`Claude translation context ledger is malformed: ${J}`)};if(!$7($))return Q();if($.workDir!==Z||$.sessionId!==J)throw Error(`Claude translation context session/cwd mismatch for ${J}`);if($.version!==1&&$.version!==2||$.coverage!=="since-enabled"||!Number.isSafeInteger($.sequence)||$.sequence<0||!Array.isArray($.entries)||!Array.isArray($.tools)||!Array.isArray($.checkpoints))return Q();let Y=$.sequence,V=(B)=>Number.isSafeInteger(B)&&B>=0&&B<=Y,X=new Set,z=new Set,H=[],G=0;for(let B of $.entries){let _=$.version===1?["role","text","uuid","status","sequence","key"]:["role","text","original","translated","origin","uuid","status","sequence","key"];if(!$7(B)||Object.keys(B).some((q)=>!_.includes(q))||!L0(B.role)||B.status!=="consumed"||!V(B.sequence)||B.sequence===0||B.origin!==void 0&&!L0(B.origin)||B.uuid!==void 0&&!L0(B.uuid)||B.key!==void 0&&!L0(B.key))return Q();if($.version===1&&!L0(B.text))return Q();if($.version===2&&(typeof B.original!=="string"||typeof B.translated!=="string"||B.text!==void 0&&typeof B.text!=="string"))return Q();if(B.sequence<=G||X.has(B.sequence)||typeof B.key==="string"&&z.has(B.key))return Q();if(G=B.sequence,X.add(B.sequence),typeof B.key==="string")z.add(B.key);let{text:P,...L}=B;H.push({...L,origin:B.origin??t9(B.role),...$.version===1?jM(B.role,P,J):{}})}let W=new Set;for(let B of $.tools){if(!$7(B)||Object.keys(B).some((_)=>!["id","name","sequence"].includes(_))||!L0(B.id)||!L0(B.name)||!V(B.sequence)||B.sequence===0||W.has(B.id)||X.has(B.sequence))return Q();W.add(B.id),X.add(B.sequence)}let K=new Set;for(let B of $.checkpoints){if(!$7(B)||Object.keys(B).some((_)=>!["uuid","sequence"].includes(_))||!L0(B.uuid)||!V(B.sequence)||K.has(B.uuid))return Q();K.add(B.uuid)}return{...$,version:2,entries:H}}class uZ{options;workDir="";sessionId=null;entries=[];stoppedInputs=new Map;tools=[];checkpoints=[];sequence=0;initialization=null;initialized=!1;constructor($){this.options=$}initialize($){if($.throwIfAborted(),!this.initialization)this.initialization=this.loadHistory($);return this.initialization.then(()=>{$.throwIfAborted()})}async loadHistory($){let{resumeSessionId:Z,resumeSessionAt:J,forkSession:Q,workDir:Y}=this.options;if(!Z&&(J||Q))throw Error("Claude translation context requires a fork/resume source session");if(this.workDir=BM(MH(Y)),Z!==void 0&&!L0(Z))throw Error("Claude translation context session id is empty");if(Z){let V=this.readLedger(Z);if(V){let X=V.sequence;if(J){let z=V.checkpoints.find((H)=>H.uuid===J);if(!z)throw Error(`Claude translation context checkpoint not found: ${J}`);X=z.sequence}this.entries=V.entries.filter((z)=>z.sequence<=X),this.tools=V.tools.filter((z)=>z.sequence<=X),this.checkpoints=V.checkpoints.filter((z)=>z.sequence<=X),this.sequence=X}this.sessionId=Q?null:Z}$.throwIfAborted(),this.initialized=!0}storeRoot(){return MH(this.options.storeDir??GX)}workspaceDir(){return FH(this.storeRoot(),UH(this.workDir))}filePath($){return FH(this.workspaceDir(),`${UH($)}.json`)}readLedger($){if(!R2(this.storeRoot(),!0)||!R2(this.workspaceDir(),!0))return null;let Z=this.filePath($);if(!R2(Z,!1))return null;let J;try{J=JSON.parse(KM(Z,"utf8"))}catch(Q){throw Error(`Claude translation context ledger cannot be read: ${$}: ${Q instanceof Error?Q.message:String(Q)}`,{cause:Q})}return _M(J,this.workDir,$)}persist(){if(!this.sessionId)return;for(let J of[this.storeRoot(),this.workspaceDir()]){if(!R2(J,!0))WM(J,{recursive:!0,mode:448});R2(J,!0)}let $=this.filePath(this.sessionId);R2($,!1);let Z={version:2,workDir:this.workDir,sessionId:this.sessionId,coverage:"since-enabled",sequence:this.sequence,entries:this.entries.filter((J)=>J.status==="consumed"),tools:this.tools,checkpoints:this.checkpoints};r($,Z),R2($,!1)}change($){let Z={entries:this.entries,stoppedInputs:this.stoppedInputs,tools:this.tools,checkpoints:this.checkpoints,sequence:this.sequence};this.entries=this.entries.map((J)=>({...J})),this.stoppedInputs=new Map([...this.stoppedInputs].map(([J,Q])=>[J,{...Q}])),this.tools=this.tools.map((J)=>({...J})),this.checkpoints=this.checkpoints.map((J)=>({...J}));try{$(),this.persist()}catch(J){throw Object.assign(this,Z),J}}assertInitialized(){if(!this.initialized)throw Error("Claude translation context has not initialized")}bindSession($){if(this.assertInitialized(),!L0($))throw Error("Claude translation context session id is empty");if(this.options.forkSession&&$===this.options.resumeSessionId)throw Error("Claude translation fork context cannot bind to the source session");if(this.sessionId&&this.sessionId!==$)throw Error(`Claude translation context session mismatch: expected ${this.sessionId}, received ${$}`);if(this.sessionId===$)return;if(!this.sessionId&&this.readLedger($))throw Error(`Claude translation context session already exists: ${$}`);let Z=this.sessionId;this.sessionId=$;try{this.persist()}catch(J){throw this.sessionId=Z,J}}snapshot(){return this.assertInitialized(),Object.freeze({sessionId:this.sessionId,sourceSessionId:this.options.resumeSessionId??null,coverage:"since-enabled",entries:Object.freeze(this.entries.map(({sequence:$,key:Z,...J})=>Object.freeze(J)))})}toolName($){return this.assertInitialized(),this.tools.find((Z)=>Z.id===$)?.name}stageInput($,Z,J,Q=i.userMessage){if(this.assertInitialized(),!L0(Q))throw Error("Claude translation context origin is empty");if(!L0($)||this.stoppedInputs.has($)||this.entries.some((Y)=>Y.role==="user"&&Y.uuid===$))throw Error("Claude translation input id is empty or duplicated");this.entries.push({role:"user",origin:Q,uuid:$,status:"pending",sequence:0,original:T2(Z),translated:T2(J)})}confirmInput($){if(this.assertInitialized(),!this.entries.some((Z)=>Z.uuid===$&&Z.status==="pending")&&!this.stoppedInputs.has($))return;this.change(()=>{let Z=this.entries.find((J)=>J.uuid===$&&J.status==="pending")??this.stoppedInputs.get($);Z.status="consumed",Z.sequence=++this.sequence,this.stoppedInputs.delete($),this.entries=this.entries.filter((J)=>J!==Z),this.entries.push(Z)})}cancelPendingInputs(){this.assertInitialized();for(let $ of this.entries)if($.status==="pending")this.stoppedInputs.set($.uuid,$);this.entries=this.entries.filter(($)=>$.status!=="pending")}cancelInput($){this.assertInitialized(),this.entries=this.entries.filter((Z)=>Z.uuid!==$||Z.status!=="pending"),this.stoppedInputs.delete($)}recordInteraction($,Z,J,Q=t9($)){if(this.assertInitialized(),!L0($))throw Error("Claude translation context interaction role is empty");if(!L0(Q))throw Error("Claude translation context origin is empty");let Y=T2(Z),V=T2(J);if(Y||V)this.change(()=>{this.entries.push({role:$,origin:Q,original:Y,translated:V,status:"consumed",sequence:++this.sequence})})}recordOutput($,Z,J,Q,Y,V){this.recordDisplay({output:{kind:$,original:Z,display:J,uuid:Q,key:Y,origin:V}})}recordDisplay($){this.assertInitialized();let Z=[],J=new Map(this.tools.map((X)=>[X.id,X.name]));for(let X of $.tools??[]){if(!L0(X.id)||!L0(X.name))throw Error("Claude translation context tool id/name is empty");let z=J.get(X.id);if(z!==void 0){if(z!==X.name)throw Error(`Claude translation context tool name mismatch: ${X.id}`)}else J.set(X.id,X.name),Z.push(X)}let Q=$.output;if(Q&&(!L0(Q.kind)||Q.uuid!==void 0&&!L0(Q.uuid)||Q.key!==void 0&&!L0(Q.key)))throw Error("Claude translation context output kind/uuid/key is empty");if(Q?.origin!==void 0&&!L0(Q.origin))throw Error("Claude translation context origin is empty");if($.checkpoint!==void 0&&!L0($.checkpoint))throw Error("Claude translation context checkpoint uuid is empty");let Y=Q&&(Q.original.trim()||Q.display.trim())&&(!Q.key||!this.entries.some((X)=>X.key===Q.key)),V=$.checkpoint!==void 0&&!this.checkpoints.some((X)=>X.uuid===$.checkpoint);if(!Z.length&&!Y&&!V)return;this.change(()=>{for(let X of Z)this.tools.push({...X,sequence:++this.sequence});if(Y&&Q)this.entries.push({role:`assistant/${Q.kind}`,status:"consumed",sequence:++this.sequence,origin:Q.origin??t9(`assistant/${Q.kind}`),original:T2(Q.original),translated:T2(Q.display),...Q.uuid?{uuid:Q.uuid}:{},...Q.key?{key:Q.key}:{}});if(V)this.checkpoints.push({uuid:$.checkpoint,sequence:this.sequence})})}}var i;var r9=R(()=>{H0();b0();i={userMessage:"Feishu user → Claude Code: user message.",userAnswer:"Feishu user → Claude Code: answer to a question.",reply:"Claude Code → Feishu user: conversational reply.",commandExplanation:"Claude Code → Feishu user: explanation accompanying a command.",taskText:"Claude Code → Feishu user: task title, description or progress text.",question:"Claude Code → Feishu user: question or answer option.",toolResult:"Tool → Claude Code, also shown to the Feishu user: visible tool result.",subagentOutput:"Claude Code subagent → parent agent, also shown to the Feishu user: visible subagent text.",delegatedRequest:"Caller → delegated Claude Code agent, also shown to the Feishu user: delegated task request.",delegatedAnswer:"Caller → delegated Claude Code agent, also shown to the Feishu user: answer to a delegated-agent question.",delegatedQuestion:"Delegated Claude Code agent → caller, also shown to the Feishu user: question or answer option.",delegatedOutput:"Delegated agent → caller, also shown to the Feishu user: visible delegated-task text.",backgroundUpdate:"Claude Code background task → Feishu user: visible task update.",scheduledPrompt:"Scheduled task → Claude Code, also shown to the Feishu user: scheduled prompt.",error:"Claude Code runtime → Feishu user: visible error.",legacyUserMessage:"User or caller → Claude Code: message (older record did not distinguish the input source).",legacyUserAnswer:"User or caller → Claude Code: answer to a question (older record did not distinguish the input source).",legacyVisibleOutput:"Conversation → Feishu user: visible output (older record did not identify the source more precisely).",legacyUnknown:"Visible conversation text (older record did not identify its sender, recipient or source)."}});function q1($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function S2($){return $.replace(/^server_tool:/,"").split(".").at(-1).toLowerCase()}function E2($){return["bash","exec_command","write_stdin","bashoutput"].includes(S2($))}function lZ($){if(E2($))return i.commandExplanation;let Z=S2($);if(["taskcreate","taskupdate","taskget","tasklist","todowrite"].includes(Z))return i.taskText;if(Z==="agent"||Z==="task")return i.delegatedRequest;if(Z==="askuserquestion")return i.question;return"Claude Code → Feishu user: explanation accompanying a tool call."}function NH($,Z){return $.startsWith("server_tool:")&&q1(Z.input)?Z.input:Z}function Z7($){return structuredClone($)}function o$($,Z,J,Q={},Y=""){if(Array.isArray($)){for(let V of $)o$(V,Z,J,Q,Y);return}if(!q1($))return;for(let[V,X]of Object.entries($)){if(PM.has(V))continue;let z=Q.todos&&V==="content"&&Y==="todos",H=Q.textBlocks&&V==="text"&&$.type==="text";if(typeof X==="string"){if(H){let G=dZ(X);if(G){let W=J.fields.length;if(o$(G.value,Z,J,Q),J.fields.length>W)J.finish.push(()=>{$[V]=JSON.stringify(G.value,null,2)});continue}}if((Z.has(V)||z||H)&&X.trim())J.fields.push({object:$,key:V,value:X})}else if(V!=="content"||Array.isArray(X))o$(X,Z,J,Q,V)}}function dZ($){if(!/^[\s]*[\[{]/.test($))return null;try{return{value:JSON.parse($)}}catch{return null}}function RH($,Z,J){return!Z&&!J&&($==="AskUserQuestion"||$==="TaskCreate"||$==="TaskUpdate")}function TH($,Z,J){return J==="main"&&Z&&["TaskCreate","TaskUpdate","TaskList","TaskGet"].includes($)}function EH($,Z){return Z==="main"&&($==="TaskList"||$==="TaskGet")}function SH($,Z,J){let Q=$==="TaskList"?q1(Z)&&Array.isArray(Z.tasks)?Z.tasks:Array.isArray(Z)?Z:[]:[q1(Z)?Z.task??Z:null];for(let Y of Q){if(!q1(Y)||Y.status==="deleted")continue;let V=Y.subject!=null?"subject":"content";if($==="TaskList"&&!String(Y[V]??"").trim())continue;for(let X of[V,"activeForm"]){let z=Y[X];if(typeof z==="string"&&z.trim())J.fields.push({object:Y,key:X,value:z})}}}function CH($,Z){return Z==="main"&&($==="TaskCreate"||$==="TaskUpdate")?new Set(["subject","activeForm"]):new Set(OH)}function xH($,Z){let J=S2($);return J==="tasklist"||J==="taskget"?new Set(["subject","activeForm","description",...Z?["message","reason"]:[]]):new Set(OH)}function bH($){if(!q1($))return null;for(let J of["__displayDescription","description"])if(typeof $[J]==="string")return{key:J,value:$[J]};let Z=$.command??$.cmd??$.script;if(typeof Z==="string")return{key:"__displayDescription",value:B1(Z).description};return typeof $.subject==="string"?{key:"subject",value:$.subject}:null}function iZ($,Z,J,Q=!1,Y="main"){if(Y==="worker")return[];if(!Z.trim())return[];let V=S2($);if(TH($,J,Y))return[];if(RH($,J,Q))return[];let X=dZ(Z),z={fields:[],finish:[]};if(EH($,Y)){if(X)SH($,X.value,z);return z.fields.map((H)=>H.value)}if(E2($)||AH.has(V)){if(!J)return[];if(X)o$(X.value,new Set(["message","reason"]),z);else if(!E2($))return[Z]}else if(X){let H=xH($,J);if(V==="agent"||V==="task"||V==="webfetch")H.add("result"),H.add("content"),H.add("text");o$(X.value,H,z,{textBlocks:V!=="tasklist"&&V!=="taskget",todos:V==="todowrite"})}else return[Z];return z.fields.map((H)=>H.value)}function nZ($,Z,J="main"){if(J==="worker"){let z=bH(Z);return z?.value.trim()?[z.value]:[]}let Q={fields:[],finish:[]},Y=CH($,J),V=S2($);if(E2($)&&q1(Z)){let z=NH($,Z),H=typeof Z.__displayDescription==="string"?Z.__displayDescription:typeof z.__displayDescription==="string"?z.__displayDescription:B1(z.command??z.cmd??z.script).description||(typeof z.description==="string"?z.description:"")||(typeof z.reason==="string"?z.reason:"");if($.startsWith("server_tool:")){o$(z,Y,Q);let G=Q.fields.map((W)=>W.value);if(H.trim())G.push(H);return G}return H.trim()?[H]:[]}if(V==="websearch")Y.add("query");if(V==="sendmessage")Y.add("content");if(V==="askuserquestion")Y.add("header"),Y.add("label");return o$(Z,Y,Q,{todos:V==="todowrite"}),Q.fields.map((z)=>z.value)}class aZ{translator;constructor($){this.translator=$}async translateFields({fields:$,finish:Z},J,Q){if(J.throwIfAborted(),!$.length)return;let Y=await this.translator.toChineseFields($.map((V)=>V.value),J,Q);if(J.throwIfAborted(),Y.length!==$.length||Y.some((V)=>typeof V!=="string"||!V.trim()))throw Error("GLM 展示翻译返回了无效字段");$.forEach((V,X)=>{V.object[V.key]=Y[X]});for(let V of Z)V()}async naturalFields($,Z,J,Q=i.reply){let Y=Z7($),V={fields:[],finish:[]};return o$(Y,new Set(Z),V),await this.translateFields(V,J,Q),Y}async toolInput($,Z,J,Q="main",Y=lZ($)){let V=Z7(Z);J.throwIfAborted();let X={fields:[],finish:[]};if(Q==="worker"){let G=bH(V);if(q1(V)&&G?.value.trim()){let W=V;W[G.key]=G.value,X.fields.push({object:W,key:G.key,value:G.value})}return await this.translateFields(X,J,Y),V}let z=CH($,Q),H=S2($);if(H==="websearch")z.add("query");if(H==="sendmessage")z.add("content");if(H==="askuserquestion")z.add("header"),z.add("label");if(E2($)&&q1(V)){if(!$.startsWith("server_tool:")&&(H==="bash"||H==="exec_command"))z.clear();let G=NH($,V),W=G.command??G.cmd??G.script,K=B1(W).description||(typeof G.description==="string"?G.description:"")||(typeof G.reason==="string"?G.reason:"");if(K.trim()){let B=V;B.__displayDescription=K,z.add("__displayDescription")}}return o$(V,z,X,{todos:H==="todowrite"}),await this.translateFields(X,J,Y),V}async toolResult($,Z,J,Q,Y=!1,V="main",X=i.toolResult){if(Q.throwIfAborted(),V==="worker")return Z;if(!Z.trim())return Z;let z=S2($);if(TH($,J,V))return Z;if(RH($,J,Y))return Z;let H=dZ(Z);if(EH($,V)){if(!H)return Z;let G=Z7(H.value),W={fields:[],finish:[]};if(SH($,G,W),!W.fields.length)return Z;return await this.translateFields(W,Q,X),JSON.stringify(G,null,2)}if(E2($)||AH.has(z)){if(!J)return Z;if(H)return this.structuredResult(H.value,Z,new Set(["message","reason"]),Q,X);if(E2($))return Z;return this.prose(Z,Q,X)}if(H){let G=xH($,J);if(z==="agent"||z==="task"||z==="webfetch")G.add("result"),G.add("content"),G.add("text");return this.structuredResult(H.value,Z,G,Q,X,{textBlocks:z!=="tasklist"&&z!=="taskget",todos:z==="todowrite"})}return this.prose(Z,Q,X)}async structuredResult($,Z,J,Q,Y,V={}){let X=Z7($),z={fields:[],finish:[]};if(o$(X,J,z,V),!z.fields.length)return Z;return await this.translateFields(z,Q,Y),JSON.stringify(X,null,2)}async prose($,Z,J){let Q={message:$};return(await this.naturalFields(Q,["message"],Z,J)).message}}var OH,PM,AH;var kH=R(()=>{A4();r9();OH=new Set(["description","reason","summary","message","subject","activeForm","title","explanation","prompt","revisedPrompt","revised_prompt","question","preview","justification","plan"]),PM=new Set(["command","cmd","script","code","diff","patch","unified_diff","changes","old_string","new_string","new_source","source","edits","file","files","path","paths","file_path","notebook_path","cwd","workdir","grantRoot","url","urls","uri","link","links","id","ids","name","status","type","taskId","task_id","tool_use_id","session_id","agent_id","owner","recipient","recipients","env","environment","headers","metadata","_meta","schema","inputSchema","outputSchema","structuredContent","resource","resources","data","blob","stdout","stderr","output","raw","raw_output","chars","pattern","glob"]),AH=new Set(["read","write","edit","notebookedit","multiedit","glob","grep","ls","filechange","apply_patch"])});var JJ={};H1(JJ,{toolsFromProfile:()=>aH,settingSourcesFromProfile:()=>nH,resolveClaudeExecutableConfig:()=>ZJ,resetClaudeContextWindowCache:()=>UM,readProjectMcpServers:()=>oH,readLastCallUsageFromTranscript:()=>dH,claudeTranscriptPath:()=>V7,claudeTranscriptDir:()=>Y7,claudeManagedSkillOptions:()=>uH,buildClaudeSpawnPath:()=>lH,assertClaudeCodeAvailable:()=>$J,ClaudeAgentProcess:()=>X7,CLAUDE_PERMISSION_MODE:()=>iH});import{existsSync as mH,readFileSync as pH}from"node:fs";import{homedir as Q7}from"node:os";import{spawn as LM}from"cross-spawn";import{delimiter as wH,join as C2}from"node:path";import{EventEmitter as qM}from"node:events";import{randomUUID as vH}from"node:crypto";function uH($,Z){if(!Z||$.includes("user"))return{};return{plugins:[{type:"local",path:Z,skipMcpDiscovery:!0}],skills:"all"}}function DM($){let Z=$.toLowerCase();return Z.endsWith(".cmd")||Z.endsWith(".bat")}function FM($){let Z=LM($.command,$.args,{cwd:$.cwd,env:$.env,shell:!1,signal:$.signal,stdio:["pipe","pipe","ignore"],windowsHide:!0});if(!Z.stdin||!Z.stdout)throw Z.kill(),Error("failed to open stdio for Claude Code Windows shell shim");return Z}function $J(){ZJ(),e5("claude","@anthropic-ai/claude-agent-sdk")}function ZJ($={}){let Z=$.platform??process.platform,J=$.configuredBin===void 0?g.claude.bin:$.configuredBin;if(J){if(!($.exists??mH)(J))throw Error(`lodestar: [claude].bin not found: ${J} (config.toml)`);if(Z==="win32"&&DM(J))return{pathToClaudeCodeExecutable:J,spawnClaudeCodeProcess:FM,description:`windows-shell-shim:${J}`};return{pathToClaudeCodeExecutable:J,description:`config:${J}`}}return{description:"sdk-default"}}function lH(){if(process.platform==="win32")return process.env.PATH??"";let $=[C2(Q7(),".local","npm-global","bin"),C2(Q7(),".local","bin"),C2(Q7(),".bun","bin"),...(process.env.PATH??"").split(wH),"/usr/local/bin","/usr/bin","/bin"];return[...new Set($.filter(Boolean))].join(wH)}function MM($){let Z=U4($);if(!Z)return null;let J=(Z.input_tokens??0)+(Z.output_tokens??0)+(Z.cache_creation_input_tokens??0)+(Z.cache_read_input_tokens??0);if((Z.total_tokens??J)<=0)return null;if(Z.total_tokens==null)Z.total_tokens=J;return Z}function fH($){if(!$)return null;let Z=($.input_tokens??0)+($.cache_read_input_tokens??0)+($.cache_creation_input_tokens??0);return Z>0?Z:null}function Y7($){let Z=$.replace(/[^a-zA-Z0-9]/g,"-"),J=process.env.CLAUDE_CONFIG_DIR||C2(Q7(),".claude");return C2(J,"projects",Z)}function V7($,Z){return C2(Y7($),`${Z}.jsonl`)}function dH($){let Z;try{Z=pH($,"utf8")}catch{return null}let J=Z.split(`
103
- `);for(let Q=J.length-1;Q>=0;Q--){let Y=J[Q].trim();if(!Y)continue;try{let V=JSON.parse(Y);if(V?.type==="assistant"&&V?.message?.usage){let X=V.message.usage;if((X.input_tokens??0)+(X.cache_read_input_tokens??0)+(X.cache_creation_input_tokens??0)+(X.output_tokens??0)>0)return X}}catch{}}return null}function yH($,Z){let J=Z?.trim()||"no-source",Q=$&&$.trim()?$:"claude:default";return`${J}:${Q}`}function UM(){rZ.clear()}function OM($){if(!$||typeof $!=="object")return{usage:null,contextWindow:null};let Z={},J=null;for(let Y of Object.values($)){if(!Y||typeof Y!=="object")continue;let V=Y;Z.input_tokens=(Z.input_tokens??0)+w4(V.inputTokens??V.input_tokens),Z.output_tokens=(Z.output_tokens??0)+w4(V.outputTokens??V.output_tokens),Z.reasoning_output_tokens=(Z.reasoning_output_tokens??0)+w4(V.reasoningOutputTokens??V.reasoning_output_tokens),Z.cache_read_input_tokens=(Z.cache_read_input_tokens??0)+w4(V.cacheReadInputTokens??V.cache_read_input_tokens),Z.cache_creation_input_tokens=(Z.cache_creation_input_tokens??0)+w4(V.cacheCreationInputTokens??V.cache_creation_input_tokens);let X=w4(V.contextWindow??V.context_window);if(X>0)J=Math.max(J??0,X)}let Q=(Z.input_tokens??0)+(Z.output_tokens??0)+(Z.cache_creation_input_tokens??0)+(Z.cache_read_input_tokens??0);if(Q<=0)return{usage:null,contextWindow:J};return Z.total_tokens=Q,{usage:Z,contextWindow:J}}function J7($){return{...$}}function oZ($){if(!$||typeof $!=="object")return[];return Object.keys($).slice(0,20)}function hH($,Z){let J=$?{...$}:{},Q=(Y)=>{let V=Z[Y];if(typeof V!=="number"||!Number.isFinite(V))return;J[Y]=(J[Y]??0)+V};return Q("total_tokens"),Q("input_tokens"),Q("output_tokens"),Q("reasoning_output_tokens"),Q("cache_creation_input_tokens"),Q("cache_read_input_tokens"),J}function w4($){return typeof $==="number"&&Number.isFinite($)?$:0}function e9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&typeof Z.text==="string")return Z.text;return JSON.stringify(Z)}).join(`
102
+ `;else return Q();if(!Z.startsWith(Y))return Q();let X=Z.slice(Y.length).split(V);if(X.length!==2)return Q();let z=(H)=>T2(H.replaceAll("[Code omitted from translation context.]",""));return{original:z(X[0]),translated:z(X[1])}}function R2($,Z){let J;try{J=GM($)}catch(Y){if(Y.code==="ENOENT")return!1;throw Y}if(J.isSymbolicLink()||(Z?!J.isDirectory():!J.isFile()))throw Error(`Claude translation context path is not a regular ${Z?"directory":"file"}: ${$}`);let Q=Z?448:384;if(process.platform!=="win32"&&(J.mode&511)!==Q)throw Error(`Claude translation context permissions must be ${Q.toString(8)}: ${$}`);return!0}function _M($,Z,J){let Q=()=>{throw Error(`Claude translation context ledger is malformed: ${J}`)};if(!$7($))return Q();if($.workDir!==Z||$.sessionId!==J)throw Error(`Claude translation context session/cwd mismatch for ${J}`);if($.version!==1&&$.version!==2||$.coverage!=="since-enabled"||!Number.isSafeInteger($.sequence)||$.sequence<0||!Array.isArray($.entries)||!Array.isArray($.tools)||!Array.isArray($.checkpoints))return Q();let Y=$.sequence,V=(B)=>Number.isSafeInteger(B)&&B>=0&&B<=Y,X=new Set,z=new Set,H=[],G=0;for(let B of $.entries){let _=$.version===1?["role","text","uuid","status","sequence","key"]:["role","text","original","translated","origin","uuid","status","sequence","key"];if(!$7(B)||Object.keys(B).some((q)=>!_.includes(q))||!L0(B.role)||B.status!=="consumed"||!V(B.sequence)||B.sequence===0||B.origin!==void 0&&!L0(B.origin)||B.uuid!==void 0&&!L0(B.uuid)||B.key!==void 0&&!L0(B.key))return Q();if($.version===1&&!L0(B.text))return Q();if($.version===2&&(typeof B.original!=="string"||typeof B.translated!=="string"||B.text!==void 0&&typeof B.text!=="string"))return Q();if(B.sequence<=G||X.has(B.sequence)||typeof B.key==="string"&&z.has(B.key))return Q();if(G=B.sequence,X.add(B.sequence),typeof B.key==="string")z.add(B.key);let{text:P,...L}=B;H.push({...L,origin:B.origin??t9(B.role),...$.version===1?jM(B.role,P,J):{}})}let W=new Set;for(let B of $.tools){if(!$7(B)||Object.keys(B).some((_)=>!["id","name","sequence"].includes(_))||!L0(B.id)||!L0(B.name)||!V(B.sequence)||B.sequence===0||W.has(B.id)||X.has(B.sequence))return Q();W.add(B.id),X.add(B.sequence)}let K=new Set;for(let B of $.checkpoints){if(!$7(B)||Object.keys(B).some((_)=>!["uuid","sequence"].includes(_))||!L0(B.uuid)||!V(B.sequence)||K.has(B.uuid))return Q();K.add(B.uuid)}return{...$,version:2,entries:H}}class uZ{options;workDir="";sessionId=null;entries=[];stoppedInputs=new Map;tools=[];checkpoints=[];sequence=0;initialization=null;initialized=!1;constructor($){this.options=$}initialize($){if($.throwIfAborted(),!this.initialization)this.initialization=this.loadHistory($);return this.initialization.then(()=>{$.throwIfAborted()})}async loadHistory($){let{resumeSessionId:Z,resumeSessionAt:J,forkSession:Q,workDir:Y}=this.options;if(!Z&&(J||Q))throw Error("Claude translation context requires a fork/resume source session");if(this.workDir=BM(MH(Y)),Z!==void 0&&!L0(Z))throw Error("Claude translation context session id is empty");if(Z){let V=this.readLedger(Z);if(V){let X=V.sequence;if(J){let z=V.checkpoints.find((H)=>H.uuid===J);if(!z)throw Error(`Claude translation context checkpoint not found: ${J}`);X=z.sequence}this.entries=V.entries.filter((z)=>z.sequence<=X),this.tools=V.tools.filter((z)=>z.sequence<=X),this.checkpoints=V.checkpoints.filter((z)=>z.sequence<=X),this.sequence=X}this.sessionId=Q?null:Z}$.throwIfAborted(),this.initialized=!0}storeRoot(){return MH(this.options.storeDir??GX)}workspaceDir(){return DH(this.storeRoot(),UH(this.workDir))}filePath($){return DH(this.workspaceDir(),`${UH($)}.json`)}readLedger($){if(!R2(this.storeRoot(),!0)||!R2(this.workspaceDir(),!0))return null;let Z=this.filePath($);if(!R2(Z,!1))return null;let J;try{J=JSON.parse(KM(Z,"utf8"))}catch(Q){throw Error(`Claude translation context ledger cannot be read: ${$}: ${Q instanceof Error?Q.message:String(Q)}`,{cause:Q})}return _M(J,this.workDir,$)}persist(){if(!this.sessionId)return;for(let J of[this.storeRoot(),this.workspaceDir()]){if(!R2(J,!0))WM(J,{recursive:!0,mode:448});R2(J,!0)}let $=this.filePath(this.sessionId);R2($,!1);let Z={version:2,workDir:this.workDir,sessionId:this.sessionId,coverage:"since-enabled",sequence:this.sequence,entries:this.entries.filter((J)=>J.status==="consumed"),tools:this.tools,checkpoints:this.checkpoints};r($,Z),R2($,!1)}change($){let Z={entries:this.entries,stoppedInputs:this.stoppedInputs,tools:this.tools,checkpoints:this.checkpoints,sequence:this.sequence};this.entries=this.entries.map((J)=>({...J})),this.stoppedInputs=new Map([...this.stoppedInputs].map(([J,Q])=>[J,{...Q}])),this.tools=this.tools.map((J)=>({...J})),this.checkpoints=this.checkpoints.map((J)=>({...J}));try{$(),this.persist()}catch(J){throw Object.assign(this,Z),J}}assertInitialized(){if(!this.initialized)throw Error("Claude translation context has not initialized")}bindSession($){if(this.assertInitialized(),!L0($))throw Error("Claude translation context session id is empty");if(this.options.forkSession&&$===this.options.resumeSessionId)throw Error("Claude translation fork context cannot bind to the source session");if(this.sessionId&&this.sessionId!==$)throw Error(`Claude translation context session mismatch: expected ${this.sessionId}, received ${$}`);if(this.sessionId===$)return;if(!this.sessionId&&this.readLedger($))throw Error(`Claude translation context session already exists: ${$}`);let Z=this.sessionId;this.sessionId=$;try{this.persist()}catch(J){throw this.sessionId=Z,J}}snapshot(){return this.assertInitialized(),Object.freeze({sessionId:this.sessionId,sourceSessionId:this.options.resumeSessionId??null,coverage:"since-enabled",entries:Object.freeze(this.entries.map(({sequence:$,key:Z,...J})=>Object.freeze(J)))})}toolName($){return this.assertInitialized(),this.tools.find((Z)=>Z.id===$)?.name}stageInput($,Z,J,Q=i.userMessage){if(this.assertInitialized(),!L0(Q))throw Error("Claude translation context origin is empty");if(!L0($)||this.stoppedInputs.has($)||this.entries.some((Y)=>Y.role==="user"&&Y.uuid===$))throw Error("Claude translation input id is empty or duplicated");this.entries.push({role:"user",origin:Q,uuid:$,status:"pending",sequence:0,original:T2(Z),translated:T2(J)})}confirmInput($){if(this.assertInitialized(),!this.entries.some((Z)=>Z.uuid===$&&Z.status==="pending")&&!this.stoppedInputs.has($))return;this.change(()=>{let Z=this.entries.find((J)=>J.uuid===$&&J.status==="pending")??this.stoppedInputs.get($);Z.status="consumed",Z.sequence=++this.sequence,this.stoppedInputs.delete($),this.entries=this.entries.filter((J)=>J!==Z),this.entries.push(Z)})}cancelPendingInputs(){this.assertInitialized();for(let $ of this.entries)if($.status==="pending")this.stoppedInputs.set($.uuid,$);this.entries=this.entries.filter(($)=>$.status!=="pending")}cancelInput($){this.assertInitialized(),this.entries=this.entries.filter((Z)=>Z.uuid!==$||Z.status!=="pending"),this.stoppedInputs.delete($)}recordInteraction($,Z,J,Q=t9($)){if(this.assertInitialized(),!L0($))throw Error("Claude translation context interaction role is empty");if(!L0(Q))throw Error("Claude translation context origin is empty");let Y=T2(Z),V=T2(J);if(Y||V)this.change(()=>{this.entries.push({role:$,origin:Q,original:Y,translated:V,status:"consumed",sequence:++this.sequence})})}recordOutput($,Z,J,Q,Y,V){this.recordDisplay({output:{kind:$,original:Z,display:J,uuid:Q,key:Y,origin:V}})}recordDisplay($){this.assertInitialized();let Z=[],J=new Map(this.tools.map((X)=>[X.id,X.name]));for(let X of $.tools??[]){if(!L0(X.id)||!L0(X.name))throw Error("Claude translation context tool id/name is empty");let z=J.get(X.id);if(z!==void 0){if(z!==X.name)throw Error(`Claude translation context tool name mismatch: ${X.id}`)}else J.set(X.id,X.name),Z.push(X)}let Q=$.output;if(Q&&(!L0(Q.kind)||Q.uuid!==void 0&&!L0(Q.uuid)||Q.key!==void 0&&!L0(Q.key)))throw Error("Claude translation context output kind/uuid/key is empty");if(Q?.origin!==void 0&&!L0(Q.origin))throw Error("Claude translation context origin is empty");if($.checkpoint!==void 0&&!L0($.checkpoint))throw Error("Claude translation context checkpoint uuid is empty");let Y=Q&&(Q.original.trim()||Q.display.trim())&&(!Q.key||!this.entries.some((X)=>X.key===Q.key)),V=$.checkpoint!==void 0&&!this.checkpoints.some((X)=>X.uuid===$.checkpoint);if(!Z.length&&!Y&&!V)return;this.change(()=>{for(let X of Z)this.tools.push({...X,sequence:++this.sequence});if(Y&&Q)this.entries.push({role:`assistant/${Q.kind}`,status:"consumed",sequence:++this.sequence,origin:Q.origin??t9(`assistant/${Q.kind}`),original:T2(Q.original),translated:T2(Q.display),...Q.uuid?{uuid:Q.uuid}:{},...Q.key?{key:Q.key}:{}});if(V)this.checkpoints.push({uuid:$.checkpoint,sequence:this.sequence})})}}var i;var r9=R(()=>{H0();b0();i={userMessage:"Feishu user → Claude Code: user message.",userAnswer:"Feishu user → Claude Code: answer to a question.",reply:"Claude Code → Feishu user: conversational reply.",commandExplanation:"Claude Code → Feishu user: explanation accompanying a command.",taskText:"Claude Code → Feishu user: task title, description or progress text.",question:"Claude Code → Feishu user: question or answer option.",toolResult:"Tool → Claude Code, also shown to the Feishu user: visible tool result.",subagentOutput:"Claude Code subagent → parent agent, also shown to the Feishu user: visible subagent text.",delegatedRequest:"Caller → delegated Claude Code agent, also shown to the Feishu user: delegated task request.",delegatedAnswer:"Caller → delegated Claude Code agent, also shown to the Feishu user: answer to a delegated-agent question.",delegatedQuestion:"Delegated Claude Code agent → caller, also shown to the Feishu user: question or answer option.",delegatedOutput:"Delegated agent → caller, also shown to the Feishu user: visible delegated-task text.",backgroundUpdate:"Claude Code background task → Feishu user: visible task update.",scheduledPrompt:"Scheduled task → Claude Code, also shown to the Feishu user: scheduled prompt.",error:"Claude Code runtime → Feishu user: visible error.",legacyUserMessage:"User or caller → Claude Code: message (older record did not distinguish the input source).",legacyUserAnswer:"User or caller → Claude Code: answer to a question (older record did not distinguish the input source).",legacyVisibleOutput:"Conversation → Feishu user: visible output (older record did not identify the source more precisely).",legacyUnknown:"Visible conversation text (older record did not identify its sender, recipient or source)."}});function q1($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function S2($){return $.replace(/^server_tool:/,"").split(".").at(-1).toLowerCase()}function E2($){return["bash","exec_command","write_stdin","bashoutput"].includes(S2($))}function lZ($){if(E2($))return i.commandExplanation;let Z=S2($);if(["taskcreate","taskupdate","taskget","tasklist","todowrite"].includes(Z))return i.taskText;if(Z==="agent"||Z==="task")return i.delegatedRequest;if(Z==="askuserquestion")return i.question;return"Claude Code → Feishu user: explanation accompanying a tool call."}function NH($,Z){return $.startsWith("server_tool:")&&q1(Z.input)?Z.input:Z}function Z7($){return structuredClone($)}function o$($,Z,J,Q={},Y=""){if(Array.isArray($)){for(let V of $)o$(V,Z,J,Q,Y);return}if(!q1($))return;for(let[V,X]of Object.entries($)){if(PM.has(V))continue;let z=Q.todos&&V==="content"&&Y==="todos",H=Q.textBlocks&&V==="text"&&$.type==="text";if(typeof X==="string"){if(H){let G=dZ(X);if(G){let W=J.fields.length;if(o$(G.value,Z,J,Q),J.fields.length>W)J.finish.push(()=>{$[V]=JSON.stringify(G.value,null,2)});continue}}if((Z.has(V)||z||H)&&X.trim())J.fields.push({object:$,key:V,value:X})}else if(V!=="content"||Array.isArray(X))o$(X,Z,J,Q,V)}}function dZ($){if(!/^[\s]*[\[{]/.test($))return null;try{return{value:JSON.parse($)}}catch{return null}}function RH($,Z,J){return!Z&&!J&&($==="AskUserQuestion"||$==="TaskCreate"||$==="TaskUpdate")}function TH($,Z,J){return J==="main"&&Z&&["TaskCreate","TaskUpdate","TaskList","TaskGet"].includes($)}function EH($,Z){return Z==="main"&&($==="TaskList"||$==="TaskGet")}function SH($,Z,J){let Q=$==="TaskList"?q1(Z)&&Array.isArray(Z.tasks)?Z.tasks:Array.isArray(Z)?Z:[]:[q1(Z)?Z.task??Z:null];for(let Y of Q){if(!q1(Y)||Y.status==="deleted")continue;let V=Y.subject!=null?"subject":"content";if($==="TaskList"&&!String(Y[V]??"").trim())continue;for(let X of[V,"activeForm"]){let z=Y[X];if(typeof z==="string"&&z.trim())J.fields.push({object:Y,key:X,value:z})}}}function CH($,Z){return Z==="main"&&($==="TaskCreate"||$==="TaskUpdate")?new Set(["subject","activeForm"]):new Set(OH)}function xH($,Z){let J=S2($);return J==="tasklist"||J==="taskget"?new Set(["subject","activeForm","description",...Z?["message","reason"]:[]]):new Set(OH)}function bH($){if(!q1($))return null;for(let J of["__displayDescription","description"])if(typeof $[J]==="string")return{key:J,value:$[J]};let Z=$.command??$.cmd??$.script;if(typeof Z==="string")return{key:"__displayDescription",value:B1(Z).description};return typeof $.subject==="string"?{key:"subject",value:$.subject}:null}function iZ($,Z,J,Q=!1,Y="main"){if(Y==="worker")return[];if(!Z.trim())return[];let V=S2($);if(TH($,J,Y))return[];if(RH($,J,Q))return[];let X=dZ(Z),z={fields:[],finish:[]};if(EH($,Y)){if(X)SH($,X.value,z);return z.fields.map((H)=>H.value)}if(E2($)||AH.has(V)){if(!J)return[];if(X)o$(X.value,new Set(["message","reason"]),z);else if(!E2($))return[Z]}else if(X){let H=xH($,J);if(V==="agent"||V==="task"||V==="webfetch")H.add("result"),H.add("content"),H.add("text");o$(X.value,H,z,{textBlocks:V!=="tasklist"&&V!=="taskget",todos:V==="todowrite"})}else return[Z];return z.fields.map((H)=>H.value)}function nZ($,Z,J="main"){if(J==="worker"){let z=bH(Z);return z?.value.trim()?[z.value]:[]}let Q={fields:[],finish:[]},Y=CH($,J),V=S2($);if(E2($)&&q1(Z)){let z=NH($,Z),H=typeof Z.__displayDescription==="string"?Z.__displayDescription:typeof z.__displayDescription==="string"?z.__displayDescription:B1(z.command??z.cmd??z.script).description||(typeof z.description==="string"?z.description:"")||(typeof z.reason==="string"?z.reason:"");if($.startsWith("server_tool:")){o$(z,Y,Q);let G=Q.fields.map((W)=>W.value);if(H.trim())G.push(H);return G}return H.trim()?[H]:[]}if(V==="websearch")Y.add("query");if(V==="sendmessage")Y.add("content");if(V==="askuserquestion")Y.add("header"),Y.add("label");return o$(Z,Y,Q,{todos:V==="todowrite"}),Q.fields.map((z)=>z.value)}class aZ{translator;constructor($){this.translator=$}async translateFields({fields:$,finish:Z},J,Q){if(J.throwIfAborted(),!$.length)return;let Y=await this.translator.toChineseFields($.map((V)=>V.value),J,Q);if(J.throwIfAborted(),Y.length!==$.length||Y.some((V)=>typeof V!=="string"||!V.trim()))throw Error("GLM 展示翻译返回了无效字段");$.forEach((V,X)=>{V.object[V.key]=Y[X]});for(let V of Z)V()}async naturalFields($,Z,J,Q=i.reply){let Y=Z7($),V={fields:[],finish:[]};return o$(Y,new Set(Z),V),await this.translateFields(V,J,Q),Y}async toolInput($,Z,J,Q="main",Y=lZ($)){let V=Z7(Z);J.throwIfAborted();let X={fields:[],finish:[]};if(Q==="worker"){let G=bH(V);if(q1(V)&&G?.value.trim()){let W=V;W[G.key]=G.value,X.fields.push({object:W,key:G.key,value:G.value})}return await this.translateFields(X,J,Y),V}let z=CH($,Q),H=S2($);if(H==="websearch")z.add("query");if(H==="sendmessage")z.add("content");if(H==="askuserquestion")z.add("header"),z.add("label");if(E2($)&&q1(V)){if(!$.startsWith("server_tool:")&&(H==="bash"||H==="exec_command"))z.clear();let G=NH($,V),W=G.command??G.cmd??G.script,K=B1(W).description||(typeof G.description==="string"?G.description:"")||(typeof G.reason==="string"?G.reason:"");if(K.trim()){let B=V;B.__displayDescription=K,z.add("__displayDescription")}}return o$(V,z,X,{todos:H==="todowrite"}),await this.translateFields(X,J,Y),V}async toolResult($,Z,J,Q,Y=!1,V="main",X=i.toolResult){if(Q.throwIfAborted(),V==="worker")return Z;if(!Z.trim())return Z;let z=S2($);if(TH($,J,V))return Z;if(RH($,J,Y))return Z;let H=dZ(Z);if(EH($,V)){if(!H)return Z;let G=Z7(H.value),W={fields:[],finish:[]};if(SH($,G,W),!W.fields.length)return Z;return await this.translateFields(W,Q,X),JSON.stringify(G,null,2)}if(E2($)||AH.has(z)){if(!J)return Z;if(H)return this.structuredResult(H.value,Z,new Set(["message","reason"]),Q,X);if(E2($))return Z;return this.prose(Z,Q,X)}if(H){let G=xH($,J);if(z==="agent"||z==="task"||z==="webfetch")G.add("result"),G.add("content"),G.add("text");return this.structuredResult(H.value,Z,G,Q,X,{textBlocks:z!=="tasklist"&&z!=="taskget",todos:z==="todowrite"})}return this.prose(Z,Q,X)}async structuredResult($,Z,J,Q,Y,V={}){let X=Z7($),z={fields:[],finish:[]};if(o$(X,J,z,V),!z.fields.length)return Z;return await this.translateFields(z,Q,Y),JSON.stringify(X,null,2)}async prose($,Z,J){let Q={message:$};return(await this.naturalFields(Q,["message"],Z,J)).message}}var OH,PM,AH;var kH=R(()=>{A4();r9();OH=new Set(["description","reason","summary","message","subject","activeForm","title","explanation","prompt","revisedPrompt","revised_prompt","question","preview","justification","plan"]),PM=new Set(["command","cmd","script","code","diff","patch","unified_diff","changes","old_string","new_string","new_source","source","edits","file","files","path","paths","file_path","notebook_path","cwd","workdir","grantRoot","url","urls","uri","link","links","id","ids","name","status","type","taskId","task_id","tool_use_id","session_id","agent_id","owner","recipient","recipients","env","environment","headers","metadata","_meta","schema","inputSchema","outputSchema","structuredContent","resource","resources","data","blob","stdout","stderr","output","raw","raw_output","chars","pattern","glob"]),AH=new Set(["read","write","edit","notebookedit","multiedit","glob","grep","ls","filechange","apply_patch"])});var JJ={};H1(JJ,{toolsFromProfile:()=>aH,settingSourcesFromProfile:()=>nH,resolveClaudeExecutableConfig:()=>ZJ,resetClaudeContextWindowCache:()=>UM,readProjectMcpServers:()=>oH,readLastCallUsageFromTranscript:()=>dH,claudeTranscriptPath:()=>V7,claudeTranscriptDir:()=>Y7,claudeManagedSkillOptions:()=>uH,buildClaudeSpawnPath:()=>lH,assertClaudeCodeAvailable:()=>$J,ClaudeAgentProcess:()=>X7,CLAUDE_PERMISSION_MODE:()=>iH});import{existsSync as mH,readFileSync as pH}from"node:fs";import{homedir as Q7}from"node:os";import{spawn as LM}from"cross-spawn";import{delimiter as wH,join as C2}from"node:path";import{EventEmitter as qM}from"node:events";import{randomUUID as vH}from"node:crypto";function uH($,Z){if(!Z||$.includes("user"))return{};return{plugins:[{type:"local",path:Z,skipMcpDiscovery:!0}],skills:"all"}}function FM($){let Z=$.toLowerCase();return Z.endsWith(".cmd")||Z.endsWith(".bat")}function DM($){let Z=LM($.command,$.args,{cwd:$.cwd,env:$.env,shell:!1,signal:$.signal,stdio:["pipe","pipe","ignore"],windowsHide:!0});if(!Z.stdin||!Z.stdout)throw Z.kill(),Error("failed to open stdio for Claude Code Windows shell shim");return Z}function $J(){ZJ(),e5("claude","@anthropic-ai/claude-agent-sdk")}function ZJ($={}){let Z=$.platform??process.platform,J=$.configuredBin===void 0?g.claude.bin:$.configuredBin;if(J){if(!($.exists??mH)(J))throw Error(`lodestar: [claude].bin not found: ${J} (config.toml)`);if(Z==="win32"&&FM(J))return{pathToClaudeCodeExecutable:J,spawnClaudeCodeProcess:DM,description:`windows-shell-shim:${J}`};return{pathToClaudeCodeExecutable:J,description:`config:${J}`}}return{description:"sdk-default"}}function lH(){if(process.platform==="win32")return process.env.PATH??"";let $=[C2(Q7(),".local","npm-global","bin"),C2(Q7(),".local","bin"),C2(Q7(),".bun","bin"),...(process.env.PATH??"").split(wH),"/usr/local/bin","/usr/bin","/bin"];return[...new Set($.filter(Boolean))].join(wH)}function MM($){let Z=U4($);if(!Z)return null;let J=(Z.input_tokens??0)+(Z.output_tokens??0)+(Z.cache_creation_input_tokens??0)+(Z.cache_read_input_tokens??0);if((Z.total_tokens??J)<=0)return null;if(Z.total_tokens==null)Z.total_tokens=J;return Z}function yH($){if(!$)return null;let Z=($.input_tokens??0)+($.cache_read_input_tokens??0)+($.cache_creation_input_tokens??0);return Z>0?Z:null}function Y7($){let Z=$.replace(/[^a-zA-Z0-9]/g,"-"),J=process.env.CLAUDE_CONFIG_DIR||C2(Q7(),".claude");return C2(J,"projects",Z)}function V7($,Z){return C2(Y7($),`${Z}.jsonl`)}function dH($){let Z;try{Z=pH($,"utf8")}catch{return null}let J=Z.split(`
103
+ `);for(let Q=J.length-1;Q>=0;Q--){let Y=J[Q].trim();if(!Y)continue;try{let V=JSON.parse(Y);if(V?.type==="assistant"&&V?.message?.usage){let X=V.message.usage;if((X.input_tokens??0)+(X.cache_read_input_tokens??0)+(X.cache_creation_input_tokens??0)+(X.output_tokens??0)>0)return X}}catch{}}return null}function fH($,Z){let J=Z?.trim()||"no-source",Q=$&&$.trim()?$:"claude:default";return`${J}:${Q}`}function UM(){rZ.clear()}function OM($){if(!$||typeof $!=="object")return{usage:null,contextWindow:null};let Z={},J=null;for(let Y of Object.values($)){if(!Y||typeof Y!=="object")continue;let V=Y;Z.input_tokens=(Z.input_tokens??0)+w4(V.inputTokens??V.input_tokens),Z.output_tokens=(Z.output_tokens??0)+w4(V.outputTokens??V.output_tokens),Z.reasoning_output_tokens=(Z.reasoning_output_tokens??0)+w4(V.reasoningOutputTokens??V.reasoning_output_tokens),Z.cache_read_input_tokens=(Z.cache_read_input_tokens??0)+w4(V.cacheReadInputTokens??V.cache_read_input_tokens),Z.cache_creation_input_tokens=(Z.cache_creation_input_tokens??0)+w4(V.cacheCreationInputTokens??V.cache_creation_input_tokens);let X=w4(V.contextWindow??V.context_window);if(X>0)J=Math.max(J??0,X)}let Q=(Z.input_tokens??0)+(Z.output_tokens??0)+(Z.cache_creation_input_tokens??0)+(Z.cache_read_input_tokens??0);if(Q<=0)return{usage:null,contextWindow:J};return Z.total_tokens=Q,{usage:Z,contextWindow:J}}function J7($){return{...$}}function oZ($){if(!$||typeof $!=="object")return[];return Object.keys($).slice(0,20)}function hH($,Z){let J=$?{...$}:{},Q=(Y)=>{let V=Z[Y];if(typeof V!=="number"||!Number.isFinite(V))return;J[Y]=(J[Y]??0)+V};return Q("total_tokens"),Q("input_tokens"),Q("output_tokens"),Q("reasoning_output_tokens"),Q("cache_creation_input_tokens"),Q("cache_read_input_tokens"),J}function w4($){return typeof $==="number"&&Number.isFinite($)?$:0}function e9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&typeof Z.text==="string")return Z.text;return JSON.stringify(Z)}).join(`
104
104
  `);return $==null?"":JSON.stringify($,null,2)}function sZ($){let Z=e9($);try{let J=JSON.parse(Z);if(Array.isArray(J)){let Q=J.map((Y)=>{if(typeof Y==="string")return Y;if(Y&&typeof Y==="object"&&typeof Y.text==="string")return Y.text;return JSON.stringify(Y)}).filter(Boolean);if(Q.length>0)return Q.join(`
105
- `)}}catch{}return Z}function tZ($){return`server_tool:${$}`}function AM($){let Z=$.match(/Built-in Tool:\s*([A-Za-z0-9_.:-]+)/)?.[1];if(!Z)return null;let J=$.match(/\*\*Input:\*\*\s*```(?:json)?\s*([\s\S]*?)```/)?.[1]?.trim();if(!J)return{name:Z,input:{}};try{return{name:Z,input:JSON.parse(J)}}catch{return{name:Z,input:{raw:J}}}}function IH($){let Z=$.trim();return Z.includes("Built-in Tool:")||Z.startsWith("**Output:**")&&Z.includes("_result")}function NM($){let Z=$.supportedEffortLevels&&$.supportedEffortLevels.length>0?$.supportedEffortLevels:[h1];return{id:I1($.value),model:I1($.value),displayName:$.displayName||I1($.value),description:$.description||"Claude Agent SDK backend",hidden:!1,isDefault:!1,supportedReasoningEfforts:Z.map((J)=>({reasoningEffort:J,description:""})),defaultReasoningEffort:Z.includes(h1)?h1:Z[0]}}function nH($){if(!$?.settingSources)return[...gH];let Z=$.settingSources.split(",").map((J)=>J.trim()).filter(Boolean);return Z.length?Z:[...gH]}function aH($){if(!$?.tools)return{type:"preset",preset:"claude_code"};let Z=$.tools.split(",").map((J)=>J.trim()).filter(Boolean);return Z.length?Z:{type:"preset",preset:"claude_code"}}function oH($){let Z=C2($,".mcp.json"),J;try{J=pH(Z,"utf8")}catch(V){if(V.code==="ENOENT")return;throw Error(`project .mcp.json not readable at ${Z}: ${V}`,{cause:V})}let Q;try{Q=JSON.parse(J)}catch(V){throw Error(`project .mcp.json parse failed at ${Z}: ${V}`,{cause:V})}let Y=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.mcpServers:void 0;if(!Y||typeof Y!=="object"||Array.isArray(Y))throw Error(`project .mcp.json has no valid mcpServers object at ${Z}`);return Y}function RM($,Z=!1){let J=$.questions;return(Array.isArray(J)?J:J&&typeof J==="object"?[J]:[$]).map((Y)=>TM(Y,Z)).filter((Y)=>Y!==null)}function TM($,Z){let J=$&&typeof $==="object"?$:{question:$},Q=eZ(J.question,J.prompt,J.title,J.message,J.text,J.label);if(!Q)return null;if(!Q.trim())return null;let Y=EM(J.options??J.choices??J.suggestions,Z);return{...J,question:Q,options:Y,...typeof J.header==="string"?{header:J.header}:{},...typeof J.multiSelect==="boolean"?{multiSelect:J.multiSelect}:{}}}function EM($,Z){if(!Array.isArray($))return[];let J=[];for(let Q of $){if(typeof Q==="string"){J.push({label:Q});continue}if(!Q||typeof Q!=="object")continue;let Y=Q,V=eZ(Y.label,Y.value,Y.text,Y.title);if(!V?.trim())continue;let X=eZ(Y.description,Y.detail,Y.preview);J.push({label:V,...X?{description:X}:{},...Z&&typeof Y.preview==="string"?{preview:Y.preview}:{}})}return J}function eZ(...$){for(let Z of $)if(typeof Z==="string")return Z;return}var cH,rZ,iH="default",gH,X7;var v4=R(()=>{F4();k0();I();P0();gZ();o9();r9();kH();cH=class cH{items=[];waiters=[];closed=!1;push($){if(this.closed)throw Error("input stream is closed");let Z=this.waiters.shift();if(Z)Z({value:$,done:!1});else this.items.push($)}close(){if(this.closed)return;this.closed=!0;while(this.waiters.length)this.waiters.shift()?.({value:void 0,done:!0})}abort(){this.clear(),this.close()}clear(){this.items=[]}[Symbol.asyncIterator](){return this}next(){if(this.items.length>0)return Promise.resolve({value:this.items.shift(),done:!1});if(this.closed)return Promise.resolve({value:void 0,done:!0});return new Promise(($)=>this.waiters.push($))}};rZ=new Map;gH=["project","local"];X7=class X7 extends qM{provider="claude";tokenSourceId;translationEnabled;opts;input=new cH;query=null;abortController=new AbortController;alive=!0;expectedExit=!1;exitPromise;resolveExit;started=!1;queryStart;initializationError=null;pendingPermissions=new Map;requestCounter=0;cumulativeUsageFromResults=null;turnActive=!1;inputTurnPending=!1;nativeTurnPending=!1;steeringInputs=new Set;steeringResults=[];steeringFailures=[];deferredSteeringResult=null;emittedToolUseIds=new Set;emittedToolResultIds=new Set;pendingServerToolInputs=[];translationController=new AbortController;translationInputQueue=Promise.resolve();translationFailure=null;translationOutputStopped=!1;translationContextInitialized=!1;translationContextFailure=null;presentation;presentationPolicy;translatedToolNames=new Map;translatedToolInputs=new Map;translatedErrors=new Map;sessionId=null;lastAssistantUuid=null;lastModel=null;lastEffort=null;lastThinkingTokens=null;lastUsage=null;lastTotalUsage=null;lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1};lastContextWindow=null;lastContextTokens=null;constructor($){super();this.on("error",()=>{}),this.exitPromise=new Promise((Z)=>{this.resolveExit=Z}),this.opts=$,this.presentation=$.translation?new aZ($.translation):void 0,this.tokenSourceId=$.tokenSourceId??null,this.translationEnabled=!!$.translation,this.lastEffort=$.effort,this.lastModel=$.model?I1($.model):null}sendInitialize(){if(this.started)return;this.started=!0,this.queryStart=this.initializeQuery().catch(($)=>{if(this.initializationError=$ instanceof Error?$:Error(String($)),this.emit("error",this.initializationError),!this.query)this.finishExit(1,null)})}async*validatedInput(){if(await this.queryStart,this.initializationError||!this.alive)return;yield*this.input}async initializeQuery(){let $=i9(this.opts.model),Z=this.opts.profile;if(Z)j(`claude-agent-process: project profile active — settingSources=${Z.settingSources??"-"} strictMcp=${Z.strictMcp??!1} tools=${Z.tools??"-"} loadProjectMcp=${Z.loadProjectMcp??!0}`);let J=this.opts.settingSources??nH(Z),Q=uH(J,this.opts.managedSkillPluginPath),Y=aH(Z),V=[...this.opts.allowUserInput===!1?["AskUserQuestion","EnterPlanMode","ExitPlanMode"]:[]],X=Z?.strictMcp===!0,z=Z?.loadProjectMcp!==!1?oH(this.opts.workDir):void 0;try{let H=ZJ();if(this.opts.translation)await this.initializeTranslationContext();if(!this.alive||this.abortController.signal.aborted)return;let{query:G}=await rX();if(!this.alive||this.abortController.signal.aborted)return;let W={...process.env,PATH:lH(),...g.claude.env,...this.opts.hostEnv??{}},K=this.opts.transformEnv?this.opts.transformEnv(W):W;if(K.CLAUDE_CODE_ENABLE_TODO_TOOLS="1",this.opts.effort==="default")K.CLAUDE_CODE_EFFORT_LEVEL="unset";j(`claude-agent-process: spawn SDK query model=${$??"default"} effort=${this.opts.effort} cwd=${this.opts.workDir} executable=${H.description}`),this.query=G({prompt:this.opts.validateAccount?this.validatedInput():this.input,options:{cwd:this.opts.workDir,abortController:this.abortController,...$?{model:$}:{},effort:this.opts.effort==="default"?"high":this.opts.effort,resume:this.opts.resumeSessionId,...this.opts.resumeSessionAt?{resumeSessionAt:this.opts.resumeSessionAt}:{},...this.opts.forkSession?{forkSession:!0}:{},...H.pathToClaudeCodeExecutable?{pathToClaudeCodeExecutable:H.pathToClaudeCodeExecutable}:{},...H.spawnClaudeCodeProcess?{spawnClaudeCodeProcess:H.spawnClaudeCodeProcess}:{},permissionMode:iH,env:K,settingSources:[...J],...this.opts.settings?{settings:this.opts.settings}:{},...Q,tools:Y,...V.length?{disallowedTools:V}:{},...X?{strictMcpConfig:!0}:{},...z?{mcpServers:z}:{},toolConfig:{askUserQuestion:{previewFormat:"markdown"}},canUseTool:(B,_,P)=>this.canUseTool(B,_,P),includePartialMessages:!1,systemPrompt:{type:"preset",preset:"claude_code",...this.opts.appendSystemPrompt?{append:this.opts.appendSystemPrompt,snapshot:!1}:{}},stderr:(B)=>{let _=B.trim();if(_)j(`claude-agent-process[stderr]: ${_}`)}}})}catch(H){if(this.opts.translation&&this.expectedExit)return;let G=H instanceof Error?H:Error(String(H));this.initializationError=G,this.emit("error",G),this.finishExit(1,null);return}if(this.readLoop(this.query),this.opts.validateAccount)try{this.opts.validateAccount(await this.query.accountInfo())}catch(H){this.initializationError=H instanceof Error?H:Error(String(H)),this.emit("error",this.initializationError),await this.kill()}}sendUserText($,Z=[],J){if(!this.alive){j("claude-agent-process: sendUserText ignored on dead process");return}if(this.translationContextFailure){this.failTurnStart(this.translationContextFailure);return}if(!this.started)this.sendInitialize();let Q=(J?.contextPrefix??"")+(Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
105
+ `)}}catch{}return Z}function tZ($){return`server_tool:${$}`}function AM($){let Z=$.match(/Built-in Tool:\s*([A-Za-z0-9_.:-]+)/)?.[1];if(!Z)return null;let J=$.match(/\*\*Input:\*\*\s*```(?:json)?\s*([\s\S]*?)```/)?.[1]?.trim();if(!J)return{name:Z,input:{}};try{return{name:Z,input:JSON.parse(J)}}catch{return{name:Z,input:{raw:J}}}}function IH($){let Z=$.trim();return Z.includes("Built-in Tool:")||Z.startsWith("**Output:**")&&Z.includes("_result")}function NM($){let Z=$.supportedEffortLevels&&$.supportedEffortLevels.length>0?$.supportedEffortLevels:[h1];return{id:I1($.value),model:I1($.value),displayName:$.displayName||I1($.value),description:$.description||"Claude Agent SDK backend",hidden:!1,isDefault:!1,supportedReasoningEfforts:Z.map((J)=>({reasoningEffort:J,description:""})),defaultReasoningEffort:Z.includes(h1)?h1:Z[0]}}function nH($){if(!$?.settingSources)return[...gH];let Z=$.settingSources.split(",").map((J)=>J.trim()).filter(Boolean);return Z.length?Z:[...gH]}function aH($){if(!$?.tools)return{type:"preset",preset:"claude_code"};let Z=$.tools.split(",").map((J)=>J.trim()).filter(Boolean);return Z.length?Z:{type:"preset",preset:"claude_code"}}function oH($){let Z=C2($,".mcp.json"),J;try{J=pH(Z,"utf8")}catch(V){if(V.code==="ENOENT")return;throw Error(`project .mcp.json not readable at ${Z}: ${V}`,{cause:V})}let Q;try{Q=JSON.parse(J)}catch(V){throw Error(`project .mcp.json parse failed at ${Z}: ${V}`,{cause:V})}let Y=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.mcpServers:void 0;if(!Y||typeof Y!=="object"||Array.isArray(Y))throw Error(`project .mcp.json has no valid mcpServers object at ${Z}`);return Y}function RM($,Z=!1){let J=$.questions;return(Array.isArray(J)?J:J&&typeof J==="object"?[J]:[$]).map((Y)=>TM(Y,Z)).filter((Y)=>Y!==null)}function TM($,Z){let J=$&&typeof $==="object"?$:{question:$},Q=eZ(J.question,J.prompt,J.title,J.message,J.text,J.label);if(!Q)return null;if(!Q.trim())return null;let Y=EM(J.options??J.choices??J.suggestions,Z);return{...J,question:Q,options:Y,...typeof J.header==="string"?{header:J.header}:{},...typeof J.multiSelect==="boolean"?{multiSelect:J.multiSelect}:{}}}function EM($,Z){if(!Array.isArray($))return[];let J=[];for(let Q of $){if(typeof Q==="string"){J.push({label:Q});continue}if(!Q||typeof Q!=="object")continue;let Y=Q,V=eZ(Y.label,Y.value,Y.text,Y.title);if(!V?.trim())continue;let X=eZ(Y.description,Y.detail,Y.preview);J.push({label:V,...X?{description:X}:{},...Z&&typeof Y.preview==="string"?{preview:Y.preview}:{}})}return J}function eZ(...$){for(let Z of $)if(typeof Z==="string")return Z;return}var cH,rZ,iH="default",gH,X7;var v4=R(()=>{D4();k0();I();P0();gZ();o9();r9();kH();cH=class cH{items=[];waiters=[];closed=!1;push($){if(this.closed)throw Error("input stream is closed");let Z=this.waiters.shift();if(Z)Z({value:$,done:!1});else this.items.push($)}close(){if(this.closed)return;this.closed=!0;while(this.waiters.length)this.waiters.shift()?.({value:void 0,done:!0})}abort(){this.clear(),this.close()}clear(){this.items=[]}[Symbol.asyncIterator](){return this}next(){if(this.items.length>0)return Promise.resolve({value:this.items.shift(),done:!1});if(this.closed)return Promise.resolve({value:void 0,done:!0});return new Promise(($)=>this.waiters.push($))}};rZ=new Map;gH=["project","local"];X7=class X7 extends qM{provider="claude";tokenSourceId;translationEnabled;opts;input=new cH;query=null;abortController=new AbortController;alive=!0;expectedExit=!1;exitPromise;resolveExit;started=!1;queryStart;initializationError=null;pendingPermissions=new Map;requestCounter=0;cumulativeUsageFromResults=null;turnActive=!1;inputTurnPending=!1;nativeTurnPending=!1;steeringInputs=new Set;steeringResults=[];steeringFailures=[];deferredSteeringResult=null;emittedToolUseIds=new Set;emittedToolResultIds=new Set;pendingServerToolInputs=[];translationController=new AbortController;translationInputQueue=Promise.resolve();translationFailure=null;translationOutputStopped=!1;translationContextInitialized=!1;translationContextFailure=null;presentation;presentationPolicy;translatedToolNames=new Map;translatedToolInputs=new Map;translatedErrors=new Map;sessionId=null;lastAssistantUuid=null;lastModel=null;lastEffort=null;lastThinkingTokens=null;lastUsage=null;lastTotalUsage=null;lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1};lastContextWindow=null;lastContextTokens=null;constructor($){super();this.on("error",()=>{}),this.exitPromise=new Promise((Z)=>{this.resolveExit=Z}),this.opts=$,this.presentation=$.translation?new aZ($.translation):void 0,this.tokenSourceId=$.tokenSourceId??null,this.translationEnabled=!!$.translation,this.lastEffort=$.effort,this.lastModel=$.model?I1($.model):null}sendInitialize(){if(this.started)return;this.started=!0,this.queryStart=this.initializeQuery().catch(($)=>{if(this.initializationError=$ instanceof Error?$:Error(String($)),this.emit("error",this.initializationError),!this.query)this.finishExit(1,null)})}async*validatedInput(){if(await this.queryStart,this.initializationError||!this.alive)return;yield*this.input}async initializeQuery(){let $=i9(this.opts.model),Z=this.opts.profile;if(Z)j(`claude-agent-process: project profile active — settingSources=${Z.settingSources??"-"} strictMcp=${Z.strictMcp??!1} tools=${Z.tools??"-"} loadProjectMcp=${Z.loadProjectMcp??!0}`);let J=this.opts.settingSources??nH(Z),Q=uH(J,this.opts.managedSkillPluginPath),Y=aH(Z),V=[...this.opts.allowUserInput===!1?["AskUserQuestion","EnterPlanMode","ExitPlanMode"]:[]],X=Z?.strictMcp===!0,z=Z?.loadProjectMcp!==!1?oH(this.opts.workDir):void 0;try{let H=ZJ();if(this.opts.translation)await this.initializeTranslationContext();if(!this.alive||this.abortController.signal.aborted)return;let{query:G}=await rX();if(!this.alive||this.abortController.signal.aborted)return;let W={...process.env,PATH:lH(),...g.claude.env,...this.opts.hostEnv??{}},K=this.opts.transformEnv?this.opts.transformEnv(W):W;if(K.CLAUDE_CODE_ENABLE_TODO_TOOLS="1",this.opts.effort==="default")K.CLAUDE_CODE_EFFORT_LEVEL="unset";j(`claude-agent-process: spawn SDK query model=${$??"default"} effort=${this.opts.effort} cwd=${this.opts.workDir} executable=${H.description}`),this.query=G({prompt:this.opts.validateAccount?this.validatedInput():this.input,options:{cwd:this.opts.workDir,abortController:this.abortController,...$?{model:$}:{},effort:this.opts.effort==="default"?"high":this.opts.effort,resume:this.opts.resumeSessionId,...this.opts.resumeSessionAt?{resumeSessionAt:this.opts.resumeSessionAt}:{},...this.opts.forkSession?{forkSession:!0}:{},...H.pathToClaudeCodeExecutable?{pathToClaudeCodeExecutable:H.pathToClaudeCodeExecutable}:{},...H.spawnClaudeCodeProcess?{spawnClaudeCodeProcess:H.spawnClaudeCodeProcess}:{},permissionMode:iH,env:K,settingSources:[...J],...this.opts.settings?{settings:this.opts.settings}:{},...Q,tools:Y,...V.length?{disallowedTools:V}:{},...X?{strictMcpConfig:!0}:{},...z?{mcpServers:z}:{},toolConfig:{askUserQuestion:{previewFormat:"markdown"}},canUseTool:(B,_,P)=>this.canUseTool(B,_,P),includePartialMessages:!1,systemPrompt:{type:"preset",preset:"claude_code",...this.opts.appendSystemPrompt?{append:this.opts.appendSystemPrompt,snapshot:!1}:{}},stderr:(B)=>{let _=B.trim();if(_)j(`claude-agent-process[stderr]: ${_}`)}}})}catch(H){if(this.opts.translation&&this.expectedExit)return;let G=H instanceof Error?H:Error(String(H));this.initializationError=G,this.emit("error",G),this.finishExit(1,null);return}if(this.readLoop(this.query),this.opts.validateAccount)try{this.opts.validateAccount(await this.query.accountInfo())}catch(H){this.initializationError=H instanceof Error?H:Error(String(H)),this.emit("error",this.initializationError),await this.kill()}}sendUserText($,Z=[],J){if(!this.alive){j("claude-agent-process: sendUserText ignored on dead process");return}if(this.translationContextFailure){this.failTurnStart(this.translationContextFailure);return}if(!this.started)this.sendInitialize();let Q=(J?.contextPrefix??"")+(Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
106
106
 
107
107
  `:"");if(this.opts.translation){this.translationOutputStopped=!1,this.inputTurnPending=!0;let Y=this.translationController.signal,V=vH();this.queueTranslatedInput($,Y).then((X)=>{if(Y.aborted||!this.alive||this.expectedExit)return;this.pushUserText(Q+X,V),this.opts.translationContext?.stageInput(V,$,X,this.translationInputOrigin()),this.emit("user_input_submitted",{})}).catch((X)=>{if(Y.aborted||!this.alive||this.expectedExit)return;this.invalidateTranslations(),this.failTurnStart(this.translationError("input",X))});return}try{this.inputTurnPending=!0,this.pushUserText(Q+$)}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));j(`claude-agent-process: sendUserText failed: ${V.message}`),this.failTurnStart(V)}}async steerUserText($,Z=[],J=vH()){if(!this.alive||this.expectedExit)throw Error("Claude 进程已关闭");if(!this.turnActive&&!this.inputTurnPending&&this.steeringResults.length===0)return!1;let Q=J,Y=$,V=Z.length?Z.map((z)=>`[file: ${z}]`).join(" ")+`
108
108
 
@@ -114,26 +114,26 @@ Verified display text:
114
114
 
115
115
  `),W.join(`
116
116
 
117
- `),void 0,Z.toolUseID?`question:${Z.toolUseID}`:void 0,this.translationQuestionOrigin()),await this.beginDialog({...$,questions:G},{...Z,signal:J.signal},$,V)}catch(X){if(V(),J.signal.aborted||!this.alive||this.expectedExit)return{behavior:"deny",message:"aborted"};return this.reportTranslationFailure("question",X),{behavior:"deny",message:"The host could not translate or validate this question. The user has been informed and this turn is being interrupted."}}}async resolveTranslatedPermission($,Z,J,Q){let Y=Z.translationSignal;try{let V;if(J==="deny")V={behavior:"deny",message:Q?.denyMessage?await this.opts.translation.toEnglish(Q.denyMessage,Y,this.translationAnswerOrigin()):""};else{let z=Q?.updatedInput?.answers;if(!z||typeof z!=="object"||Array.isArray(z))throw Error("question response has no valid answers object");let H=Z.originalInput.questions,G=Z.request.input.questions,W={};for(let[K,B]of Object.entries(z)){if(typeof B!=="string")throw Error("question answer must be text");let _=G.findIndex((U,A)=>U.question===K||H[A]?.question===K||H[A]?.id===K);if(_<0)throw Error("question response references an unknown question");let P=H[_],L=String(P.question);if(Object.hasOwn(W,L))throw Error("question response contains duplicate answer keys");let q=G[_].options,D=P.options,M=this.resolveAnswerSelection(B,D,q,P.multiSelect===!0);if(M){let U=M.map((A)=>String(D[A].label)).join(", ");this.resolveAnswerSelection(U,D,D,P.multiSelect===!0)}W[L]=await this.opts.translation.toEnglish(B,Y,this.translationAnswerOrigin())}V={behavior:"allow",updatedInput:{...Z.originalInput,answers:W}}}if(Y.throwIfAborted(),this.pendingPermissions.get($)!==Z||!this.alive||this.expectedExit)return;let X=(z)=>z&&typeof z==="object"&&!Array.isArray(z)?Object.entries(z).map(([H,G])=>`${H}: ${String(G)}`).join(`
117
+ `),void 0,Z.toolUseID?`question:${Z.toolUseID}`:void 0,this.translationQuestionOrigin()),await this.beginDialog({...$,questions:G},{...Z,signal:J.signal},$,V)}catch(X){if(V(),J.signal.aborted||!this.alive||this.expectedExit)return{behavior:"deny",message:"aborted"};return this.reportTranslationFailure("question",X),{behavior:"deny",message:"The host could not translate or validate this question. The user has been informed and this turn is being interrupted."}}}async resolveTranslatedPermission($,Z,J,Q){let Y=Z.translationSignal;try{let V;if(J==="deny")V={behavior:"deny",message:Q?.denyMessage?await this.opts.translation.toEnglish(Q.denyMessage,Y,this.translationAnswerOrigin()):""};else{let z=Q?.updatedInput?.answers;if(!z||typeof z!=="object"||Array.isArray(z))throw Error("question response has no valid answers object");let H=Z.originalInput.questions,G=Z.request.input.questions,W={};for(let[K,B]of Object.entries(z)){if(typeof B!=="string")throw Error("question answer must be text");let _=G.findIndex((U,A)=>U.question===K||H[A]?.question===K||H[A]?.id===K);if(_<0)throw Error("question response references an unknown question");let P=H[_],L=String(P.question);if(Object.hasOwn(W,L))throw Error("question response contains duplicate answer keys");let q=G[_].options,F=P.options,M=this.resolveAnswerSelection(B,F,q,P.multiSelect===!0);if(M){let U=M.map((A)=>String(F[A].label)).join(", ");this.resolveAnswerSelection(U,F,F,P.multiSelect===!0)}W[L]=await this.opts.translation.toEnglish(B,Y,this.translationAnswerOrigin())}V={behavior:"allow",updatedInput:{...Z.originalInput,answers:W}}}if(Y.throwIfAborted(),this.pendingPermissions.get($)!==Z||!this.alive||this.expectedExit)return;let X=(z)=>z&&typeof z==="object"&&!Array.isArray(z)?Object.entries(z).map(([H,G])=>`${H}: ${String(G)}`).join(`
118
118
  `):String(z??"");this.opts.translationContext?.recordInteraction("user/answer",X(Q?.updatedInput?.answers??Q?.denyMessage),X(V.behavior==="allow"?V.updatedInput?.answers:V.message),this.translationAnswerOrigin()),this.pendingPermissions.delete($),Z.resolve(V)}catch(V){if(this.pendingPermissions.get($)!==Z)return;if(this.pendingPermissions.delete($),Y.aborted||!this.alive||this.expectedExit){Z.resolve({behavior:"deny",message:"aborted"});return}this.reportTranslationFailure("question answer",V),Z.resolve({behavior:"deny",message:"The host could not translate or validate the answer. The user has been informed and this turn is being interrupted."})}}resolveAnswerSelection($,Z,J,Q){let Y=new Map,V=(X,z)=>{if(Y.size>1)return;for(let H=0;H<Z.length;H++){if(z.includes(H))continue;for(let G of new Set([String(Z[H].label),String(J[H].label)])){if(!G||!$.startsWith(G,X))continue;let W=X+G.length,K=[...z,H];if(W===$.length)Y.set(K.join(","),K);else if(Q&&$[W]===","){let B=$.slice(W).match(/^,\s*/)?.[0];if(B)V(W+B.length,K)}}}};if(V(0,[]),Y.size>1)throw Error("question answer has ambiguous option labels");return Y.values().next().value??null}async readLoop($){try{for await(let Z of $)if(this.opts.translation)await this.handleTranslatedMessage(Z);else this.handleMessage(Z);this.finishExit(null,null)}catch(Z){let J=Z instanceof Error?Z:Error(String(Z));if(this.expectedExit&&this.abortController.signal.aborted){j(`claude-agent-process: read loop stopped after requested shutdown: ${J.message}`),this.finishExit(null,null);return}j(`claude-agent-process: read loop failed: ${J.message}`),this.emit("error",J),this.finishExit(1,null)}}finishExit($,Z){if(!this.alive)return;if(this.alive=!1,this.opts.translation)this.invalidateTranslations();this.translatedToolInputs.clear(),this.turnActive=!1,this.nativeTurnPending=!1,this.inputTurnPending=!1,this.steeringInputs.clear(),this.steeringResults=[],this.steeringFailures=[],this.deferredSteeringResult=null,this.denyPendingPermissions("claude process exited"),this.resolveExit(),j(`claude-agent-process: exited code=${$} signal=${Z} expected=${this.expectedExit}`),this.emit("exit",{code:$,signal:Z,expected:this.expectedExit})}denyPendingPermissions($){for(let[Z,J]of this.pendingPermissions)J.cleanup?.(),J.resolve({behavior:"deny",message:$}),this.pendingPermissions.delete(Z)}async waitForExit($){if(!this.alive)return!0;return new Promise((Z)=>{let J=!1,Q=(V)=>{if(J)return;J=!0,clearTimeout(Y),Z(V)},Y=setTimeout(()=>Q(!this.alive),Math.max(0,$));this.exitPromise.then(()=>Q(!0))})}observeTranslationContext($){if(!this.translationContextInitialized||!this.opts.translationContext)return;let Z=this.opts.translationContext;if(!$.parent_tool_use_id&&typeof $.session_id==="string"&&$.session_id)Z.bindSession($.session_id),this.opts.translation?.bindSession?.($.session_id);if($.type==="command_lifecycle"&&typeof $.command_uuid==="string"){if($.state==="started"||$.state==="completed")Z.confirmInput($.command_uuid);if($.state==="cancelled")Z.cancelInput($.command_uuid)}if(!$.parent_tool_use_id){let J=Array.isArray($.user_message_uuids)?$.user_message_uuids:[];for(let Q of[...J,$.user_message_uuid])if(typeof Q==="string")Z.confirmInput(Q);if($.type==="user"&&typeof $.uuid==="string")Z.confirmInput($.uuid)}}resultErrorText($){let Z=typeof $.subtype==="string"?$.subtype:$.is_error?"error":"success";return $.is_error===!0||Z!=="success"?Array.isArray($.errors)&&$.errors.length?$.errors.map(String).join(`
119
119
  `):String($.result??$.error??$.api_error_message??Z):null}userToolOutput($,Z){let J=e9(Z.content);if(J)return J;let Q=$.tool_use_result;return Q&&typeof Q==="object"?[typeof Q.stdout==="string"?Q.stdout:"",typeof Q.stderr==="string"?Q.stderr:""].filter(Boolean).join(`
120
- `):""}async handleTranslatedMessage($){let Z=$,J=typeof Z.parent_tool_use_id==="string"&&Z.parent_tool_use_id.length>0;if(Z.type==="assistant")this.emitAssistantControlText(Z);let Q=Z.type==="user"&&Z.isMeta===!0&&Z.promptSource==="sdk"&&typeof Z.message?.content==="string"&&Z.message.content.trim();if(Q)this.translationOutputStopped=!1;let Y=this.translationController.signal,V={texts:new Map,toolInputs:new Map,toolResults:new Map,serverToolInputs:Z.type==="assistant"?this.prepareServerToolInputs(Z):new Map,presentations:new Map,hidden:new Set},X=typeof Z.parent_tool_use_id==="string"?Z.parent_tool_use_id:null,z=async(G,W,K)=>{let B=this.presentationSurface(W);if(B==="hidden"){V.hidden.add(G);return}let _=await K(B);if(Y.throwIfAborted(),this.presentationSurface(W)==="hidden"){V.hidden.add(G);return}return V.presentations.set(G,{event:W,surface:B}),_};try{if(!this.translationContextFailure)this.observeTranslationContext(Z)}catch(G){this.translationContextFailure=this.translationError("context",G),this.reportTranslationFailure("context",G)}let H=!this.translationContextFailure&&!this.translationFailure&&!this.translationOutputStopped&&this.alive&&!this.expectedExit;try{if(H){if(Z.type==="assistant"){let G=Array.isArray(Z.message?.content)?Z.message.content:[];for(let W=0;W<G.length;W++){let K=G[W];if(K?.type==="text"&&typeof K.text==="string"&&K.text&&!IH(K.text)){let B=await z(`text:${W}`,{kind:"assistant_text",parentToolUseId:X},()=>this.opts.translation.toChinese(K.text,Y,this.translationReplyOrigin(X)));if(B!==void 0)V.texts.set(W,B)}else if((K?.type==="tool_use"||K?.type==="server_tool_use")&&typeof K.id==="string"&&typeof K.name==="string"&&K.name!=="AskUserQuestion"){let B=K.type==="server_tool_use"?tZ(K.name):K.name,_=K.type==="server_tool_use"?V.serverToolInputs.get(K.id):K.input??{};this.translatedToolNames.set(K.id,B);let P=await z(`input:${K.id}`,{kind:"tool_input",parentToolUseId:X,toolUseId:K.id,toolName:B},(L)=>this.presentation.toolInput(B,_,Y,L,this.translationToolOrigin(B,X)));if(P!==void 0)V.toolInputs.set(K.id,P),this.translatedToolInputs.set(K.id,P)}else if(K?.type==="tool_result"&&typeof K.tool_use_id==="string"){let B=sZ(K.content),_=await z(`result:${K.tool_use_id}`,{kind:"tool_result",parentToolUseId:X,toolUseId:K.tool_use_id,isError:K.is_error===!0,toolName:this.translatedToolNames.get(K.tool_use_id)??this.opts.translationContext?.toolName(K.tool_use_id)},(P)=>this.presentation.toolResult(this.toolNameForResult(K.tool_use_id),B,K.is_error===!0,Y,J,P,this.translationToolOrigin("",X,!0)));if(_!==void 0)V.toolResults.set(K.tool_use_id,_)}Y.throwIfAborted()}}else if(Z.type==="user"){if(Q)V.scheduledText=await z("scheduled",{kind:"scheduled_input",parentToolUseId:X},()=>this.opts.translation.toChinese(Z.message.content,Y,i.scheduledPrompt));for(let G of Array.isArray(Z.message?.content)?Z.message.content:[]){if(G?.type!=="tool_result"||typeof G.tool_use_id!=="string")continue;let W=this.userToolOutput(Z,G),K=!e9(G.content)&&Z.tool_use_result&&(typeof Z.tool_use_result.stdout==="string"||typeof Z.tool_use_result.stderr==="string"),B=G.is_error===!0||Z.tool_use_result?.interrupted===!0,_=K?"Bash":this.translatedToolNames.get(G.tool_use_id)??this.opts.translationContext?.toolName(G.tool_use_id),P=await z(`result:${G.tool_use_id}`,{kind:"tool_result",parentToolUseId:X,toolUseId:G.tool_use_id,toolName:_,isError:B},(L)=>this.presentation.toolResult(_??this.toolNameForResult(G.tool_use_id),W,B,Y,J,L,this.translationToolOrigin("",X,!0)));if(P!==void 0)V.toolResults.set(G.tool_use_id,P)}}else if(Z.type==="system"){let G=Z.subtype==="task_started"?["description","prompt","workflow_name"]:Z.subtype==="task_progress"?["description","summary"]:Z.subtype==="task_notification"?["summary"]:Z.subtype==="task_updated"?["description","error"]:[],W=Z.subtype==="task_updated"?Z.patch??{}:Z;if(G.length)V.system=await z("background",{kind:"background",parentToolUseId:X,subtype:Z.subtype,...typeof Z.task_id==="string"?{taskId:Z.task_id}:{}},()=>this.presentation.naturalFields(W,G,Y,i.backgroundUpdate))}else if(Z.type==="result"){let G=this.resultErrorText(Z);if(G)V.error=await this.opts.translation.toChinese(G,Y,i.error),this.translatedErrors.set(G,V.error)}Y.throwIfAborted()}else V.failed=!0}catch(G){if(V.failed=!0,V.texts.clear(),V.toolInputs.clear(),V.toolResults.clear(),V.system=void 0,V.scheduledText=void 0,!Y.aborted&&this.alive&&!this.expectedExit)this.reportTranslationFailure("output",G,this.hasPendingNativeTurn()||Z.type==="result"||Z.type==="assistant"&&!Z.parent_tool_use_id);if(Z.type==="result"){let W=this.resultErrorText(Z);if(W)j(`claude-agent-process: untranslated native error: ${W}`),this.translatedErrors.set(W,"原生错误翻译失败,原始诊断已保留在日志中。")}}if(Z.type==="result"&&V.failed){let G=this.resultErrorText(Z);if(G&&!this.translatedErrors.has(G))j(`claude-agent-process: untranslated native error: ${G}`),this.translatedErrors.set(G,"原生错误未能翻译,原始诊断已保留在日志中。")}if(!V.failed&&!this.translationContextFailure)try{this.discardHiddenPresentations(V),this.recordDisplayContext(Z,V)}catch(G){this.translationContextFailure=this.translationError("context",G),V.failed=!0,V.texts.clear(),V.toolInputs.clear(),V.toolResults.clear(),V.system=void 0,V.scheduledText=void 0,this.reportTranslationFailure("context",G,this.hasPendingNativeTurn()||Z.type==="result"||Z.type==="assistant"&&!Z.parent_tool_use_id)}this.handleMessage($,V,!0)}recordDisplayContext($,Z){let J=this.opts.translationContext;if(!J||Z.failed)return;let Q=typeof $.parent_tool_use_id==="string"&&$.parent_tool_use_id.length>0,Y=[],V=[],X=new Set,z=[],H=(B,_,P)=>{if(B.trim())Y.push(B),V.push(_),X.add(P)},G=Array.isArray($.message?.content)?$.message.content:[];if($.type==="assistant")for(let B=0;B<G.length;B++){let _=G[B],P=Z.texts.get(B);if(_?.type==="text"&&P!==void 0)H(_.text,P,this.translationReplyOrigin($.parent_tool_use_id));if((_?.type==="tool_use"||_?.type==="server_tool_use")&&typeof _.id==="string"&&typeof _.name==="string"){let L=_.type==="server_tool_use"?tZ(_.name):_.name;z.push({id:_.id,name:L});let q=Z.toolInputs.get(_.id);if(q!==void 0&&!this.emittedToolUseIds.has(_.id)){let D=_.type==="server_tool_use"?Z.serverToolInputs.get(_.id):_.input??{},M=Z.presentations.get(`input:${_.id}`).surface;H(nZ(L,D,M).join(`
120
+ `):""}async handleTranslatedMessage($){let Z=$,J=typeof Z.parent_tool_use_id==="string"&&Z.parent_tool_use_id.length>0;if(Z.type==="assistant")this.emitAssistantControlText(Z);let Q=Z.type==="user"&&Z.isMeta===!0&&Z.promptSource==="sdk"&&typeof Z.message?.content==="string"&&Z.message.content.trim();if(Q)this.translationOutputStopped=!1;let Y=this.translationController.signal,V={texts:new Map,toolInputs:new Map,toolResults:new Map,serverToolInputs:Z.type==="assistant"?this.prepareServerToolInputs(Z):new Map,presentations:new Map,hidden:new Set},X=typeof Z.parent_tool_use_id==="string"?Z.parent_tool_use_id:null,z=async(G,W,K)=>{let B=this.presentationSurface(W);if(B==="hidden"){V.hidden.add(G);return}let _=await K(B);if(Y.throwIfAborted(),this.presentationSurface(W)==="hidden"){V.hidden.add(G);return}return V.presentations.set(G,{event:W,surface:B}),_};try{if(!this.translationContextFailure)this.observeTranslationContext(Z)}catch(G){this.translationContextFailure=this.translationError("context",G),this.reportTranslationFailure("context",G)}let H=!this.translationContextFailure&&!this.translationFailure&&!this.translationOutputStopped&&this.alive&&!this.expectedExit;try{if(H){if(Z.type==="assistant"){let G=Array.isArray(Z.message?.content)?Z.message.content:[];for(let W=0;W<G.length;W++){let K=G[W];if(K?.type==="text"&&typeof K.text==="string"&&K.text&&!IH(K.text)){let B=await z(`text:${W}`,{kind:"assistant_text",parentToolUseId:X},()=>this.opts.translation.toChinese(K.text,Y,this.translationReplyOrigin(X)));if(B!==void 0)V.texts.set(W,B)}else if((K?.type==="tool_use"||K?.type==="server_tool_use")&&typeof K.id==="string"&&typeof K.name==="string"&&K.name!=="AskUserQuestion"){let B=K.type==="server_tool_use"?tZ(K.name):K.name,_=K.type==="server_tool_use"?V.serverToolInputs.get(K.id):K.input??{};this.translatedToolNames.set(K.id,B);let P=await z(`input:${K.id}`,{kind:"tool_input",parentToolUseId:X,toolUseId:K.id,toolName:B},(L)=>this.presentation.toolInput(B,_,Y,L,this.translationToolOrigin(B,X)));if(P!==void 0)V.toolInputs.set(K.id,P),this.translatedToolInputs.set(K.id,P)}else if(K?.type==="tool_result"&&typeof K.tool_use_id==="string"){let B=sZ(K.content),_=await z(`result:${K.tool_use_id}`,{kind:"tool_result",parentToolUseId:X,toolUseId:K.tool_use_id,isError:K.is_error===!0,toolName:this.translatedToolNames.get(K.tool_use_id)??this.opts.translationContext?.toolName(K.tool_use_id)},(P)=>this.presentation.toolResult(this.toolNameForResult(K.tool_use_id),B,K.is_error===!0,Y,J,P,this.translationToolOrigin("",X,!0)));if(_!==void 0)V.toolResults.set(K.tool_use_id,_)}Y.throwIfAborted()}}else if(Z.type==="user"){if(Q)V.scheduledText=await z("scheduled",{kind:"scheduled_input",parentToolUseId:X},()=>this.opts.translation.toChinese(Z.message.content,Y,i.scheduledPrompt));for(let G of Array.isArray(Z.message?.content)?Z.message.content:[]){if(G?.type!=="tool_result"||typeof G.tool_use_id!=="string")continue;let W=this.userToolOutput(Z,G),K=!e9(G.content)&&Z.tool_use_result&&(typeof Z.tool_use_result.stdout==="string"||typeof Z.tool_use_result.stderr==="string"),B=G.is_error===!0||Z.tool_use_result?.interrupted===!0,_=K?"Bash":this.translatedToolNames.get(G.tool_use_id)??this.opts.translationContext?.toolName(G.tool_use_id),P=await z(`result:${G.tool_use_id}`,{kind:"tool_result",parentToolUseId:X,toolUseId:G.tool_use_id,toolName:_,isError:B},(L)=>this.presentation.toolResult(_??this.toolNameForResult(G.tool_use_id),W,B,Y,J,L,this.translationToolOrigin("",X,!0)));if(P!==void 0)V.toolResults.set(G.tool_use_id,P)}}else if(Z.type==="system"){let G=Z.subtype==="task_started"?["description","prompt","workflow_name"]:Z.subtype==="task_progress"?["description","summary"]:Z.subtype==="task_notification"?["summary"]:Z.subtype==="task_updated"?["description","error"]:[],W=Z.subtype==="task_updated"?Z.patch??{}:Z;if(G.length)V.system=await z("background",{kind:"background",parentToolUseId:X,subtype:Z.subtype,...typeof Z.task_id==="string"?{taskId:Z.task_id}:{}},()=>this.presentation.naturalFields(W,G,Y,i.backgroundUpdate))}else if(Z.type==="result"){let G=this.resultErrorText(Z);if(G)V.error=await this.opts.translation.toChinese(G,Y,i.error),this.translatedErrors.set(G,V.error)}Y.throwIfAborted()}else V.failed=!0}catch(G){if(V.failed=!0,V.texts.clear(),V.toolInputs.clear(),V.toolResults.clear(),V.system=void 0,V.scheduledText=void 0,!Y.aborted&&this.alive&&!this.expectedExit)this.reportTranslationFailure("output",G,this.hasPendingNativeTurn()||Z.type==="result"||Z.type==="assistant"&&!Z.parent_tool_use_id);if(Z.type==="result"){let W=this.resultErrorText(Z);if(W)j(`claude-agent-process: untranslated native error: ${W}`),this.translatedErrors.set(W,"原生错误翻译失败,原始诊断已保留在日志中。")}}if(Z.type==="result"&&V.failed){let G=this.resultErrorText(Z);if(G&&!this.translatedErrors.has(G))j(`claude-agent-process: untranslated native error: ${G}`),this.translatedErrors.set(G,"原生错误未能翻译,原始诊断已保留在日志中。")}if(!V.failed&&!this.translationContextFailure)try{this.discardHiddenPresentations(V),this.recordDisplayContext(Z,V)}catch(G){this.translationContextFailure=this.translationError("context",G),V.failed=!0,V.texts.clear(),V.toolInputs.clear(),V.toolResults.clear(),V.system=void 0,V.scheduledText=void 0,this.reportTranslationFailure("context",G,this.hasPendingNativeTurn()||Z.type==="result"||Z.type==="assistant"&&!Z.parent_tool_use_id)}this.handleMessage($,V,!0)}recordDisplayContext($,Z){let J=this.opts.translationContext;if(!J||Z.failed)return;let Q=typeof $.parent_tool_use_id==="string"&&$.parent_tool_use_id.length>0,Y=[],V=[],X=new Set,z=[],H=(B,_,P)=>{if(B.trim())Y.push(B),V.push(_),X.add(P)},G=Array.isArray($.message?.content)?$.message.content:[];if($.type==="assistant")for(let B=0;B<G.length;B++){let _=G[B],P=Z.texts.get(B);if(_?.type==="text"&&P!==void 0)H(_.text,P,this.translationReplyOrigin($.parent_tool_use_id));if((_?.type==="tool_use"||_?.type==="server_tool_use")&&typeof _.id==="string"&&typeof _.name==="string"){let L=_.type==="server_tool_use"?tZ(_.name):_.name;z.push({id:_.id,name:L});let q=Z.toolInputs.get(_.id);if(q!==void 0&&!this.emittedToolUseIds.has(_.id)){let F=_.type==="server_tool_use"?Z.serverToolInputs.get(_.id):_.input??{},M=Z.presentations.get(`input:${_.id}`).surface;H(nZ(L,F,M).join(`
121
121
  `),nZ(L,q,M).join(`
122
- `),this.translationToolOrigin(L,$.parent_tool_use_id))}}}if($.type==="assistant"||$.type==="user")for(let B of G){if(B?.type!=="tool_result"||typeof B.tool_use_id!=="string")continue;let _=Z.toolResults.get(B.tool_use_id);if(_===void 0||this.emittedToolResultIds.has(B.tool_use_id))continue;let L=$.type==="user"&&!e9(B.content)&&$.tool_use_result&&(typeof $.tool_use_result.stdout==="string"||typeof $.tool_use_result.stderr==="string")?"Bash":this.toolNameForResult(B.tool_use_id),q=$.type==="user"?this.userToolOutput($,B):sZ(B.content),D=B.is_error===!0||$.tool_use_result?.interrupted===!0,M=Z.presentations.get(`result:${B.tool_use_id}`).surface;H(iZ(L,q,D,Q,M).join(`
123
- `),iZ(L,_,D,Q,M).join(`
122
+ `),this.translationToolOrigin(L,$.parent_tool_use_id))}}}if($.type==="assistant"||$.type==="user")for(let B of G){if(B?.type!=="tool_result"||typeof B.tool_use_id!=="string")continue;let _=Z.toolResults.get(B.tool_use_id);if(_===void 0||this.emittedToolResultIds.has(B.tool_use_id))continue;let L=$.type==="user"&&!e9(B.content)&&$.tool_use_result&&(typeof $.tool_use_result.stdout==="string"||typeof $.tool_use_result.stderr==="string")?"Bash":this.toolNameForResult(B.tool_use_id),q=$.type==="user"?this.userToolOutput($,B):sZ(B.content),F=B.is_error===!0||$.tool_use_result?.interrupted===!0,M=Z.presentations.get(`result:${B.tool_use_id}`).surface;H(iZ(L,q,F,Q,M).join(`
123
+ `),iZ(L,_,F,Q,M).join(`
124
124
  `),this.translationToolOrigin(L,$.parent_tool_use_id,!0))}if(Z.system){let B=$.subtype==="task_started"?["description","prompt","workflow_name"]:$.subtype==="task_progress"?["description","summary"]:$.subtype==="task_updated"?["description","error"]:$.subtype==="task_notification"?["summary"]:[],_=$.subtype==="task_updated"?$.patch??{}:$;for(let P of B)if(typeof _[P]==="string"&&typeof Z.system[P]==="string")H(_[P],Z.system[P],i.backgroundUpdate)}if(Z.scheduledText!==void 0)H($.message.content,Z.scheduledText,i.scheduledPrompt);if(Z.error!==void 0)H(this.resultErrorText($)??"",Z.error,i.error);let W=$.parent_tool_use_id?`subagent:${$.parent_tool_use_id}`:$.type==="assistant"?"message":$.type==="system"?"background":$.type==="result"?"error":Z.scheduledText!==void 0?"scheduled":"tool-result",K=typeof $.uuid==="string"?$.uuid:void 0;J.recordDisplay({tools:z,...Y.length?{output:{kind:W,original:Y.join(`
125
125
 
126
126
  `),display:V.join(`
127
127
 
128
128
  `),uuid:K,origin:[...X].join(" "),...K?{key:`${$.type}:${$.parent_tool_use_id??""}:${K}`}:{}}}:{},...$.type==="assistant"&&!$.parent_tool_use_id&&K?{checkpoint:K}:{}})}toolNameForResult($){let Z=this.translatedToolNames.get($)??this.opts.translationContext?.toolName($);if(!Z)throw Error(`工具结果来源 MISS,不能判定可翻译字段:${$}`);return Z}handleMessage($,Z,J=!1){let Q=$;if(!J&&!this.translationContextFailure)this.observeTranslationContext(Q);if(!this.translationContextFailure&&(!this.opts.translation||!Q.parent_tool_use_id)&&typeof Q.session_id==="string"&&Q.session_id)this.sessionId=Q.session_id;switch(Q.type){case"system":this.handleSystemMessage(Q,Z);return;case"assistant":this.handleAssistantMessage(Q,Z);return;case"user":this.handleUserMessage(Q,Z);return;case"result":this.handleResultMessage(Q);return;case"command_lifecycle":if(typeof Q.command_uuid!=="string"||!["queued","started","completed","cancelled"].includes(Q.state)){j(`claude-agent-process: malformed command lifecycle ${JSON.stringify(Q)}`);return}if(Q.state==="started"||Q.state==="completed"){if(this.steeringInputs.delete(Q.command_uuid)){if(this.inputTurnPending=!0,Q.state==="started")this.nativeTurnPending=!0;if(Q.state==="started")this.emit("user_input_consumed",{inputId:Q.command_uuid})}}if(Q.state==="cancelled"&&this.steeringInputs.delete(Q.command_uuid)){if(this.steeringFailures.push("原生 Claude 取消了一条尚未处理的追加消息,请重新发送。"),this.emit("turn_input_error",{error:"原生 Claude 取消了一条尚未处理的追加消息,请重新发送。"}),!this.steeringInputs.size&&!this.inputTurnPending&&!this.turnActive&&this.deferredSteeringResult){let V=this.deferredSteeringResult;this.finishInputResult(V.raw,V.subtype,V.error)}}return;case"rate_limit_event":this.emit("rate_limits_updated",Q.rate_limit_info);return;case"stream_event":return;default:j(`claude-agent-process: unhandled message type=${Q.type??"unknown"} subtype=${Q.subtype??""}`)}}handleSystemMessage($,Z){let J=(Q,Y=$)=>{if(!Z||Z.hidden.has("background"))return;return Object.fromEntries(Q.filter((V)=>typeof Y[V]==="string").map((V)=>[V,typeof Z.system?.[V]==="string"?Z.system[V]:"翻译失败,详情见本轮错误提示。"]))};switch($.subtype){case"init":if(typeof $.model==="string"&&$.model)this.lastModel=I1($.model);this.lastEffort=this.opts.effort,this.emit("init",{session_id:this.sessionId,raw:$});return;case"session_state_changed":if($.state==="running")this.nativeTurnPending=!0;if($.state==="running"&&!this.turnActive)this.turnActive=!0,this.lastThinkingTokens=null,this.lastAssistantUuid=null,this.emit("turn_started",{turn_id:$.uuid,thread_id:this.sessionId,...this.steeringResults.length?{retry:!0}:{}});else if($.state==="idle")this.turnActive=!1;return;case"compact_boundary":this.emit("context_compacted",{threadId:$.session_id??this.sessionId??void 0,sessionId:$.session_id??this.sessionId??void 0,itemId:$.uuid,phase:"event",sourceMethod:"claude_agent_sdk",sourceType:"compact_boundary",preTokens:$.compact_metadata?.pre_tokens,trigger:$.compact_metadata?.trigger});return;case"api_retry":j(`claude-agent-process: api retry attempt=${$.attempt}/${$.max_retries} status=${$.error_status} error=${$.error}`);return;case"thinking_tokens":if(typeof $.estimated_tokens!=="number"||!Number.isFinite($.estimated_tokens)||$.estimated_tokens<0){j("claude-agent-process: invalid thinking_tokens estimate");return}this.lastThinkingTokens=$.estimated_tokens,this.emit("thinking_progress",{estimatedTokens:$.estimated_tokens});return;case"permission_denied":j(`claude-agent-process: permission denied ${$.tool_name} ${$.tool_use_id}: ${$.message}`);return;case"task_started":this.emit("bg_task_started",{task_id:String($.task_id??""),tool_use_id:typeof $.tool_use_id==="string"?$.tool_use_id:void 0,task_type:typeof $.task_type==="string"?$.task_type:void 0,description:String($.description??""),subagent_type:typeof $.subagent_type==="string"?$.subagent_type:void 0,workflow_name:typeof $.workflow_name==="string"?$.workflow_name:void 0,prompt:typeof $.prompt==="string"?$.prompt:void 0,...Z?{display:J(["description","prompt","workflow_name"])}:{}});return;case"task_progress":this.emit("bg_task_progress",{task_id:String($.task_id??""),description:typeof $.description==="string"?$.description:void 0,subagent_type:typeof $.subagent_type==="string"?$.subagent_type:void 0,usage:$.usage,last_tool_name:typeof $.last_tool_name==="string"?$.last_tool_name:void 0,summary:typeof $.summary==="string"?$.summary:void 0,...Z?{display:J(["description","summary"])}:{}});return;case"task_updated":this.emit("bg_task_updated",{task_id:String($.task_id??""),patch:$.patch&&typeof $.patch==="object"?$.patch:{},...Z?{display:J(["description","error"],$.patch??{})}:{}});return;case"task_notification":if(typeof $.task_id!=="string"||!$.task_id){j("claude-agent-process: task_notification missing task_id");return}if($.status!=="completed"&&$.status!=="failed"&&$.status!=="stopped"){j(`claude-agent-process: task_notification unknown status=${String($.status)} task=${$.task_id}`);return}this.emit("bg_task_settled",{task_id:$.task_id,tool_use_id:typeof $.tool_use_id==="string"?$.tool_use_id:void 0,status:$.status,summary:typeof $.summary==="string"?$.summary:void 0,usage:$.usage,...Z?{display:J(["summary"])}:{}});return;default:j(`claude-agent-process: unhandled system subtype=${String($.subtype??"unknown")}`);return}}handleAssistantMessage($,Z){let J=Z?.texts;if(this.opts.translation&&!J)this.emitAssistantControlText($);if(this.confirmSteeringInputs($),!$.parent_tool_use_id)this.lastThinkingTokens=null;let Q=$.message,Y=typeof $.parent_tool_use_id==="string"&&$.parent_tool_use_id?$.parent_tool_use_id:null;if(!Y&&typeof $.uuid==="string")this.lastAssistantUuid=$.uuid;if(typeof Q?.model==="string"&&Q.model)this.lastModel=I1(Q.model);let V=Array.isArray(Q?.content)?Q.content:[];for(let X=0;X<V.length;X++){let z=V[X];if(!z||typeof z!=="object")continue;if(z.type==="text"&&typeof z.text==="string"&&z.text.length>0){if(!Z)this.rememberServerToolInput(z.text);if(IH(z.text))continue;if(J&&!J.has(X)&&!Z?.hidden.has(`text:${X}`))continue;let H=$.uuid??Q?.id;this.emit("assistant_text",{uuid:H,text:z.text,parentToolUseId:Y,...J?.has(X)?{displayText:J.get(X)}:{}}),this.emit("assistant_block_stop",{index:H,parentToolUseId:Y})}else if(z.type==="tool_use"&&typeof z.id==="string"&&typeof z.name==="string"){if(this.opts.translation&&z.name==="AskUserQuestion")continue;if(Z&&!Z.toolInputs.has(z.id)&&!Z.hidden.has(`input:${z.id}`))continue;this.emitToolUseOnce(z.id,z.name,z.input??{},Y,Z?.toolInputs.get(z.id))}else if(z.type==="server_tool_use"&&typeof z.id==="string"&&typeof z.name==="string"){if(Z&&!Z.toolInputs.has(z.id)&&!Z.hidden.has(`input:${z.id}`))continue;this.emitToolUseOnce(z.id,tZ(z.name),Z?Z.serverToolInputs.get(z.id):{tool:z.name,input:this.serverToolInput(z.name,z.input??{})},Y,Z?.toolInputs.get(z.id))}else if(z.type==="tool_result"&&typeof z.tool_use_id==="string")this.emitToolResultOnce(z.tool_use_id,sZ(z.content),z.is_error===!0,Y,Z&&!Z.hidden.has(`result:${z.tool_use_id}`)?Z.toolResults.get(z.tool_use_id)??"工具结果翻译失败。":void 0)}}emitAssistantControlText($){if($.parent_tool_use_id)return;for(let Z of Array.isArray($.message?.content)?$.message.content:[])if(Z?.type==="text"&&typeof Z.text==="string")this.emit("assistant_control_text",{text:Z.text})}emitToolUseOnce($,Z,J,Q,Y){if(this.emittedToolUseIds.has($))return;if(this.emittedToolUseIds.add($),!Z.trim())j(`claude-agent-process: tool_use ${$} has an empty name`),Z="MISS";if(this.opts.translation)this.translatedToolNames.set($,Z);this.emit("tool_use",{id:$,name:Z,input:J,parentToolUseId:Q,...Y!==void 0?{displayInput:Y}:{}})}rememberServerToolInput($){let Z=AM($);if(!Z)return;if(this.pendingServerToolInputs.push(Z),this.pendingServerToolInputs.length>20)this.pendingServerToolInputs.shift()}prepareServerToolInputs($){let Z=new Map;for(let J of Array.isArray($.message?.content)?$.message.content:[])if(J?.type==="text"&&typeof J.text==="string")this.rememberServerToolInput(J.text);else if(J?.type==="server_tool_use"&&typeof J.id==="string"&&typeof J.name==="string")Z.set(J.id,{tool:J.name,input:this.serverToolInput(J.name,J.input??{})});return Z}serverToolInput($,Z){let J=Z;if(J&&typeof J==="object"&&!Array.isArray(J)&&Object.keys(J).length>0)return J;let Q=this.pendingServerToolInputs.findIndex((Y)=>Y.name===$);if(Q>=0){let[Y]=this.pendingServerToolInputs.splice(Q,1);return Y.input}return J}emitToolResultOnce($,Z,J,Q,Y){if(this.emittedToolResultIds.has($))return;this.emittedToolResultIds.add($);let V=this.translatedToolInputs.get($);this.translatedToolInputs.delete($),this.emit("tool_result",{tool_use_id:$,content:Z,...Y!==void 0?{displayContent:Y,displayInput:V}:{},is_error:J,parentToolUseId:Q})}handleUserMessage($,Z){let J=$.message?.content;if($.isMeta===!0&&$.promptSource==="sdk"&&typeof J==="string"&&J.trim())this.translationOutputStopped=!1,this.emit("scheduled_turn_input",{text:J,...Z&&!Z.hidden.has("scheduled")?{displayText:Z.scheduledText??"定时任务提示词翻译失败。"}:{},promptId:typeof $.promptId==="string"&&$.promptId?$.promptId:null});let Q=Array.isArray(J)?J:[];for(let Y of Q){if(!Y||typeof Y!=="object")continue;if(Y.type!=="tool_result"||typeof Y.tool_use_id!=="string")continue;let V=$.tool_use_result,X=e9(Y.content),z=V&&typeof V==="object"?[typeof V.stdout==="string"?V.stdout:"",typeof V.stderr==="string"?V.stderr:""].filter(Boolean).join(`
129
- `):"",H=X||z;this.emitToolResultOnce(Y.tool_use_id,H,Y.is_error===!0||V?.interrupted===!0,$.parent_tool_use_id??null,Z&&!Z.hidden.has(`result:${Y.tool_use_id}`)?Z.toolResults.get(Y.tool_use_id)??"工具结果翻译失败。":void 0)}}handleResultMessage($){if(!this.translationContextFailure&&typeof $.session_id==="string"&&$.session_id)this.sessionId=$.session_id;this.turnActive=!1,this.nativeTurnPending=!1,this.inputTurnPending=!1;let Z=MM($.usage),J=$.modelUsage??$.model_usage,Q=OM(J);if(!Z&&!Q.usage)j(`claude-agent-process: result usage missing rootKeys=${oZ($).join(",")||"-"} usageKeys=${oZ($.usage).join(",")||"-"} modelUsageKeys=${oZ(J).join(",")||"-"}`);if(this.lastUsage=Z,Q.usage)this.cumulativeUsageFromResults=J7(Q.usage),this.lastTotalUsage=J7(Q.usage);else if(Z)this.cumulativeUsageFromResults=hH(this.cumulativeUsageFromResults,Z),this.lastTotalUsage=J7(this.cumulativeUsageFromResults);else this.lastTotalUsage=this.cumulativeUsageFromResults?J7(this.cumulativeUsageFromResults):null;if(Q.contextWindow!=null){let H=yH(this.opts.model,this.tokenSourceId);if(rZ.set(H,Q.contextWindow),this.tokenSourceId)for(let[G,W]of Object.entries(J??{})){let K=W?.contextWindow;if(typeof K==="number"&&K>0)DH(this.tokenSourceId,G,K)}}this.lastContextWindow=rZ.get(yH(this.opts.model,this.tokenSourceId))??Q.contextWindow??null;let Y=V7(this.opts.workDir,this.sessionId??""),V=dH(Y);if(this.lastContextTokens=fH(V)??(mH(Y)?fH(Z):null),this.lastTotalUsage||this.lastUsage)this.emit("token_usage",{usage:this.lastUsage,totalUsage:this.lastTotalUsage,contextWindow:this.lastContextWindow,threadId:this.sessionId??void 0,turnId:$.uuid});let X=typeof $.subtype==="string"?$.subtype:$.is_error?"error":"success";this.confirmSteeringInputs($);let z=this.resultErrorText($);if(this.steeringInputs.size||this.steeringResults.length){if(this.steeringResults.push({usage:Z,duration:typeof $.duration_ms==="number"?$.duration_ms:null,turns:typeof $.num_turns==="number"?$.num_turns:1,error:z}),this.steeringInputs.size){if(this.deferredSteeringResult={raw:$,subtype:X,error:z},z)this.emit("turn_input_error",{error:z,displayError:this.translatedErrors.get(z)});j(`claude-agent-process: native result has ${this.steeringInputs.size} unconsumed steering inputs`);return}}this.finishInputResult($,X,z)}finishInputResult($,Z,J){this.deferredSteeringResult=null;let Q=this.steeringResults.splice(0),Y=Q.length?Q.flatMap((X)=>X.error?[X.error]:[]):J?[J]:[];Y.push(...this.steeringFailures.splice(0));let V=this.translationFailure!==null||this.translationContextFailure!==null;if(this.translationContextFailure&&!Y.includes(this.translationContextFailure.message))Y.push(this.translationContextFailure.message);if(this.translationFailure)Y.push(this.translationFailure.message),this.translationFailure=null;if(Q.length)this.lastUsage=Q.every((X)=>X.usage!==null)?Q.reduce((X,z)=>hH(X,z.usage),null):null;this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:Q.length?Q.every((X)=>X.duration!==null)?Q.reduce((X,z)=>X+z.duration,0):null:typeof $.duration_ms==="number"?$.duration_ms:null,num_turns:Q.length?Q.reduce((X,z)=>X+z.turns,0):typeof $.num_turns==="number"?$.num_turns:1,usage:this.lastUsage,subtype:Y.length&&Z==="success"?V?"claude_translation_failed":"claude_steering_failed":Z,is_error:Y.length>0},this.emit("result",{subtype:this.lastResult.subtype,is_error:this.lastResult.is_error,...this.lastResult.is_error?{error:Y.join(`
129
+ `):"",H=X||z;this.emitToolResultOnce(Y.tool_use_id,H,Y.is_error===!0||V?.interrupted===!0,$.parent_tool_use_id??null,Z&&!Z.hidden.has(`result:${Y.tool_use_id}`)?Z.toolResults.get(Y.tool_use_id)??"工具结果翻译失败。":void 0)}}handleResultMessage($){if(!this.translationContextFailure&&typeof $.session_id==="string"&&$.session_id)this.sessionId=$.session_id;this.turnActive=!1,this.nativeTurnPending=!1,this.inputTurnPending=!1;let Z=MM($.usage),J=$.modelUsage??$.model_usage,Q=OM(J);if(!Z&&!Q.usage)j(`claude-agent-process: result usage missing rootKeys=${oZ($).join(",")||"-"} usageKeys=${oZ($.usage).join(",")||"-"} modelUsageKeys=${oZ(J).join(",")||"-"}`);if(this.lastUsage=Z,Q.usage)this.cumulativeUsageFromResults=J7(Q.usage),this.lastTotalUsage=J7(Q.usage);else if(Z)this.cumulativeUsageFromResults=hH(this.cumulativeUsageFromResults,Z),this.lastTotalUsage=J7(this.cumulativeUsageFromResults);else this.lastTotalUsage=this.cumulativeUsageFromResults?J7(this.cumulativeUsageFromResults):null;if(Q.contextWindow!=null){let H=fH(this.opts.model,this.tokenSourceId);if(rZ.set(H,Q.contextWindow),this.tokenSourceId)for(let[G,W]of Object.entries(J??{})){let K=W?.contextWindow;if(typeof K==="number"&&K>0)FH(this.tokenSourceId,G,K)}}this.lastContextWindow=rZ.get(fH(this.opts.model,this.tokenSourceId))??Q.contextWindow??null;let Y=V7(this.opts.workDir,this.sessionId??""),V=dH(Y);if(this.lastContextTokens=yH(V)??(mH(Y)?yH(Z):null),this.lastTotalUsage||this.lastUsage)this.emit("token_usage",{usage:this.lastUsage,totalUsage:this.lastTotalUsage,contextWindow:this.lastContextWindow,threadId:this.sessionId??void 0,turnId:$.uuid});let X=typeof $.subtype==="string"?$.subtype:$.is_error?"error":"success";this.confirmSteeringInputs($);let z=this.resultErrorText($);if(this.steeringInputs.size||this.steeringResults.length){if(this.steeringResults.push({usage:Z,duration:typeof $.duration_ms==="number"?$.duration_ms:null,turns:typeof $.num_turns==="number"?$.num_turns:1,error:z}),this.steeringInputs.size){if(this.deferredSteeringResult={raw:$,subtype:X,error:z},z)this.emit("turn_input_error",{error:z,displayError:this.translatedErrors.get(z)});j(`claude-agent-process: native result has ${this.steeringInputs.size} unconsumed steering inputs`);return}}this.finishInputResult($,X,z)}finishInputResult($,Z,J){this.deferredSteeringResult=null;let Q=this.steeringResults.splice(0),Y=Q.length?Q.flatMap((X)=>X.error?[X.error]:[]):J?[J]:[];Y.push(...this.steeringFailures.splice(0));let V=this.translationFailure!==null||this.translationContextFailure!==null;if(this.translationContextFailure&&!Y.includes(this.translationContextFailure.message))Y.push(this.translationContextFailure.message);if(this.translationFailure)Y.push(this.translationFailure.message),this.translationFailure=null;if(Q.length)this.lastUsage=Q.every((X)=>X.usage!==null)?Q.reduce((X,z)=>hH(X,z.usage),null):null;this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:Q.length?Q.every((X)=>X.duration!==null)?Q.reduce((X,z)=>X+z.duration,0):null:typeof $.duration_ms==="number"?$.duration_ms:null,num_turns:Q.length?Q.reduce((X,z)=>X+z.turns,0):typeof $.num_turns==="number"?$.num_turns:1,usage:this.lastUsage,subtype:Y.length&&Z==="success"?V?"claude_translation_failed":"claude_steering_failed":Z,is_error:Y.length>0},this.emit("result",{subtype:this.lastResult.subtype,is_error:this.lastResult.is_error,...this.lastResult.is_error?{error:Y.join(`
130
130
  `),...this.opts.translation?{displayError:Y.map((X)=>this.translatedErrors.get(X)??X).join(`
131
- `)}:{}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,checkpoint:!this.lastResult.is_error&&this.lastAssistantUuid&&this.sessionId?{provider:"claude",kind:"assistant-message",id:this.lastAssistantUuid,source:{provider:"claude",sessionId:this.sessionId,cwd:this.opts.workDir}}:null})}confirmSteeringInputs($){if($.parent_tool_use_id)return;let Z=Array.isArray($.user_message_uuids)?$.user_message_uuids:[];for(let J of[...Z,$.user_message_uuid])if(typeof J==="string"&&this.steeringInputs.delete(J)&&$.type!=="result")this.inputTurnPending=!0}failTurnStart($){this.turnActive=!1,this.inputTurnPending=!1,this.lastAssistantUuid=null,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"claude_turn_start_failed",is_error:!0},this.emit("result",{subtype:this.lastResult.subtype,is_error:!0,duration_ms:null,usage:this.lastUsage,error:$.message})}}});import{homedir as SM}from"node:os";function xM($,Z=CM){return new Promise((J,Q)=>{let Y=setTimeout(()=>Q(Error(`timeout ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Y),J(V)},(V)=>{clearTimeout(Y),Q(V)})})}function sH($){return typeof $==="string"&&bM.includes($)?$:null}async function z7($={}){let{ClaudeAgentProcess:Z}=await Promise.resolve().then(() => (v4(),JJ)),J=new Z({workDir:SM(),effort:"high",settingSources:["user"],profile:{loadProjectMcp:!1},...$});J.on("error",(Q)=>j(`Claude model catalog MISS: ${Q.message}`));try{let Q=await xM(J.listModels());if(!Q.length)throw Error("Claude SDK model catalog is empty");return Q.map((Y)=>({model:Y.model.replace(/^claude:/,""),display:Y.displayName,efforts:Y.supportedReasoningEfforts.map((V)=>V.reasoningEffort),defaultEffort:Y.defaultReasoningEffort}))}finally{await J.kill()}}async function tH($="default"){let Z=v.revision($),J=new w$({accountId:$});try{await J.initialize("lodestar-models");let Q=await i$(()=>J.request("account/read",{refreshToken:!1}),"账号查询");if(l3($,Q?.account,Z),Q?.account?.type!=="chatgpt")throw Object.assign(Error("Codex 订阅未登录;发送 codex-login 或 codex-login 备注完成授权"),{code:"CODEX_AUTH_MISSING"});let Y=[],V=new Set,X=null;do{let z=await i$(()=>J.request("model/list",{cursor:X,limit:100,includeHidden:!1}),"模型查询");if(!Array.isArray(z?.data))throw Error("Codex model/list 缺少 data 数组");for(let G of z.data){if(!G||G.hidden||!G.id)continue;let W=(Array.isArray(G.supportedReasoningEfforts)?G.supportedReasoningEfforts:[]).map((B)=>sH(B?.reasoningEffort)).filter((B)=>B!==null);if(!W.length)continue;let K=sH(G.defaultReasoningEffort)??W[0];Y.push({model:String(G.id),display:typeof G.displayName==="string"&&G.displayName?String(G.displayName):String(G.id),efforts:W,defaultEffort:K})}let H=z.nextCursor;if(H!==null&&typeof H!=="string")throw Error("Codex model/list 返回无效 nextCursor");if(X=H||null,X){if(V.has(X))throw Error("Codex model/list 返回重复 nextCursor");V.add(X)}}while(X);if(!Y.length)throw Error("Codex model/list 未返回可用模型");return Y}finally{await J.close()}}async function rH($,Z){return(await L4($,Z)).map((Q)=>({model:Q,display:Q,efforts:f4,defaultEffort:"max"}))}var CM=1e4,bM,f4;var y4=R(()=>{E9();z$();I();d3();F0();bM=["none","minimal","low","medium","high","xhigh","max","ultra"];f4=["max","xhigh","high","medium","low"]});import{existsSync as kM}from"node:fs";import{join as wM}from"node:path";function eH($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function $8($){if($.state!=="ok")return{state:$.state==="auth_failed"?"no_credentials":$.state==="no_credentials"?"no_credentials":$.state==="rate_limited"?"rate_limited":"network",windows:[],resetCredits:null,credits:null,...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(eH($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(eH($.weekly,"weekly","周配额"));return{state:"ok",planLabel:$.subscriptionType,windows:Z,fetchedAt:$.fetchedAt,resetCredits:$.resetCredits??null,credits:$.credits??null}}function $G($){return $===d||kM(wM(v.home($),"auth.json"))}var H7=R(()=>{k0();X0();z$();y4();I();F0();L1();N0({kind:"codex-subscription",configSectionId:"codex-sub",build:($)=>{let Z=new Map,J=(Y)=>{let V=$G(Y),X=$.model?.trim()||void 0,z=$.effort?.trim()||void 0,H={id:"codex-sub",kind:"codex-subscription",agent:"codex",display:$.display?.trim()||"Codex 订阅",spawnRevision:JSON.stringify([$.model,$.effort,v.revision(Y)]),enabled:V,models:[],modelCatalogState:{status:V?"idle":"disabled",updatedAt:Date.now()},defaultModel:X??"",async refreshModels(){if(H.enabled=$G(Y),!H.enabled){H.models=[],H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{if(H.models=await tH(Y),z)for(let G of H.models)G.defaultEffort=z;if(!X)H.defaultModel=H.models[0]?.model??"";H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){if(j(`codex-sub ${Y} refreshModels MISS: ${G?.message??G}`),H.models=[],G?.code==="CODEX_AUTH_MISSING")H.enabled=!1;H.modelCatalogState={status:H.enabled?"failed":"disabled",updatedAt:Date.now(),error:G?.message??String(G)}}},spawnEnv(G){let W=o0(G);return Object.assign(W,g.codex.env),v.env(Y,W)},resolveSpawnModel(G){return G},async readUsage(){return $8(await ZH(Y))}};return H},Q=J(d);return Q.forAccount=(Y)=>{if(Y===d)return Q;let V=v.revision(Y),X=Z.get(Y);if(X?.revision===V)return X.source;let z=r3(J(Y),$);return Z.set(Y,{revision:V,source:z}),z},Q}})});function ZG($,Z,J){if(!$.enabled||Z.modelCatalogState?.status!=="ready")return;let Q=$.modelSelection,Y=(Z.modelSelection?.availableModels??Z.models).filter((P)=>P.origin!=="custom").map((P)=>({...P,efforts:[...P.efforts]})),V=[...new Set([...s(J.custom_models),...Q?.mode==="catalog"||$.kind.startsWith("packy")?s(J.models):[]])],X=[...Y];for(let P of V)if(!X.some((L)=>L.model.toLowerCase()===P.toLowerCase())){let L=Z.modelSelection?.availableModels.find((q)=>q.model===P);X.push(L?{...L,efforts:[...L.efforts]}:{model:P,display:P,origin:"custom",...N2($,J)})}let z=new Set(s(J.hidden_models)),H=Q?.visibilityKey??((P)=>P),G=new Set(Q?.selectDefaults?.(X)??[]),W=new Set(s(J.shown_models)),K=$.kind==="openrouter"?J.model?.trim().replace(/\[1m\]$/,""):J.model?.trim(),B=J.models!==void 0?s(J.models):Q?.selectDefaults?[...new Set([...K?[K]:[],...G,...W])]:Q?.modelIds.length?Q.modelIds:Z.modelSelection?.modelIds??[],_=Q?.mode==="allowlist"?B.map((P)=>{let L=$.agent==="claude"?P.replace(/\[1m\]$/,""):P,q=X.find((D)=>D.model===L)??Z.models.find((D)=>D.model===P);return q?{...q,model:P}:{model:P,display:P,efforts:[],defaultEffort:null,unavailableReason:"账号目录缓存未返回该模型"}}).filter((P)=>P.origin==="custom"||!z.has(P.model)&&(!G.has(P.model)||W.has(P.model)||!z.has(H(P.model)))):X.filter((P)=>P.origin==="custom"||!z.has(P.model));if($.models=[..._,...X.filter((P)=>P.origin==="custom"&&!_.some((L)=>L.model===P.model))],Q)Q.availableModels=X,Q.modelIds=$.models.map((P)=>P.model);$.defaultModel=$.kind==="openrouter"?J.model?.trim()||"":J.model?.trim()||(X.some((P)=>P.model===Z.defaultModel)?Z.defaultModel:$.models[0]?.model??""),$.modelCatalogState={...Z.modelCatalogState}}function QJ($,Z,J,Q,Y,V){let X=Y&&Z8.get(Y),z=$(),H=z.kind==="codex-subscription"?`${J}:${v.revision(V??d)}`:J;if(X?.active()&&X.configuration===Q&&X.identity===H)return Y;if(X?.identity===H)ZG(z,Y,Z);let G={...z},W=!0,K=X?.identity===H?X.snapshot():void 0,B=new Map,_=(q)=>{z=q;let{refreshModels:D,readUsage:M,forAccount:U,...A}=q;Object.assign(G,A)},P=new b3(`token-source ${G.id}${V?`/${V}`:""} models`,vM,async()=>{let q=G7.get(H);if(!q){let O;try{O=$()}catch(S){throw G.modelCatalogState={status:G.modelCatalogState?.status==="ready"?"ready":"failed",updatedAt:G.modelCatalogState?.updatedAt??null,error:S instanceof Error?S.message:String(S)},S}let N=Promise.resolve().then(()=>O.refreshModels()).then(()=>({source:O}),(S)=>({source:O,error:S})).finally(()=>{if(G7.get(H)?.promise===N)G7.delete(H)});q={configuration:Q,promise:N},G7.set(H,q)}let D=await q.promise,M=D.source,U=D.error;if(q.configuration!==Q){if(M=$(),D.source.modelCatalogState?.status==="ready")ZG(M,D.source,Z);else if(M.modelCatalogState=D.source.modelCatalogState&&{...D.source.modelCatalogState},!D.source.enabled)M.enabled=!1}if(!W)return;if(U!==void 0&&!M.modelCatalogState?.error)M.modelCatalogState={status:"failed",updatedAt:Date.now(),error:U instanceof Error?U.message:String(U)};let A=M.modelCatalogState?.error;if(A&&a0(A)){if(K={state:"no_credentials",windows:[],reason:A},G.kind==="codex-subscription")d$(V??d)}if(M.modelCatalogState?.status==="failed"||U){let O=M.modelCatalogState?.error??(U instanceof Error?U.message:String(U));if(G.modelCatalogState?.status==="ready"&&!a0(O))G.modelCatalogState={...G.modelCatalogState,error:O};else _(M);throw U??Error(O)}_(M)},X?.identity===H?X.model.nextRefreshAt:0),L=new b3(`token-source ${G.id}${V?`/${V}`:""} usage`,fM,async()=>{let q;try{q=await z.readUsage()}catch(D){let M=D instanceof Error?D.message:String(D);if(W&&(K?.state!=="ok"||a0(M)))K={state:a0(M)?"no_credentials":"network",windows:[],reason:M};throw D}if(!W)return;if(K?.state!=="ok"||!["network","rate_limited"].includes(q.state)||a0(q.reason))K=q;if(q.state!=="ok"&&q.state!=="not_applicable"&&q.state!=="no_credentials")throw Object.assign(Error(q.reason??q.state),{retryAfterMs:q.retryAfterMs})},X?.identity===H?X.usage.nextRefreshAt:0);if(G.refreshModels=()=>P.refresh(),G.readUsage=async()=>!G.enabled?{state:"no_credentials",windows:[],reason:G.modelCatalogState?.error}:G.kind==="codex-subscription"?$8(F2(V)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"}):K??{state:G.enabled?"network":"no_credentials",windows:[],reason:"额度缓存尚未就绪,后台刷新中"},z.forAccount)G.forAccount=(q)=>{if(q===d)return G;let D=v.revision(q),M=B.get(q);if(M?.revision===D)return M.source;if(M)J8(M.source);let U=X?.baseIdentity===J?X.children.get(q):void 0,A=QJ(()=>$().forAccount(q),Z,J,Q,U?.revision===D?U.source:void 0,q);return B.set(q,{revision:D,source:A}),A};return Z8.set(G,{baseIdentity:J,identity:H,configuration:Q,model:P,usage:L,children:B,snapshot:()=>K,active:()=>W,dispose(){W=!1,P.dispose(),L.dispose();for(let q of B.values())J8(q.source)}}),G}function J8($){Z8.get($)?.dispose()}function JG($,Z){let J=$&&Z8.get($),Q=J?.children.get(Z);if(Q)J8(Q.source),J.children.delete(Z)}function QG($){return Z8.get($)?.usage.refresh()??Promise.resolve()}var vM=300000,fM=60000,Z8,G7;var W7=R(()=>{YZ();F0();L1();z$();H7();_1();Z8=new WeakMap,G7=new Map});function hM($){let Z=$?.action?.value??{},J=String(Z.kind??"");if(!J)return"无效操作";if(!yM.has(J))return`不支持的操作: ${J}`;let Q=J==="notify_callback"||J==="notify_reply"||J==="notify_reply_cancel";if(!Q&&!String($?.context?.open_chat_id??""))return"回调缺少 chat_id,操作未执行";if(!Q&&!String($?.context?.open_message_id??""))return"回调缺少原卡 message_id,操作未执行";if(J==="permission"&&!["allow","allow_always","deny"].includes(String(Z.decision??"")))return"无效的权限决定,操作未执行";return null}class Y8{tails=new Map;accepting=!0;tryEnqueue($,Z){if(!this.accepting)return{accepted:!1,reason:"closed"};let J=$.trim();if(!J)return{accepted:!1,reason:"invalid-key"};let Y=(this.tails.get(J)??Promise.resolve()).then(Z),V;return V=Y.then(()=>{},()=>{}).finally(()=>{if(this.tails.get(J)===V)this.tails.delete(J)}),this.tails.set(J,V),{accepted:!0,completion:Y}}enqueue($,Z){let J=this.tryEnqueue($,Z);return J.accepted?J.completion:Promise.reject(Error(`per-key actor ${J.reason}`))}close(){this.accepting=!1}isAccepting(){return this.accepting}pending(){return this.tails.values()}}function YG($){let Z=$.now??Date.now;return{accept(J){let Q=Z();return $.actor.tryEnqueue($.key(J),()=>$.execute(J,Q))}}}class VJ{completedTtlMs;now;maxCompletedEntries;inflight=new Set;completed=new Map;constructor($=30000,Z=Date.now,J=4096){this.completedTtlMs=$;this.now=Z;this.maxCompletedEntries=J}claim($){return this.claimAll([$])}claimAll($){if(this.prune(),$.some((Z)=>this.inflight.has(Z)))return"inflight";if($.some((Z)=>this.completed.has(Z)))return"completed";for(let Z of $)this.inflight.add(Z);return"started"}complete($){this.completeAll([$])}completeAll($){this.prune();let Z=this.now()+this.completedTtlMs;for(let J of $)this.inflight.delete(J),this.completed.delete(J),this.completed.set(J,Z);while(this.completed.size>this.maxCompletedEntries){let J=this.completed.keys().next().value;if(J===void 0)break;this.completed.delete(J)}}fail($){this.failAll([$])}failAll($){for(let Z of $)this.inflight.delete(Z)}prune(){let $=this.now();for(let[Z,J]of this.completed)if(J<=$)this.completed.delete(Z)}}function YJ($){if(Array.isArray($))return`[${$.map(YJ).join(",")}]`;if($===void 0)return"undefined";if(!$||typeof $!=="object")return JSON.stringify($);return`{${Object.entries($).sort(([Z],[J])=>Z.localeCompare(J)).map(([Z,J])=>`${JSON.stringify(Z)}:${YJ(J)}`).join(",")}}`}function IM($){let Z=$?.action?.value??{},J=String(Z?.kind??"unknown"),Q=String($?.context?.open_chat_id??""),Y=String($?.context?.open_message_id??""),V=null;switch(J){case"menu":V={request_id:Z.request_id};break;case"permission":V={request_id:Z.request_id};break;case"ask":V={tool_use_id:Z.tool_use_id,question_idx:Z.question_idx};break;case"worktree_disband":V={slug:Z.slug};break;case"temp_fork_select":case"temp_back_select":case"temp_resume_select":V={panel_id:Z.panel_id};break;case"tasklist_delete_prompt":case"tasklist_delete_confirm":V={guid:Z.guid};break;case"tasklist_enable":V={guid:Z.guid,project:Z.project,panel_id:Z.panel_id};break;case"token_source_enable":V={source_id:Z.source_id};break;case"agent_identity_page":V={panel_id:Z.panel_id,page:Z.page};break;case"model_page":V={panel_id:Z.panel_id,source_id:Z.source_id,page:Z.page};break;case"model_list_open":V={panel_id:Z.panel_id,source_id:Z.source_id,mode:Z.mode};break;case"model_add":case"model_remove":case"model_custom_remove":V={panel_id:Z.panel_id,source_id:Z.source_id,model:Z.model};break;case"notify_callback":V={notify_id:Z.notify_id};break;case"notify_reply":V={notify_id:Z.notify_id};break;case"notify_reply_cancel":V={notify_id:Z.notify_id,reply_id:Z.reply_id};break;case"provider_select":case"model_select":case"model_custom_prompt":case"model_panel_cancel":case"model_effort_select":V={panel_id:Z.panel_id};break;default:V=Z}return`${Q}\x00${Y}\x00${J}\x00${YJ(V)}`}function gM($){let Z=String($?.event_id??$?.header?.event_id??$?.event?.event_id??"");return{...Z?{deliveryKey:`event\x00${Z}`}:{},businessKey:`semantic\x00${IM($)}`,...["agent_identity_page","model_page","model_list_open","model_add","model_remove","model_custom_remove","notify_reply"].includes($?.action?.value?.kind)?{repeatable:!0}:{}}}function mM(){return new Promise(($)=>setTimeout($,0))}function Q8($,Z,J){if(Z.deliveryKey)$.complete(Z.deliveryKey);if(J&&!Z.repeatable)$.complete(Z.businessKey);else $.fail(Z.businessKey)}function VG($){let Z=$.afterAck??mM,J=(Y)=>{try{$.onBackgroundError?.(Y)}catch{}},Q=async(Y)=>{try{await Y()}catch(V){J(V)}};return{accept(Y){if(!$.actor.isAccepting())return $.responses.closed(Y);let V=hM(Y);if(V)return $.responses.invalid(Y,V);let X=gM(Y),z=X.deliveryKey?[X.deliveryKey,X.businessKey]:[X.businessKey],H=$.deduper.claimAll(z);if(H==="inflight")return $.responses.inflight(Y);if(H==="completed")return $.responses.completed(Y);let G=$.actor.tryEnqueue($.scope(Y),async()=>{try{await Z()}catch(B){$.deduper.failAll(z),J(B);return}let W;try{W=await $.execute(Y)}catch(B){Q8($.deduper,X,!0),await Q(()=>$.presentExecutionFailure(Y,B));return}await Q(async()=>{try{await $.present(Y,W)}catch(B){await $.presentPresentationFailure(Y,B)}});let K;try{K=$.completion(Y,W)}catch(B){Q8($.deduper,X,!1),J(B);return}if(K){let B=K.then((_)=>{Q8($.deduper,X,_==="complete")},(_)=>{Q8($.deduper,X,!1),J(_)});$.track(B);return}Q8($.deduper,X,$.businessSucceeded(Y,W))});if(!G.accepted)return $.deduper.failAll(z),$.responses.closed(Y);return $.track(G.completion),G.completion.catch(J),$.responses.accepted(Y)}}}var yM;var XJ=R(()=>{yM=new Set(["permission","menu","provider_select","model_select","model_custom_prompt","model_panel_cancel","model_effort_select","ask","worktree_disband","temp_fork_select","temp_back_select","temp_resume_select","tasklist_enable","tasklist_delete_prompt","tasklist_delete_confirm","token_source_enable","agent_identity_page","model_page","notify_callback","notify_reply","notify_reply_cancel","model_list_open","model_add","model_remove","model_custom_remove"])});import{AsyncLocalStorage as pM}from"node:async_hooks";class XG{actor=new Y8;context=new pM;run($,Z){let J=this.context.getStore();if(J?.active&&J.chatId===$)return Z();return this.actor.enqueue($,async()=>{let Q={chatId:$,active:!0};try{return await this.context.run(Q,Z)}finally{Q.active=!1}})}}function f$($,Z){return cM.run($,Z)}var cM;var zJ=R(()=>{XJ();cM=new XG});import{execFileSync as uM}from"node:child_process";import{existsSync as g1,readdirSync as lM,readFileSync as dM,realpathSync as B7,statSync as iM}from"node:fs";import{dirname as nM,join as HG,resolve as aM}from"node:path";async function j7($,Z){let J=B7($),Q=process.platform==="win32"?J.toLowerCase():J,Y=K7.get(Q)??Promise.resolve(),V,X=new Promise((H)=>{V=H}),z=Y.catch(()=>{}).then(()=>X);K7.set(Q,z),await Y.catch(()=>{});try{return await Z()}finally{if(V(),K7.get(Q)===z)K7.delete(Q)}}function x2($){let Z=$.trim();if(!oM.test(Z))return null;return Z}function _7($){return $.match(/^(.+)\[[^\[\]]+\]$/)?.[1]??$}function I4($,Z){return`${$}[${Z}]`}function GG($){return`${h4}${$}`}function g4($,Z,J){return HG(nM($),I4(Z,J))}function WG($,Z,J){let Q=sM($,Z,J);if(!Q)return null;let Y=dM(Q.path,"utf8").trim();if(!Y)return null;return{path:Q.path,content:Y,slug:Q.slug}}function KG($,Z){GJ($);let J=I0($,["for-each-ref","--format=%(refname:short)",`refs/heads/${h4}`]).split(`
131
+ `)}:{}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,checkpoint:!this.lastResult.is_error&&this.lastAssistantUuid&&this.sessionId?{provider:"claude",kind:"assistant-message",id:this.lastAssistantUuid,source:{provider:"claude",sessionId:this.sessionId,cwd:this.opts.workDir}}:null})}confirmSteeringInputs($){if($.parent_tool_use_id)return;let Z=Array.isArray($.user_message_uuids)?$.user_message_uuids:[];for(let J of[...Z,$.user_message_uuid])if(typeof J==="string"&&this.steeringInputs.delete(J)&&$.type!=="result")this.inputTurnPending=!0}failTurnStart($){this.turnActive=!1,this.inputTurnPending=!1,this.lastAssistantUuid=null,this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:this.lastUsage,subtype:"claude_turn_start_failed",is_error:!0},this.emit("result",{subtype:this.lastResult.subtype,is_error:!0,duration_ms:null,usage:this.lastUsage,error:$.message})}}});import{homedir as SM}from"node:os";function xM($,Z=CM){return new Promise((J,Q)=>{let Y=setTimeout(()=>Q(Error(`timeout ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Y),J(V)},(V)=>{clearTimeout(Y),Q(V)})})}function sH($){return typeof $==="string"&&bM.includes($)?$:null}async function z7($={}){let{ClaudeAgentProcess:Z}=await Promise.resolve().then(() => (v4(),JJ)),J=new Z({workDir:SM(),effort:"high",settingSources:["user"],profile:{loadProjectMcp:!1},...$});J.on("error",(Q)=>j(`Claude model catalog MISS: ${Q.message}`));try{let Q=await xM(J.listModels());if(!Q.length)throw Error("Claude SDK model catalog is empty");return Q.map((Y)=>({model:Y.model.replace(/^claude:/,""),display:Y.displayName,efforts:Y.supportedReasoningEfforts.map((V)=>V.reasoningEffort),defaultEffort:Y.defaultReasoningEffort}))}finally{await J.kill()}}async function tH($="default"){let Z=v.revision($),J=new w$({accountId:$});try{await J.initialize("lodestar-models");let Q=await i$(()=>J.request("account/read",{refreshToken:!1}),"账号查询");if(l3($,Q?.account,Z),Q?.account?.type!=="chatgpt")throw Object.assign(Error("Codex 订阅未登录;发送 codex-login 或 codex-login 备注完成授权"),{code:"CODEX_AUTH_MISSING"});let Y=[],V=new Set,X=null;do{let z=await i$(()=>J.request("model/list",{cursor:X,limit:100,includeHidden:!1}),"模型查询");if(!Array.isArray(z?.data))throw Error("Codex model/list 缺少 data 数组");for(let G of z.data){if(!G||G.hidden||!G.id)continue;let W=(Array.isArray(G.supportedReasoningEfforts)?G.supportedReasoningEfforts:[]).map((B)=>sH(B?.reasoningEffort)).filter((B)=>B!==null);if(!W.length)continue;let K=sH(G.defaultReasoningEffort)??W[0];Y.push({model:String(G.id),display:typeof G.displayName==="string"&&G.displayName?String(G.displayName):String(G.id),efforts:W,defaultEffort:K})}let H=z.nextCursor;if(H!==null&&typeof H!=="string")throw Error("Codex model/list 返回无效 nextCursor");if(X=H||null,X){if(V.has(X))throw Error("Codex model/list 返回重复 nextCursor");V.add(X)}}while(X);if(!Y.length)throw Error("Codex model/list 未返回可用模型");return Y}finally{await J.close()}}async function rH($,Z){return(await L4($,Z)).map((Q)=>({model:Q,display:Q,efforts:y4,defaultEffort:"max"}))}var CM=1e4,bM,y4;var f4=R(()=>{E9();z$();I();d3();D0();bM=["none","minimal","low","medium","high","xhigh","max","ultra"];y4=["max","xhigh","high","medium","low"]});import{existsSync as kM}from"node:fs";import{join as wM}from"node:path";function eH($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function $8($){if($.state!=="ok")return{state:$.state==="auth_failed"?"no_credentials":$.state==="no_credentials"?"no_credentials":$.state==="rate_limited"?"rate_limited":"network",windows:[],resetCredits:null,credits:null,...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(eH($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(eH($.weekly,"weekly","周配额"));return{state:"ok",planLabel:$.subscriptionType,windows:Z,fetchedAt:$.fetchedAt,resetCredits:$.resetCredits??null,credits:$.credits??null}}function $G($){return $===d||kM(wM(v.home($),"auth.json"))}var H7=R(()=>{k0();X0();z$();f4();I();D0();L1();N0({kind:"codex-subscription",configSectionId:"codex-sub",build:($)=>{let Z=new Map,J=(Y)=>{let V=$G(Y),X=$.model?.trim()||void 0,z=$.effort?.trim()||void 0,H={id:"codex-sub",kind:"codex-subscription",agent:"codex",display:$.display?.trim()||"Codex 订阅",spawnRevision:JSON.stringify([$.model,$.effort,v.revision(Y)]),enabled:V,models:[],modelCatalogState:{status:V?"idle":"disabled",updatedAt:Date.now()},defaultModel:X??"",async refreshModels(){if(H.enabled=$G(Y),!H.enabled){H.models=[],H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{if(H.models=await tH(Y),z)for(let G of H.models)G.defaultEffort=z;if(!X)H.defaultModel=H.models[0]?.model??"";H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){if(j(`codex-sub ${Y} refreshModels MISS: ${G?.message??G}`),H.models=[],G?.code==="CODEX_AUTH_MISSING")H.enabled=!1;H.modelCatalogState={status:H.enabled?"failed":"disabled",updatedAt:Date.now(),error:G?.message??String(G)}}},spawnEnv(G){let W=o0(G);return Object.assign(W,g.codex.env),v.env(Y,W)},resolveSpawnModel(G){return G},async readUsage(){return $8(await ZH(Y))}};return H},Q=J(d);return Q.forAccount=(Y)=>{if(Y===d)return Q;let V=v.revision(Y),X=Z.get(Y);if(X?.revision===V)return X.source;let z=r3(J(Y),$);return Z.set(Y,{revision:V,source:z}),z},Q}})});function ZG($,Z,J){if(!$.enabled||Z.modelCatalogState?.status!=="ready")return;let Q=$.modelSelection,Y=(Z.modelSelection?.availableModels??Z.models).filter((P)=>P.origin!=="custom").map((P)=>({...P,efforts:[...P.efforts]})),V=[...new Set([...s(J.custom_models),...Q?.mode==="catalog"||$.kind.startsWith("packy")?s(J.models):[]])],X=[...Y];for(let P of V)if(!X.some((L)=>L.model.toLowerCase()===P.toLowerCase())){let L=Z.modelSelection?.availableModels.find((q)=>q.model===P);X.push(L?{...L,efforts:[...L.efforts]}:{model:P,display:P,origin:"custom",...N2($,J)})}let z=new Set(s(J.hidden_models)),H=Q?.visibilityKey??((P)=>P),G=new Set(Q?.selectDefaults?.(X)??[]),W=new Set(s(J.shown_models)),K=$.kind==="openrouter"?J.model?.trim().replace(/\[1m\]$/,""):J.model?.trim(),B=J.models!==void 0?s(J.models):Q?.selectDefaults?[...new Set([...K?[K]:[],...G,...W])]:Q?.modelIds.length?Q.modelIds:Z.modelSelection?.modelIds??[],_=Q?.mode==="allowlist"?B.map((P)=>{let L=$.agent==="claude"?P.replace(/\[1m\]$/,""):P,q=X.find((F)=>F.model===L)??Z.models.find((F)=>F.model===P);return q?{...q,model:P}:{model:P,display:P,efforts:[],defaultEffort:null,unavailableReason:"账号目录缓存未返回该模型"}}).filter((P)=>P.origin==="custom"||!z.has(P.model)&&(!G.has(P.model)||W.has(P.model)||!z.has(H(P.model)))):X.filter((P)=>P.origin==="custom"||!z.has(P.model));if($.models=[..._,...X.filter((P)=>P.origin==="custom"&&!_.some((L)=>L.model===P.model))],Q)Q.availableModels=X,Q.modelIds=$.models.map((P)=>P.model);$.defaultModel=$.kind==="openrouter"?J.model?.trim()||"":J.model?.trim()||(X.some((P)=>P.model===Z.defaultModel)?Z.defaultModel:$.models[0]?.model??""),$.modelCatalogState={...Z.modelCatalogState}}function QJ($,Z,J,Q,Y,V){let X=Y&&Z8.get(Y),z=$(),H=z.kind==="codex-subscription"?`${J}:${v.revision(V??d)}`:J;if(X?.active()&&X.configuration===Q&&X.identity===H)return Y;if(X?.identity===H)ZG(z,Y,Z);let G={...z},W=!0,K=X?.identity===H?X.snapshot():void 0,B=new Map,_=(q)=>{z=q;let{refreshModels:F,readUsage:M,forAccount:U,...A}=q;Object.assign(G,A)},P=new b3(`token-source ${G.id}${V?`/${V}`:""} models`,vM,async()=>{let q=G7.get(H);if(!q){let O;try{O=$()}catch(S){throw G.modelCatalogState={status:G.modelCatalogState?.status==="ready"?"ready":"failed",updatedAt:G.modelCatalogState?.updatedAt??null,error:S instanceof Error?S.message:String(S)},S}let N=Promise.resolve().then(()=>O.refreshModels()).then(()=>({source:O}),(S)=>({source:O,error:S})).finally(()=>{if(G7.get(H)?.promise===N)G7.delete(H)});q={configuration:Q,promise:N},G7.set(H,q)}let F=await q.promise,M=F.source,U=F.error;if(q.configuration!==Q){if(M=$(),F.source.modelCatalogState?.status==="ready")ZG(M,F.source,Z);else if(M.modelCatalogState=F.source.modelCatalogState&&{...F.source.modelCatalogState},!F.source.enabled)M.enabled=!1}if(!W)return;if(U!==void 0&&!M.modelCatalogState?.error)M.modelCatalogState={status:"failed",updatedAt:Date.now(),error:U instanceof Error?U.message:String(U)};let A=M.modelCatalogState?.error;if(A&&a0(A)){if(K={state:"no_credentials",windows:[],reason:A},G.kind==="codex-subscription")d$(V??d)}if(M.modelCatalogState?.status==="failed"||U){let O=M.modelCatalogState?.error??(U instanceof Error?U.message:String(U));if(G.modelCatalogState?.status==="ready"&&!a0(O))G.modelCatalogState={...G.modelCatalogState,error:O};else _(M);throw U??Error(O)}_(M)},X?.identity===H?X.model.nextRefreshAt:0),L=new b3(`token-source ${G.id}${V?`/${V}`:""} usage`,yM,async()=>{let q;try{q=await z.readUsage()}catch(F){let M=F instanceof Error?F.message:String(F);if(W&&(K?.state!=="ok"||a0(M)))K={state:a0(M)?"no_credentials":"network",windows:[],reason:M};throw F}if(!W)return;if(K?.state!=="ok"||!["network","rate_limited"].includes(q.state)||a0(q.reason))K=q;if(q.state!=="ok"&&q.state!=="not_applicable"&&q.state!=="no_credentials")throw Object.assign(Error(q.reason??q.state),{retryAfterMs:q.retryAfterMs})},X?.identity===H?X.usage.nextRefreshAt:0);if(G.refreshModels=()=>P.refresh(),G.readUsage=async()=>!G.enabled?{state:"no_credentials",windows:[],reason:G.modelCatalogState?.error}:G.kind==="codex-subscription"?$8(D2(V)??{state:"network",reason:"额度缓存尚未就绪,后台刷新中"}):K??{state:G.enabled?"network":"no_credentials",windows:[],reason:"额度缓存尚未就绪,后台刷新中"},z.forAccount)G.forAccount=(q)=>{if(q===d)return G;let F=v.revision(q),M=B.get(q);if(M?.revision===F)return M.source;if(M)J8(M.source);let U=X?.baseIdentity===J?X.children.get(q):void 0,A=QJ(()=>$().forAccount(q),Z,J,Q,U?.revision===F?U.source:void 0,q);return B.set(q,{revision:F,source:A}),A};return Z8.set(G,{baseIdentity:J,identity:H,configuration:Q,model:P,usage:L,children:B,snapshot:()=>K,active:()=>W,dispose(){W=!1,P.dispose(),L.dispose();for(let q of B.values())J8(q.source)}}),G}function J8($){Z8.get($)?.dispose()}function JG($,Z){let J=$&&Z8.get($),Q=J?.children.get(Z);if(Q)J8(Q.source),J.children.delete(Z)}function QG($){return Z8.get($)?.usage.refresh()??Promise.resolve()}var vM=300000,yM=60000,Z8,G7;var W7=R(()=>{YZ();D0();L1();z$();H7();_1();Z8=new WeakMap,G7=new Map});function hM($){let Z=$?.action?.value??{},J=String(Z.kind??"");if(!J)return"无效操作";if(!fM.has(J))return`不支持的操作: ${J}`;let Q=J==="notify_callback"||J==="notify_reply"||J==="notify_reply_cancel";if(!Q&&!String($?.context?.open_chat_id??""))return"回调缺少 chat_id,操作未执行";if(!Q&&!String($?.context?.open_message_id??""))return"回调缺少原卡 message_id,操作未执行";if(J==="permission"&&!["allow","allow_always","deny"].includes(String(Z.decision??"")))return"无效的权限决定,操作未执行";return null}class Y8{tails=new Map;accepting=!0;tryEnqueue($,Z){if(!this.accepting)return{accepted:!1,reason:"closed"};let J=$.trim();if(!J)return{accepted:!1,reason:"invalid-key"};let Y=(this.tails.get(J)??Promise.resolve()).then(Z),V;return V=Y.then(()=>{},()=>{}).finally(()=>{if(this.tails.get(J)===V)this.tails.delete(J)}),this.tails.set(J,V),{accepted:!0,completion:Y}}enqueue($,Z){let J=this.tryEnqueue($,Z);return J.accepted?J.completion:Promise.reject(Error(`per-key actor ${J.reason}`))}close(){this.accepting=!1}isAccepting(){return this.accepting}pending(){return this.tails.values()}}function YG($){let Z=$.now??Date.now;return{accept(J){let Q=Z();return $.actor.tryEnqueue($.key(J),()=>$.execute(J,Q))}}}class VJ{completedTtlMs;now;maxCompletedEntries;inflight=new Set;completed=new Map;constructor($=30000,Z=Date.now,J=4096){this.completedTtlMs=$;this.now=Z;this.maxCompletedEntries=J}claim($){return this.claimAll([$])}claimAll($){if(this.prune(),$.some((Z)=>this.inflight.has(Z)))return"inflight";if($.some((Z)=>this.completed.has(Z)))return"completed";for(let Z of $)this.inflight.add(Z);return"started"}complete($){this.completeAll([$])}completeAll($){this.prune();let Z=this.now()+this.completedTtlMs;for(let J of $)this.inflight.delete(J),this.completed.delete(J),this.completed.set(J,Z);while(this.completed.size>this.maxCompletedEntries){let J=this.completed.keys().next().value;if(J===void 0)break;this.completed.delete(J)}}fail($){this.failAll([$])}failAll($){for(let Z of $)this.inflight.delete(Z)}prune(){let $=this.now();for(let[Z,J]of this.completed)if(J<=$)this.completed.delete(Z)}}function YJ($){if(Array.isArray($))return`[${$.map(YJ).join(",")}]`;if($===void 0)return"undefined";if(!$||typeof $!=="object")return JSON.stringify($);return`{${Object.entries($).sort(([Z],[J])=>Z.localeCompare(J)).map(([Z,J])=>`${JSON.stringify(Z)}:${YJ(J)}`).join(",")}}`}function IM($){let Z=$?.action?.value??{},J=String(Z?.kind??"unknown"),Q=String($?.context?.open_chat_id??""),Y=String($?.context?.open_message_id??""),V=null;switch(J){case"menu":V={request_id:Z.request_id};break;case"permission":V={request_id:Z.request_id};break;case"ask":V={tool_use_id:Z.tool_use_id,question_idx:Z.question_idx};break;case"worktree_disband":V={slug:Z.slug};break;case"temp_fork_select":case"temp_back_select":case"temp_resume_select":V={panel_id:Z.panel_id};break;case"tasklist_delete_prompt":case"tasklist_delete_confirm":V={guid:Z.guid};break;case"tasklist_enable":V={guid:Z.guid,project:Z.project,panel_id:Z.panel_id};break;case"token_source_enable":V={source_id:Z.source_id};break;case"agent_identity_page":V={panel_id:Z.panel_id,page:Z.page};break;case"model_page":V={panel_id:Z.panel_id,source_id:Z.source_id,page:Z.page};break;case"model_list_open":V={panel_id:Z.panel_id,source_id:Z.source_id,mode:Z.mode};break;case"model_add":case"model_remove":case"model_custom_remove":V={panel_id:Z.panel_id,source_id:Z.source_id,model:Z.model};break;case"notify_callback":V={notify_id:Z.notify_id};break;case"notify_reply":V={notify_id:Z.notify_id};break;case"notify_reply_cancel":V={notify_id:Z.notify_id,reply_id:Z.reply_id};break;case"provider_select":case"model_select":case"model_custom_prompt":case"model_panel_cancel":case"model_effort_select":V={panel_id:Z.panel_id};break;default:V=Z}return`${Q}\x00${Y}\x00${J}\x00${YJ(V)}`}function gM($){let Z=String($?.event_id??$?.header?.event_id??$?.event?.event_id??"");return{...Z?{deliveryKey:`event\x00${Z}`}:{},businessKey:`semantic\x00${IM($)}`,...["agent_identity_page","model_page","model_list_open","model_add","model_remove","model_custom_remove","notify_reply"].includes($?.action?.value?.kind)?{repeatable:!0}:{}}}function mM(){return new Promise(($)=>setTimeout($,0))}function Q8($,Z,J){if(Z.deliveryKey)$.complete(Z.deliveryKey);if(J&&!Z.repeatable)$.complete(Z.businessKey);else $.fail(Z.businessKey)}function VG($){let Z=$.afterAck??mM,J=(Y)=>{try{$.onBackgroundError?.(Y)}catch{}},Q=async(Y)=>{try{await Y()}catch(V){J(V)}};return{accept(Y){if(!$.actor.isAccepting())return $.responses.closed(Y);let V=hM(Y);if(V)return $.responses.invalid(Y,V);let X=gM(Y),z=X.deliveryKey?[X.deliveryKey,X.businessKey]:[X.businessKey],H=$.deduper.claimAll(z);if(H==="inflight")return $.responses.inflight(Y);if(H==="completed")return $.responses.completed(Y);let G=$.actor.tryEnqueue($.scope(Y),async()=>{try{await Z()}catch(B){$.deduper.failAll(z),J(B);return}let W;try{W=await $.execute(Y)}catch(B){Q8($.deduper,X,!0),await Q(()=>$.presentExecutionFailure(Y,B));return}await Q(async()=>{try{await $.present(Y,W)}catch(B){await $.presentPresentationFailure(Y,B)}});let K;try{K=$.completion(Y,W)}catch(B){Q8($.deduper,X,!1),J(B);return}if(K){let B=K.then((_)=>{Q8($.deduper,X,_==="complete")},(_)=>{Q8($.deduper,X,!1),J(_)});$.track(B);return}Q8($.deduper,X,$.businessSucceeded(Y,W))});if(!G.accepted)return $.deduper.failAll(z),$.responses.closed(Y);return $.track(G.completion),G.completion.catch(J),$.responses.accepted(Y)}}}var fM;var XJ=R(()=>{fM=new Set(["permission","menu","provider_select","model_select","model_custom_prompt","model_panel_cancel","model_effort_select","ask","worktree_disband","temp_fork_select","temp_back_select","temp_resume_select","tasklist_enable","tasklist_delete_prompt","tasklist_delete_confirm","token_source_enable","agent_identity_page","model_page","notify_callback","notify_reply","notify_reply_cancel","model_list_open","model_add","model_remove","model_custom_remove"])});import{AsyncLocalStorage as pM}from"node:async_hooks";class XG{actor=new Y8;context=new pM;run($,Z){let J=this.context.getStore();if(J?.active&&J.chatId===$)return Z();return this.actor.enqueue($,async()=>{let Q={chatId:$,active:!0};try{return await this.context.run(Q,Z)}finally{Q.active=!1}})}}function y$($,Z){return cM.run($,Z)}var cM;var zJ=R(()=>{XJ();cM=new XG});import{execFileSync as uM}from"node:child_process";import{existsSync as g1,readdirSync as lM,readFileSync as dM,realpathSync as B7,statSync as iM}from"node:fs";import{dirname as nM,join as HG,resolve as aM}from"node:path";async function j7($,Z){let J=B7($),Q=process.platform==="win32"?J.toLowerCase():J,Y=K7.get(Q)??Promise.resolve(),V,X=new Promise((H)=>{V=H}),z=Y.catch(()=>{}).then(()=>X);K7.set(Q,z),await Y.catch(()=>{});try{return await Z()}finally{if(V(),K7.get(Q)===z)K7.delete(Q)}}function x2($){let Z=$.trim();if(!oM.test(Z))return null;return Z}function _7($){return $.match(/^(.+)\[[^\[\]]+\]$/)?.[1]??$}function I4($,Z){return`${$}[${Z}]`}function GG($){return`${h4}${$}`}function g4($,Z,J){return HG(nM($),I4(Z,J))}function WG($,Z,J){let Q=sM($,Z,J);if(!Q)return null;let Y=dM(Q.path,"utf8").trim();if(!Y)return null;return{path:Q.path,content:Y,slug:Q.slug}}function KG($,Z){GJ($);let J=I0($,["for-each-ref","--format=%(refname:short)",`refs/heads/${h4}`]).split(`
132
132
  `).map((V)=>V.trim()).filter(Boolean).filter((V)=>V.startsWith(h4)),Q=WJ($),Y=[];for(let V of J){let X=V.slice(h4.length);if(!x2(X))continue;let z=I4(Z,X),H=g4($,Z,X),G=Q.get(V)??null,W=!!G&&g1(G),K=PG($,V,W),B={slug:X,chatName:z,branch:V,state:K,expectedPath:H,worktreePath:W?G:null,mounted:W,dirtyCount:null,statusLine:null,error:null};if(G&&g1(G))try{let P=I0(G,["status","--porcelain=v1","--branch"]).split(`
133
133
  `).filter(Boolean);B.statusLine=P[0]?.startsWith("## ")?P[0].slice(3):null,B.dirtyCount=P.filter((L)=>!L.startsWith("## ")).length}catch(_){B.error=BJ(_)}Y.push(B)}return Y.sort((V,X)=>V.slug.localeCompare(X.slug))}function BG($,Z,J){let Q=x2(J);if(!Q)throw Error(`invalid worktree name "${J}"`);GJ($);let Y=GG(Q),V=I4(Z,Q),X=g4($,Z,Q),z=$U($,Y),H=WJ($).get(Y)??null,G=z&&!H&&PG($,Y,!1)==="merged"?I0($,["rev-parse","HEAD"]).trim():null;if(H){if(!KJ(H,X))throw Error(`branch ${Y} is already mounted at ${H}`);return _G(X,Y),{slug:Q,chatName:V,branch:Y,worktreePath:X,createdBranch:!1,createdWorktree:!1}}if(g1(X)){if(!iM(X).isDirectory())throw Error(`${X} exists but is not a directory`);if(!z)throw Error(`${X} already exists while branch ${Y} does not`)}if(z){if(I0($,["worktree","add",X,Y]),G)I0(X,["rebase",G]);return{slug:Q,chatName:V,branch:Y,worktreePath:X,createdBranch:!1,createdWorktree:!0}}return I0($,["worktree","add","-b",Y,X,"HEAD"]),{slug:Q,chatName:V,branch:Y,worktreePath:X,createdBranch:!0,createdWorktree:!0}}function jG($,Z,J){let Q=HJ($,Z,J);if(!g1(Q.worktreePath))return Q;return I0($,["worktree","remove",Q.worktreePath]),{...Q,removedWorktree:!0}}function HJ($,Z,J){let Q=x2(J);if(!Q)throw Error(`invalid worktree name "${J}"`);GJ($);let Y=GG(Q),V=I4(Z,Q),X=g4($,Z,Q),z=WJ($).get(Y)??null;if(z&&!KJ(z,X))throw Error(`branch ${Y} is already mounted at ${z}, outside managed path ${X}`);let H=z??X;if(!g1(H))return{slug:Q,chatName:V,branch:Y,worktreePath:H,removedWorktree:!1};if(!z)throw Error(`${H} is not a registered worktree of ${$}`);_G(H,Y);let G=I0(H,["status","--porcelain=v1"]).split(`
134
134
  `).filter(Boolean);if(G.length>0){let W=G.slice(0,8).join(`
135
135
  `);throw Error(`worktree has uncommitted changes:
136
- ${W}`)}return{slug:Q,chatName:V,branch:Y,worktreePath:H,removedWorktree:!1}}function GJ($){if(!g1($))throw Error(`project directory does not exist: ${$}`);let Z=I0($,["rev-parse","--show-toplevel"]).trim();if(B7(Z)!==B7($))throw Error(`${$} is not the git repository root (${Z})`)}function _G($,Z){let J=I0($,["rev-parse","--abbrev-ref","HEAD"]).trim();if(J!==Z)throw Error(`${$} is on ${J}, expected ${Z}`)}function sM($,Z,J){let Q=tM($);if(!Q?.startsWith(h4))return null;let Y=Q.slice(h4.length);if(!x2(Y))throw Error(`invalid worktree branch "${Q}"`);let V=g4(Z,J,Y);if(!KJ($,V))return null;let X=eM($,rM(Y));return X?{path:X,slug:Y}:null}function tM($){if(!g1($))return null;try{return I0($,["branch","--show-current"]).trim()||null}catch(Z){if(ZU(Z))return null;throw Z}}function rM($){return $.split("-",1)[0]??$}function eM($,Z){let J=`agents.${Z}.md`.toLowerCase(),Q=lM($).filter((Y)=>Y.toLowerCase()===J).sort();if(Q.length>1)throw Error(`multiple worktree instruction files match ${J}: ${Q.join(", ")}`);return Q[0]?HG($,Q[0]):null}function $U($,Z){try{return I0($,["show-ref","--verify","--quiet",`refs/heads/${Z}`]),!0}catch{return!1}}function PG($,Z,J){let Q=I0($,["rev-parse",Z]).trim(),Y=I0($,["rev-parse","HEAD"]).trim();if(Q===Y)return J?"active":"merged";if(zG($,Z,"HEAD"))return"merged";if(zG($,"HEAD",Z))return"active";return"stale"}function zG($,Z,J){try{return I0($,["merge-base","--is-ancestor",Z,J]),!0}catch{return!1}}function WJ($){let Z=new Map,J=I0($,["worktree","list","--porcelain","-z"]),Q="";for(let Y of J.split("\x00")){if(!Y)Q="";if(Y.startsWith("worktree ")){Q=Y.slice(9);continue}if(Y.startsWith("branch refs/heads/")&&Q)Z.set(Y.slice(18),Q)}return Z}function KJ($,Z){let J=(Q)=>{let Y=g1(Q)?B7(Q):aM(Q);return process.platform==="win32"?Y.toLowerCase():Y};return J($)===J(Z)}function I0($,Z){try{return uM("git",Z,{cwd:$,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}catch(J){throw Error(BJ(J))}}function BJ($){if($&&typeof $==="object"){let Z=$,J=Z.stderr?String(Z.stderr).trim():"";if(J)return J;if(Z.message)return Z.message}return String($)}function ZU($){return/not a git repository/i.test(BJ($))}var h4="work/",oM,K7;var jJ=R(()=>{oM=/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/,K7=new Map});import{lstatSync as QU,realpathSync as YU,statSync as VU}from"node:fs";import{basename as XU,dirname as LG,isAbsolute as zU,join as qG,resolve as HU}from"node:path";function _J($){return $.replace(/\*[0-9]{4}-[0-9]{4}(?:-[0-9]+)?$/,"")}function PJ($,Z,J){let Q=_J($),Y=_7(Q),V=J[Y]?.cwd?.trim()||qG(Z,Y);if(Q===Y)return V;return g4(V,Y,Q.slice(Y.length+1,-1))}function H$($){if(!zU($))throw Error(`工作目录必须是绝对路径: ${$}`);let Z=DG(HU($));return process.platform==="win32"?Z.toLowerCase():Z}function DG($){try{let Z=YU($);if(!VU(Z).isDirectory())throw Error(`工作目录不是文件夹: ${$}`);return Z}catch(Z){if(Z?.code!=="ENOENT"||LG($)===$)throw Z;try{if(QU($).isSymbolicLink())throw Z}catch(J){if(J===Z||J?.code!=="ENOENT")throw J}return qG(DG(LG($)),XU($))}}function FG($,Z,J){let Q=H$($),Y,V=new Map;for(let[X,z]of Object.entries(J)){if(H$(PJ(X,Z,J))!==Q)continue;Y??={cwd:$};for(let H of["settingSources","strictMcp","tools","loadProjectMcp"]){let G=z[H];if(G===void 0)continue;if(Y[H]!==void 0&&Y[H]!==G)throw Error(`同一工作目录的项目配置冲突: ${V.get(H)} / ${X}, ${H} (${$})`);Object.assign(Y,{[H]:G}),V.set(H,X)}}return Y}var m4=R(()=>{jJ()});function GU($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LJ($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Q=0;while(Q<$.length){J.lastIndex=Q;let z=J.exec($);if(!z)break;let H=z[1],G=new RegExp(`^(?: {0,3})${GU(H[0])}{${H.length},}[ \\t]*(?:\\n|$)`,"gm");G.lastIndex=z.index+z[0].length;let W=G.exec($),K=W?W.index+W[0].length:$.length;Z.push({start:z.index,end:K}),Q=K}let Y=[...Z],V=[],X=0;for(let z of Z){if(X<z.start)V.push({start:X,end:z.start});X=z.end}if(X<$.length)V.push({start:X,end:$.length});for(let z of V){let H=$.slice(z.start,z.end),G=/(`+)[^\n]*?\1/g,W;while((W=G.exec(H))!==null)Y.push({start:z.start+W.index,end:z.start+W.index+W[0].length})}return Y.sort((z,H)=>z.start-H.start)}function qJ($,Z){if(!$)return $;let J=LJ($);if(!J.length)return Z($);let Q="",Y=0;for(let V of J){if(V.start>Y)Q+=Z($.slice(Y,V.start));Q+=$.slice(V.start,V.end),Y=Math.max(Y,V.end)}if(Y<$.length)Q+=Z($.slice(Y));return Q}function WU($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function MG($){return $.replace(/!\[([^\]]*)\]\(([^)]*)\)/g,(J,Q,Y)=>{let V=Y.trim();return Q.trim()?`\uD83D\uDDBC️ ${Q.trim()} (${V})`:`\uD83D\uDDBC️ ${V}`}).replace(/!\[/g,"\uD83D\uDDBC️ [")}function m1($){if(Array.isArray($))return $.map((Q)=>m1(Q));if($==null||typeof $!=="object")return $;let Z=$,J={};for(let[Q,Y]of Object.entries(Z))J[Q]=m1(Y);if(Z.tag==="markdown"&&typeof Z.content==="string")J.content=DJ(Z.content);return J}function G0($){return qJ($,(Z)=>KU(MG(WU(Z))))}function KU($){return $.replace(/\\\[([\s\S]*?)\\\]/g,(Z,J)=>`
136
+ ${W}`)}return{slug:Q,chatName:V,branch:Y,worktreePath:H,removedWorktree:!1}}function GJ($){if(!g1($))throw Error(`project directory does not exist: ${$}`);let Z=I0($,["rev-parse","--show-toplevel"]).trim();if(B7(Z)!==B7($))throw Error(`${$} is not the git repository root (${Z})`)}function _G($,Z){let J=I0($,["rev-parse","--abbrev-ref","HEAD"]).trim();if(J!==Z)throw Error(`${$} is on ${J}, expected ${Z}`)}function sM($,Z,J){let Q=tM($);if(!Q?.startsWith(h4))return null;let Y=Q.slice(h4.length);if(!x2(Y))throw Error(`invalid worktree branch "${Q}"`);let V=g4(Z,J,Y);if(!KJ($,V))return null;let X=eM($,rM(Y));return X?{path:X,slug:Y}:null}function tM($){if(!g1($))return null;try{return I0($,["branch","--show-current"]).trim()||null}catch(Z){if(ZU(Z))return null;throw Z}}function rM($){return $.split("-",1)[0]??$}function eM($,Z){let J=`agents.${Z}.md`.toLowerCase(),Q=lM($).filter((Y)=>Y.toLowerCase()===J).sort();if(Q.length>1)throw Error(`multiple worktree instruction files match ${J}: ${Q.join(", ")}`);return Q[0]?HG($,Q[0]):null}function $U($,Z){try{return I0($,["show-ref","--verify","--quiet",`refs/heads/${Z}`]),!0}catch{return!1}}function PG($,Z,J){let Q=I0($,["rev-parse",Z]).trim(),Y=I0($,["rev-parse","HEAD"]).trim();if(Q===Y)return J?"active":"merged";if(zG($,Z,"HEAD"))return"merged";if(zG($,"HEAD",Z))return"active";return"stale"}function zG($,Z,J){try{return I0($,["merge-base","--is-ancestor",Z,J]),!0}catch{return!1}}function WJ($){let Z=new Map,J=I0($,["worktree","list","--porcelain","-z"]),Q="";for(let Y of J.split("\x00")){if(!Y)Q="";if(Y.startsWith("worktree ")){Q=Y.slice(9);continue}if(Y.startsWith("branch refs/heads/")&&Q)Z.set(Y.slice(18),Q)}return Z}function KJ($,Z){let J=(Q)=>{let Y=g1(Q)?B7(Q):aM(Q);return process.platform==="win32"?Y.toLowerCase():Y};return J($)===J(Z)}function I0($,Z){try{return uM("git",Z,{cwd:$,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}catch(J){throw Error(BJ(J))}}function BJ($){if($&&typeof $==="object"){let Z=$,J=Z.stderr?String(Z.stderr).trim():"";if(J)return J;if(Z.message)return Z.message}return String($)}function ZU($){return/not a git repository/i.test(BJ($))}var h4="work/",oM,K7;var jJ=R(()=>{oM=/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/,K7=new Map});import{lstatSync as QU,realpathSync as YU,statSync as VU}from"node:fs";import{basename as XU,dirname as LG,isAbsolute as zU,join as qG,resolve as HU}from"node:path";function _J($){return $.replace(/\*[0-9]{4}-[0-9]{4}(?:-[0-9]+)?$/,"")}function PJ($,Z,J){let Q=_J($),Y=_7(Q),V=J[Y]?.cwd?.trim()||qG(Z,Y);if(Q===Y)return V;return g4(V,Y,Q.slice(Y.length+1,-1))}function H$($){if(!zU($))throw Error(`工作目录必须是绝对路径: ${$}`);let Z=FG(HU($));return process.platform==="win32"?Z.toLowerCase():Z}function FG($){try{let Z=YU($);if(!VU(Z).isDirectory())throw Error(`工作目录不是文件夹: ${$}`);return Z}catch(Z){if(Z?.code!=="ENOENT"||LG($)===$)throw Z;try{if(QU($).isSymbolicLink())throw Z}catch(J){if(J===Z||J?.code!=="ENOENT")throw J}return qG(FG(LG($)),XU($))}}function DG($,Z,J){let Q=H$($),Y,V=new Map;for(let[X,z]of Object.entries(J)){if(H$(PJ(X,Z,J))!==Q)continue;Y??={cwd:$};for(let H of["settingSources","strictMcp","tools","loadProjectMcp"]){let G=z[H];if(G===void 0)continue;if(Y[H]!==void 0&&Y[H]!==G)throw Error(`同一工作目录的项目配置冲突: ${V.get(H)} / ${X}, ${H} (${$})`);Object.assign(Y,{[H]:G}),V.set(H,X)}}return Y}var m4=R(()=>{jJ()});function GU($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LJ($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Q=0;while(Q<$.length){J.lastIndex=Q;let z=J.exec($);if(!z)break;let H=z[1],G=new RegExp(`^(?: {0,3})${GU(H[0])}{${H.length},}[ \\t]*(?:\\n|$)`,"gm");G.lastIndex=z.index+z[0].length;let W=G.exec($),K=W?W.index+W[0].length:$.length;Z.push({start:z.index,end:K}),Q=K}let Y=[...Z],V=[],X=0;for(let z of Z){if(X<z.start)V.push({start:X,end:z.start});X=z.end}if(X<$.length)V.push({start:X,end:$.length});for(let z of V){let H=$.slice(z.start,z.end),G=/(`+)[^\n]*?\1/g,W;while((W=G.exec(H))!==null)Y.push({start:z.start+W.index,end:z.start+W.index+W[0].length})}return Y.sort((z,H)=>z.start-H.start)}function qJ($,Z){if(!$)return $;let J=LJ($);if(!J.length)return Z($);let Q="",Y=0;for(let V of J){if(V.start>Y)Q+=Z($.slice(Y,V.start));Q+=$.slice(V.start,V.end),Y=Math.max(Y,V.end)}if(Y<$.length)Q+=Z($.slice(Y));return Q}function WU($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function MG($){return $.replace(/!\[([^\]]*)\]\(([^)]*)\)/g,(J,Q,Y)=>{let V=Y.trim();return Q.trim()?`\uD83D\uDDBC️ ${Q.trim()} (${V})`:`\uD83D\uDDBC️ ${V}`}).replace(/!\[/g,"\uD83D\uDDBC️ [")}function m1($){if(Array.isArray($))return $.map((Q)=>m1(Q));if($==null||typeof $!=="object")return $;let Z=$,J={};for(let[Q,Y]of Object.entries(Z))J[Q]=m1(Y);if(Z.tag==="markdown"&&typeof Z.content==="string")J.content=FJ(Z.content);return J}function G0($){return qJ($,(Z)=>KU(MG(WU(Z))))}function KU($){return $.replace(/\\\[([\s\S]*?)\\\]/g,(Z,J)=>`
137
137
  \`\`\`
138
138
  ${J.trim()}
139
139
  \`\`\`
@@ -141,21 +141,21 @@ ${J.trim()}
141
141
  \`\`\`
142
142
  ${J.trim()}
143
143
  \`\`\`
144
- `).replace(/\\\(([\s\S]*?)\\\)/g,(Z,J)=>`\`${J.trim()}\``).replace(/\$([^$\n]+)\$/g,(Z,J)=>/\\|\^|_|=/.test(J)?`\`${J.trim()}\``:Z)}function DJ($){return qJ($,MG)}var C;var d0=R(()=>{C={userInput:"user_input",footer:"footer",taskBoardLive:"task_board_live",planLive:"plan_live",tool:($)=>`tool_${$}`,planUpdate:($)=>`plan_update_${$}`,goalUpdate:($)=>`goal_update_${$}`,contextCompact:($)=>`context_compact_${$}`,assistant:($)=>`assistant_${$}`,consoleCurrentModel:"console_model",consoleProjects:"console_projects",consoleHost:"console_host",consoleUsage:"console_usage",modelPanel:"model_panel",codexAccountPanel:"codex_account_panel",modelAgentGroup:($)=>`model_agent_${$}`,tasklistPanel:"tasklist_panel",fileDeliveryList:"file_delivery_list",agentIdentityPanel:"agent_id_panel",agentRunFooter:"agent_run_footer"}});async function FJ($){let Z=await OJ("feishu chat.get",()=>q0.im.chat.get({path:{chat_id:$},params:{user_id_type:"open_id"}}));if(Z.code&&Z.code!==0)P7("feishu chat.get",Z);let J=Z.data?.owner_id;if(!J)throw Error("feishu chat.get returned no owner_id; cannot add project group owner to tasklist");return J}async function MJ($,Z){let J=await OJ("feishu tasklist.create",()=>q0.task.v2.tasklist.create({params:{user_id_type:"open_id"},data:{name:$,members:[{id:Z,type:"user",role:"editor"}]}}));if(J.code&&J.code!==0)P7("feishu tasklist.create",J);let Q=J.data?.tasklist,Y=Q?.guid;if(!Y)throw Error("feishu tasklist.create returned no guid");return{guid:Y,name:Q?.name||$,url:Q?.url??"",createdAt:Q?.created_at}}async function UJ($){let Z=await OJ("feishu tasklist.delete",()=>q0.task.v2.tasklist.delete({path:{tasklist_guid:$}}));if(Z.code&&Z.code!==0)P7("feishu tasklist.delete",Z)}function UG($,Z){let J=Z&&typeof Z==="object"?Z:{},Q=J.response?.data&&typeof J.response.data==="object"?J.response.data:J.data&&typeof J.data==="object"?J.data:J,Y=Q.error?.permission_violations??Q.permission_violations??J.error?.permission_violations,V=Array.isArray(Y)?Y.map((X)=>X?.scope??X?.subject??X?.name??X).filter(Boolean).join(", "):"";return`${$} failed ${w(Z)}${V?` missing_scopes=${V}`:""}`}async function OJ($,Z){try{return await Z()}catch(J){P7($,J)}}function P7($,Z){throw Error(UG($,Z))}var OG=R(()=>{Y0()});var z0={};H1(z0,{writeAliveMarker:()=>mJ,urgentApp:()=>w2,uploadImageKey:()=>aJ,uploadAndSend:()=>j8,updateCard:()=>n4,unbindSessionChat:()=>D7,tempProjectName:()=>D1,tempChatName:()=>yJ,setPendingConversationLaunchChecked:()=>u1,sendTextRaw:()=>h,sendText:()=>k,sendImage:()=>C7,sendFile:()=>iG,sendCard:()=>o,sanitizeSessionName:()=>sJ,resolveProjectDir:()=>c4,replaceTurnAnchors:()=>W$,registerTempSessionLease:()=>CJ,refreshChatList:()=>K8,readAliveMarker:()=>pJ,provisionProject:()=>oJ,projectProfileForDirectory:()=>z8,projectProfile:()=>qU,preferredChatForSession:()=>U0,loadTempSessionLeases:()=>SJ,loadSessionTurnsMap:()=>vJ,loadSessionResumeMap:()=>kJ,loadSessionModelMap:()=>hJ,loadSessionChatMap:()=>bJ,listNormalChatIdsByName:()=>R7,isOpenAIChatGPTAuthenticated:()=>_8,hasTempSessionLease:()=>xJ,getTurnAnchors:()=>l4,getTenantToken:()=>s$,getSessionResumeRef:()=>c1,getSessionModelSelection:()=>IJ,getSessionBranchBase:()=>d4,getPendingConversationLaunch:()=>i4,getChatTailMessageId:()=>nJ,formatFeishuApiError:()=>UG,findNormalChatIdByName:()=>T7,fetchChatOwnerOpenId:()=>FJ,fetchChatName:()=>iJ,ensureChatForSession:()=>cJ,downloadAttachment:()=>B8,disbandChatForSessionExact:()=>dJ,disbandChatForSession:()=>lJ,deleteTasklistByGuid:()=>UJ,deleteReaction:()=>g0,createTempChatForSession:()=>uJ,createTasklistWithOwner:()=>MJ,client:()=>q0,clearSessionResumeChecked:()=>u4,clearSessionConversationState:()=>gJ,chatNameCache:()=>O0,chatIdForSession:()=>N7,bindSessionToChat:()=>p4,bindSessionResumeChecked:()=>W8,bindSessionModelChecked:()=>l1,bindSessionModel:()=>NU,appendTurnAnchorChecked:()=>fJ,addReaction:()=>K$,PROJECTS_ROOT:()=>EJ,MAX_UPLOAD_BYTES:()=>S7});import*as U7 from"@larksuiteoapi/node-sdk";import{AsyncLocalStorage as BU}from"node:async_hooks";import{execSync as jU}from"node:child_process";import{randomUUID as O7}from"node:crypto";import{mkdirSync as AJ,readFileSync as k2,statSync as kG,writeFileSync as wG}from"node:fs";import{readFile as _U}from"node:fs/promises";import{homedir as AG}from"node:os";import{basename as b2,extname as PU,isAbsolute as vG,join as NJ}from"node:path";import{sync as LU}from"cross-spawn";function RJ(){let $={};for(let[Z,J]of G$)$[Z]=J;r(v5,$)}function SJ(){G$.clear();try{let $=JSON.parse(k2(v5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("lease file must contain an object");for(let[Z,J]of Object.entries($)){let Q=J;if(typeof Z!=="string"||!Z||Q.chatId!==Z||typeof Q.sessionName!=="string"||!D1(Q.sessionName)||typeof Q.createdAt!=="number"||!Number.isFinite(Q.createdAt)){j(`feishu: rejected malformed temp-session lease chat=${Z}`);continue}G$.set(Z,{chatId:Z,sessionName:Q.sessionName,createdAt:Q.createdAt})}j(`feishu: loaded ${G$.size} temporary-session leases`)}catch($){if($?.code!=="ENOENT")j(`feishu: load temp-session leases failed: ${$?.message??$}`)}}function CJ($,Z){if(!D1($))throw Error(`refusing to lease non-temporary session name "${$}"`);if(!Z)throw Error("cannot lease a temporary session without chat_id");for(let Y of G$.values())if(Y.sessionName===$&&Y.chatId!==Z)throw Error(`temporary session name "${$}" is already leased to ${Y.chatId}`);let J=G$.get(Z),Q={sessionName:$,chatId:Z,createdAt:Date.now()};G$.set(Z,Q);try{RJ()}catch(Y){if(J)G$.set(Z,J);else G$.delete(Z);throw Y}}function xJ($,Z){let J=G$.get(Z);return J?.sessionName===$&&J.chatId===Z}function qU($){return g.projects[$]}function c4($){return PJ($,EJ,g.projects)}function z8($){return FG($,EJ,g.projects)}function r0($,Z){let J=k$(Z);return new l0(`${$} failed ${w(Z)}`,J.status,J.code,J.retryAfter,J.logId,J.message)}function A7($,Z){let J=new H2;return hG.run(J,async()=>{try{return await G2($,()=>Z(J),{recovery:J})}catch(Q){if(!(Q instanceof Error&&Q.name==="AbortError"))await J.waitUntilDeadline();throw Q}})}function G8($,Z={}){return V0($,{...Z,signal:Z.signal??AbortSignal.timeout(H8)})}async function IG($,Z,J){let Q=Z.signal??AbortSignal.timeout(H8);try{return await F$(await G8($,{...Z,signal:Q}),J)}catch(Y){if(Q.aborted&&Q.reason?.name==="TimeoutError")throw Q.reason;throw Y}}async function s$($){if($?.timeoutMs(H8),L7&&Date.now()<NG)return L7;if(q7??=(async()=>{let Q=await IG("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:fG,app_secret:yG})},"tenant token");if(typeof Q.tenant_access_token!=="string"||!Q.tenant_access_token.trim())throw Error("feishu: tenant token MISS");return L7=Q.tenant_access_token,NG=Date.now()+Math.max(0,(Q.expire??7200)-60)*1000,L7})().finally(()=>{q7=null}),!$)return q7;let Z=q7,J=AbortSignal.timeout($.timeoutMs(60000));return new Promise((Q,Y)=>{let V=()=>{try{$.timeoutMs(1)}catch(X){Y(X);return}Y(J.reason)};J.addEventListener("abort",V,{once:!0}),Z.then((X)=>{J.removeEventListener("abort",V);try{$.timeoutMs(1),Q(X)}catch(z){Y(z)}},(X)=>{J.removeEventListener("abort",V),Y(X)})})}function bJ(){try{let $=JSON.parse(k2(x5,"utf8"));for(let[Z,J]of Object.entries($))if(typeof J==="string")U0.set(Z,J);j(`feishu: loaded ${U0.size} session→chat bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-chat-map failed: ${$?.message??$}`)}}function gG(){try{TJ()}catch($){j(`feishu: save session-chat-map failed: ${$}`)}}function TJ(){let $={};for(let[Z,J]of U0)$[Z]=J;r(x5,$)}function p4($,Z){if(U0.get($)===Z)return;let J=U0.get($);U0.set($,Z),gG(),j(`feishu: bound session "${$}" → ${Z}${J?` (was ${J})`:""}`)}function D7($){let Z=U0.get($);if(!Z)return;U0.delete($),gG(),j(`feishu: unbound session "${$}" from ${Z}`)}function V8($,Z){let J=C0.get($)??{};J[Z.provider]=Z,C0.set($,J)}function RG($,Z){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$,Q=a$(J.provider)?J.provider:Z??null;if(!Q||Z&&Q!==Z)return null;let Y=typeof J.sessionId==="string"?J.sessionId.trim():typeof J.session_id==="string"?J.session_id.trim():"";if(!Y)return null;if(J.cwd===void 0||J.cwd===null)return{provider:Q,sessionId:Y,cwd:null};if(typeof J.cwd!=="string"||!vG(J.cwd))return null;return{provider:Q,sessionId:Y,cwd:J.cwd}}function TG($){let Z=$.sessionId.trim();if(!Z)throw Error("cannot bind an empty conversation session id");if(!a$($.provider))throw Error(`cannot bind an unknown conversation provider: ${String($.provider)}`);if(typeof $.cwd!=="string"||!vG($.cwd))throw Error(`cannot bind a conversation without an absolute cwd: ${String($.cwd)}`);return{provider:$.provider,sessionId:Z,cwd:$.cwd}}function FU($,Z,J){if(typeof $!=="string")return TG($);if(!Z)throw Error("cannot bind a conversation without a provider");return TG({provider:Z,sessionId:$,cwd:J??null})}function kJ(){try{let $=JSON.parse(k2(b5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("resume map must contain an object");C0.clear();for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){V8(Z,{provider:"codex",sessionId:J.trim(),cwd:null});continue}if(!J||typeof J!=="object"||Array.isArray(J))continue;let Q=J,Y=RG(Q);if(Y){V8(Z,Y);continue}for(let V of IZ){let X=Q[V];if(typeof X==="string"&&X.trim()){V8(Z,{provider:V,sessionId:X.trim(),cwd:null});continue}let z=RG(X,V);if(z)V8(Z,z)}}j(`feishu: loaded ${C0.size} session→resume bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-resume-map failed: ${$?.message??$}`)}}function F7(){let $={};for(let[Z,J]of C0){let Q={};if(J.codex)Q.codex={...J.codex};if(J.claude)Q.claude={...J.claude};if(J.dsh)Q.dsh={...J.dsh};$[Z]=Q}r(b5,$)}function W8($,Z,J,Q){let Y=FU(Z,J,Q),V=C0.get($),X=V?{...V}:void 0,z=V?.[Y.provider];if(z?.sessionId===Y.sessionId&&z.cwd===Y.cwd)return;V8($,Y);try{F7()}catch(H){if(X)C0.set($,X);else C0.delete($);throw H}}function c1($,Z="codex"){let J=C0.get($)?.[Z];return J?{...J}:null}function u4($,Z){let J=C0.get($);if(!J||Z&&J[Z]===void 0)return;let Q={...J};if(!Z)C0.delete($);else{let Y={...J};if(delete Y[Z],!Y.codex&&!Y.claude)C0.delete($);else C0.set($,Y)}try{F7()}catch(Y){throw C0.set($,Q),Y}}function mG($){if(!$||typeof $!=="object")return null;let Z=$;if(!a$(Z.provider))return null;let J=typeof Z.sessionId==="string"?Z.sessionId.trim():"";if(!J)return null;let Q;if(Z.cwd===void 0||Z.cwd===null)Q=null;else if(typeof Z.cwd==="string"&&Z.cwd.trim())Q=Z.cwd;else return null;return{provider:Z.provider,sessionId:J,cwd:Q}}function pG($){if(!$||typeof $!=="object")return null;let Z=$,J=Z.source;if(!J||typeof J!=="object")return null;let Q=mG(J),Y=typeof Z.id==="string"?Z.id.trim():"";if(!Y||!Q)return null;if(Z.provider==="dsh"&&Z.kind==="event"&&Q.provider==="dsh"&&/^\d+$/.test(Y)&&Number.isSafeInteger(Number(Y)))return{provider:"dsh",kind:"event",id:Y,source:{...Q,provider:"dsh"}};if(Z.provider==="claude"&&Z.kind==="assistant-message"&&Q.provider==="claude")return{provider:"claude",kind:"assistant-message",id:Y,source:{...Q,provider:"claude"}};if(Z.provider==="codex"&&Z.kind==="turn"&&Q.provider==="codex")return{provider:"codex",kind:"turn",id:Y,source:{...Q,provider:"codex"}};return null}function cG($){if(!$||typeof $!=="object")return null;let Z=$;if(Z.kind==="fresh")return{kind:"fresh"};if(Z.kind!=="resume"&&Z.kind!=="fork")return null;let J=mG(Z.source);if(!J)return null;let Q=Z.kind==="resume"?{kind:"resume",source:J}:(()=>{if(!Object.prototype.hasOwnProperty.call(Z,"through"))return{kind:"fork",source:J};let Y=pG(Z.through);return Y?{kind:"fork",source:J,through:Y}:null})();if(!Q)return null;try{E0(Q,J.provider)}catch{return null}return Q}function MU($){if(!Array.isArray($))return[];return $.filter((Z)=>Z&&typeof Z.path==="string").map((Z)=>({tool:String(Z.tool??"Write"),path:String(Z.path),body:String(Z.body??"")})).filter((Z)=>Z.path!==""||Z.body!=="")}function UU($,Z){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.ts!=="number"||!Number.isFinite(J.ts))return null;let Q=Object.prototype.hasOwnProperty.call(J,"checkpoint"),Y=pG(J.checkpoint);if(Q&&!Y)return null;if(!Y){if(Z!=="claude")return null;let V=typeof J.uuid==="string"?J.uuid.trim():"",X=typeof J.sid==="string"?J.sid.trim():"";if(!V||!X)return null;Y={provider:"claude",kind:"assistant-message",id:V,source:{provider:"claude",sessionId:X,cwd:null}}}return{checkpoint:Y,preview:String(J.preview??""),ts:J.ts,writes:MU(J.writes)}}function OU($){if(!$||typeof $!=="object")return null;let Z=$,J=cG(Z.launch);if(J?.kind!=="fork"||J.source.provider!=="claude"||J.source.cwd===null)return null;let Q=Z.previousSessionId,Y=Q===null?null:typeof Q==="string"&&Q.trim()?Q.trim():void 0;if(Y===void 0)return null;return{launch:{...J,source:{...J.source,provider:"claude"}},previousSessionId:Y}}function wJ($){let Z=$.launch.through;if($.launch.source.provider!=="claude"||Z&&(Z.provider!=="claude"||Z.kind!=="assistant-message"||Z.source.provider!=="claude"))throw Error("pending conversation launch is not a Claude fork");return{launch:{kind:"fork",source:{...$.launch.source,provider:"claude"},...Z?{through:{...Z,provider:"claude",kind:"assistant-message",source:{...Z.source,provider:"claude"}}}:{}},previousSessionId:$.previousSessionId}}function vJ(){try{let $=JSON.parse(k2(k5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("turns map must contain an object");W0.clear();let Z=0,J=0;for(let[Q,Y]of Object.entries($)){let V,X,z=null;if(Array.isArray(Y))V=Y,X=null;else if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let K=Y;if(!Array.isArray(K.anchors)||!Object.prototype.hasOwnProperty.call(K,"base")){J++;continue}if(V=K.anchors,K.base===null)X=null;else{let B=cG(K.base);if(!B){J++;continue}X=B}if(Object.prototype.hasOwnProperty.call(K,"pendingLaunch")){let B=OU(K.pendingLaunch);if(!B){J++;continue}z=B}}else{J++;continue}let H=C0.get(Q),G=H?.claude!==void 0&&H.codex===void 0?"claude":null,W=[];for(let K of V){let B=UU(K,G);if(B)W.push(B);else J++}if(W.length||X!==null||z)W0.set(Q,{base:X,anchors:W,...z?{pendingLaunch:z}:{}}),Z+=W.length}if(j(`feishu: loaded ${Z} turn anchors across ${W0.size} sessions`),J>0)j(`feishu: rejected ${J} malformed turn anchors while loading`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-turns-map failed: ${$?.message??$}`)}}function X8(){let $={};for(let[Z,J]of W0)$[Z]=J;r(k5,$)}function fJ($,Z){let J=W0.get($),Q=[...J?.anchors??[],Z],Y=J?.base??null;if(Q.length>EG){let V=Q.splice(0,Q.length-EG),X=V[V.length-1].checkpoint;Y={kind:"fork",source:X.source,through:X}}W0.set($,{base:Y,anchors:Q,...J?.pendingLaunch?{pendingLaunch:J.pendingLaunch}:{}});try{X8()}catch(V){if(J)W0.set($,J);else W0.delete($);throw V}}function l4($){return W0.get($)?.anchors??[]}function d4($){return W0.get($)?.base??null}function i4($){let Z=W0.get($)?.pendingLaunch;return Z?wJ(Z):null}function u1($,Z){if(Z){if(Z.launch.source.cwd===null)throw Error("pending conversation launch source cwd is missing");E0(Z.launch,"claude",Z.launch.source.cwd)}let J=W0.get($),Q=J?.base??null,Y=J?.anchors.slice()??[];if(!Z&&Y.length===0&&Q===null)W0.delete($);else W0.set($,{base:Q,anchors:Y,...Z?{pendingLaunch:wJ(Z)}:{}});try{X8()}catch(V){if(J)W0.set($,J);else W0.delete($);throw V}}function W$($,Z,J,Q){let Y=W0.get($),V=Q===void 0?Y?.pendingLaunch:Q??void 0,X=V?wJ(V):void 0;if(Z.length===0&&J===null&&!X)W0.delete($);else W0.set($,{base:J,anchors:Z.slice(),...X?{pendingLaunch:X}:{}});try{X8()}catch(z){if(Y)W0.set($,Y);else W0.delete($);throw z}}function D1($){return SG.test($)?$.replace(SG,""):null}function yJ($,Z=[]){let J=new Date,Q=(z)=>String(z).padStart(2,"0"),Y=`${Q(J.getMonth()+1)}${Q(J.getDate())}-${Q(J.getHours())}${Q(J.getMinutes())}`,V=new Set([...O0.values(),...W0.keys(),...Z]),X=`${$}*${Y}`;for(let z=2;V.has(X);z++)X=`${$}*${Y}-${z}`;return X}function hJ(){try{let $=JSON.parse(k2(w5,"utf8"));for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){i0.set(Z,{provider:x4(J),model:J,effort:null});continue}if(!J||typeof J!=="object")continue;let{model:Q,provider:Y}=J,V=a$(Y)?Y:typeof Q==="string"&&Q.trim()?x4(Q):"claude",X=typeof Q==="string"&&Q.trim()?Q:null;if(V==="claude"&&!X)continue;let{effort:z,tokenSourceId:H}=J,G=typeof H==="string"&&H.trim()?H.trim():null,W=V==="dsh"?S0(z)?z:null:V==="claude"?w0(z)?z:null:U$(z)?z:null;i0.set(Z,{provider:V,model:X,effort:W,...G?{tokenSourceId:G}:{}})}j(`feishu: loaded ${i0.size} session→model bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-model-map failed: ${$?.message??$}`)}}function AU(){try{M7()}catch($){j(`feishu: save session-model-map failed: ${$}`)}}function M7(){let $={};for(let[Z,J]of i0)$[Z]=J;r(w5,$)}function NU($,Z,J,Q,Y){let V=i0.get($);if(V?.provider===Z&&V.model===J&&V.effort===Q&&(V.tokenSourceId??null)===(Y??null))return;i0.set($,{provider:Z,model:J,effort:Q,...Y?{tokenSourceId:Y}:{}}),AU()}function l1($,Z,J,Q,Y){let V=i0.get($),X={provider:Z,model:J,effort:Q,...Y?{tokenSourceId:Y}:{}};if(V?.provider===Z&&V.model===J&&V.effort===Q&&(V.tokenSourceId??null)===(Y??null))return;i0.set($,X);try{M7()}catch(z){if(V)i0.set($,V);else i0.delete($);throw z}}function IJ($){let Z=i0.get($);if(Z)return Z;let J=D1($);return J?i0.get(J)??null:null}function gJ($){let Z=U0.get($),J=C0.get($),Q=i0.get($),Y=W0.get($),V=[...G$.entries()].filter(([,X])=>X.sessionName===$);U0.delete($),C0.delete($),i0.delete($),W0.delete($);for(let[X]of V)G$.delete(X);try{TJ(),F7(),M7(),X8(),RJ()}catch(X){if(Z)U0.set($,Z);if(J)C0.set($,J);if(Q)i0.set($,Q);if(Y)W0.set($,Y);for(let[H,G]of V)G$.set(H,G);let z=[X];for(let H of[TJ,F7,M7,X8,RJ])try{H()}catch(G){z.push(G)}throw z.length===1?z[0]:AggregateError(z,`failed to clear and restore conversation state for ${$}`)}}function mJ($){r(y5,$)}function pJ(){let $;try{$=k2(y5,"utf8")}catch(J){if(J.code==="ENOENT")return[];throw J}let Z=JSON.parse($);if(!Array.isArray(Z)||Z.some((J)=>typeof J!=="string"||!J.trim()))throw Error("invalid alive session marker: expected non-empty session names");return Z}function N7($){let Z=U0.get($);if(Z){let Q=O0.get(Z);if(Q&&Q!==$)j(`feishu: chatIdForSession("${$}"): persisted binding ${Z} has cached name "${Q}", using persisted binding`);return Z}let J=[];for(let[Q,Y]of O0)if(Y===$)J.push(Q);if(J.length===1)return J[0];if(J.length>1)j(`feishu: chatIdForSession("${$}"): ${J.length} candidates with no binding — [${J.join(", ")}]`);return null}async function K8(){try{let $;do{let Z=await q0.im.chat.list({params:{page_size:100,...$?{page_token:$}:{}}});if(Z.code&&Z.code!==0)throw r0("feishu chat.list",Z);for(let J of Z.data?.items??[])if(J.chat_id&&J.name)O0.set(J.chat_id,J.name);$=Z.data?.page_token}while($);j(`feishu: refreshed chat list — ${O0.size} groups`)}catch($){j(`feishu: refresh chat list failed: ${$}`)}}async function R7(){let $=new Map,Z;do{let J=await q0.im.chat.list({params:{page_size:100,...Z?{page_token:Z}:{}}});if(J.code&&J.code!==0)throw r0("feishu chat.list",J);for(let Q of J.data?.items??[]){if(!Q.chat_id||!Q.name)continue;if(Q.chat_status&&Q.chat_status!=="normal")continue;O0.set(Q.chat_id,Q.name);let Y=$.get(Q.name)??[];Y.push(Q.chat_id),$.set(Q.name,Y)}Z=J.data?.page_token}while(Z);return $}async function T7($){let Z=U0.get($);if(Z&&O0.get(Z)===$){let V=await uG(Z);if(V.name===$&&lG(V.status))return Z;O0.delete(Z),D7($)}let Q=(await R7()).get($)??[];if(Q.length===0)return null;let Y=U0.get($);if(Y&&Q.includes(Y))return Y;if(Q.length===1)return Q[0];throw Error(`multiple Feishu groups named "${$}": ${Q.join(", ")}`)}async function cJ($,Z){if(!Z)throw Error("missing sender open_id; cannot add user to worktree group");let J=await T7($);if(J){let V=await RU(J,Z);return p4($,J),{chatId:J,created:!1,joined:V}}let Q=await q0.im.chat.create({params:{user_id_type:"open_id",uuid:O7()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Q.code&&Q.code!==0)throw r0("feishu chat.create",Q);let Y=Q.data?.chat_id;if(!Y)throw Error("feishu chat.create returned no chat_id");return O0.set(Y,$),p4($,Y),{chatId:Y,created:!0,joined:!0}}async function uJ($,Z){if(!Z)throw Error("missing sender open_id; cannot create temporary group");if(await T7($))throw Error(`temporary group name already exists: ${$}`);let Q=await q0.im.chat.create({params:{user_id_type:"open_id",uuid:O7()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Q.code&&Q.code!==0)throw r0("feishu chat.create",Q);let Y=Q.data?.chat_id;if(!Y)throw Error("feishu chat.create returned no chat_id");return O0.set(Y,$),p4($,Y),{chatId:Y,created:!0,joined:!0}}async function lJ($){let Z=await T7($);if(!Z)return D7($),{chatId:null,disbanded:!1};let J=await q0.im.chat.delete({path:{chat_id:Z}});if(J.code&&J.code!==0)throw r0("feishu chat.delete",J);if(O0.delete(Z),U0.get($)===Z)D7($);return{chatId:Z,disbanded:!0}}async function dJ($,Z){if(!Z)throw Error("cannot disband a temporary session without an exact chat_id");let J=await uG(Z);if(J.name!==$)throw Error(`refusing to delete chat ${Z}: expected name "${$}", got "${J.name??""}"`);if(!lG(J.status))throw Error(`refusing to delete chat ${Z}: status=${J.status??"unknown"}`);let Q=await q0.im.chat.delete({path:{chat_id:Z}});if(Q.code&&Q.code!==0)throw r0("feishu chat.delete",Q);return O0.delete(Z),{chatId:Z,disbanded:!0}}async function RU($,Z){let J;do{let Y=await q0.im.chatMembers.get({path:{chat_id:$},params:{member_id_type:"open_id",page_size:100,...J?{page_token:J}:{}}});if(Y.code&&Y.code!==0)throw r0("feishu chatMembers.get",Y);for(let V of Y.data?.items??[])if(V.member_id===Z)return!1;J=Y.data?.page_token}while(J);let Q=await q0.im.chatMembers.create({path:{chat_id:$},params:{member_id_type:"open_id"},data:{id_list:[Z]}});if(Q.code&&Q.code!==0)throw r0("feishu chatMembers.create",Q);return!0}async function iJ($){try{let Z=await s$(),J=await G8(`https://open.feishu.cn/open-apis/im/v1/chats/${encodeURIComponent($)}`,{headers:{Authorization:`Bearer ${Z}`}}),Y=(await F$(J,`fetchChatName ${$}`)).data?.name;if(typeof Y==="string"&&Y)return O0.set($,Y),j(`feishu: fetchChatName ${$} → "${Y}" (point lookup)`),Y;return j(`feishu: fetchChatName ${$} — chat has no name (unnamed group?)`),null}catch(Z){return j(`feishu: fetchChatName ${$} failed: ${Z}`),null}}async function E7($,Z,J,Q,Y){let V=O7();try{return await A7(`send${$} chat=${Z}`,async()=>{let X=await q0.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:Z,msg_type:J,content:Q,uuid:V}});if(X?.code!==0)throw r0(`send${$}`,X);let z=X?.data?.message_id;if(typeof z!=="string"||!z.trim())throw Error(`send${$} message_id MISS`);return z})}catch(X){return Y?.(X),null}}async function uG($){let Z=await q0.im.chat.get({path:{chat_id:$}});if(Z.code&&Z.code!==0)throw r0("feishu chat.get",Z);return{name:Z.data?.name??null,status:Z.data?.chat_status??null}}function lG($){return $===null||$==="normal"}async function k($,Z,J){return f$($,()=>E7("Text",$,"text",JSON.stringify({text:Z}),J))}async function o($,Z,J){return f$($,()=>E7("Card",$,"interactive",JSON.stringify(m1(Z)),J))}async function nJ($){return A7(`message.list chat=${$}`,async()=>{let Z=await q0.im.message.list({params:{container_id_type:"chat",container_id:$,sort_type:"ByCreateTimeDesc",page_size:1}});if(Z.code!==0)throw r0("feishu message.list",Z);if(!Array.isArray(Z.data?.items))throw Error("feishu message.list items MISS");if(Z.data.items.length===0)return null;let J=Z.data.items[0]?.message_id;if(typeof J!=="string"||!J.trim())throw Error("feishu message.list message_id MISS");return J})}async function n4($,Z){let J=JSON.stringify(m1(Z));await A7(`message.patch message=${$}`,async()=>{let Q=await q0.im.v1.message.patch({path:{message_id:$},data:{content:J}});if(Q?.code!==0)throw r0("feishu message.patch",Q)})}async function h($,Z){return f$($,()=>TU($,Z))}async function TU($,Z){try{let J=await s$(),Q=await G8("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id",{method:"POST",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:$,msg_type:"text",content:JSON.stringify({text:Z})})});return(await F$(Q,`sendTextRaw chat=${$}`)).data?.message_id??null}catch(J){return j(`feishu: sendTextRaw chat=${$} failed: ${J}`),null}}async function K$($,Z){if(!$)return null;try{let J=await q0.im.messageReaction.create({path:{message_id:$},data:{reaction_type:{emoji_type:Z}}});if(J?.code&&J.code!==0)throw r0("feishu messageReaction.create",J);return J?.data?.reaction_id??null}catch(J){return j(`feishu: addReaction ${Z} on ${$} failed: ${J}`),null}}async function g0($,Z){if(!$||!Z)return;try{let J=await q0.im.messageReaction.delete({path:{message_id:$,reaction_id:Z}});if(J?.code&&J.code!==0)throw r0("feishu messageReaction.delete",J)}catch(J){j(`feishu: deleteReaction ${Z} on ${$} failed: ${J}`)}}async function w2($,Z){if(!$){j("feishu: urgentApp skip — missing messageId");return}if(Z.length===0){j(`feishu: urgentApp skip — empty openIds (msg=${$})`);return}let J=await s$(),Q=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/urgent_app?user_id_type=open_id`;try{let Y=await G8(Q,{method:"PATCH",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({user_id_list:Z})}),X=(await F$(Y,`urgentApp ${$}`)).data?.invalid_user_id_list??[],z=Z.length-X.length;j(`feishu: urgentApp ${$} ok — delivered=${z}${X.length?` invalid=${X.length}`:""}`)}catch(Y){j(`feishu: urgentApp ${$} failed: ${Y}`)}}async function B8($,Z,J,Q){try{let Y=await s$(),V=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/resources/${Z}?type=${J}`,X=await G8(V,{headers:{Authorization:`Bearer ${Y}`}});if(!X.ok)await F$(X,`download ${J}`);let z=Buffer.from(await X.arrayBuffer());AJ(h5,{recursive:!0});let H=Q?Q.replace(/[^a-zA-Z0-9._-]/g,"_"):`${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}.png`,G=NJ(h5,`${Date.now()}-${O7()}-${H}`);return wG(G,z,{flag:"wx"}),j(`feishu: downloaded ${J} ${G} (${z.length}B)`),G}catch(Y){j(`feishu: download ${J} failed: ${Y instanceof Error?Y.message:Y}`);return}}function SU($){return EU.has(PU($).toLowerCase())}async function dG($,Z){let J=`upload${Z==="image"?"Image":"File"}`,Q;try{if(Q=new Blob([Uint8Array.from(await _U($))]),Q.size>S7)throw Error(`${b2($)} 超过 30 MB`)}catch(X){throw j(`feishu: ${J} local file validation failed ${$}: ${X}`),X}let Y=async(X)=>{let z=await s$(X),H=new FormData;if(Z==="image")H.append("image_type","message");else H.append("file_type","stream"),H.append("file_name",b2($));H.append(Z,Q,b2($));let G=X.timeoutMs(Z==="file"?CG:H8),K=(await IG(`https://open.feishu.cn/open-apis/im/v1/${Z}s`,{method:"POST",headers:{Authorization:`Bearer ${z}`},body:H,signal:AbortSignal.timeout(G)},J)).data?.[`${Z}_key`];if(typeof K!=="string"||!K.trim())throw Error(`${J} ${Z}_key MISS`);return K};if(Z==="image")return A7(`${J} ${$}`,Y);let V=new H2(xG,bG);return j(`feishu: ${J} ${$} started: bytes=${Q.size} timeout=${CG}ms maxAttempts=${bG+1} recovery=${xG}ms`),G2(`${J} ${$}`,()=>Y(V),{recovery:V})}async function aJ($,Z){try{let J=kG($);if(!J.isFile())return j(`feishu: uploadImageKey not a file — ${$}`),Z?.(Error("路径不是普通文件")),null;if(J.size>S7)return j(`feishu: uploadImageKey oversize — ${$} (${(J.size/1024/1024).toFixed(1)} MB)`),Z?.(Error(`${b2($)} 超过 30 MB`)),null}catch(J){return j(`feishu: uploadImageKey stat failed — ${$}: ${J}`),Z?.(J),null}try{return await dG($,"image")}catch(J){return Z?.(J),null}}async function C7($,Z,J){return f$($,()=>E7("Image",$,"image",JSON.stringify({image_key:Z}),J))}async function iG($,Z,J){return f$($,()=>E7("File",$,"file",JSON.stringify({file_key:Z}),J))}async function j8($,Z){try{let Y=kG(Z);if(!Y.isFile())return j(`feishu: uploadAndSend not a file — ${Z}`),await k($,`❌ 出站文件: 路径不是文件 — ${Z}`),!1;if(Y.size>S7)return j(`feishu: uploadAndSend oversize — ${Z} (${Y.size}B)`),await k($,`❌ 出站文件: ${b2(Z)} 超过 30 MB (${(Y.size/1024/1024).toFixed(1)} MB)`),!1}catch(Y){return j(`feishu: uploadAndSend stat failed — ${Z}: ${Y}`),await k($,`❌ 出站文件: 无法读取 ${Z} (${Y})`),!1}let J=SU(Z)?"image":"file",Q=J==="image"?"出站图片":"出站文件";try{let Y=await dG(Z,J),V,X=(H)=>{V=H},z=await(J==="image"?C7($,Y,X):iG($,Y,X));if(!z)return j(`feishu: uploadAndSend ${Z} send failed after upload`),await k($,`❌ ${Q}发送失败: ${b2(Z)}(上传已完成)
144
+ `).replace(/\\\(([\s\S]*?)\\\)/g,(Z,J)=>`\`${J.trim()}\``).replace(/\$([^$\n]+)\$/g,(Z,J)=>/\\|\^|_|=/.test(J)?`\`${J.trim()}\``:Z)}function FJ($){return qJ($,MG)}var C;var d0=R(()=>{C={userInput:"user_input",footer:"footer",taskBoardLive:"task_board_live",planLive:"plan_live",tool:($)=>`tool_${$}`,planUpdate:($)=>`plan_update_${$}`,goalUpdate:($)=>`goal_update_${$}`,contextCompact:($)=>`context_compact_${$}`,assistant:($)=>`assistant_${$}`,consoleCurrentModel:"console_model",consoleProjects:"console_projects",consoleHost:"console_host",consoleUsage:"console_usage",modelPanel:"model_panel",codexAccountPanel:"codex_account_panel",modelAgentGroup:($)=>`model_agent_${$}`,tasklistPanel:"tasklist_panel",fileDeliveryList:"file_delivery_list",agentIdentityPanel:"agent_id_panel",agentRunFooter:"agent_run_footer"}});async function DJ($){let Z=await OJ("feishu chat.get",()=>q0.im.chat.get({path:{chat_id:$},params:{user_id_type:"open_id"}}));if(Z.code&&Z.code!==0)P7("feishu chat.get",Z);let J=Z.data?.owner_id;if(!J)throw Error("feishu chat.get returned no owner_id; cannot add project group owner to tasklist");return J}async function MJ($,Z){let J=await OJ("feishu tasklist.create",()=>q0.task.v2.tasklist.create({params:{user_id_type:"open_id"},data:{name:$,members:[{id:Z,type:"user",role:"editor"}]}}));if(J.code&&J.code!==0)P7("feishu tasklist.create",J);let Q=J.data?.tasklist,Y=Q?.guid;if(!Y)throw Error("feishu tasklist.create returned no guid");return{guid:Y,name:Q?.name||$,url:Q?.url??"",createdAt:Q?.created_at}}async function UJ($){let Z=await OJ("feishu tasklist.delete",()=>q0.task.v2.tasklist.delete({path:{tasklist_guid:$}}));if(Z.code&&Z.code!==0)P7("feishu tasklist.delete",Z)}function UG($,Z){let J=Z&&typeof Z==="object"?Z:{},Q=J.response?.data&&typeof J.response.data==="object"?J.response.data:J.data&&typeof J.data==="object"?J.data:J,Y=Q.error?.permission_violations??Q.permission_violations??J.error?.permission_violations,V=Array.isArray(Y)?Y.map((X)=>X?.scope??X?.subject??X?.name??X).filter(Boolean).join(", "):"";return`${$} failed ${w(Z)}${V?` missing_scopes=${V}`:""}`}async function OJ($,Z){try{return await Z()}catch(J){P7($,J)}}function P7($,Z){throw Error(UG($,Z))}var OG=R(()=>{Y0()});var z0={};H1(z0,{writeAliveMarker:()=>mJ,urgentApp:()=>w2,uploadImageKey:()=>aJ,uploadAndSend:()=>j8,updateCard:()=>n4,unbindSessionChat:()=>F7,tempProjectName:()=>F1,tempChatName:()=>fJ,setPendingConversationLaunchChecked:()=>u1,sendTextRaw:()=>h,sendText:()=>k,sendImage:()=>C7,sendFile:()=>iG,sendCard:()=>o,sanitizeSessionName:()=>sJ,resolveProjectDir:()=>c4,replaceTurnAnchors:()=>W$,registerTempSessionLease:()=>CJ,refreshChatList:()=>K8,readAliveMarker:()=>pJ,provisionProject:()=>oJ,projectProfileForDirectory:()=>z8,projectProfile:()=>qU,preferredChatForSession:()=>U0,loadTempSessionLeases:()=>SJ,loadSessionTurnsMap:()=>vJ,loadSessionResumeMap:()=>kJ,loadSessionModelMap:()=>hJ,loadSessionChatMap:()=>bJ,listNormalChatIdsByName:()=>R7,isOpenAIChatGPTAuthenticated:()=>_8,hasTempSessionLease:()=>xJ,getTurnAnchors:()=>l4,getTenantToken:()=>s$,getSessionResumeRef:()=>c1,getSessionModelSelection:()=>IJ,getSessionBranchBase:()=>d4,getPendingConversationLaunch:()=>i4,getChatTailMessageId:()=>nJ,formatFeishuApiError:()=>UG,findNormalChatIdByName:()=>T7,fetchChatOwnerOpenId:()=>DJ,fetchChatName:()=>iJ,ensureChatForSession:()=>cJ,downloadAttachment:()=>B8,disbandChatForSessionExact:()=>dJ,disbandChatForSession:()=>lJ,deleteTasklistByGuid:()=>UJ,deleteReaction:()=>g0,createTempChatForSession:()=>uJ,createTasklistWithOwner:()=>MJ,client:()=>q0,clearSessionResumeChecked:()=>u4,clearSessionConversationState:()=>gJ,chatNameCache:()=>O0,chatIdForSession:()=>N7,bindSessionToChat:()=>p4,bindSessionResumeChecked:()=>W8,bindSessionModelChecked:()=>l1,bindSessionModel:()=>NU,appendTurnAnchorChecked:()=>yJ,addReaction:()=>K$,PROJECTS_ROOT:()=>EJ,MAX_UPLOAD_BYTES:()=>S7});import*as U7 from"@larksuiteoapi/node-sdk";import{AsyncLocalStorage as BU}from"node:async_hooks";import{execSync as jU}from"node:child_process";import{randomUUID as O7}from"node:crypto";import{mkdirSync as AJ,readFileSync as k2,statSync as kG,writeFileSync as wG}from"node:fs";import{readFile as _U}from"node:fs/promises";import{homedir as AG}from"node:os";import{basename as b2,extname as PU,isAbsolute as vG,join as NJ}from"node:path";import{sync as LU}from"cross-spawn";function RJ(){let $={};for(let[Z,J]of G$)$[Z]=J;r(v5,$)}function SJ(){G$.clear();try{let $=JSON.parse(k2(v5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("lease file must contain an object");for(let[Z,J]of Object.entries($)){let Q=J;if(typeof Z!=="string"||!Z||Q.chatId!==Z||typeof Q.sessionName!=="string"||!F1(Q.sessionName)||typeof Q.createdAt!=="number"||!Number.isFinite(Q.createdAt)){j(`feishu: rejected malformed temp-session lease chat=${Z}`);continue}G$.set(Z,{chatId:Z,sessionName:Q.sessionName,createdAt:Q.createdAt})}j(`feishu: loaded ${G$.size} temporary-session leases`)}catch($){if($?.code!=="ENOENT")j(`feishu: load temp-session leases failed: ${$?.message??$}`)}}function CJ($,Z){if(!F1($))throw Error(`refusing to lease non-temporary session name "${$}"`);if(!Z)throw Error("cannot lease a temporary session without chat_id");for(let Y of G$.values())if(Y.sessionName===$&&Y.chatId!==Z)throw Error(`temporary session name "${$}" is already leased to ${Y.chatId}`);let J=G$.get(Z),Q={sessionName:$,chatId:Z,createdAt:Date.now()};G$.set(Z,Q);try{RJ()}catch(Y){if(J)G$.set(Z,J);else G$.delete(Z);throw Y}}function xJ($,Z){let J=G$.get(Z);return J?.sessionName===$&&J.chatId===Z}function qU($){return g.projects[$]}function c4($){return PJ($,EJ,g.projects)}function z8($){return DG($,EJ,g.projects)}function r0($,Z){let J=k$(Z);return new l0(`${$} failed ${w(Z)}`,J.status,J.code,J.retryAfter,J.logId,J.message)}function A7($,Z){let J=new H2;return hG.run(J,async()=>{try{return await G2($,()=>Z(J),{recovery:J})}catch(Q){if(!(Q instanceof Error&&Q.name==="AbortError"))await J.waitUntilDeadline();throw Q}})}function G8($,Z={}){return V0($,{...Z,signal:Z.signal??AbortSignal.timeout(H8)})}async function IG($,Z,J){let Q=Z.signal??AbortSignal.timeout(H8);try{return await D$(await G8($,{...Z,signal:Q}),J)}catch(Y){if(Q.aborted&&Q.reason?.name==="TimeoutError")throw Q.reason;throw Y}}async function s$($){if($?.timeoutMs(H8),L7&&Date.now()<NG)return L7;if(q7??=(async()=>{let Q=await IG("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:yG,app_secret:fG})},"tenant token");if(typeof Q.tenant_access_token!=="string"||!Q.tenant_access_token.trim())throw Error("feishu: tenant token MISS");return L7=Q.tenant_access_token,NG=Date.now()+Math.max(0,(Q.expire??7200)-60)*1000,L7})().finally(()=>{q7=null}),!$)return q7;let Z=q7,J=AbortSignal.timeout($.timeoutMs(60000));return new Promise((Q,Y)=>{let V=()=>{try{$.timeoutMs(1)}catch(X){Y(X);return}Y(J.reason)};J.addEventListener("abort",V,{once:!0}),Z.then((X)=>{J.removeEventListener("abort",V);try{$.timeoutMs(1),Q(X)}catch(z){Y(z)}},(X)=>{J.removeEventListener("abort",V),Y(X)})})}function bJ(){try{let $=JSON.parse(k2(x5,"utf8"));for(let[Z,J]of Object.entries($))if(typeof J==="string")U0.set(Z,J);j(`feishu: loaded ${U0.size} session→chat bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-chat-map failed: ${$?.message??$}`)}}function gG(){try{TJ()}catch($){j(`feishu: save session-chat-map failed: ${$}`)}}function TJ(){let $={};for(let[Z,J]of U0)$[Z]=J;r(x5,$)}function p4($,Z){if(U0.get($)===Z)return;let J=U0.get($);U0.set($,Z),gG(),j(`feishu: bound session "${$}" → ${Z}${J?` (was ${J})`:""}`)}function F7($){let Z=U0.get($);if(!Z)return;U0.delete($),gG(),j(`feishu: unbound session "${$}" from ${Z}`)}function V8($,Z){let J=C0.get($)??{};J[Z.provider]=Z,C0.set($,J)}function RG($,Z){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$,Q=a$(J.provider)?J.provider:Z??null;if(!Q||Z&&Q!==Z)return null;let Y=typeof J.sessionId==="string"?J.sessionId.trim():typeof J.session_id==="string"?J.session_id.trim():"";if(!Y)return null;if(J.cwd===void 0||J.cwd===null)return{provider:Q,sessionId:Y,cwd:null};if(typeof J.cwd!=="string"||!vG(J.cwd))return null;return{provider:Q,sessionId:Y,cwd:J.cwd}}function TG($){let Z=$.sessionId.trim();if(!Z)throw Error("cannot bind an empty conversation session id");if(!a$($.provider))throw Error(`cannot bind an unknown conversation provider: ${String($.provider)}`);if(typeof $.cwd!=="string"||!vG($.cwd))throw Error(`cannot bind a conversation without an absolute cwd: ${String($.cwd)}`);return{provider:$.provider,sessionId:Z,cwd:$.cwd}}function DU($,Z,J){if(typeof $!=="string")return TG($);if(!Z)throw Error("cannot bind a conversation without a provider");return TG({provider:Z,sessionId:$,cwd:J??null})}function kJ(){try{let $=JSON.parse(k2(b5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("resume map must contain an object");C0.clear();for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){V8(Z,{provider:"codex",sessionId:J.trim(),cwd:null});continue}if(!J||typeof J!=="object"||Array.isArray(J))continue;let Q=J,Y=RG(Q);if(Y){V8(Z,Y);continue}for(let V of IZ){let X=Q[V];if(typeof X==="string"&&X.trim()){V8(Z,{provider:V,sessionId:X.trim(),cwd:null});continue}let z=RG(X,V);if(z)V8(Z,z)}}j(`feishu: loaded ${C0.size} session→resume bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-resume-map failed: ${$?.message??$}`)}}function D7(){let $={};for(let[Z,J]of C0){let Q={};if(J.codex)Q.codex={...J.codex};if(J.claude)Q.claude={...J.claude};if(J.dsh)Q.dsh={...J.dsh};$[Z]=Q}r(b5,$)}function W8($,Z,J,Q){let Y=DU(Z,J,Q),V=C0.get($),X=V?{...V}:void 0,z=V?.[Y.provider];if(z?.sessionId===Y.sessionId&&z.cwd===Y.cwd)return;V8($,Y);try{D7()}catch(H){if(X)C0.set($,X);else C0.delete($);throw H}}function c1($,Z="codex"){let J=C0.get($)?.[Z];return J?{...J}:null}function u4($,Z){let J=C0.get($);if(!J||Z&&J[Z]===void 0)return;let Q={...J};if(!Z)C0.delete($);else{let Y={...J};if(delete Y[Z],!Y.codex&&!Y.claude)C0.delete($);else C0.set($,Y)}try{D7()}catch(Y){throw C0.set($,Q),Y}}function mG($){if(!$||typeof $!=="object")return null;let Z=$;if(!a$(Z.provider))return null;let J=typeof Z.sessionId==="string"?Z.sessionId.trim():"";if(!J)return null;let Q;if(Z.cwd===void 0||Z.cwd===null)Q=null;else if(typeof Z.cwd==="string"&&Z.cwd.trim())Q=Z.cwd;else return null;return{provider:Z.provider,sessionId:J,cwd:Q}}function pG($){if(!$||typeof $!=="object")return null;let Z=$,J=Z.source;if(!J||typeof J!=="object")return null;let Q=mG(J),Y=typeof Z.id==="string"?Z.id.trim():"";if(!Y||!Q)return null;if(Z.provider==="dsh"&&Z.kind==="event"&&Q.provider==="dsh"&&/^\d+$/.test(Y)&&Number.isSafeInteger(Number(Y)))return{provider:"dsh",kind:"event",id:Y,source:{...Q,provider:"dsh"}};if(Z.provider==="claude"&&Z.kind==="assistant-message"&&Q.provider==="claude")return{provider:"claude",kind:"assistant-message",id:Y,source:{...Q,provider:"claude"}};if(Z.provider==="codex"&&Z.kind==="turn"&&Q.provider==="codex")return{provider:"codex",kind:"turn",id:Y,source:{...Q,provider:"codex"}};return null}function cG($){if(!$||typeof $!=="object")return null;let Z=$;if(Z.kind==="fresh")return{kind:"fresh"};if(Z.kind!=="resume"&&Z.kind!=="fork")return null;let J=mG(Z.source);if(!J)return null;let Q=Z.kind==="resume"?{kind:"resume",source:J}:(()=>{if(!Object.prototype.hasOwnProperty.call(Z,"through"))return{kind:"fork",source:J};let Y=pG(Z.through);return Y?{kind:"fork",source:J,through:Y}:null})();if(!Q)return null;try{E0(Q,J.provider)}catch{return null}return Q}function MU($){if(!Array.isArray($))return[];return $.filter((Z)=>Z&&typeof Z.path==="string").map((Z)=>({tool:String(Z.tool??"Write"),path:String(Z.path),body:String(Z.body??"")})).filter((Z)=>Z.path!==""||Z.body!=="")}function UU($,Z){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.ts!=="number"||!Number.isFinite(J.ts))return null;let Q=Object.prototype.hasOwnProperty.call(J,"checkpoint"),Y=pG(J.checkpoint);if(Q&&!Y)return null;if(!Y){if(Z!=="claude")return null;let V=typeof J.uuid==="string"?J.uuid.trim():"",X=typeof J.sid==="string"?J.sid.trim():"";if(!V||!X)return null;Y={provider:"claude",kind:"assistant-message",id:V,source:{provider:"claude",sessionId:X,cwd:null}}}return{checkpoint:Y,preview:String(J.preview??""),ts:J.ts,writes:MU(J.writes)}}function OU($){if(!$||typeof $!=="object")return null;let Z=$,J=cG(Z.launch);if(J?.kind!=="fork"||J.source.provider!=="claude"||J.source.cwd===null)return null;let Q=Z.previousSessionId,Y=Q===null?null:typeof Q==="string"&&Q.trim()?Q.trim():void 0;if(Y===void 0)return null;return{launch:{...J,source:{...J.source,provider:"claude"}},previousSessionId:Y}}function wJ($){let Z=$.launch.through;if($.launch.source.provider!=="claude"||Z&&(Z.provider!=="claude"||Z.kind!=="assistant-message"||Z.source.provider!=="claude"))throw Error("pending conversation launch is not a Claude fork");return{launch:{kind:"fork",source:{...$.launch.source,provider:"claude"},...Z?{through:{...Z,provider:"claude",kind:"assistant-message",source:{...Z.source,provider:"claude"}}}:{}},previousSessionId:$.previousSessionId}}function vJ(){try{let $=JSON.parse(k2(k5,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("turns map must contain an object");W0.clear();let Z=0,J=0;for(let[Q,Y]of Object.entries($)){let V,X,z=null;if(Array.isArray(Y))V=Y,X=null;else if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let K=Y;if(!Array.isArray(K.anchors)||!Object.prototype.hasOwnProperty.call(K,"base")){J++;continue}if(V=K.anchors,K.base===null)X=null;else{let B=cG(K.base);if(!B){J++;continue}X=B}if(Object.prototype.hasOwnProperty.call(K,"pendingLaunch")){let B=OU(K.pendingLaunch);if(!B){J++;continue}z=B}}else{J++;continue}let H=C0.get(Q),G=H?.claude!==void 0&&H.codex===void 0?"claude":null,W=[];for(let K of V){let B=UU(K,G);if(B)W.push(B);else J++}if(W.length||X!==null||z)W0.set(Q,{base:X,anchors:W,...z?{pendingLaunch:z}:{}}),Z+=W.length}if(j(`feishu: loaded ${Z} turn anchors across ${W0.size} sessions`),J>0)j(`feishu: rejected ${J} malformed turn anchors while loading`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-turns-map failed: ${$?.message??$}`)}}function X8(){let $={};for(let[Z,J]of W0)$[Z]=J;r(k5,$)}function yJ($,Z){let J=W0.get($),Q=[...J?.anchors??[],Z],Y=J?.base??null;if(Q.length>EG){let V=Q.splice(0,Q.length-EG),X=V[V.length-1].checkpoint;Y={kind:"fork",source:X.source,through:X}}W0.set($,{base:Y,anchors:Q,...J?.pendingLaunch?{pendingLaunch:J.pendingLaunch}:{}});try{X8()}catch(V){if(J)W0.set($,J);else W0.delete($);throw V}}function l4($){return W0.get($)?.anchors??[]}function d4($){return W0.get($)?.base??null}function i4($){let Z=W0.get($)?.pendingLaunch;return Z?wJ(Z):null}function u1($,Z){if(Z){if(Z.launch.source.cwd===null)throw Error("pending conversation launch source cwd is missing");E0(Z.launch,"claude",Z.launch.source.cwd)}let J=W0.get($),Q=J?.base??null,Y=J?.anchors.slice()??[];if(!Z&&Y.length===0&&Q===null)W0.delete($);else W0.set($,{base:Q,anchors:Y,...Z?{pendingLaunch:wJ(Z)}:{}});try{X8()}catch(V){if(J)W0.set($,J);else W0.delete($);throw V}}function W$($,Z,J,Q){let Y=W0.get($),V=Q===void 0?Y?.pendingLaunch:Q??void 0,X=V?wJ(V):void 0;if(Z.length===0&&J===null&&!X)W0.delete($);else W0.set($,{base:J,anchors:Z.slice(),...X?{pendingLaunch:X}:{}});try{X8()}catch(z){if(Y)W0.set($,Y);else W0.delete($);throw z}}function F1($){return SG.test($)?$.replace(SG,""):null}function fJ($,Z=[]){let J=new Date,Q=(z)=>String(z).padStart(2,"0"),Y=`${Q(J.getMonth()+1)}${Q(J.getDate())}-${Q(J.getHours())}${Q(J.getMinutes())}`,V=new Set([...O0.values(),...W0.keys(),...Z]),X=`${$}*${Y}`;for(let z=2;V.has(X);z++)X=`${$}*${Y}-${z}`;return X}function hJ(){try{let $=JSON.parse(k2(w5,"utf8"));for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){i0.set(Z,{provider:x4(J),model:J,effort:null});continue}if(!J||typeof J!=="object")continue;let{model:Q,provider:Y}=J,V=a$(Y)?Y:typeof Q==="string"&&Q.trim()?x4(Q):"claude",X=typeof Q==="string"&&Q.trim()?Q:null;if(V==="claude"&&!X)continue;let{effort:z,tokenSourceId:H}=J,G=typeof H==="string"&&H.trim()?H.trim():null,W=V==="dsh"?S0(z)?z:null:V==="claude"?w0(z)?z:null:U$(z)?z:null;i0.set(Z,{provider:V,model:X,effort:W,...G?{tokenSourceId:G}:{}})}j(`feishu: loaded ${i0.size} session→model bindings`)}catch($){if($?.code!=="ENOENT")j(`feishu: load session-model-map failed: ${$?.message??$}`)}}function AU(){try{M7()}catch($){j(`feishu: save session-model-map failed: ${$}`)}}function M7(){let $={};for(let[Z,J]of i0)$[Z]=J;r(w5,$)}function NU($,Z,J,Q,Y){let V=i0.get($);if(V?.provider===Z&&V.model===J&&V.effort===Q&&(V.tokenSourceId??null)===(Y??null))return;i0.set($,{provider:Z,model:J,effort:Q,...Y?{tokenSourceId:Y}:{}}),AU()}function l1($,Z,J,Q,Y){let V=i0.get($),X={provider:Z,model:J,effort:Q,...Y?{tokenSourceId:Y}:{}};if(V?.provider===Z&&V.model===J&&V.effort===Q&&(V.tokenSourceId??null)===(Y??null))return;i0.set($,X);try{M7()}catch(z){if(V)i0.set($,V);else i0.delete($);throw z}}function IJ($){let Z=i0.get($);if(Z)return Z;let J=F1($);return J?i0.get(J)??null:null}function gJ($){let Z=U0.get($),J=C0.get($),Q=i0.get($),Y=W0.get($),V=[...G$.entries()].filter(([,X])=>X.sessionName===$);U0.delete($),C0.delete($),i0.delete($),W0.delete($);for(let[X]of V)G$.delete(X);try{TJ(),D7(),M7(),X8(),RJ()}catch(X){if(Z)U0.set($,Z);if(J)C0.set($,J);if(Q)i0.set($,Q);if(Y)W0.set($,Y);for(let[H,G]of V)G$.set(H,G);let z=[X];for(let H of[TJ,D7,M7,X8,RJ])try{H()}catch(G){z.push(G)}throw z.length===1?z[0]:AggregateError(z,`failed to clear and restore conversation state for ${$}`)}}function mJ($){r(f5,$)}function pJ(){let $;try{$=k2(f5,"utf8")}catch(J){if(J.code==="ENOENT")return[];throw J}let Z=JSON.parse($);if(!Array.isArray(Z)||Z.some((J)=>typeof J!=="string"||!J.trim()))throw Error("invalid alive session marker: expected non-empty session names");return Z}function N7($){let Z=U0.get($);if(Z){let Q=O0.get(Z);if(Q&&Q!==$)j(`feishu: chatIdForSession("${$}"): persisted binding ${Z} has cached name "${Q}", using persisted binding`);return Z}let J=[];for(let[Q,Y]of O0)if(Y===$)J.push(Q);if(J.length===1)return J[0];if(J.length>1)j(`feishu: chatIdForSession("${$}"): ${J.length} candidates with no binding — [${J.join(", ")}]`);return null}async function K8(){try{let $;do{let Z=await q0.im.chat.list({params:{page_size:100,...$?{page_token:$}:{}}});if(Z.code&&Z.code!==0)throw r0("feishu chat.list",Z);for(let J of Z.data?.items??[])if(J.chat_id&&J.name)O0.set(J.chat_id,J.name);$=Z.data?.page_token}while($);j(`feishu: refreshed chat list — ${O0.size} groups`)}catch($){j(`feishu: refresh chat list failed: ${$}`)}}async function R7(){let $=new Map,Z;do{let J=await q0.im.chat.list({params:{page_size:100,...Z?{page_token:Z}:{}}});if(J.code&&J.code!==0)throw r0("feishu chat.list",J);for(let Q of J.data?.items??[]){if(!Q.chat_id||!Q.name)continue;if(Q.chat_status&&Q.chat_status!=="normal")continue;O0.set(Q.chat_id,Q.name);let Y=$.get(Q.name)??[];Y.push(Q.chat_id),$.set(Q.name,Y)}Z=J.data?.page_token}while(Z);return $}async function T7($){let Z=U0.get($);if(Z&&O0.get(Z)===$){let V=await uG(Z);if(V.name===$&&lG(V.status))return Z;O0.delete(Z),F7($)}let Q=(await R7()).get($)??[];if(Q.length===0)return null;let Y=U0.get($);if(Y&&Q.includes(Y))return Y;if(Q.length===1)return Q[0];throw Error(`multiple Feishu groups named "${$}": ${Q.join(", ")}`)}async function cJ($,Z){if(!Z)throw Error("missing sender open_id; cannot add user to worktree group");let J=await T7($);if(J){let V=await RU(J,Z);return p4($,J),{chatId:J,created:!1,joined:V}}let Q=await q0.im.chat.create({params:{user_id_type:"open_id",uuid:O7()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Q.code&&Q.code!==0)throw r0("feishu chat.create",Q);let Y=Q.data?.chat_id;if(!Y)throw Error("feishu chat.create returned no chat_id");return O0.set(Y,$),p4($,Y),{chatId:Y,created:!0,joined:!0}}async function uJ($,Z){if(!Z)throw Error("missing sender open_id; cannot create temporary group");if(await T7($))throw Error(`temporary group name already exists: ${$}`);let Q=await q0.im.chat.create({params:{user_id_type:"open_id",uuid:O7()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Q.code&&Q.code!==0)throw r0("feishu chat.create",Q);let Y=Q.data?.chat_id;if(!Y)throw Error("feishu chat.create returned no chat_id");return O0.set(Y,$),p4($,Y),{chatId:Y,created:!0,joined:!0}}async function lJ($){let Z=await T7($);if(!Z)return F7($),{chatId:null,disbanded:!1};let J=await q0.im.chat.delete({path:{chat_id:Z}});if(J.code&&J.code!==0)throw r0("feishu chat.delete",J);if(O0.delete(Z),U0.get($)===Z)F7($);return{chatId:Z,disbanded:!0}}async function dJ($,Z){if(!Z)throw Error("cannot disband a temporary session without an exact chat_id");let J=await uG(Z);if(J.name!==$)throw Error(`refusing to delete chat ${Z}: expected name "${$}", got "${J.name??""}"`);if(!lG(J.status))throw Error(`refusing to delete chat ${Z}: status=${J.status??"unknown"}`);let Q=await q0.im.chat.delete({path:{chat_id:Z}});if(Q.code&&Q.code!==0)throw r0("feishu chat.delete",Q);return O0.delete(Z),{chatId:Z,disbanded:!0}}async function RU($,Z){let J;do{let Y=await q0.im.chatMembers.get({path:{chat_id:$},params:{member_id_type:"open_id",page_size:100,...J?{page_token:J}:{}}});if(Y.code&&Y.code!==0)throw r0("feishu chatMembers.get",Y);for(let V of Y.data?.items??[])if(V.member_id===Z)return!1;J=Y.data?.page_token}while(J);let Q=await q0.im.chatMembers.create({path:{chat_id:$},params:{member_id_type:"open_id"},data:{id_list:[Z]}});if(Q.code&&Q.code!==0)throw r0("feishu chatMembers.create",Q);return!0}async function iJ($){try{let Z=await s$(),J=await G8(`https://open.feishu.cn/open-apis/im/v1/chats/${encodeURIComponent($)}`,{headers:{Authorization:`Bearer ${Z}`}}),Y=(await D$(J,`fetchChatName ${$}`)).data?.name;if(typeof Y==="string"&&Y)return O0.set($,Y),j(`feishu: fetchChatName ${$} → "${Y}" (point lookup)`),Y;return j(`feishu: fetchChatName ${$} — chat has no name (unnamed group?)`),null}catch(Z){return j(`feishu: fetchChatName ${$} failed: ${Z}`),null}}async function E7($,Z,J,Q,Y){let V=O7();try{return await A7(`send${$} chat=${Z}`,async()=>{let X=await q0.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:Z,msg_type:J,content:Q,uuid:V}});if(X?.code!==0)throw r0(`send${$}`,X);let z=X?.data?.message_id;if(typeof z!=="string"||!z.trim())throw Error(`send${$} message_id MISS`);return z})}catch(X){return Y?.(X),null}}async function uG($){let Z=await q0.im.chat.get({path:{chat_id:$}});if(Z.code&&Z.code!==0)throw r0("feishu chat.get",Z);return{name:Z.data?.name??null,status:Z.data?.chat_status??null}}function lG($){return $===null||$==="normal"}async function k($,Z,J){return y$($,()=>E7("Text",$,"text",JSON.stringify({text:Z}),J))}async function o($,Z,J){return y$($,()=>E7("Card",$,"interactive",JSON.stringify(m1(Z)),J))}async function nJ($){return A7(`message.list chat=${$}`,async()=>{let Z=await q0.im.message.list({params:{container_id_type:"chat",container_id:$,sort_type:"ByCreateTimeDesc",page_size:1}});if(Z.code!==0)throw r0("feishu message.list",Z);if(!Array.isArray(Z.data?.items))throw Error("feishu message.list items MISS");if(Z.data.items.length===0)return null;let J=Z.data.items[0]?.message_id;if(typeof J!=="string"||!J.trim())throw Error("feishu message.list message_id MISS");return J})}async function n4($,Z){let J=JSON.stringify(m1(Z));await A7(`message.patch message=${$}`,async()=>{let Q=await q0.im.v1.message.patch({path:{message_id:$},data:{content:J}});if(Q?.code!==0)throw r0("feishu message.patch",Q)})}async function h($,Z){return y$($,()=>TU($,Z))}async function TU($,Z){try{let J=await s$(),Q=await G8("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id",{method:"POST",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:$,msg_type:"text",content:JSON.stringify({text:Z})})});return(await D$(Q,`sendTextRaw chat=${$}`)).data?.message_id??null}catch(J){return j(`feishu: sendTextRaw chat=${$} failed: ${J}`),null}}async function K$($,Z){if(!$)return null;try{let J=await q0.im.messageReaction.create({path:{message_id:$},data:{reaction_type:{emoji_type:Z}}});if(J?.code&&J.code!==0)throw r0("feishu messageReaction.create",J);return J?.data?.reaction_id??null}catch(J){return j(`feishu: addReaction ${Z} on ${$} failed: ${J}`),null}}async function g0($,Z){if(!$||!Z)return;try{let J=await q0.im.messageReaction.delete({path:{message_id:$,reaction_id:Z}});if(J?.code&&J.code!==0)throw r0("feishu messageReaction.delete",J)}catch(J){j(`feishu: deleteReaction ${Z} on ${$} failed: ${J}`)}}async function w2($,Z){if(!$){j("feishu: urgentApp skip — missing messageId");return}if(Z.length===0){j(`feishu: urgentApp skip — empty openIds (msg=${$})`);return}let J=await s$(),Q=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/urgent_app?user_id_type=open_id`;try{let Y=await G8(Q,{method:"PATCH",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({user_id_list:Z})}),X=(await D$(Y,`urgentApp ${$}`)).data?.invalid_user_id_list??[],z=Z.length-X.length;j(`feishu: urgentApp ${$} ok — delivered=${z}${X.length?` invalid=${X.length}`:""}`)}catch(Y){j(`feishu: urgentApp ${$} failed: ${Y}`)}}async function B8($,Z,J,Q){try{let Y=await s$(),V=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/resources/${Z}?type=${J}`,X=await G8(V,{headers:{Authorization:`Bearer ${Y}`}});if(!X.ok)await D$(X,`download ${J}`);let z=Buffer.from(await X.arrayBuffer());AJ(h5,{recursive:!0});let H=Q?Q.replace(/[^a-zA-Z0-9._-]/g,"_"):`${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}.png`,G=NJ(h5,`${Date.now()}-${O7()}-${H}`);return wG(G,z,{flag:"wx"}),j(`feishu: downloaded ${J} ${G} (${z.length}B)`),G}catch(Y){j(`feishu: download ${J} failed: ${Y instanceof Error?Y.message:Y}`);return}}function SU($){return EU.has(PU($).toLowerCase())}async function dG($,Z){let J=`upload${Z==="image"?"Image":"File"}`,Q;try{if(Q=new Blob([Uint8Array.from(await _U($))]),Q.size>S7)throw Error(`${b2($)} 超过 30 MB`)}catch(X){throw j(`feishu: ${J} local file validation failed ${$}: ${X}`),X}let Y=async(X)=>{let z=await s$(X),H=new FormData;if(Z==="image")H.append("image_type","message");else H.append("file_type","stream"),H.append("file_name",b2($));H.append(Z,Q,b2($));let G=X.timeoutMs(Z==="file"?CG:H8),K=(await IG(`https://open.feishu.cn/open-apis/im/v1/${Z}s`,{method:"POST",headers:{Authorization:`Bearer ${z}`},body:H,signal:AbortSignal.timeout(G)},J)).data?.[`${Z}_key`];if(typeof K!=="string"||!K.trim())throw Error(`${J} ${Z}_key MISS`);return K};if(Z==="image")return A7(`${J} ${$}`,Y);let V=new H2(xG,bG);return j(`feishu: ${J} ${$} started: bytes=${Q.size} timeout=${CG}ms maxAttempts=${bG+1} recovery=${xG}ms`),G2(`${J} ${$}`,()=>Y(V),{recovery:V})}async function aJ($,Z){try{let J=kG($);if(!J.isFile())return j(`feishu: uploadImageKey not a file — ${$}`),Z?.(Error("路径不是普通文件")),null;if(J.size>S7)return j(`feishu: uploadImageKey oversize — ${$} (${(J.size/1024/1024).toFixed(1)} MB)`),Z?.(Error(`${b2($)} 超过 30 MB`)),null}catch(J){return j(`feishu: uploadImageKey stat failed — ${$}: ${J}`),Z?.(J),null}try{return await dG($,"image")}catch(J){return Z?.(J),null}}async function C7($,Z,J){return y$($,()=>E7("Image",$,"image",JSON.stringify({image_key:Z}),J))}async function iG($,Z,J){return y$($,()=>E7("File",$,"file",JSON.stringify({file_key:Z}),J))}async function j8($,Z){try{let Y=kG(Z);if(!Y.isFile())return j(`feishu: uploadAndSend not a file — ${Z}`),await k($,`❌ 出站文件: 路径不是文件 — ${Z}`),!1;if(Y.size>S7)return j(`feishu: uploadAndSend oversize — ${Z} (${Y.size}B)`),await k($,`❌ 出站文件: ${b2(Z)} 超过 30 MB (${(Y.size/1024/1024).toFixed(1)} MB)`),!1}catch(Y){return j(`feishu: uploadAndSend stat failed — ${Z}: ${Y}`),await k($,`❌ 出站文件: 无法读取 ${Z} (${Y})`),!1}let J=SU(Z)?"image":"file",Q=J==="image"?"出站图片":"出站文件";try{let Y=await dG(Z,J),V,X=(H)=>{V=H},z=await(J==="image"?C7($,Y,X):iG($,Y,X));if(!z)return j(`feishu: uploadAndSend ${Z} send failed after upload`),await k($,`❌ ${Q}发送失败: ${b2(Z)}(上传已完成)
145
145
  ${w(V)}`),!1;return j(`feishu: uploadAndSend ${Z} delivered msg=${z}`),!0}catch(Y){return j(`feishu: uploadAndSend ${Z} failed: ${Y}`),await k($,`❌ ${Q}上传失败: ${b2(Z)} — ${w(Y)}`),!1}}function oJ($){AJ($,{recursive:!0}),j(`feishu: provisioned ${$}`);let Z=NJ(AG(),".codex","config.toml");try{AJ(NJ(AG(),".codex"),{recursive:!0});let J="";try{J=k2(Z,"utf8")}catch{}let Q=`[projects.${JSON.stringify($)}]`;if(!J.includes(Q)){let Y=J.trimEnd();J=`${Y}${Y?`
146
146
 
147
147
  `:""}${Q}
148
148
  trust_level = "trusted"
149
149
  `,wG(Z,J)}}catch(J){j(`feishu: codex trust write failed for ${$}: ${J}`)}try{jU("git init -q",{cwd:$,stdio:"ignore"})}catch{}}function _8($=d){let Z=LU(I9(),["login","status",...v.cliArgs($)],{timeout:1e4,shell:!1,encoding:"utf8",env:v.env($,{...process.env,...g.codex.env})});if(Z.error)j(`codex login status failed: ${Z.error.message}`);return Z.status===0&&/Logged in using ChatGPT/i.test(`${Z.stdout}
150
- ${Z.stderr}`)}function sJ($){return $.replace(/[^\w一-鿿\-\[\]\*]/g,"_").slice(0,64)}var fG,yG,EJ,G$,hG,p1=async($)=>{let J=hG.getStore()?.timeoutMs(H8),Q=J===void 0?void 0:AbortSignal.timeout(J);try{let Y=await U7.defaultHttpInstance.request({...$,...J===void 0?{}:{timeout:J,signal:Q},$return_headers:!0}),V=k$({data:Y.data,headers:Y.headers});if(V.logId&&Y.data&&typeof Y.data==="object"&&!Array.isArray(Y.data))Y.data.log_id=V.logId;return $.$return_headers?Y:Y.data}catch(Y){if(Q?.aborted&&Q.reason?.name==="TimeoutError")throw Q.reason;if(Y instanceof Error){let V=k$(Y);Y.message=w(Y),Object.assign(Y,{apiMessage:V.message,logId:V.logId})}throw Y}},DU,q0,H8=15000,L7="",NG=0,q7=null,O0,U0,C0,W0,EG=200,SG,i0,S7=31457280,CG=300000,xG=1920000,bG=5,EU;var Y0=R(()=>{u0();j4();zJ();P0();k0();j1();P0();H0();I();F0();b0();m4();d0();K2();OG();fG=g.feishu.app_id,yG=g.feishu.app_secret,EJ=g.runtime.projects_root,G$=new Map;hG=new BU,DU={request:p1,get:($,Z)=>p1({...Z,url:$,method:"GET"}),delete:($,Z)=>p1({...Z,url:$,method:"DELETE"}),head:($,Z)=>p1({...Z,url:$,method:"HEAD"}),options:($,Z)=>p1({...Z,url:$,method:"OPTIONS"}),post:($,Z,J)=>p1({...J,url:$,data:Z,method:"POST"}),put:($,Z,J)=>p1({...J,url:$,data:Z,method:"PUT"}),patch:($,Z,J)=>p1({...J,url:$,data:Z,method:"PATCH"})},q0=new U7.Client({appId:fG,appSecret:yG,disableTokenCache:!1,httpInstance:DU});O0=new Map,U0=new Map;C0=new Map;W0=new Map;SG=/\*[0-9]{4}-[0-9]{4}(-[0-9]+)?$/;i0=new Map;EU=new Set([".png",".jpg",".jpeg",".gif",".bmp",".webp"])});async function nG($=(Z)=>new w$({accountId:Z})){if(k1(d))throw Error("默认账号正在登录,请先完成默认账号授权,再添加额外账号。");let Z,J,Q;try{Z=$(d),await Z.initialize("lodestar-login-check"),Q=await i$(()=>Z.request("account/read",{refreshToken:!1}),"默认账号登录检查")}catch(Y){J=Error(`默认账号登录检查失败:${a4(Y).message}`,{cause:Y})}if(!J){if(Q?.account===null||Q?.account?.type==="apiKey")J=Error("默认账号未登录 ChatGPT,请先发送不带备注的 codex-login 完成登录,再添加额外账号。");else if(Q?.account?.type!=="chatgpt")J=Error("默认账号登录检查失败:account/read 返回的账号状态无效")}if(Z)try{if(await Z.close(),Z.isAlive())throw Error("检查进程仍未退出")}catch(Y){J=Error([J?.message,`默认账号检查进程关闭失败:${a4(Y).message}`].filter(Boolean).join(";"),{cause:Y})}if(J)throw J}class aG{createClient;waitMs;recordLogin;stateWaitMs;attempts=new Map;stopping=!1;constructor($=(Y)=>new w$({accountId:Y,login:!0}),Z=900000,J=(Y,V)=>{v.recordLogin(Y,V),d$(Y)},Q=1e4){this.createClient=$;this.waitMs=Z;this.recordLogin=J;this.stateWaitMs=Q}async start($,Z){if(this.stopping)throw Error("服务正在退出,无法开始登录");if(!Z.userOpenId)throw Error("无法确认登录发起者");if(this.attempts.has($))throw Error("该账号已有登录任务;使用 codex-login-cancel 取消后再登录");let J=_z($),Q;try{Q=this.createClient($)}catch(H){throw J(),H}let Y,V,X=new Promise((H,G)=>{Y=H,V=G});X.catch(()=>{});let z={owner:Z,client:Q,accountId:$,loginId:null,loginRequested:!1,loginSucceeded:!1,authUpdated:!1,finishing:!1,done:X,resolve:Y,reject:V,timer:null,notification:()=>{},closed:()=>{},early:[],releaseAuth:J};z.notification=(H,G)=>{if(z.finishing||!z.loginRequested)return;if(H==="account/updated"){if(G?.authMode==="chatgpt"){if(z.authUpdated=!0,z.loginSucceeded)this.finish(z)}return}if(H!=="account/login/completed")return;if(!z.loginId){z.early.push(G);return}if(G?.loginId!==z.loginId)return;if(G?.success!==!0){this.finish(z,Error(typeof G?.error==="string"?G.error:"Codex 登录未成功"));return}if(z.loginSucceeded)return;if(z.loginSucceeded=!0,j(`codex-login: authorization completed account=${$} authUpdated=${z.authUpdated}`),z.timer)clearTimeout(z.timer);if(z.authUpdated)this.finish(z);else z.timer=setTimeout(()=>{this.finish(z,Error("设备码授权已完成,但 Codex 未及时更新账号状态;认证文件已保留,可用 codex-accounts 检查"))},this.stateWaitMs)},z.closed=(H)=>{this.finish(z,H)},Q.on("notification",z.notification),Q.on("closed",z.closed),Q.on("protocolError",z.closed),this.attempts.set($,z);try{await Q.initialize("lodestar-login"),z.loginRequested=!0;let H=await Q.request("account/login/start",{type:"chatgptDeviceCode"},30000);if(H?.type!=="chatgptDeviceCode"||typeof H.loginId!=="string"||!H.loginId||typeof H.userCode!=="string"||!H.userCode||typeof H.verificationUrl!=="string"||new URL(H.verificationUrl).protocol!=="https:")throw Error("Codex 设备码登录响应不完整");if(z.loginId=H.loginId,z.finishing)throw await X,Error("登录已结束");z.timer=setTimeout(()=>{this.cancelAttempt(z,"登录等待超过 15 分钟,请重新发送 codex-login [备注]").catch(()=>{})},this.waitMs);for(let G of z.early)z.notification("account/login/completed",G);return z.early.length=0,{accountId:$,loginId:H.loginId,verificationUrl:H.verificationUrl,userCode:H.userCode,done:X}}catch(H){return await this.finish(z,a4(H)),await X}}pending($){return[...this.attempts.values()].filter((Z)=>Z.owner.chatId===$.chatId&&Z.owner.userOpenId===$.userOpenId).map((Z)=>Z.accountId)}async cancel($,Z){let J=this.attempts.get($);if(!J)throw Error("该账号没有等待中的登录");if(!Z.userOpenId||Z.chatId!==J.owner.chatId||Z.userOpenId!==J.owner.userOpenId)throw Error("只有发起登录的用户可在原群取消");if(J.finishing)throw Error("登录正在收尾,请等待结果");await this.cancelAttempt(J,"登录已取消")}async cancelAttempt($,Z){if($.finishing)return;$.finishing=!0;let J=Error(Z);if($.loginId&&$.client.isAlive())try{await $.client.request("account/login/cancel",{loginId:$.loginId})}catch(Q){J=Error(`${Z};取消请求失败:${a4(Q).message}`)}await this.complete($,J)}async finish($,Z){if($.finishing)return;if($.finishing=!0,$.timer)clearTimeout($.timer);let J;if(!Z)try{let Q=await $.client.request("account/read",{refreshToken:!1});if(Q?.account?.type!=="chatgpt"){let Y=typeof Q?.account?.type==="string"?Q.account.type:"null";throw Error(`设备码授权已完成,但账号状态校验失败(account/read.type=${Y});认证文件已保留`)}J=Q.account,this.recordLogin($.accountId,J)}catch(Q){Z=a4(Q)}await this.complete($,Z,J)}async complete($,Z,J){if($.timer)clearTimeout($.timer);$.client.off("notification",$.notification),$.client.off("closed",$.closed),$.client.off("protocolError",$.closed);try{await $.client.close()}catch(Q){Z=Error([Z?.message,`登录进程关闭失败:${a4(Q).message}`].filter(Boolean).join(";"))}if(!$.client.isAlive())this.attempts.delete($.accountId),$.releaseAuth();if(Z)$.reject(Z);else if(J)$.resolve(J);else $.reject(Error("登录结束但账号信息缺失"))}async shutdown(){this.stopping=!0;let Z=(await Promise.allSettled([...this.attempts.values()].map(async(J)=>{if(await this.cancelAttempt(J,"服务退出,登录已取消"),J.client.isAlive())await J.client.close();if(J.client.isAlive())throw Error("登录进程仍未退出");J.releaseAuth(),this.attempts.delete(J.accountId),await J.done.then(()=>{},()=>{})}))).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 登录进程未完全退出")}}function a4($){return $ instanceof Error?$:Error(String($))}var v2;var tJ=R(()=>{z$();F0();I();v2=new aG});import{readFileSync as CU}from"node:fs";import{homedir as xU}from"node:os";import{join as rG}from"node:path";function kU(){return process.env.CLAUDE_CONFIG_DIR||rG(xU(),".claude")}function rJ(){try{let $=CU(rG(kU(),"settings.json"),"utf8"),Z=JSON.parse($)?.env;return Z&&typeof Z==="object"?Z:{}}catch($){return j(`glm-usage: read settings.json env failed: ${$}`),{}}}function f2($){try{let Z=new URL($).hostname.toLowerCase();return Z==="open.bigmodel.cn"||Z==="dev.bigmodel.cn"||Z==="api.z.ai"}catch{return!1}}function wU($){try{let Z=new URL($);return`${Z.protocol}//${Z.host}`}catch{return null}}function vU($){let Z=wU($);return Z&&f2($)?Z:null}function sG($){return typeof $==="number"&&isFinite($)?Math.max(0,Math.min(100,$)):null}function tG($){return typeof $==="number"&&isFinite($)&&$>0?new Date($):null}function fU($){let Z=Array.isArray($)?$:Array.isArray($?.limits)?$.limits:void 0;if(!Z)return{state:"network",reason:"GLM 额度响应缺少 limits 数组"};let J=Z.filter((W)=>W?.type==="TOKENS_LIMIT"||W?.type==="CREDIT_LIMIT"),Q=J.find((W)=>W?.unit===3&&W?.number===5),Y=J.find((W)=>W?.unit===6&&W?.number===1),V=Z.find((W)=>W?.type==="TIME_LIMIT"),X=(W)=>W?{percent:sG(W.percentage),resetsAt:tG(W.nextResetTime)}:null,z=X(Q),H=X(Y),G=V?{percent:sG(V.percentage),resetsAt:tG(V.nextResetTime),...typeof V.currentValue==="number"?{used:V.currentValue}:{},...typeof V.usage==="number"?{total:V.usage}:{}}:null;if(!z&&!H&&!G)return{state:"network",reason:"GLM 额度响应没有可识别的额度窗口"};return{state:"ok",level:typeof $?.level==="string"&&$.level?$.level:void 0,fiveHour:z,weekly:H,monthly:G,fetchedAt:Date.now()}}async function x7($,Z){let J=$!==void 0||Z!==void 0?{ANTHROPIC_BASE_URL:$,ANTHROPIC_AUTH_TOKEN:Z}:rJ(),Q=J.ANTHROPIC_AUTH_TOKEN,Y=J.ANTHROPIC_BASE_URL||"";if(!Q)return{state:"no_credentials"};let V=vU(Y);if(!V)return{state:"not_glm",baseUrl:Y||void 0};return bU.readStale(O$("glm",V,Q),()=>yU(V,Q))}async function yU($,Z){let J=`${$}/api/monitor/usage/quota/limit`,Q=new AbortController,Y=setTimeout(()=>Q.abort(),oG);try{let V=await V0(J,{headers:{Authorization:Z,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:Q.signal});if(!V.ok)return j(`glm-usage: quota/limit HTTP ${V.status}`),{state:V.status===429?"rate_limited":"network",reason:`HTTP ${V.status}`,retryAfterMs:l$(V.headers)};let X=await V.json(),z=X?.error?.code??X?.code;if(X?.success===!1||X?.error!=null||z!==void 0&&String(z)!=="200"){let W=X?.error?.message??X?.msg??X?.message??(typeof X?.error==="string"?X.error:void 0),K=[z===void 0?"":`code ${z}`,W===void 0?"":String(W)].filter(Boolean).join(": ").replaceAll(Z,"[redacted]")||"GLM 额度接口返回失败";return j(`glm-usage: quota/limit MISS: ${K}`),{state:String(z)==="429"?"rate_limited":"network",reason:K,retryAfterMs:l$(V.headers)}}let H=X?.data??X,G=fU(H);if(G.state==="network")j(`glm-usage: quota/limit MISS: ${G.reason}`);return G}catch(V){let X=(V?.name==="AbortError"?`timeout ${oG}ms`:V?.message??String(V)).replaceAll(Z,"[redacted]");return j(`glm-usage: quota/limit fetch failed: ${X}`),{state:"network",reason:X}}finally{clearTimeout(Y)}}var oG=1e4,bU;var b7=R(()=>{u0();I();_1();bU=new X$});function r$($){let Z=new URL($);if(!["http:","https:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("PackyAPI 地址必须是无凭据、查询参数和 fragment 的 HTTP(S) API 根地址");return Z.pathname=Z.pathname.replace(/\/+$/,"").replace(/\/v1$/,""),Z.toString().replace(/\/$/,"")}function o4($){let Z=r$($),J=new URL(Z);return J.protocol==="https:"&&!J.port&&J.pathname==="/"&&["cf.api.fan","slb-v1.api.fan","www.packyapi.ai"].includes(J.hostname)?hU:Z}function eJ($,Z){let J=r$($),Q=O$("packy-models",J,Z),Y=k7.get(Q);if(Y)return Y;let V=u$(`${J}/v1/models`,Z,"PackyAPI models").then((X)=>{let z=new Set;return X.map((H)=>{if(typeof H.id!=="string"||!H.id.trim()||z.has(H.id)||!Array.isArray(H.supported_endpoint_types)||!H.supported_endpoint_types.length||!H.supported_endpoint_types.every((G)=>typeof G==="string"&&G))throw Error("PackyAPI 模型目录缺少有效 id/协议声明,或含重复模型");return z.add(H.id),{id:H.id,display:typeof H.name==="string"&&H.name?H.name:H.id,protocols:[...H.supported_endpoint_types],...t$(H.reasoning)?{reasoning:H.reasoning}:{}}})}).finally(()=>{if(k7.get(Q)===V)k7.delete(Q)});return k7.set(Q,V),V}function t$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function v7($,Z,J={}){let Q=await V0($,{headers:{Accept:"application/json","Cache-Control":"no-cache","User-Agent":"Lodestar-Account-Balance/1.0",...J,...Z?{Authorization:`Bearer ${Z}`}:{}},redirect:"error",signal:AbortSignal.timeout(15000)}),Y=await Q.text(),V;try{V=JSON.parse(Y)}catch{throw new F1(Q.status,"响应不是有效 JSON",l$(Q.headers))}let X=t$(V)?V.code:void 0,z=X!==void 0&&![!0,0,200,"0","200"].some((H)=>H===X);if(!Q.ok||!t$(V)||V.success===!1||z||V.error!=null){let H=t$(V)&&t$(V.error)?V.error.message:t$(V)?V.message:null;throw new F1(Q.status,typeof H==="string"?H:"上游接口返回错误",l$(Q.headers))}return V}async function $Q($,Z,J,Q=!1){if(Z=Z.trim(),J=J.trim(),!Z||!/^[1-9]\d*$/.test(J)||!Number.isSafeInteger(Number(J)))return{state:"no_credentials",kind:"balance",windows:[],reason:"PackyAPI 真实余额需要系统访问令牌和正整数用户 ID;请配置 packy-balance-setup。"};let Y=r$($),V=O$("packy-balance",Y,JSON.stringify([J,Z])),X=async()=>{try{let H=await v7(`${Y}/api/user/self`,Z,{"New-Api-User":J}),G=H.data;if(H.success!==!0||!t$(G)||G.id!==Number(J))throw Error("PackyAPI 账户响应缺少成功状态,或用户 ID 与余额凭据不匹配");if(typeof G.quota!=="number"||!Number.isSafeInteger(G.quota))throw Error("PackyAPI 账户余额 quota 缺失或无效");let W=(await v7(`${Y}/api/status`)).data;if(!t$(W)||typeof W.quota_per_unit!=="number"||!Number.isFinite(W.quota_per_unit)||W.quota_per_unit<=0||W.quota_display_type!=="USD")throw Error("PackyAPI 账户余额单位缺失或不是已支持的 USD 单位");let K=G.quota/W.quota_per_unit;if(!Number.isFinite(K))throw Error("PackyAPI 账户余额换算结果无效");return{state:"ok",kind:"balance",windows:[],fetchedAt:Date.now(),balance:{remaining:K,currency:"USD"}}}catch(H){let G=y0(H,[Z]);return j(`PackyAPI balance MISS: ${G}`),{state:H instanceof F1&&[401,403].includes(H.status)?"no_credentials":H instanceof F1&&H.status===429?"rate_limited":"network",kind:"balance",windows:[],reason:G,...H instanceof F1&&H.retryAfterMs!==void 0?{retryAfterMs:H.retryAfterMs}:{}}}};if(!Q)return w7.readStale(V,X);let z=await X();if(z.state==="ok")w7.prime(V,z);else w7.invalidate(V);return z}async function eG($,Z){if(!Z)return{state:"no_credentials",kind:"quota",windows:[]};let J=o4($);return w7.readStale(O$("packy",J,Z),async()=>{try{let Y=(await v7(`${J}/api/usage/token/`,Z)).data;if(!t$(Y)||typeof Y.unlimited_quota!=="boolean")throw Error("PackyAPI 令牌配额响应缺少 unlimited_quota");if(Y.unlimited_quota)return{state:"not_applicable",kind:"balance",windows:[],reason:"此 API key 为无限额度令牌;令牌接口不提供账户余额,需要系统访问令牌查询。"};let{total_available:V,total_granted:X}=Y;if(typeof V!=="number"||!Number.isFinite(V)||typeof X!=="number"||!Number.isFinite(X)||X<0)throw Error("PackyAPI 令牌配额数值缺失或无效");let z=(await v7(`${J}/api/status`)).data;if(!t$(z)||typeof z.quota_per_unit!=="number"||!Number.isFinite(z.quota_per_unit)||z.quota_per_unit<=0||z.quota_display_type!=="USD")throw Error("PackyAPI 配额单位缺失或不是已支持的 USD 额度单位");return{state:"ok",kind:"quota",windows:[],fetchedAt:Date.now(),quota:{remaining:V/z.quota_per_unit,limit:X/z.quota_per_unit,currency:"USD"}}}catch(Q){let Y=y0(Q,[Z]);return j(`PackyAPI quota MISS: ${Y}`),{state:Q instanceof F1&&[401,403].includes(Q.status)?"no_credentials":Q instanceof F1&&Q.status===429?"rate_limited":"network",kind:"quota",windows:[],reason:Y,...Q instanceof F1&&Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{}}}})}var y2="https://cf.api.fan",hU="https://www.packyapi.ai",k7,F1,w7;var ZQ=R(()=>{u0();_4();_1();I();k7=new Map;F1=class F1 extends Error{status;retryAfterMs;constructor($,Z,J){super(`PackyAPI HTTP ${$}: ${Z}`);this.status=$;this.retryAfterMs=J}};w7=new X$});function $W($){return h7.find((Z)=>Z.other===$)?.id??$}function ZW($){let Z=h7.find((J)=>J.id===$||J.other===$);return Z?[Z.id,Z.other]:[$]}function P8($){let Z=$.api_key?.trim(),J=$.auth_token?.trim();if(Z&&J&&Z!==J)throw Error("同一账号的 api_key 与 auth_token 不一致,请重新配置");return Z||J}function y7($,Z){if($.id==="packy")return r$(Z);let J=new URL(Z);if(!["http:","https:"].includes(J.protocol)||J.username||J.password||J.search||J.hash)throw Error(`${$.id} 接口地址必须是无凭据、查询参数和 fragment 的 HTTP(S) 地址`);if($.id==="glm")return T9(`${J.origin}/api/anthropic`);if(J.pathname=J.pathname.replace(/\/+$/,""),J.hostname==="api.deepseek.com"&&["/","/v1"].includes(J.pathname))J.pathname="/anthropic";return J.toString().replace(/\/+$/,"")}function f7($,Z){let J=y7($,Z);return $.id==="deepseek"?J.replace(/\/anthropic$/,""):J}function s4($){let{api_key:Z,auth_token:J,base_url:Q,...Y}=$;return Y}function JQ($,Z,J={}){let Q=Z[$.id]??{},Y=Z[$.other]??{},V=P8(Q),X=P8(Y),z=Q.base_url?.trim(),H=Y.base_url?.trim();if(V&&X&&V!==X||z&&H&&f7($,z)!==f7($,H))throw Error(`${$.id} 与 ${$.other} 的旧账号配置冲突;请用 ${$.id}-setup 重新设置共享账号`);if(V||X)return{key:V||X,base:y7($,z||H||$.base)};let G=J[$.id]??J[$.other]??{};if(P8(G)&&(z||H)&&G.base_url&&f7($,z||H)!==f7($,G.base_url))throw Error(`${$.id} 的平台地址与本机识别的账号不一致,请用 ${$.id}-setup 配置 Key`);return{key:P8(G),base:y7($,z||H||G.base_url||$.base)}}function L8($,Z={}){let J={...$};for(let Q of h7){let{key:Y,base:V}=JQ(Q,$,Z);J[Q.id]={...s4($[Q.id]??{}),base_url:V,...Q.id==="glm"?{auth_token:Y??""}:{api_key:Y??""}},J[Q.other]={...s4($[Q.other]??{}),api_key:Y??"",base_url:Q.id==="glm"?`${new URL(V).origin}/api/coding/paas/v4`:Q.id==="deepseek"?V.replace(/\/anthropic$/,""):V}}return IU(J),J}function IU($){let Z=new Set(["packy","packy-secondary","packy-codex"]),J=new Set,Q=new Set,Y=(X)=>!!(X.management_token?.trim()||X.management_user_id?.trim()||X.management_url?.trim()),V=(X)=>{if(Q.has(X))throw Error(`PackyAPI 余额账号引用循环:${X}`);if(J.has(X))return $[X];Q.add(X);let z=$[X]??{},H=z.billing_source?.trim(),G=H||(X==="packy-codex"&&!Y(z)?"packy":void 0);if(G){if(!Z.has(G)||!$[G])throw Error(`PackyAPI 余额账号引用不存在:${G}`);if(H&&Y(z))throw Error(`PackyAPI ${X} 不能同时配置 billing_source 和独立余额凭据`);let W=V(G);$[X]={...z,...H||Y(W)||W.billing_source?{billing_source:G,management_token:W.management_token,management_user_id:W.management_user_id,management_url:W.management_url||o4(W.base_url||y2)}:{}}}return Q.delete(X),J.add(X),$[X]??z};for(let X of Z)if($[X])V(X)}function QQ($,Z,J){let Q=Object.fromEntries(Object.entries(J).filter(([,H])=>H!==void 0)),Y={...$,[Z]:{...$[Z],...Q}},V=h7.find((H)=>H.id===Z||H.other===Z);if(!V)return{[Z]:Y[Z]};let X=J.api_key!==void 0||J.auth_token!==void 0,z=J.base_url!==void 0;if(X||z){let H=$[Z]??{},G=$[V.id]??{},W=$[V.other]??{},K=X?P8(J):JQ(V,$).key,B=y7(V,J.base_url?.trim()||H.base_url||G.base_url||W.base_url||V.base);Y[V.id]={...s4(Y[V.id]??{}),base_url:B,...V.id==="glm"?{auth_token:K??""}:{api_key:K??""}},Y[V.other]=s4(Y[V.other]??{})}else{let{key:H,base:G}=JQ(V,Y);Y[V.id]={...s4(Y[V.id]??{}),base_url:G,...V.id==="glm"?{auth_token:H??""}:{api_key:H??""}},Y[V.other]=s4(Y[V.other]??{})}return{[V.id]:Y[V.id],[V.other]:Y[V.other]}}var h7;var q8=R(()=>{E9();ZQ();h7=[{id:"deepseek",other:"deepseek-harness",base:"https://api.deepseek.com/anthropic"},{id:"glm",other:"dsh-glm",base:"https://open.bigmodel.cn/api/anthropic"},{id:"packy",other:"packy-codex",base:"https://cf.api.fan"}]});function mU($){let Z=new URL($),J=Z.pathname.replace(/\/+$/,"");return`${Z.protocol}//${Z.host}${J}/v1/messages`}async function I7($,Z,J){try{let Q=await V0(mU($),{method:"POST",headers:{"Content-Type":"application/json",...Z},body:JSON.stringify({model:J,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:AbortSignal.timeout(gU)});if(Q.ok)return"exists";if(Q.status===400){let Y=await Q.text();return Y.includes("1214")||Y.includes("不存在")||Y.includes("not exist")?"not_found":"no_verdict"}return j(`model-existence: ${J} HTTP ${Q.status}, no verdict`),"no_verdict"}catch(Q){return j(`model-existence: ${J} MISS (${Q?.message??Q})`),"no_verdict"}}var gU=15000;var YQ=R(()=>{u0();I()});function JW($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function pU($){return{kind:"monthly",label:"月度工具",percent:$.percent,resetsAt:$.resetsAt,...$.used!=null?{used:$.used}:{},...$.total!=null?{total:$.total}:{}}}function QW($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function cU($){let Z=(J)=>{let Q=J.match(/(\d+(?:\.\d+)?)/);return Q?Number(Q[1]):-1};return[...$].sort((J,Q)=>Z(Q)-Z(J))[0]??""}function uU($){let Z={};for(let J of($??"").split(",")){let Q=J.indexOf("=");if(Q<=0)continue;let Y=J.slice(0,Q).trim().toLowerCase(),V=J.slice(Q+1).trim();if((Y==="opus"||Y==="sonnet"||Y==="haiku")&&V)Z[Y]=V}return Z}function VQ($){if($.state!=="ok")return{state:$.state==="no_credentials"?"no_credentials":$.state==="not_glm"?"not_applicable":$.state==="rate_limited"?"rate_limited":"network",windows:[],..."retryAfterMs"in $?{retryAfterMs:$.retryAfterMs}:{},...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(JW($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(JW($.weekly,"weekly","周额度"));if($.monthly)Z.push(pU($.monthly));return{state:"ok",planLabel:$.level?`${$.level} 套餐`:void 0,windows:Z,fetchedAt:$.fetchedAt}}var XQ=R(()=>{X0();b7();y4();o9();YQ();I();E9();N0({kind:"glm-coding-plan",configSectionId:"glm",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||"",Q=$.auth_token?.trim()||Z?.auth_token?.trim()||"",Y=!!(J&&Q)&&f2(J),V=$.model?.trim()||void 0,X=uU($.slots),z={id:"glm",kind:"glm-coding-plan",agent:"claude",display:$.display?.trim()||"GLM Coding Plan",enabled:Y,models:[],modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!z.enabled){z.models=[],z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}z.modelCatalogState={status:"loading",updatedAt:null};try{let H=await rH(J,Q),W=[...new Set([...QW($.models),...QW($.custom_models)])].filter((K)=>!H.some((B)=>B.model.toLowerCase()===K.toLowerCase())).map((K)=>({model:K,display:K,efforts:f4,defaultEffort:"max",origin:"custom"}));if(z.models=[...H,...W],!V)z.defaultModel=cU(z.models.map((K)=>K.model));for(let K of z.models){let B=k4("glm",K.model);K.context1m=B!=null&&B>=1e6||void 0}z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(H){j(`glm refreshModels MISS: ${H?.message??H}`),z.models=[],z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:H?.message??String(H)}}},spawnEnv(H){let W={...o0(H)};if(W.ANTHROPIC_BASE_URL=J,W.ANTHROPIC_AUTH_TOKEN=Q,X.opus)W.ANTHROPIC_DEFAULT_OPUS_MODEL=X.opus;if(X.sonnet)W.ANTHROPIC_DEFAULT_SONNET_MODEL=X.sonnet;if(X.haiku)W.ANTHROPIC_DEFAULT_HAIKU_MODEL=X.haiku;return W},resolveSpawnModel(H){return e3("glm",H)},async verifyModel(H){return I7(J,{Authorization:`Bearer ${Q}`},H)},async readUsage(){return VQ(await x7(J,Q))}};return z},setup:{commandSuffix:"glm",hint:($)=>`配置 ${$}:发送 \`glm-setup <api_key>\`(智谱国内站),或 \`glm-setup <base_url> <api_key>\`(指定平台)。Claude Code 和 DeepSeek Harness 共用该账号;校验失败保留原配置。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:glm-setup <api_key>,或 glm-setup <base_url> <api_key>;只填写 Key 本身,不加 Bearer 前缀。"};try{return{config:{agent:"claude",base_url:T9(Z.length===2?Z[0]:P4),auth_token:Z.at(-1)}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}},async validate($){await L4($.base_url??P4,$.auth_token??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!f2(Z))return null;let J=$.ANTHROPIC_AUTH_TOKEN?.trim()??"";return J?{base_url:Z,auth_token:J}:null}}})});var YW=R(()=>{X0();y4();N0({kind:"claude-native",configSectionId:"claude-native",build:($)=>{let Z={id:"claude-native",kind:"claude-native",agent:"claude",display:$.display?.trim()||"Claude",enabled:!1,models:[],modelCatalogState:{status:"disabled",updatedAt:Date.now()},defaultModel:$.model?.trim()||"opus",settingSources:["user","project","local"],async refreshModels(){if(Z.models=[],!Z.enabled){Z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}Z.modelCatalogState={status:"loading",updatedAt:null};try{if(Z.models=await z7(),!Z.models.some((J)=>J.model===Z.defaultModel))throw Error("Claude 默认模型不在 SDK 目录中");Z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(J){throw Z.models=[],Z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:J instanceof Error?J.message:String(J)},J}},spawnEnv(J){return J},resolveSpawnModel(J){return J},async readUsage(){return{state:"not_applicable",windows:[]}}};return Z}})});import{homedir as lU}from"node:os";function m7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function g7($,Z,J){if($==null)return{kind:Z,label:J,percent:null,resetsAt:null};if(!m7($))throw Error(`Claude ${J}格式无效`);let Q=$.utilization;if(Q!==null&&(typeof Q!=="number"||!Number.isFinite(Q)||Q<0||Q>100))throw Error(`Claude ${J} utilization 缺失或无效`);let Y=$.resets_at;if(Y!==null&&(typeof Y!=="string"||!Number.isFinite(Date.parse(Y))))throw Error(`Claude ${J} resets_at 缺失或无效`);return{kind:Z,label:J,percent:Q,resetsAt:Y===null?null:new Date(Y)}}function XW($){return $.trim().toLowerCase().replace(/^claude:/,"").replace(/\[1m\]$/,"").replace(/^claude[-\s]+/,"").replace(/^(?:\d+[.-])+/,"").split(/[-\s]+/,1)[0]}function zW($,Z){if($.state!=="ok"||!Z?.trim())return null;let J=XW(i9(Z.trim()));if(!J||J==="default")return null;let Q=$.windows.filter((Y)=>{let V=Y.kind.startsWith("modelWeekly:")?Y.kind.slice(12):Y.kind==="seven_day_opus"?"opus":Y.kind==="seven_day_sonnet"?"sonnet":null;return V!==null&&XW(V)===J});if(Q.length>1)return j(`Claude weekly usage MISS: ${Z} 匹配多个模型专属周额度窗口`),null;if(Q.length===1)return Q[0];return $.windows.find((Y)=>Y.kind==="weekly")??null}function iU($){if(!m7($)||typeof $.subscription_type!=="string"||!$.subscription_type.trim())throw Error("Claude 订阅额度响应缺少订阅身份");if($.rate_limits_available!==!0)throw Error("Claude 原生接口未开放当前订阅额度查询");if(!m7($.rate_limits))throw Error("Claude 原生额度接口未返回 rate_limits 数据");let Z=$.rate_limits,J=[g7(Z.five_hour,"fiveHour","5h 窗口"),g7(Z.seven_day,"weekly","周额度")],Q=Z.five_hour!=null||Z.seven_day!=null;for(let[Y,V]of[["seven_day_oauth_apps","OAuth 应用周额度"],["seven_day_opus","Opus 周额度"],["seven_day_sonnet","Sonnet 周额度"]]){if(Z[Y]==null)continue;J.push(g7(Z[Y],Y,V)),Q=!0}if(Z.model_scoped!=null){if(!Array.isArray(Z.model_scoped))throw Error("Claude 模型专属额度 model_scoped 格式无效");for(let Y of Z.model_scoped){if(!m7(Y)||typeof Y.display_name!=="string"||!Y.display_name.trim())throw Error("Claude 模型专属额度缺少模型名称");let V=Y.display_name.trim();J.push(g7(Y,`modelWeekly:${V}`,`${V} 周额度`)),Q=!0}}if(!Q)throw Error("Claude 原生额度接口未返回任何订阅额度窗口");return{state:"ok",windows:J,fetchedAt:Date.now()}}async function HW($){return dU.readStale("claude-subscription",()=>nU($))}async function nU($){try{let{ClaudeAgentProcess:Z}=await Promise.resolve().then(() => (v4(),JJ)),J=new Z({workDir:lU(),effort:"default",profile:{loadProjectMcp:!1},...$});J.on("error",(V)=>j(`Claude subscription usage MISS: ${V.message}`));let Q,Y;try{let V=await Promise.race([J.readSubscriptionUsage(),new Promise((X,z)=>{Q=setTimeout(()=>z(Error(`Claude 订阅额度查询超时(${VW/1000}s)`)),VW)})]);return iU(V)}catch(V){throw Y=V instanceof Error?V:Error(String(V)),Y}finally{clearTimeout(Q);try{await J.kill()}catch(V){if(Y)throw AggregateError([Y,V],`${Y.message};额度查询进程关闭失败:${V instanceof Error?V.message:String(V)}`);throw V}}}catch(Z){let J=Z instanceof Error?Z.message:String(Z);return j(`claude-sub readUsage MISS: ${J}`),{state:Z?.code==="CLAUDE_SUBSCRIPTION_AUTH_MISSING"?"no_credentials":q2(Z)?"rate_limited":"network",windows:[],reason:J}}}var VW=30000,dU;var zQ=R(()=>{I();gZ();_1();dU=new X$});function aU(){let $=Object.fromEntries(s3.map((Z)=>[Z,""]));return $.ANTHROPIC_BASE_URL="https://api.anthropic.com",$.CLAUDE_CODE_NO_MODEL_FALLBACK="1",{env:$,apiKeyHelper:"",forceLoginMethod:"claudeai"}}function oU($){if(!$.subscriptionType?.trim())throw Object.assign(Error("Claude Code 订阅未登录;请在本机运行 claude auth login,完成后等待后台刷新,发送 md 查看状态"),{code:"CLAUDE_SUBSCRIPTION_AUTH_MISSING"});if($.apiProvider!=="firstParty"||$.apiKeySource&&$.apiKeySource!=="none")throw Error("Claude Code 当前认证不是第一方订阅;请检查本机登录方式和托管设置")}var GW=R(()=>{P0();I();X0();y4();zQ();L1();N0({kind:"claude-subscription",configSectionId:"claude-sub",build($){let Z=aU(),J=$.model?.trim(),Q="Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用",Y,V={id:"claude-sub",kind:"claude-subscription",agent:"claude",display:$.display?.trim()||"Claude Code 订阅",enabled:$.enabled!==!1,models:[],defaultModel:J??"",modelCatalogState:$.enabled===!1?{status:"disabled",updatedAt:Date.now(),error:"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"}:{status:"idle",updatedAt:Date.now()},settingSources:["user","project","local"],claudeSettings:Z,validateClaudeAccount:oU,spawnEnv(X){return{...o0(X),...Z.env}},resolveSpawnModel(X){return X},async refreshModels(){if($.enabled===!1){V.enabled=!1,V.models=[],V.modelCatalogState={status:"disabled",updatedAt:Date.now(),error:"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"};return}V.enabled=!0,V.models=[],V.modelCatalogState={status:"loading",updatedAt:null};try{let X=await z7({settingSources:["user"],settings:Z,transformEnv:V.spawnEnv,validateAccount:V.validateClaudeAccount,tokenSourceId:V.id});if(!X.length)throw Error("Claude Code 订阅模型目录为空");let z=[...s($.custom_models),...s($.models)];if(J&&!X.some((H)=>H.model===J)&&!z.includes(J))throw Error(`Claude Code 订阅默认模型不在目录中且未补录: ${J}`);if($.effort){let H=X.find((G)=>G.model===(J??X[0].model));if(!w0($.effort)||H&&!H.efforts.includes($.effort))throw Error(`Claude Code 订阅默认模型不支持 effort: ${$.effort}`);if(H)H.defaultEffort=$.effort}V.defaultModel=J??X[0].model,V.models=X,V.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(X){let z=X instanceof Error?X.message:String(X);if(j(`claude-sub refreshModels MISS: ${z}`),X?.code==="CLAUDE_SUBSCRIPTION_AUTH_MISSING")V.enabled=!1;V.modelCatalogState={status:V.enabled?"failed":"disabled",updatedAt:Date.now(),error:z}}},readUsage(){if(!V.enabled)return Promise.resolve({state:"not_applicable",windows:[],reason:V.modelCatalogState?.error??"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"});return Y??=HW({settingSources:["user"],settings:Z,transformEnv:V.spawnEnv,validateAccount:V.validateClaudeAccount,tokenSourceId:V.id}).finally(()=>{Y=void 0}),Y}};return V}})});function KW($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function sU($){let Z=(J)=>{let Q=J.match(/(\d+(?:\.\d+)?)/);return Q?Number(Q[1]):-1};return[...$].sort((J,Q)=>Z(Q)-Z(J))[0]??""}function tU($){let Z={};for(let J of($??"").split(",")){let Q=J.indexOf("=");if(Q<=0)continue;let Y=J.slice(0,Q).trim().toLowerCase(),V=J.slice(Q+1).trim();if((Y==="opus"||Y==="sonnet"||Y==="haiku")&&V)Z[Y]=V}return Z}function rU($){try{return new URL($).hostname.toLowerCase()==="api.deepseek.com"}catch{return!1}}async function BW($,Z){return(await HQ(new URL($).origin,Z)).map((Q)=>({model:Q,display:Q,efforts:f4,defaultEffort:"high"}))}async function HQ($,Z){let J=new URL($);if(!["https:","http:"].includes(J.protocol)||J.username||J.password||J.search||J.hash)throw Error("DeepSeek 需要无凭据和查询参数的 HTTP(S) API 根地址");return(await u$(`${J.toString().replace(/\/+$/,"")}/models`,Z,"DeepSeek models")).map((Y)=>{if(typeof Y.id!=="string"||!Y.id.trim())throw Error("DeepSeek models 模型 id 无效");return Y.id})}async function GQ($,Z){if(!Z.trim())return{kind:"balance",state:"no_credentials",windows:[]};let J;try{J=new URL($).origin}catch{return{kind:"balance",state:"network",windows:[],reason:"bad base_url"}}return $O.readStale(O$("deepseek",J,Z),()=>ZO(J,Z))}async function ZO($,Z){try{let J=await V0(`${$}/user/balance`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(eU)});if(!J.ok)return j(`deepseek readUsage MISS: HTTP ${J.status}`),{kind:"balance",state:J.status===429?"rate_limited":"network",windows:[],reason:`HTTP ${J.status}`,retryAfterMs:l$(J.headers)};let Q=await J.json(),V=(Array.isArray(Q?.balance_infos)?Q.balance_infos:[])[0],X=typeof V?.currency==="string"?V.currency:"",z=V?.total_balance;if(!X||typeof z!=="string"&&typeof z!=="number"||String(z).trim()===""||!Number.isFinite(Number(z)))throw Error("余额明细缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Number(z),currency:X}}}catch(J){return j(`deepseek readUsage MISS: ${J?.message??J}`),{kind:"balance",state:"network",windows:[],reason:J?.message??String(J)}}}var WW="https://api.deepseek.com/anthropic",eU=1e4,$O;var WQ=R(()=>{u0();X0();y4();o9();YQ();I();_4();_1();$O=new X$;N0({kind:"deepseek",configSectionId:"deepseek",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||WW,Q=$.api_key?.trim()||Z?.api_key?.trim()||"",Y=!!Q,V=$.model?.trim()||void 0,X=tU($.slots),z={id:"deepseek",kind:"deepseek",agent:"claude",display:$.display?.trim()||"DeepSeek",enabled:Y,models:[],modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!z.enabled){z.models=[],z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}z.modelCatalogState={status:"loading",updatedAt:null};try{let H=await BW(J,Q),W=[...new Set([...KW($.models),...KW($.custom_models)])].filter((K)=>!H.some((B)=>B.model.toLowerCase()===K.toLowerCase())).map((K)=>({model:K,display:K,efforts:f4,defaultEffort:"high",origin:"custom"}));if(z.models=[...H,...W],!V)z.defaultModel=sU(z.models.map((K)=>K.model));for(let K of z.models){let B=k4("deepseek",K.model);K.context1m=B!=null&&B>=1e6||void 0}z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(H){j(`deepseek refreshModels MISS: ${H?.message??H}`),z.models=[],z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:H?.message??String(H)}}},spawnEnv(H){let W={...o0(H)};if(W.ANTHROPIC_BASE_URL=J,W.ANTHROPIC_API_KEY=Q,X.opus)W.ANTHROPIC_DEFAULT_OPUS_MODEL=X.opus;if(X.sonnet)W.ANTHROPIC_DEFAULT_SONNET_MODEL=X.sonnet;if(X.haiku)W.ANTHROPIC_DEFAULT_HAIKU_MODEL=X.haiku;return W},resolveSpawnModel(H){return e3("deepseek",H)},async verifyModel(H){return I7(J,{"x-api-key":Q},H)},async readUsage(){if(!Q)return{kind:"balance",state:"no_credentials",windows:[]};return GQ(J,Q)}};return z},setup:{commandSuffix:"deepseek",hint:($)=>`配置 ${$}:发送 \`deepseek-setup <api_key>\`;Claude Code 和 DeepSeek Harness 共用该账号。自建端点用 \`deepseek-setup <base_url> <api_key>\`。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(!Z.length||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:`deepseek-setup <api_key>`(官方端点)或 `deepseek-setup <base_url> <api_key>`(自建中转)"};let J=Z.length>=2?Z[0]:void 0,Q=Z.length>=2?Z[1]:Z[0];return{config:{agent:"claude",...J?{base_url:J}:{},api_key:Q}}},async validate($){await BW($.base_url??WW,$.api_key??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!rU(Z))return null;let J=$.ANTHROPIC_API_KEY?.trim()??"";return J?{base_url:Z,api_key:J}:null}}})});function KQ($){for(let Z of jW){let J=Z.pattern.exec($.toLowerCase());if(!J)continue;let Q=J.groups,Y=Q.version.split(/[.-]/),V=Q.date??(Y.at(-1).length===8?Y.pop():void 0);if(!Y.length||Y.some((X)=>!Number.isSafeInteger(Number(X))))return;return{preset:Z,version:Y.map(Number),date:V?Number(V):0,preview:!!Q.preview}}return}function _W($){return KQ($)?.preset}function PW($){let Z=KQ($.replace(/\[1m\]$/,""))?.preset.family;return Z?`family:${Z}`:`model:${$}`}function LW($){let Z=new Map;for(let J of $){let Q=KQ(J);if(!Q)continue;let Y=Z.get(Q.preset.family),V=0;if(Y){for(let X=0;X<Math.max(Q.version.length,Y.version.length);X++)if(V=(Q.version[X]??0)-(Y.version[X]??0),V)break;V||=Number(Y.preview)-Number(Q.preview)||Q.date-Y.date||Y.model.length-J.length||Y.model.localeCompare(J)}if(!Y||V>0)Z.set(Q.preset.family,{...Q,model:J})}return jW.flatMap((J)=>{let Q=Z.get(J.family);return Q?[Q.model]:[]})}function h2($){let Z=$.toLowerCase().replace(/^~/,"");return/^(openai|deepseek|z-ai|zai-org|thudm)\//.test(Z)||/^(openrouter\/|@)/.test(Z)}var jW;var qW=R(()=>{jW=[{rank:4,lab:"Tencent",model:"tencent/hy4-preview",effort:"high",family:"hy",pattern:/^tencent\/hy(?<version>\d+(?:[.-]\d+)*)(?:-(?<preview>preview))?(?:-(?<date>\d{8}))?$/},{rank:7,lab:"Google",model:"google/gemini-3.8-flash",effort:"high",family:"gemini-flash",pattern:/^google\/gemini-(?<version>\d+(?:[.-]\d+)*)-flash(?:-(?<date>\d{8}))?$/},{rank:10,lab:"Meta",model:"meta/muse-spark-1.2",effort:"xhigh",family:"muse-spark",pattern:/^meta\/muse-spark-(?<version>\d+(?:[.-]\d+)*)$/},{rank:11,lab:"Xiaomi",model:"xiaomi/mimo-v2.5-pro",effort:"default",family:"mimo-pro",pattern:/^xiaomi\/mimo-v(?<version>\d+(?:[.-]\d+)*)-pro(?:-(?<date>\d{8}))?$/},{lab:"ByteDance",model:"bytedance-seed/seed-2-1-turbo",effort:"default",family:"seed-turbo",pattern:/^bytedance-seed\/seed-(?<version>\d+(?:[.-]\d+)*)-turbo(?:-(?<date>\d{8}))?$/},{lab:"Meituan",model:"meituan/longcat-2.0",effort:"default",family:"longcat",pattern:/^meituan\/longcat-(?<version>\d+(?:[.-]\d+)*)$/}]});function g2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _Q($){return $ instanceof Error?$.message:String($)}function jQ($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function I2($){return $.replace(/\[1m\]$/,"")}function t4($){let Z=new URL($);if(!["https:","http:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("OpenRouter base_url 必须是无凭据、查询参数和 fragment 的 HTTP(S) API 根地址");return Z.pathname=Z.pathname.replace(/\/+$/,"").replace(/\/v1$/,""),Z.toString().replace(/\/+$/,"")}async function YO($,Z,J){if(!Z)throw Error("OpenRouter API key missing");let Q=await V0(`${t4($)}/v1/${J}`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(JO)});if(!Q.ok){let Y=await Q.text(),V="";if(Y.trim().startsWith("{"))try{let X=JSON.parse(Y);if(g2(X)&&g2(X.error)&&typeof X.error.message==="string")V=X.error.message}catch{}throw new p7(Q.status,V.replaceAll(Z,"[redacted]"),l$(Q.headers))}return Q.json()}async function FW($,Z){let J=await u$(`${t4($)}/v1/models/user`,Z,"OpenRouter models"),Q=[],Y=new Set;for(let V of J){if(!g2(V)||typeof V.id!=="string"||!V.id||typeof V.name!=="string")throw Error("OpenRouter models: 模型 id/name 无效");if(!g2(V.architecture)||!Array.isArray(V.architecture.output_modalities)||!Array.isArray(V.supported_parameters))throw Error(`OpenRouter models: ${V.id} 的模型能力缺失`);if(h2(V.id)||!V.architecture.output_modalities.includes("text")||!V.supported_parameters.includes("tools")||V.id.endsWith(":batch")||Y.has(V.id))continue;let X=g2(V.reasoning)?V.reasoning:void 0,z=X?.supported_efforts,H=z===null||z===void 0&&V.supported_parameters.includes("reasoning_effort")?["max","xhigh","high","medium","low"]:Array.isArray(z)?[...new Set(z.filter((B)=>B!=="default"&&w0(B)))]:["default"],G=_W(V.id),W=G?H.includes(G.effort)?G.effort:null:H[0]==="default"?"default":w0(X?.default_effort)&&H.includes(X.default_effort)?X.default_effort:null,K=k4("openrouter",V.id);Q.push({model:V.id,display:V.name,efforts:H,defaultEffort:W,context1m:K!==void 0&&K>=1e6||void 0}),Y.add(V.id)}if(!Q.length)throw Error("OpenRouter 未返回支持文本和工具调用的交互模型");return Q}function MW($){return typeof $==="number"&&Number.isFinite($)&&$>=0}async function VO($,Z){if(!Z)return{kind:"balance",state:"no_credentials",windows:[]};return QO.readStale(O$("openrouter",t4($),Z),()=>XO($,Z))}async function XO($,Z){try{let J=await YO($,Z,"credits");if(!g2(J)||!g2(J.data))throw Error("OpenRouter credits: data 对象缺失");let{total_credits:Q,total_usage:Y}=J.data;if(!MW(Q)||!MW(Y))throw Error("OpenRouter credits: total_credits/total_usage 缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Q-Y,currency:"USD"}}}catch(J){let Q=_Q(J);return j(`openrouter readUsage MISS: ${Q}`),{kind:"balance",state:J instanceof p7&&J.status===429?"rate_limited":"network",windows:[],reason:Q,...J instanceof p7?{retryAfterMs:J.retryAfterMs}:{}}}}var DW="https://openrouter.ai/api",JO=1e4,QO,BQ,p7;var UW=R(()=>{u0();P0();X0();o9();I();qW();_4();_1();QO=new X$,BQ={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL"};p7=class p7 extends Error{status;retryAfterMs;constructor($,Z,J){super(`HTTP ${$}${Z?`: ${Z}`:""}`);this.status=$;this.retryAfterMs=J}};N0({kind:"openrouter",configSectionId:"openrouter",build($,Z){let J=$.api_key||$.auth_token||$.base_url?$:Z,Q=J?.api_key?.trim()||J?.auth_token?.trim()||"",Y=J?.base_url?.trim()||DW,V=$.model?.trim()||"",X=$.models===void 0?void 0:jQ($.models),z=(G)=>LW(G.filter((W)=>W.origin!=="custom").map((W)=>W.model)),H={id:"openrouter",kind:"openrouter",agent:"claude",display:$.display?.trim()||"OpenRouter",enabled:!!Q,models:[],defaultModel:V,modelSelection:{mode:"allowlist",modelIds:X??[],availableModels:[],...X===void 0?{selectDefaults:z,visibilityKey:PW}:{}},validateCustomModelId(G){if(h2(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);if(!G.includes("/"))throw Error("OpenRouter 模型请填写完整的 作者/模型 ID")},modelEnvironmentRevision(G){let W=H.modelSelection.availableModels.find((K)=>I2(K.model)===I2(G));if(!W||W.unavailableReason||!W.efforts.length)return"model-unavailable";return W.efforts.includes("default")?"effort-unset":"effort-level"},modelCatalogState:{status:Q?"idle":"disabled",updatedAt:Date.now()},async refreshModels(){if(H.models=[],H.modelSelection.availableModels=[],!H.enabled){H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{let G=await FW(Y,Q),W=G.find((_)=>_.model===I2(V));if(V&&!W)throw Error(`OpenRouter 默认模型不在账号目录中: ${V}`);if($.effort){if(!V)throw Error("OpenRouter effort 需要同时配置 model");if(!w0($.effort)||!W.efforts.includes($.effort))throw Error(`OpenRouter 模型 ${V} 不支持 effort ${$.effort}`);W.defaultEffort=$.effort}let B=(X??[...new Set([...V?[I2(V)]:[],...z(G),...jQ($.shown_models)])]).map((_)=>{let P=G.find((L)=>L.model===I2(_));if(!P)return{model:_,display:_,efforts:[],defaultEffort:null,unavailableReason:h2(_)?"此厂商或自动路由已被排除":"账号目录未返回该模型"};return{...P,model:_}});H.models=B,H.modelSelection.modelIds=B.map((_)=>_.model),H.modelSelection.availableModels=G,H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){let W=_Q(G);j(`openrouter refreshModels MISS: ${W}`),H.modelCatalogState={status:"failed",updatedAt:Date.now(),error:W}}},spawnEnv(G,W){if(!Q)throw Error("OpenRouter API key missing");let K=W||V;if(!K)throw Error("OpenRouter 未选择模型,请通过 model 面板选择或配置 model");if(h2(K))throw Error(`OpenRouter 已排除此厂商或自动路由: ${K}`);let B=o0(G);B.ANTHROPIC_BASE_URL=t4(Y),B.ANTHROPIC_AUTH_TOKEN=Q,B.ANTHROPIC_API_KEY="",B.CLAUDE_CODE_NO_MODEL_FALLBACK="1",B.ANTHROPIC_MODEL=K,B.ANTHROPIC_SMALL_FAST_MODEL=K,B.CLAUDE_CODE_SUBAGENT_MODEL=K,B.ANTHROPIC_DEFAULT_FABLE_MODEL=K;for(let _ of Object.values(BQ))B[_]=K;for(let _ of jQ($.slots)){let P=_.indexOf("="),L=_.slice(0,P).trim(),q=_.slice(P+1).trim();if(P<1||!Object.hasOwn(BQ,L)||!q)throw Error(`OpenRouter slots 无效: ${_}`);if(h2(q)||!H.modelSelection.availableModels.some((D)=>!D.unavailableReason&&I2(D.model)===I2(q)))throw Error(`OpenRouter slot 模型不在账号目录中: ${q}`);if(H.modelEnvironmentRevision(q)!==H.modelEnvironmentRevision(K))throw Error(`OpenRouter slot 不能混合无 effort 档位与有 effort 档位的模型: ${q}`);B[BQ[L]]=q}return B},resolveSpawnModel(G){if(h2(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);return G||void 0},readUsage(){return VO(Y,Q)}};return H},setup:{commandSuffix:"openrouter",hint:($)=>`启用 ${$}:发送 \`openrouter-setup <api_key>\`,然后通过 \`model\` 选择模型。自建端点用 \`openrouter-setup <base_url> <api_key>\`。`,parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||Z.length===1&&/^https?:\/\//i.test(Z[0]))return{error:"用法: openrouter-setup <api_key> 或 openrouter-setup <base_url> <api_key>"};try{return{config:{agent:"claude",api_key:Z[Z.length-1],...Z.length===2?{base_url:t4(Z[0])}:{}}}}catch(J){return{error:_Q(J)}}},async validate($){await FW($.base_url??DW,$.api_key??$.auth_token??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim(),J=$.ANTHROPIC_AUTH_TOKEN?.trim();if(!Z||!J)return null;try{let Q=t4(Z);if(new URL(Q).hostname!=="openrouter.ai")return null;return{base_url:Q,api_key:J}}catch{return null}}}})});function OW($,Z){let J=$.trim().toLowerCase().split("/").at(-1)??"",Q=Z==="packy-codex"?"codex":"claude";for(let Y of zO){if(Y.agent!==Q)continue;let V=Y.pattern.exec(J);if(!V)continue;let X=V[1].split(/[.-]/),z=V[2]??(X.at(-1).length===8?X.pop():void 0);if(!X.length)continue;return{family:Y.id,version:X.map(Number),date:z?Number(z):0}}return}function AW($,Z){let J=OW($,Z)?.family;return J?`family:${J}`:`model:${$}`}function NW($,Z="packy"){let J=new Map;for(let Y of $){let V=OW(Y,Z);if(!V)continue;let X=J.get(V.family),z=0;if(X){for(let H=0;H<Math.max(V.version.length,X.version.length);H++)if(z=(V.version[H]??0)-(X.version[H]??0),z)break;z||=V.date-X.date||X.model.length-Y.length||X.model.localeCompare(Y)}if(!X||z>0)J.set(V.family,{model:Y,version:V.version,date:V.date})}let Q=new Set([...J.values()].map((Y)=>Y.model));return $.filter((Y)=>Q.has(Y))}var zO;var RW=R(()=>{zO=[{id:"minimax",agent:"claude",pattern:/^minimax-m(\d+(?:[.-]\d+)*)$/},{id:"opus",agent:"claude",pattern:/^claude-opus-(\d+(?:[.-]\d+)*)$/},{id:"fable",agent:"claude",pattern:/^claude-fable-(\d+(?:[.-]\d+)*)$/},{id:"qwen-max",agent:"claude",pattern:/^qwen-?(\d+(?:[.-]\d+)*)-max(?:-(\d{4}|\d{8}))?$/},{id:"kimi",agent:"codex",pattern:/^kimi-k(\d+(?:[.-]\d+)*)$/},{id:"grok",agent:"codex",pattern:/^grok-(\d+(?:[.-]\d+)*)$/}]});function LQ($){return $.replace(/\[1m\]$/,"")==="gemini-3.8-flash"}function HO($,Z,J){let Q=Z==="claude"?d9:L2,Y=$.reasoning?.supported_efforts;if(Y!==void 0&&(!Array.isArray(Y)||!Y.length||!Y.every((H)=>typeof H==="string")))throw Error(`PackyAPI ${$.id} 的推理档位声明无效`);let V=Y===void 0?[...Q]:Q.filter((H)=>Y.includes(H));if(!V.length)throw Error(`PackyAPI ${$.id} 未声明当前 Agent 可用的推理档位`);let X=J.effort?.trim(),z=X||$.reasoning?.default_effort||(Y===void 0?Z==="claude"?"default":"medium":void 0);if(X&&!V.includes(X))throw Error(`PackyAPI effort 无效: ${X}`);return{model:$.id,display:$.display,efforts:V,defaultEffort:typeof z==="string"&&V.includes(z)?z:null}}var PQ="LODESTAR_PACKY_API_KEY",TW,EW;var SW=R(()=>{P0();j1();ZQ();RW();L1();I();_1();X0();TW={API_TIMEOUT_MS:"60000",CLAUDE_ENABLE_BYTE_WATCHDOG:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:"45000",CLAUDE_CODE_MAX_RETRIES:"2",CLAUDE_CODE_RETRY_WATCHDOG:"0"};EW=[{id:"packy",agent:"claude",display:"PackyAPI"},{id:"packy-secondary",agent:"claude",display:"PackyAPI · 令牌2"},{id:"packy-codex",agent:"codex",display:"PackyAPI"}];for(let $ of EW){let{id:Z,agent:J,display:Q}=$,Y=J==="claude"?"anthropic":"openai-response",V=(X)=>X.protocols.includes(Y)||J==="claude"&&LQ(X.id);N0({kind:Z,configSectionId:Z,build(X){let z=X.api_key?.trim()||X.auth_token?.trim()||"",H=r$(X.base_url?.trim()||y2),G=X.management_url?.trim()?r$(X.management_url):o4(H),W=X.management_token?.trim()||"",K=X.management_user_id?.trim()||"",B=!!(W||K||X.management_url?.trim()||X.billing_source?.trim()),_=X.model?.trim(),P=X.models===void 0?void 0:s(X.models),L=new Set([...s(X.custom_models),...P??[]]),q=(A)=>NW(A.filter((O)=>O.origin!=="custom").map((O)=>O.model),Z),D=[],M=(A)=>{let O=D.find((N)=>N.id===A);if(O&&!V(O)&&!L.has(A))throw Error(`PackyAPI ${A} 未声明 ${Y};确认兼容后可显式补录`)},U={id:Z,kind:Z,agent:J,display:X.display?.trim()||Q,enabled:!!z&&X.enabled!==!1,models:[],defaultModel:_??"",modelSelection:{mode:"allowlist",modelIds:P??[],availableModels:[],...P===void 0?{selectDefaults:q,visibilityKey:(A)=>AW(A,Z)}:{}},...B?{usageAccount:{id:O$("packy-account",G,K),label:"PackyAPI"}}:{},modelCatalogState:{status:z&&X.enabled!==!1?"idle":"disabled",updatedAt:Date.now()},...J==="claude"?{modelEnvironmentRevision(A){return LQ(A)?JSON.stringify(TW):"native-retries"}}:{},...J==="codex"?{codexApiProvider:{id:"packy",name:"PackyAPI",baseUrl:`${H}/v1`,envKey:PQ}}:{},async refreshModels(){if(U.models=[],D=[],!U.enabled){U.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}U.modelCatalogState={status:"loading",updatedAt:null};try{D=await eJ(H,z);let A=D.filter((T)=>V(T)||L.has(T.id));if(!A.length&&!L.size)throw Error(`PackyAPI 此令牌没有声明支持 ${Y} 的模型,请检查分组和模型限制`);let O=A.map((T)=>({...HO(T,J,X),...!T.protocols.includes(Y)&&L.has(T.id)?{origin:"custom"}:{}}));for(let T of L){if(O.some((y)=>y.model.toLowerCase()===T.toLowerCase()))continue;O.push({model:T,display:T,origin:"custom",...N2(U,X)})}if(_&&!O.some((T)=>T.model===_)){if(D.find((y)=>y.id===_))throw Error(`PackyAPI ${_} 未声明 ${Y},确认兼容后请显式补录`);if(!L.has(_))throw Error(`PackyAPI 默认模型不在目录中且未补录: ${_}`)}let S=(P??[...new Set([..._?[_]:[],...q(O),...s(X.shown_models),...O.filter((T)=>T.origin==="custom").map((T)=>T.model)])]).map((T)=>O.find((y)=>y.model===T)??{model:T,display:T,efforts:[],defaultEffort:null,unavailableReason:"账号目录未返回该模型"});U.modelSelection.availableModels=O,U.models=S,U.modelSelection.modelIds=S.map((T)=>T.model),U.defaultModel=_??S.find((T)=>!T.unavailableReason)?.model??[...L][0]??"",U.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(A){U.models=[],D=[];let O=y0(A,[z]);j(`${Z} refreshModels MISS: ${O}`),U.modelCatalogState={status:"failed",updatedAt:Date.now(),error:O}}},resolveSpawnModel(A){return M(A),A},spawnEnv(A,O){if(!z)throw Error("PackyAPI API key missing");let N=O||U.defaultModel;if(!N)throw Error("PackyAPI 尚未选择模型");M(N);let S=o0(A);if(delete S[PQ],J==="codex"){for(let y of["CODEX_API_KEY","OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete S[y];return S[PQ]=z,S}if(S.ANTHROPIC_BASE_URL=H,S.ANTHROPIC_AUTH_TOKEN=z,S.ANTHROPIC_API_KEY="",S.CLAUDE_CODE_NO_MODEL_FALLBACK="1",LQ(N))Object.assign(S,TW);S.ANTHROPIC_MODEL=N,S.ANTHROPIC_SMALL_FAST_MODEL=N,S.CLAUDE_CODE_SUBAGENT_MODEL=N;for(let y of["OPUS","SONNET","HAIKU","FABLE"])S[`ANTHROPIC_DEFAULT_${y}_MODEL`]=N;let T={opus:"OPUS",sonnet:"SONNET",haiku:"HAIKU",fable:"FABLE"};for(let y of s(X.slots)){let[m,b,p]=y.split("=");if(!m||!Object.hasOwn(T,m)||!b||p!==void 0)throw Error(`PackyAPI slots 无效: ${y}`);if(!y1(U).some((c)=>c.model===b))throw Error(`PackyAPI slot 模型不在当前来源: ${b}`);M(b),S[`ANTHROPIC_DEFAULT_${T[m]}_MODEL`]=b}return S},readUsage(){return B?$Q(G,W,K):eG(H,z)}};return U},setup:{commandSuffix:Z,hint:()=>`发送 \`${Z}-setup [base_url] <api_key>\` 配置${Q}。${Z==="packy-codex"?"与 PackyAPI 主账号共用凭据。":""}`,parseArgs(X){let z=X.trim().split(/\s+/).filter(Boolean);if(z.length<1||z.length>2||/^https?:\/\//i.test(z.at(-1)))return{error:`用法: ${Z}-setup [base_url] <api_key>`};try{return{config:{agent:J,api_key:z.at(-1),base_url:r$(z.length===2?z[0]:y2)}}}catch(H){return{error:y0(H,[z.at(-1)])}}},async validate(X){if(!(await eJ(X.base_url??y2,X.api_key??X.auth_token??"")).some(V)&&!s(X.custom_models).length&&!s(X.models).length)throw Error(`此令牌没有声明支持 ${Y} 的模型`)}},...Z==="packy-codex"?{}:{usageSetup:{commandSuffix:`${Z}-balance`,hint:()=>`发送 \`${Z}-balance-setup [management_url] <user_id> <system_token>\` 配置真实余额;共用已有账号用 \`${Z}-balance-setup share <source_id>\`。`,parseArgs(X){let z=X.trim().split(/\s+/).filter(Boolean);if(z.length===2&&z[0]==="share"){if(!EW.some((W)=>W.id===z[1])||z[1]===Z)return{error:"请指定另一个已配置的 PackyAPI 来源:packy、packy-secondary 或 packy-codex"};return{config:{billing_source:z[1],management_token:"",management_user_id:"",management_url:""}}}if(z.length<2||z.length>3)return{error:`用法:${Z}-balance-setup [management_url] <user_id> <system_token>,或 ${Z}-balance-setup share <source_id>`};let H=z.at(-2),G=z.at(-1);if(!/^[1-9]\d*$/.test(H)||!Number.isSafeInteger(Number(H)))return{error:"用户 ID 必须是正整数"};try{return{config:{billing_source:"",management_token:G,management_user_id:H,management_url:z.length===3?r$(z[0]):""}}}catch(W){return{error:y0(W,[G])}}},async validate(X){let z=X.management_url||o4(X.base_url||y2),H=await $Q(z,X.management_token||"",X.management_user_id||"",!0);if(H.state!=="ok")throw Error(H.reason||"PackyAPI 真实账户余额查询失败")}}}})}});var CW=1;import{EventEmitter as GO}from"node:events";import{createRequire as WO}from"node:module";import{createHash as KO,randomUUID as BO}from"node:crypto";import{createInterface as jO}from"node:readline";import{dirname as _O,join as M1,isAbsolute as PO}from"node:path";import{fileURLToPath as qQ}from"node:url";import{tmpdir as LO}from"node:os";import{existsSync as xW,mkdirSync as bW,mkdtempSync as qO,readFileSync as D8,renameSync as DO,writeFileSync as kW,rmSync as DQ}from"node:fs";import FO from"cross-spawn";function MO($){let Z=$.LODESTAR_DSH_PROVIDER??"deepseek-official";if(Z==="deepseek-official")return[];if(Z!=="zai-coding-cn"&&Z!=="zai")throw Error(`Unsupported DSH provider: ${Z}`);let J=$.LODESTAR_DSH_MODELS===void 0?void 0:JSON.parse($.LODESTAR_DSH_MODELS);if(J!==void 0&&(!Array.isArray(J)||!J.every((Q)=>typeof Q==="string"&&Q)))throw Error("Invalid DSH GLM model catalog");return[{id:"llm-deepseek",disabled:!0},{id:"llm-pi-ai",disabled:!1,config:{providers:{[Z]:{apiKeyEnv:"LODESTAR_DSH_GLM_API_KEY",baseURL:$.LODESTAR_DSH_BASE_URL,compat:{supportsReasoningEffort:!0},reasoning:"high",...Array.isArray(J)?{models:J.map((Q)=>({id:Q,reasoningEfforts:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"}}))}:{}}}}},{id:"agent-default-model",config:{provider:Z,model:$.LODESTAR_DSH_DEFAULT_MODEL??""}}]}function UO($,Z){if(Z?.loadProjectMcp===!1)return[];let J;try{J=D8(M1($,".mcp.json"),"utf8")}catch(Y){if(Y?.code==="ENOENT")return[];throw Y}let Q=JSON.parse(J);if(!Q.mcpServers||typeof Q.mcpServers!=="object"||Array.isArray(Q.mcpServers))throw Error("DSH project .mcp.json must contain an mcpServers object");return Object.entries(Q.mcpServers).map(([Y,V])=>{if(!/^[A-Za-z0-9_-]{1,32}$/.test(Y)||!V||typeof V!=="object")throw Error(`invalid DSH MCP server: ${Y}`);let X=V,z=X.type==="http"?{transport:"streamable-http",serverName:Y,url:X.url,headers:X.headers??{}}:X.type===void 0||X.type==="stdio"?{transport:"stdio",serverName:Y,command:X.command,args:X.args??[],env:X.env??{},cwd:$}:null;if(!z)throw Error(`DSH does not support MCP transport ${X.type} for ${Y}`);return{id:`lodestar-mcp-${Y}`,name:"@deepseek-ai/dsh-mcp-client",config:{...z,failOnStartupError:!0}}})}async function r4($,Z,J={}){let Q=new c7($);Q.on("failure",(X)=>j(`dsh catalog: ${X}`));let Y,V;try{await Q.initialize(),V=await Q.request(Z,J)}catch(X){Y=X}try{await Q.close()}catch(X){if(Y)throw AggregateError([Y,X],"DSH query and cleanup both failed");throw X}if(Y)throw Y;return V}var c7;var F8=R(()=>{H0();F4();I();c7=class c7 extends GO{child;pending=new Map;nextId=0;exited=!1;closing=!1;stderr="";initialized=!1;initTask;closeTask;exitTask;launchDir;constructor($){super();if(!PO($.cwd))throw Error("DSH requires an absolute workspace");let Z=T3("dsh"),Q=WO(M1(Z,"package.json")).resolve("@deepseek-ai/dsh/package.json"),Y=JSON.parse(D8(Q,"utf8"));j(`dsh runtime: ${Y.version} (${Z})`);let V=MO($.env),X=$.home??W4;bW(X,{recursive:!0,mode:448});let z=UO($.cwd,$.profile);this.launchDir=qO(M1(LO(),"lodestar-dsh-"));let H=import.meta.url.endsWith(".ts"),G=H?"dsh-bridge.ts":"dsh-bridge.js",W=D8(qQ(new URL(`./${G}`,import.meta.url))),K=H?D8(qQ(new URL("./dsh-protocol.ts",import.meta.url))):Buffer.alloc(0),B=JSON.parse(D8(qQ(new URL("../package.json",import.meta.url)),"utf8")),_=Buffer.from(JSON.stringify({name:B.name,version:B.version,type:"module",private:!0})),P=KO("sha256").update(W).update(K).update(_).digest("hex").slice(0,20),L=M1(Z,".lodestar-bridges",P);bW(L,{recursive:!0});let q=M1(L,G),D=(T,y)=>{if(xW(T))return;let m=`${T}.${BO()}.tmp`;try{kW(m,y),DO(m,T)}finally{if(xW(m))DQ(m)}};if(D(M1(L,"package.json"),_),H)D(M1(L,"dsh-protocol.ts"),K);D(q,W);let M=[...["sdk-jsonrpc-server","session-title-llm","session-telemetry-otel","settings","credentials","llm-pi-ai"].map((T)=>({id:T,disabled:!0})),{id:"approval",config:{policy:"ask"}},{id:"permission",config:{defaultPreset:"lodestar",presets:{lodestar:{sandbox:"danger-full-access",approval:"ask"}}}},{id:"tool-subagent",config:{provider:"spawn",toolName:"subagent",backgroundMode:"continuable",maxDepth:"provider-managed"}},{id:"tool-subagent-fork",config:{provider:"fork",toolName:"subagent_fork",backgroundMode:"one-shot",maxDepth:"provider-managed"}},{id:"system-prompt",config:{personaPrefix:"You are a coding agent powered by {{model}}.",personaSuffix:""}},{id:"skill-filesystem",config:{includeDefaultRoots:!0,...$.managedSkillDir?{customSkillDirs:[$.managedSkillDir]}:{}}},{insert:[{id:"lodestar-bridge",name:q},{id:"lodestar-ask-user",name:"@deepseek-ai/dsh-tool-ask-user"},...z]},...V],U=M1(this.launchDir,"bridge.patch.yml");kW(U,JSON.stringify(M),{mode:384});let A=$.env.LODESTAR_DSH_NODE||"node",O=[M1(_O(Q),Y.bin.dsh),"--profile","sdk","--patch",U,...($.patches??[]).flatMap((T)=>["--patch",T])],N={...$.env};if(N.LODESTAR_AGENT_CAPABILITY&&N.LODESTAR_AGENT_URL)N.DSH_LODESTAR_AGENT_CONTEXT=JSON.stringify({baseUrl:N.LODESTAR_AGENT_URL,capability:N.LODESTAR_AGENT_CAPABILITY});for(let T of Object.keys(N))if(T.startsWith("LODESTAR_AGENT_"))delete N[T];try{this.child=FO(A,O,{cwd:$.cwd,stdio:["pipe","pipe","pipe"],shell:!1,env:{...N,DSH_HOME:X,DSH_PERMISSION_MODE:"danger-full-access"}})}catch(T){throw DQ(this.launchDir,{recursive:!0,force:!0}),T}this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",(T)=>{this.stderr=(this.stderr+T).slice(-16384),j(`dsh stderr: ${T.trimEnd()}`)}),this.child.stdin.on("error",(T)=>this.transportFailure(T));let S=jO({input:this.child.stdout,crlfDelay:1/0});S.on("line",(T)=>this.receive(T)),this.exitTask=new Promise((T)=>{this.child.once("error",(y)=>this.transportFailure(y)),this.child.once("close",(y,m)=>{this.exited=!0,S.close();let b=Error(`DSH exited code=${y} signal=${m}
151
- ${this.stderr}`);this.rejectPending(b),DQ(this.launchDir,{recursive:!0,force:!0}),T(),this.emit("exit",{code:y,signal:m,expected:this.closing})})})}get pid(){return this.child.pid}isAlive(){return!this.exited}initialize(){return this.initTask??=this.request("initialize",{},30000).then(($)=>{if($.protocolVersion!==CW||typeof $.runtimeVersion!=="string"||!$.runtimeVersion)throw Error(`DSH handshake version mismatch: ${JSON.stringify($)}`);this.initialized=!0})}request($,Z={},J=30000){if(this.exited||this.closing&&$!=="shutdown")return Promise.reject(Error("DSH transport is closed"));let Q=++this.nextId;return new Promise((Y,V)=>{let X=J===null?void 0:setTimeout(()=>{this.pending.delete(Q),V(Error(`DSH ${$} timed out after ${J}ms
150
+ ${Z.stderr}`)}function sJ($){return $.replace(/[^\w一-鿿\-\[\]\*]/g,"_").slice(0,64)}var yG,fG,EJ,G$,hG,p1=async($)=>{let J=hG.getStore()?.timeoutMs(H8),Q=J===void 0?void 0:AbortSignal.timeout(J);try{let Y=await U7.defaultHttpInstance.request({...$,...J===void 0?{}:{timeout:J,signal:Q},$return_headers:!0}),V=k$({data:Y.data,headers:Y.headers});if(V.logId&&Y.data&&typeof Y.data==="object"&&!Array.isArray(Y.data))Y.data.log_id=V.logId;return $.$return_headers?Y:Y.data}catch(Y){if(Q?.aborted&&Q.reason?.name==="TimeoutError")throw Q.reason;if(Y instanceof Error){let V=k$(Y);Y.message=w(Y),Object.assign(Y,{apiMessage:V.message,logId:V.logId})}throw Y}},FU,q0,H8=15000,L7="",NG=0,q7=null,O0,U0,C0,W0,EG=200,SG,i0,S7=31457280,CG=300000,xG=1920000,bG=5,EU;var Y0=R(()=>{u0();j4();zJ();P0();k0();j1();P0();H0();I();D0();b0();m4();d0();K2();OG();yG=g.feishu.app_id,fG=g.feishu.app_secret,EJ=g.runtime.projects_root,G$=new Map;hG=new BU,FU={request:p1,get:($,Z)=>p1({...Z,url:$,method:"GET"}),delete:($,Z)=>p1({...Z,url:$,method:"DELETE"}),head:($,Z)=>p1({...Z,url:$,method:"HEAD"}),options:($,Z)=>p1({...Z,url:$,method:"OPTIONS"}),post:($,Z,J)=>p1({...J,url:$,data:Z,method:"POST"}),put:($,Z,J)=>p1({...J,url:$,data:Z,method:"PUT"}),patch:($,Z,J)=>p1({...J,url:$,data:Z,method:"PATCH"})},q0=new U7.Client({appId:yG,appSecret:fG,disableTokenCache:!1,httpInstance:FU});O0=new Map,U0=new Map;C0=new Map;W0=new Map;SG=/\*[0-9]{4}-[0-9]{4}(-[0-9]+)?$/;i0=new Map;EU=new Set([".png",".jpg",".jpeg",".gif",".bmp",".webp"])});async function nG($=(Z)=>new w$({accountId:Z})){if(k1(d))throw Error("默认账号正在登录,请先完成默认账号授权,再添加额外账号。");let Z,J,Q;try{Z=$(d),await Z.initialize("lodestar-login-check"),Q=await i$(()=>Z.request("account/read",{refreshToken:!1}),"默认账号登录检查")}catch(Y){J=Error(`默认账号登录检查失败:${a4(Y).message}`,{cause:Y})}if(!J){if(Q?.account===null||Q?.account?.type==="apiKey")J=Error("默认账号未登录 ChatGPT,请先发送不带备注的 codex-login 完成登录,再添加额外账号。");else if(Q?.account?.type!=="chatgpt")J=Error("默认账号登录检查失败:account/read 返回的账号状态无效")}if(Z)try{if(await Z.close(),Z.isAlive())throw Error("检查进程仍未退出")}catch(Y){J=Error([J?.message,`默认账号检查进程关闭失败:${a4(Y).message}`].filter(Boolean).join(";"),{cause:Y})}if(J)throw J}class aG{createClient;waitMs;recordLogin;stateWaitMs;attempts=new Map;stopping=!1;constructor($=(Y)=>new w$({accountId:Y,login:!0}),Z=900000,J=(Y,V)=>{v.recordLogin(Y,V),d$(Y)},Q=1e4){this.createClient=$;this.waitMs=Z;this.recordLogin=J;this.stateWaitMs=Q}async start($,Z){if(this.stopping)throw Error("服务正在退出,无法开始登录");if(!Z.userOpenId)throw Error("无法确认登录发起者");if(this.attempts.has($))throw Error("该账号已有登录任务;使用 codex-login-cancel 取消后再登录");let J=_z($),Q;try{Q=this.createClient($)}catch(H){throw J(),H}let Y,V,X=new Promise((H,G)=>{Y=H,V=G});X.catch(()=>{});let z={owner:Z,client:Q,accountId:$,loginId:null,loginRequested:!1,loginSucceeded:!1,authUpdated:!1,finishing:!1,done:X,resolve:Y,reject:V,timer:null,notification:()=>{},closed:()=>{},early:[],releaseAuth:J};z.notification=(H,G)=>{if(z.finishing||!z.loginRequested)return;if(H==="account/updated"){if(G?.authMode==="chatgpt"){if(z.authUpdated=!0,z.loginSucceeded)this.finish(z)}return}if(H!=="account/login/completed")return;if(!z.loginId){z.early.push(G);return}if(G?.loginId!==z.loginId)return;if(G?.success!==!0){this.finish(z,Error(typeof G?.error==="string"?G.error:"Codex 登录未成功"));return}if(z.loginSucceeded)return;if(z.loginSucceeded=!0,j(`codex-login: authorization completed account=${$} authUpdated=${z.authUpdated}`),z.timer)clearTimeout(z.timer);if(z.authUpdated)this.finish(z);else z.timer=setTimeout(()=>{this.finish(z,Error("设备码授权已完成,但 Codex 未及时更新账号状态;认证文件已保留,可用 codex-accounts 检查"))},this.stateWaitMs)},z.closed=(H)=>{this.finish(z,H)},Q.on("notification",z.notification),Q.on("closed",z.closed),Q.on("protocolError",z.closed),this.attempts.set($,z);try{await Q.initialize("lodestar-login"),z.loginRequested=!0;let H=await Q.request("account/login/start",{type:"chatgptDeviceCode"},30000);if(H?.type!=="chatgptDeviceCode"||typeof H.loginId!=="string"||!H.loginId||typeof H.userCode!=="string"||!H.userCode||typeof H.verificationUrl!=="string"||new URL(H.verificationUrl).protocol!=="https:")throw Error("Codex 设备码登录响应不完整");if(z.loginId=H.loginId,z.finishing)throw await X,Error("登录已结束");z.timer=setTimeout(()=>{this.cancelAttempt(z,"登录等待超过 15 分钟,请重新发送 codex-login [备注]").catch(()=>{})},this.waitMs);for(let G of z.early)z.notification("account/login/completed",G);return z.early.length=0,{accountId:$,loginId:H.loginId,verificationUrl:H.verificationUrl,userCode:H.userCode,done:X}}catch(H){return await this.finish(z,a4(H)),await X}}pending($){return[...this.attempts.values()].filter((Z)=>Z.owner.chatId===$.chatId&&Z.owner.userOpenId===$.userOpenId).map((Z)=>Z.accountId)}async cancel($,Z){let J=this.attempts.get($);if(!J)throw Error("该账号没有等待中的登录");if(!Z.userOpenId||Z.chatId!==J.owner.chatId||Z.userOpenId!==J.owner.userOpenId)throw Error("只有发起登录的用户可在原群取消");if(J.finishing)throw Error("登录正在收尾,请等待结果");await this.cancelAttempt(J,"登录已取消")}async cancelAttempt($,Z){if($.finishing)return;$.finishing=!0;let J=Error(Z);if($.loginId&&$.client.isAlive())try{await $.client.request("account/login/cancel",{loginId:$.loginId})}catch(Q){J=Error(`${Z};取消请求失败:${a4(Q).message}`)}await this.complete($,J)}async finish($,Z){if($.finishing)return;if($.finishing=!0,$.timer)clearTimeout($.timer);let J;if(!Z)try{let Q=await $.client.request("account/read",{refreshToken:!1});if(Q?.account?.type!=="chatgpt"){let Y=typeof Q?.account?.type==="string"?Q.account.type:"null";throw Error(`设备码授权已完成,但账号状态校验失败(account/read.type=${Y});认证文件已保留`)}J=Q.account,this.recordLogin($.accountId,J)}catch(Q){Z=a4(Q)}await this.complete($,Z,J)}async complete($,Z,J){if($.timer)clearTimeout($.timer);$.client.off("notification",$.notification),$.client.off("closed",$.closed),$.client.off("protocolError",$.closed);try{await $.client.close()}catch(Q){Z=Error([Z?.message,`登录进程关闭失败:${a4(Q).message}`].filter(Boolean).join(";"))}if(!$.client.isAlive())this.attempts.delete($.accountId),$.releaseAuth();if(Z)$.reject(Z);else if(J)$.resolve(J);else $.reject(Error("登录结束但账号信息缺失"))}async shutdown(){this.stopping=!0;let Z=(await Promise.allSettled([...this.attempts.values()].map(async(J)=>{if(await this.cancelAttempt(J,"服务退出,登录已取消"),J.client.isAlive())await J.client.close();if(J.client.isAlive())throw Error("登录进程仍未退出");J.releaseAuth(),this.attempts.delete(J.accountId),await J.done.then(()=>{},()=>{})}))).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 登录进程未完全退出")}}function a4($){return $ instanceof Error?$:Error(String($))}var v2;var tJ=R(()=>{z$();D0();I();v2=new aG});import{readFileSync as CU}from"node:fs";import{homedir as xU}from"node:os";import{join as rG}from"node:path";function kU(){return process.env.CLAUDE_CONFIG_DIR||rG(xU(),".claude")}function rJ(){try{let $=CU(rG(kU(),"settings.json"),"utf8"),Z=JSON.parse($)?.env;return Z&&typeof Z==="object"?Z:{}}catch($){return j(`glm-usage: read settings.json env failed: ${$}`),{}}}function y2($){try{let Z=new URL($).hostname.toLowerCase();return Z==="open.bigmodel.cn"||Z==="dev.bigmodel.cn"||Z==="api.z.ai"}catch{return!1}}function wU($){try{let Z=new URL($);return`${Z.protocol}//${Z.host}`}catch{return null}}function vU($){let Z=wU($);return Z&&y2($)?Z:null}function sG($){return typeof $==="number"&&isFinite($)?Math.max(0,Math.min(100,$)):null}function tG($){return typeof $==="number"&&isFinite($)&&$>0?new Date($):null}function yU($){let Z=Array.isArray($)?$:Array.isArray($?.limits)?$.limits:void 0;if(!Z)return{state:"network",reason:"GLM 额度响应缺少 limits 数组"};let J=Z.filter((W)=>W?.type==="TOKENS_LIMIT"||W?.type==="CREDIT_LIMIT"),Q=J.find((W)=>W?.unit===3&&W?.number===5),Y=J.find((W)=>W?.unit===6&&W?.number===1),V=Z.find((W)=>W?.type==="TIME_LIMIT"),X=(W)=>W?{percent:sG(W.percentage),resetsAt:tG(W.nextResetTime)}:null,z=X(Q),H=X(Y),G=V?{percent:sG(V.percentage),resetsAt:tG(V.nextResetTime),...typeof V.currentValue==="number"?{used:V.currentValue}:{},...typeof V.usage==="number"?{total:V.usage}:{}}:null;if(!z&&!H&&!G)return{state:"network",reason:"GLM 额度响应没有可识别的额度窗口"};return{state:"ok",level:typeof $?.level==="string"&&$.level?$.level:void 0,fiveHour:z,weekly:H,monthly:G,fetchedAt:Date.now()}}async function x7($,Z){let J=$!==void 0||Z!==void 0?{ANTHROPIC_BASE_URL:$,ANTHROPIC_AUTH_TOKEN:Z}:rJ(),Q=J.ANTHROPIC_AUTH_TOKEN,Y=J.ANTHROPIC_BASE_URL||"";if(!Q)return{state:"no_credentials"};let V=vU(Y);if(!V)return{state:"not_glm",baseUrl:Y||void 0};return bU.readStale(O$("glm",V,Q),()=>fU(V,Q))}async function fU($,Z){let J=`${$}/api/monitor/usage/quota/limit`,Q=new AbortController,Y=setTimeout(()=>Q.abort(),oG);try{let V=await V0(J,{headers:{Authorization:Z,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:Q.signal});if(!V.ok)return j(`glm-usage: quota/limit HTTP ${V.status}`),{state:V.status===429?"rate_limited":"network",reason:`HTTP ${V.status}`,retryAfterMs:l$(V.headers)};let X=await V.json(),z=X?.error?.code??X?.code;if(X?.success===!1||X?.error!=null||z!==void 0&&String(z)!=="200"){let W=X?.error?.message??X?.msg??X?.message??(typeof X?.error==="string"?X.error:void 0),K=[z===void 0?"":`code ${z}`,W===void 0?"":String(W)].filter(Boolean).join(": ").replaceAll(Z,"[redacted]")||"GLM 额度接口返回失败";return j(`glm-usage: quota/limit MISS: ${K}`),{state:String(z)==="429"?"rate_limited":"network",reason:K,retryAfterMs:l$(V.headers)}}let H=X?.data??X,G=yU(H);if(G.state==="network")j(`glm-usage: quota/limit MISS: ${G.reason}`);return G}catch(V){let X=(V?.name==="AbortError"?`timeout ${oG}ms`:V?.message??String(V)).replaceAll(Z,"[redacted]");return j(`glm-usage: quota/limit fetch failed: ${X}`),{state:"network",reason:X}}finally{clearTimeout(Y)}}var oG=1e4,bU;var b7=R(()=>{u0();I();_1();bU=new X$});function r$($){let Z=new URL($);if(!["http:","https:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("PackyAPI 地址必须是无凭据、查询参数和 fragment 的 HTTP(S) API 根地址");return Z.pathname=Z.pathname.replace(/\/+$/,"").replace(/\/v1$/,""),Z.toString().replace(/\/$/,"")}function o4($){let Z=r$($),J=new URL(Z);return J.protocol==="https:"&&!J.port&&J.pathname==="/"&&["cf.api.fan","slb-v1.api.fan","www.packyapi.ai"].includes(J.hostname)?hU:Z}function eJ($,Z){let J=r$($),Q=O$("packy-models",J,Z),Y=k7.get(Q);if(Y)return Y;let V=u$(`${J}/v1/models`,Z,"PackyAPI models").then((X)=>{let z=new Set;return X.map((H)=>{if(typeof H.id!=="string"||!H.id.trim()||z.has(H.id)||!Array.isArray(H.supported_endpoint_types)||!H.supported_endpoint_types.length||!H.supported_endpoint_types.every((G)=>typeof G==="string"&&G))throw Error("PackyAPI 模型目录缺少有效 id/协议声明,或含重复模型");return z.add(H.id),{id:H.id,display:typeof H.name==="string"&&H.name?H.name:H.id,protocols:[...H.supported_endpoint_types],...t$(H.reasoning)?{reasoning:H.reasoning}:{}}})}).finally(()=>{if(k7.get(Q)===V)k7.delete(Q)});return k7.set(Q,V),V}function t$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}async function v7($,Z,J={}){let Q=await V0($,{headers:{Accept:"application/json","Cache-Control":"no-cache","User-Agent":"Lodestar-Account-Balance/1.0",...J,...Z?{Authorization:`Bearer ${Z}`}:{}},redirect:"error",signal:AbortSignal.timeout(15000)}),Y=await Q.text(),V;try{V=JSON.parse(Y)}catch{throw new D1(Q.status,"响应不是有效 JSON",l$(Q.headers))}let X=t$(V)?V.code:void 0,z=X!==void 0&&![!0,0,200,"0","200"].some((H)=>H===X);if(!Q.ok||!t$(V)||V.success===!1||z||V.error!=null){let H=t$(V)&&t$(V.error)?V.error.message:t$(V)?V.message:null;throw new D1(Q.status,typeof H==="string"?H:"上游接口返回错误",l$(Q.headers))}return V}async function $Q($,Z,J,Q=!1){if(Z=Z.trim(),J=J.trim(),!Z||!/^[1-9]\d*$/.test(J)||!Number.isSafeInteger(Number(J)))return{state:"no_credentials",kind:"balance",windows:[],reason:"PackyAPI 真实余额需要系统访问令牌和正整数用户 ID;请配置 packy-balance-setup。"};let Y=r$($),V=O$("packy-balance",Y,JSON.stringify([J,Z])),X=async()=>{try{let H=await v7(`${Y}/api/user/self`,Z,{"New-Api-User":J}),G=H.data;if(H.success!==!0||!t$(G)||G.id!==Number(J))throw Error("PackyAPI 账户响应缺少成功状态,或用户 ID 与余额凭据不匹配");if(typeof G.quota!=="number"||!Number.isSafeInteger(G.quota))throw Error("PackyAPI 账户余额 quota 缺失或无效");let W=(await v7(`${Y}/api/status`)).data;if(!t$(W)||typeof W.quota_per_unit!=="number"||!Number.isFinite(W.quota_per_unit)||W.quota_per_unit<=0||W.quota_display_type!=="USD")throw Error("PackyAPI 账户余额单位缺失或不是已支持的 USD 单位");let K=G.quota/W.quota_per_unit;if(!Number.isFinite(K))throw Error("PackyAPI 账户余额换算结果无效");return{state:"ok",kind:"balance",windows:[],fetchedAt:Date.now(),balance:{remaining:K,currency:"USD"}}}catch(H){let G=f0(H,[Z]);return j(`PackyAPI balance MISS: ${G}`),{state:H instanceof D1&&[401,403].includes(H.status)?"no_credentials":H instanceof D1&&H.status===429?"rate_limited":"network",kind:"balance",windows:[],reason:G,...H instanceof D1&&H.retryAfterMs!==void 0?{retryAfterMs:H.retryAfterMs}:{}}}};if(!Q)return w7.readStale(V,X);let z=await X();if(z.state==="ok")w7.prime(V,z);else w7.invalidate(V);return z}async function eG($,Z){if(!Z)return{state:"no_credentials",kind:"quota",windows:[]};let J=o4($);return w7.readStale(O$("packy",J,Z),async()=>{try{let Y=(await v7(`${J}/api/usage/token/`,Z)).data;if(!t$(Y)||typeof Y.unlimited_quota!=="boolean")throw Error("PackyAPI 令牌配额响应缺少 unlimited_quota");if(Y.unlimited_quota)return{state:"not_applicable",kind:"balance",windows:[],reason:"此 API key 为无限额度令牌;令牌接口不提供账户余额,需要系统访问令牌查询。"};let{total_available:V,total_granted:X}=Y;if(typeof V!=="number"||!Number.isFinite(V)||typeof X!=="number"||!Number.isFinite(X)||X<0)throw Error("PackyAPI 令牌配额数值缺失或无效");let z=(await v7(`${J}/api/status`)).data;if(!t$(z)||typeof z.quota_per_unit!=="number"||!Number.isFinite(z.quota_per_unit)||z.quota_per_unit<=0||z.quota_display_type!=="USD")throw Error("PackyAPI 配额单位缺失或不是已支持的 USD 额度单位");return{state:"ok",kind:"quota",windows:[],fetchedAt:Date.now(),quota:{remaining:V/z.quota_per_unit,limit:X/z.quota_per_unit,currency:"USD"}}}catch(Q){let Y=f0(Q,[Z]);return j(`PackyAPI quota MISS: ${Y}`),{state:Q instanceof D1&&[401,403].includes(Q.status)?"no_credentials":Q instanceof D1&&Q.status===429?"rate_limited":"network",kind:"quota",windows:[],reason:Y,...Q instanceof D1&&Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{}}}})}var f2="https://cf.api.fan",hU="https://www.packyapi.ai",k7,D1,w7;var ZQ=R(()=>{u0();_4();_1();I();k7=new Map;D1=class D1 extends Error{status;retryAfterMs;constructor($,Z,J){super(`PackyAPI HTTP ${$}: ${Z}`);this.status=$;this.retryAfterMs=J}};w7=new X$});function $W($){return h7.find((Z)=>Z.other===$)?.id??$}function ZW($){let Z=h7.find((J)=>J.id===$||J.other===$);return Z?[Z.id,Z.other]:[$]}function P8($){let Z=$.api_key?.trim(),J=$.auth_token?.trim();if(Z&&J&&Z!==J)throw Error("同一账号的 api_key 与 auth_token 不一致,请重新配置");return Z||J}function f7($,Z){if($.id==="packy")return r$(Z);let J=new URL(Z);if(!["http:","https:"].includes(J.protocol)||J.username||J.password||J.search||J.hash)throw Error(`${$.id} 接口地址必须是无凭据、查询参数和 fragment 的 HTTP(S) 地址`);if($.id==="glm")return T9(`${J.origin}/api/anthropic`);if(J.pathname=J.pathname.replace(/\/+$/,""),J.hostname==="api.deepseek.com"&&["/","/v1"].includes(J.pathname))J.pathname="/anthropic";return J.toString().replace(/\/+$/,"")}function y7($,Z){let J=f7($,Z);return $.id==="deepseek"?J.replace(/\/anthropic$/,""):J}function s4($){let{api_key:Z,auth_token:J,base_url:Q,...Y}=$;return Y}function JQ($,Z,J={}){let Q=Z[$.id]??{},Y=Z[$.other]??{},V=P8(Q),X=P8(Y),z=Q.base_url?.trim(),H=Y.base_url?.trim();if(V&&X&&V!==X||z&&H&&y7($,z)!==y7($,H))throw Error(`${$.id} 与 ${$.other} 的旧账号配置冲突;请用 ${$.id}-setup 重新设置共享账号`);if(V||X)return{key:V||X,base:f7($,z||H||$.base)};let G=J[$.id]??J[$.other]??{};if(P8(G)&&(z||H)&&G.base_url&&y7($,z||H)!==y7($,G.base_url))throw Error(`${$.id} 的平台地址与本机识别的账号不一致,请用 ${$.id}-setup 配置 Key`);return{key:P8(G),base:f7($,z||H||G.base_url||$.base)}}function L8($,Z={}){let J={...$};for(let Q of h7){let{key:Y,base:V}=JQ(Q,$,Z);J[Q.id]={...s4($[Q.id]??{}),base_url:V,...Q.id==="glm"?{auth_token:Y??""}:{api_key:Y??""}},J[Q.other]={...s4($[Q.other]??{}),api_key:Y??"",base_url:Q.id==="glm"?`${new URL(V).origin}/api/coding/paas/v4`:Q.id==="deepseek"?V.replace(/\/anthropic$/,""):V}}return IU(J),J}function IU($){let Z=new Set(["packy","packy-secondary","packy-codex"]),J=new Set,Q=new Set,Y=(X)=>!!(X.management_token?.trim()||X.management_user_id?.trim()||X.management_url?.trim()),V=(X)=>{if(Q.has(X))throw Error(`PackyAPI 余额账号引用循环:${X}`);if(J.has(X))return $[X];Q.add(X);let z=$[X]??{},H=z.billing_source?.trim(),G=H||(X==="packy-codex"&&!Y(z)?"packy":void 0);if(G){if(!Z.has(G)||!$[G])throw Error(`PackyAPI 余额账号引用不存在:${G}`);if(H&&Y(z))throw Error(`PackyAPI ${X} 不能同时配置 billing_source 和独立余额凭据`);let W=V(G);$[X]={...z,...H||Y(W)||W.billing_source?{billing_source:G,management_token:W.management_token,management_user_id:W.management_user_id,management_url:W.management_url||o4(W.base_url||f2)}:{}}}return Q.delete(X),J.add(X),$[X]??z};for(let X of Z)if($[X])V(X)}function QQ($,Z,J){let Q=Object.fromEntries(Object.entries(J).filter(([,H])=>H!==void 0)),Y={...$,[Z]:{...$[Z],...Q}},V=h7.find((H)=>H.id===Z||H.other===Z);if(!V)return{[Z]:Y[Z]};let X=J.api_key!==void 0||J.auth_token!==void 0,z=J.base_url!==void 0;if(X||z){let H=$[Z]??{},G=$[V.id]??{},W=$[V.other]??{},K=X?P8(J):JQ(V,$).key,B=f7(V,J.base_url?.trim()||H.base_url||G.base_url||W.base_url||V.base);Y[V.id]={...s4(Y[V.id]??{}),base_url:B,...V.id==="glm"?{auth_token:K??""}:{api_key:K??""}},Y[V.other]=s4(Y[V.other]??{})}else{let{key:H,base:G}=JQ(V,Y);Y[V.id]={...s4(Y[V.id]??{}),base_url:G,...V.id==="glm"?{auth_token:H??""}:{api_key:H??""}},Y[V.other]=s4(Y[V.other]??{})}return{[V.id]:Y[V.id],[V.other]:Y[V.other]}}var h7;var q8=R(()=>{E9();ZQ();h7=[{id:"deepseek",other:"deepseek-harness",base:"https://api.deepseek.com/anthropic"},{id:"glm",other:"dsh-glm",base:"https://open.bigmodel.cn/api/anthropic"},{id:"packy",other:"packy-codex",base:"https://cf.api.fan"}]});function mU($){let Z=new URL($),J=Z.pathname.replace(/\/+$/,"");return`${Z.protocol}//${Z.host}${J}/v1/messages`}async function I7($,Z,J){try{let Q=await V0(mU($),{method:"POST",headers:{"Content-Type":"application/json",...Z},body:JSON.stringify({model:J,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:AbortSignal.timeout(gU)});if(Q.ok)return"exists";if(Q.status===400){let Y=await Q.text();return Y.includes("1214")||Y.includes("不存在")||Y.includes("not exist")?"not_found":"no_verdict"}return j(`model-existence: ${J} HTTP ${Q.status}, no verdict`),"no_verdict"}catch(Q){return j(`model-existence: ${J} MISS (${Q?.message??Q})`),"no_verdict"}}var gU=15000;var YQ=R(()=>{u0();I()});function JW($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function pU($){return{kind:"monthly",label:"月度工具",percent:$.percent,resetsAt:$.resetsAt,...$.used!=null?{used:$.used}:{},...$.total!=null?{total:$.total}:{}}}function QW($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function cU($){let Z=(J)=>{let Q=J.match(/(\d+(?:\.\d+)?)/);return Q?Number(Q[1]):-1};return[...$].sort((J,Q)=>Z(Q)-Z(J))[0]??""}function uU($){let Z={};for(let J of($??"").split(",")){let Q=J.indexOf("=");if(Q<=0)continue;let Y=J.slice(0,Q).trim().toLowerCase(),V=J.slice(Q+1).trim();if((Y==="opus"||Y==="sonnet"||Y==="haiku")&&V)Z[Y]=V}return Z}function VQ($){if($.state!=="ok")return{state:$.state==="no_credentials"?"no_credentials":$.state==="not_glm"?"not_applicable":$.state==="rate_limited"?"rate_limited":"network",windows:[],..."retryAfterMs"in $?{retryAfterMs:$.retryAfterMs}:{},...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(JW($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(JW($.weekly,"weekly","周额度"));if($.monthly)Z.push(pU($.monthly));return{state:"ok",planLabel:$.level?`${$.level} 套餐`:void 0,windows:Z,fetchedAt:$.fetchedAt}}var XQ=R(()=>{X0();b7();f4();o9();YQ();I();E9();N0({kind:"glm-coding-plan",configSectionId:"glm",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||"",Q=$.auth_token?.trim()||Z?.auth_token?.trim()||"",Y=!!(J&&Q)&&y2(J),V=$.model?.trim()||void 0,X=uU($.slots),z={id:"glm",kind:"glm-coding-plan",agent:"claude",display:$.display?.trim()||"GLM Coding Plan",enabled:Y,models:[],modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!z.enabled){z.models=[],z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}z.modelCatalogState={status:"loading",updatedAt:null};try{let H=await rH(J,Q),W=[...new Set([...QW($.models),...QW($.custom_models)])].filter((K)=>!H.some((B)=>B.model.toLowerCase()===K.toLowerCase())).map((K)=>({model:K,display:K,efforts:y4,defaultEffort:"max",origin:"custom"}));if(z.models=[...H,...W],!V)z.defaultModel=cU(z.models.map((K)=>K.model));for(let K of z.models){let B=k4("glm",K.model);K.context1m=B!=null&&B>=1e6||void 0}z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(H){j(`glm refreshModels MISS: ${H?.message??H}`),z.models=[],z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:H?.message??String(H)}}},spawnEnv(H){let W={...o0(H)};if(W.ANTHROPIC_BASE_URL=J,W.ANTHROPIC_AUTH_TOKEN=Q,X.opus)W.ANTHROPIC_DEFAULT_OPUS_MODEL=X.opus;if(X.sonnet)W.ANTHROPIC_DEFAULT_SONNET_MODEL=X.sonnet;if(X.haiku)W.ANTHROPIC_DEFAULT_HAIKU_MODEL=X.haiku;return W},resolveSpawnModel(H){return e3("glm",H)},async verifyModel(H){return I7(J,{Authorization:`Bearer ${Q}`},H)},async readUsage(){return VQ(await x7(J,Q))}};return z},setup:{commandSuffix:"glm",hint:($)=>`配置 ${$}:发送 \`glm-setup <api_key>\`(智谱国内站),或 \`glm-setup <base_url> <api_key>\`(指定平台)。Claude Code 和 DeepSeek Harness 共用该账号;校验失败保留原配置。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:glm-setup <api_key>,或 glm-setup <base_url> <api_key>;只填写 Key 本身,不加 Bearer 前缀。"};try{return{config:{agent:"claude",base_url:T9(Z.length===2?Z[0]:P4),auth_token:Z.at(-1)}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}},async validate($){await L4($.base_url??P4,$.auth_token??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!y2(Z))return null;let J=$.ANTHROPIC_AUTH_TOKEN?.trim()??"";return J?{base_url:Z,auth_token:J}:null}}})});var YW=R(()=>{X0();f4();N0({kind:"claude-native",configSectionId:"claude-native",build:($)=>{let Z={id:"claude-native",kind:"claude-native",agent:"claude",display:$.display?.trim()||"Claude",enabled:!1,models:[],modelCatalogState:{status:"disabled",updatedAt:Date.now()},defaultModel:$.model?.trim()||"opus",settingSources:["user","project","local"],async refreshModels(){if(Z.models=[],!Z.enabled){Z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}Z.modelCatalogState={status:"loading",updatedAt:null};try{if(Z.models=await z7(),!Z.models.some((J)=>J.model===Z.defaultModel))throw Error("Claude 默认模型不在 SDK 目录中");Z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(J){throw Z.models=[],Z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:J instanceof Error?J.message:String(J)},J}},spawnEnv(J){return J},resolveSpawnModel(J){return J},async readUsage(){return{state:"not_applicable",windows:[]}}};return Z}})});import{homedir as lU}from"node:os";function m7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function g7($,Z,J){if($==null)return{kind:Z,label:J,percent:null,resetsAt:null};if(!m7($))throw Error(`Claude ${J}格式无效`);let Q=$.utilization;if(Q!==null&&(typeof Q!=="number"||!Number.isFinite(Q)||Q<0||Q>100))throw Error(`Claude ${J} utilization 缺失或无效`);let Y=$.resets_at;if(Y!==null&&(typeof Y!=="string"||!Number.isFinite(Date.parse(Y))))throw Error(`Claude ${J} resets_at 缺失或无效`);return{kind:Z,label:J,percent:Q,resetsAt:Y===null?null:new Date(Y)}}function XW($){return $.trim().toLowerCase().replace(/^claude:/,"").replace(/\[1m\]$/,"").replace(/^claude[-\s]+/,"").replace(/^(?:\d+[.-])+/,"").split(/[-\s]+/,1)[0]}function zW($,Z){if($.state!=="ok"||!Z?.trim())return null;let J=XW(i9(Z.trim()));if(!J||J==="default")return null;let Q=$.windows.filter((Y)=>{let V=Y.kind.startsWith("modelWeekly:")?Y.kind.slice(12):Y.kind==="seven_day_opus"?"opus":Y.kind==="seven_day_sonnet"?"sonnet":null;return V!==null&&XW(V)===J});if(Q.length>1)return j(`Claude weekly usage MISS: ${Z} 匹配多个模型专属周额度窗口`),null;if(Q.length===1)return Q[0];return $.windows.find((Y)=>Y.kind==="weekly")??null}function iU($){if(!m7($)||typeof $.subscription_type!=="string"||!$.subscription_type.trim())throw Error("Claude 订阅额度响应缺少订阅身份");if($.rate_limits_available!==!0)throw Error("Claude 原生接口未开放当前订阅额度查询");if(!m7($.rate_limits))throw Error("Claude 原生额度接口未返回 rate_limits 数据");let Z=$.rate_limits,J=[g7(Z.five_hour,"fiveHour","5h 窗口"),g7(Z.seven_day,"weekly","周额度")],Q=Z.five_hour!=null||Z.seven_day!=null;for(let[Y,V]of[["seven_day_oauth_apps","OAuth 应用周额度"],["seven_day_opus","Opus 周额度"],["seven_day_sonnet","Sonnet 周额度"]]){if(Z[Y]==null)continue;J.push(g7(Z[Y],Y,V)),Q=!0}if(Z.model_scoped!=null){if(!Array.isArray(Z.model_scoped))throw Error("Claude 模型专属额度 model_scoped 格式无效");for(let Y of Z.model_scoped){if(!m7(Y)||typeof Y.display_name!=="string"||!Y.display_name.trim())throw Error("Claude 模型专属额度缺少模型名称");let V=Y.display_name.trim();J.push(g7(Y,`modelWeekly:${V}`,`${V} 周额度`)),Q=!0}}if(!Q)throw Error("Claude 原生额度接口未返回任何订阅额度窗口");return{state:"ok",windows:J,fetchedAt:Date.now()}}async function HW($){return dU.readStale("claude-subscription",()=>nU($))}async function nU($){try{let{ClaudeAgentProcess:Z}=await Promise.resolve().then(() => (v4(),JJ)),J=new Z({workDir:lU(),effort:"default",profile:{loadProjectMcp:!1},...$});J.on("error",(V)=>j(`Claude subscription usage MISS: ${V.message}`));let Q,Y;try{let V=await Promise.race([J.readSubscriptionUsage(),new Promise((X,z)=>{Q=setTimeout(()=>z(Error(`Claude 订阅额度查询超时(${VW/1000}s)`)),VW)})]);return iU(V)}catch(V){throw Y=V instanceof Error?V:Error(String(V)),Y}finally{clearTimeout(Q);try{await J.kill()}catch(V){if(Y)throw AggregateError([Y,V],`${Y.message};额度查询进程关闭失败:${V instanceof Error?V.message:String(V)}`);throw V}}}catch(Z){let J=Z instanceof Error?Z.message:String(Z);return j(`claude-sub readUsage MISS: ${J}`),{state:Z?.code==="CLAUDE_SUBSCRIPTION_AUTH_MISSING"?"no_credentials":q2(Z)?"rate_limited":"network",windows:[],reason:J}}}var VW=30000,dU;var zQ=R(()=>{I();gZ();_1();dU=new X$});function aU(){let $=Object.fromEntries(s3.map((Z)=>[Z,""]));return $.ANTHROPIC_BASE_URL="https://api.anthropic.com",$.CLAUDE_CODE_NO_MODEL_FALLBACK="1",{env:$,apiKeyHelper:"",forceLoginMethod:"claudeai"}}function oU($){if(!$.subscriptionType?.trim())throw Object.assign(Error("Claude Code 订阅未登录;请在本机运行 claude auth login,完成后等待后台刷新,发送 md 查看状态"),{code:"CLAUDE_SUBSCRIPTION_AUTH_MISSING"});if($.apiProvider!=="firstParty"||$.apiKeySource&&$.apiKeySource!=="none")throw Error("Claude Code 当前认证不是第一方订阅;请检查本机登录方式和托管设置")}var GW=R(()=>{P0();I();X0();f4();zQ();L1();N0({kind:"claude-subscription",configSectionId:"claude-sub",build($){let Z=aU(),J=$.model?.trim(),Q="Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用",Y,V={id:"claude-sub",kind:"claude-subscription",agent:"claude",display:$.display?.trim()||"Claude Code 订阅",enabled:$.enabled!==!1,models:[],defaultModel:J??"",modelCatalogState:$.enabled===!1?{status:"disabled",updatedAt:Date.now(),error:"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"}:{status:"idle",updatedAt:Date.now()},settingSources:["user","project","local"],claudeSettings:Z,validateClaudeAccount:oU,spawnEnv(X){return{...o0(X),...Z.env}},resolveSpawnModel(X){return X},async refreshModels(){if($.enabled===!1){V.enabled=!1,V.models=[],V.modelCatalogState={status:"disabled",updatedAt:Date.now(),error:"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"};return}V.enabled=!0,V.models=[],V.modelCatalogState={status:"loading",updatedAt:null};try{let X=await z7({settingSources:["user"],settings:Z,transformEnv:V.spawnEnv,validateAccount:V.validateClaudeAccount,tokenSourceId:V.id});if(!X.length)throw Error("Claude Code 订阅模型目录为空");let z=[...s($.custom_models),...s($.models)];if(J&&!X.some((H)=>H.model===J)&&!z.includes(J))throw Error(`Claude Code 订阅默认模型不在目录中且未补录: ${J}`);if($.effort){let H=X.find((G)=>G.model===(J??X[0].model));if(!w0($.effort)||H&&!H.efforts.includes($.effort))throw Error(`Claude Code 订阅默认模型不支持 effort: ${$.effort}`);if(H)H.defaultEffort=$.effort}V.defaultModel=J??X[0].model,V.models=X,V.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(X){let z=X instanceof Error?X.message:String(X);if(j(`claude-sub refreshModels MISS: ${z}`),X?.code==="CLAUDE_SUBSCRIPTION_AUTH_MISSING")V.enabled=!1;V.modelCatalogState={status:V.enabled?"failed":"disabled",updatedAt:Date.now(),error:z}}},readUsage(){if(!V.enabled)return Promise.resolve({state:"not_applicable",windows:[],reason:V.modelCatalogState?.error??"Claude Code 订阅已在 Lodestar 中禁用;发送 claude-sub on 启用"});return Y??=HW({settingSources:["user"],settings:Z,transformEnv:V.spawnEnv,validateAccount:V.validateClaudeAccount,tokenSourceId:V.id}).finally(()=>{Y=void 0}),Y}};return V}})});function KW($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function sU($){let Z=(J)=>{let Q=J.match(/(\d+(?:\.\d+)?)/);return Q?Number(Q[1]):-1};return[...$].sort((J,Q)=>Z(Q)-Z(J))[0]??""}function tU($){let Z={};for(let J of($??"").split(",")){let Q=J.indexOf("=");if(Q<=0)continue;let Y=J.slice(0,Q).trim().toLowerCase(),V=J.slice(Q+1).trim();if((Y==="opus"||Y==="sonnet"||Y==="haiku")&&V)Z[Y]=V}return Z}function rU($){try{return new URL($).hostname.toLowerCase()==="api.deepseek.com"}catch{return!1}}async function BW($,Z){return(await HQ(new URL($).origin,Z)).map((Q)=>({model:Q,display:Q,efforts:y4,defaultEffort:"high"}))}async function HQ($,Z){let J=new URL($);if(!["https:","http:"].includes(J.protocol)||J.username||J.password||J.search||J.hash)throw Error("DeepSeek 需要无凭据和查询参数的 HTTP(S) API 根地址");return(await u$(`${J.toString().replace(/\/+$/,"")}/models`,Z,"DeepSeek models")).map((Y)=>{if(typeof Y.id!=="string"||!Y.id.trim())throw Error("DeepSeek models 模型 id 无效");return Y.id})}async function GQ($,Z){if(!Z.trim())return{kind:"balance",state:"no_credentials",windows:[]};let J;try{J=new URL($).origin}catch{return{kind:"balance",state:"network",windows:[],reason:"bad base_url"}}return $O.readStale(O$("deepseek",J,Z),()=>ZO(J,Z))}async function ZO($,Z){try{let J=await V0(`${$}/user/balance`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(eU)});if(!J.ok)return j(`deepseek readUsage MISS: HTTP ${J.status}`),{kind:"balance",state:J.status===429?"rate_limited":"network",windows:[],reason:`HTTP ${J.status}`,retryAfterMs:l$(J.headers)};let Q=await J.json(),V=(Array.isArray(Q?.balance_infos)?Q.balance_infos:[])[0],X=typeof V?.currency==="string"?V.currency:"",z=V?.total_balance;if(!X||typeof z!=="string"&&typeof z!=="number"||String(z).trim()===""||!Number.isFinite(Number(z)))throw Error("余额明细缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Number(z),currency:X}}}catch(J){return j(`deepseek readUsage MISS: ${J?.message??J}`),{kind:"balance",state:"network",windows:[],reason:J?.message??String(J)}}}var WW="https://api.deepseek.com/anthropic",eU=1e4,$O;var WQ=R(()=>{u0();X0();f4();o9();YQ();I();_4();_1();$O=new X$;N0({kind:"deepseek",configSectionId:"deepseek",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||WW,Q=$.api_key?.trim()||Z?.api_key?.trim()||"",Y=!!Q,V=$.model?.trim()||void 0,X=tU($.slots),z={id:"deepseek",kind:"deepseek",agent:"claude",display:$.display?.trim()||"DeepSeek",enabled:Y,models:[],modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!z.enabled){z.models=[],z.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}z.modelCatalogState={status:"loading",updatedAt:null};try{let H=await BW(J,Q),W=[...new Set([...KW($.models),...KW($.custom_models)])].filter((K)=>!H.some((B)=>B.model.toLowerCase()===K.toLowerCase())).map((K)=>({model:K,display:K,efforts:y4,defaultEffort:"high",origin:"custom"}));if(z.models=[...H,...W],!V)z.defaultModel=sU(z.models.map((K)=>K.model));for(let K of z.models){let B=k4("deepseek",K.model);K.context1m=B!=null&&B>=1e6||void 0}z.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(H){j(`deepseek refreshModels MISS: ${H?.message??H}`),z.models=[],z.modelCatalogState={status:"failed",updatedAt:Date.now(),error:H?.message??String(H)}}},spawnEnv(H){let W={...o0(H)};if(W.ANTHROPIC_BASE_URL=J,W.ANTHROPIC_API_KEY=Q,X.opus)W.ANTHROPIC_DEFAULT_OPUS_MODEL=X.opus;if(X.sonnet)W.ANTHROPIC_DEFAULT_SONNET_MODEL=X.sonnet;if(X.haiku)W.ANTHROPIC_DEFAULT_HAIKU_MODEL=X.haiku;return W},resolveSpawnModel(H){return e3("deepseek",H)},async verifyModel(H){return I7(J,{"x-api-key":Q},H)},async readUsage(){if(!Q)return{kind:"balance",state:"no_credentials",windows:[]};return GQ(J,Q)}};return z},setup:{commandSuffix:"deepseek",hint:($)=>`配置 ${$}:发送 \`deepseek-setup <api_key>\`;Claude Code 和 DeepSeek Harness 共用该账号。自建端点用 \`deepseek-setup <base_url> <api_key>\`。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(!Z.length||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:`deepseek-setup <api_key>`(官方端点)或 `deepseek-setup <base_url> <api_key>`(自建中转)"};let J=Z.length>=2?Z[0]:void 0,Q=Z.length>=2?Z[1]:Z[0];return{config:{agent:"claude",...J?{base_url:J}:{},api_key:Q}}},async validate($){await BW($.base_url??WW,$.api_key??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!rU(Z))return null;let J=$.ANTHROPIC_API_KEY?.trim()??"";return J?{base_url:Z,api_key:J}:null}}})});function KQ($){for(let Z of jW){let J=Z.pattern.exec($.toLowerCase());if(!J)continue;let Q=J.groups,Y=Q.version.split(/[.-]/),V=Q.date??(Y.at(-1).length===8?Y.pop():void 0);if(!Y.length||Y.some((X)=>!Number.isSafeInteger(Number(X))))return;return{preset:Z,version:Y.map(Number),date:V?Number(V):0,preview:!!Q.preview}}return}function _W($){return KQ($)?.preset}function PW($){let Z=KQ($.replace(/\[1m\]$/,""))?.preset.family;return Z?`family:${Z}`:`model:${$}`}function LW($){let Z=new Map;for(let J of $){let Q=KQ(J);if(!Q)continue;let Y=Z.get(Q.preset.family),V=0;if(Y){for(let X=0;X<Math.max(Q.version.length,Y.version.length);X++)if(V=(Q.version[X]??0)-(Y.version[X]??0),V)break;V||=Number(Y.preview)-Number(Q.preview)||Q.date-Y.date||Y.model.length-J.length||Y.model.localeCompare(J)}if(!Y||V>0)Z.set(Q.preset.family,{...Q,model:J})}return jW.flatMap((J)=>{let Q=Z.get(J.family);return Q?[Q.model]:[]})}function h2($){let Z=$.toLowerCase().replace(/^~/,"");return/^(openai|deepseek|z-ai|zai-org|thudm)\//.test(Z)||/^(openrouter\/|@)/.test(Z)}var jW;var qW=R(()=>{jW=[{rank:4,lab:"Tencent",model:"tencent/hy4-preview",effort:"high",family:"hy",pattern:/^tencent\/hy(?<version>\d+(?:[.-]\d+)*)(?:-(?<preview>preview))?(?:-(?<date>\d{8}))?$/},{rank:7,lab:"Google",model:"google/gemini-3.8-flash",effort:"high",family:"gemini-flash",pattern:/^google\/gemini-(?<version>\d+(?:[.-]\d+)*)-flash(?:-(?<date>\d{8}))?$/},{rank:10,lab:"Meta",model:"meta/muse-spark-1.2",effort:"xhigh",family:"muse-spark",pattern:/^meta\/muse-spark-(?<version>\d+(?:[.-]\d+)*)$/},{rank:11,lab:"Xiaomi",model:"xiaomi/mimo-v2.5-pro",effort:"default",family:"mimo-pro",pattern:/^xiaomi\/mimo-v(?<version>\d+(?:[.-]\d+)*)-pro(?:-(?<date>\d{8}))?$/},{lab:"ByteDance",model:"bytedance-seed/seed-2-1-turbo",effort:"default",family:"seed-turbo",pattern:/^bytedance-seed\/seed-(?<version>\d+(?:[.-]\d+)*)-turbo(?:-(?<date>\d{8}))?$/},{lab:"Meituan",model:"meituan/longcat-2.0",effort:"default",family:"longcat",pattern:/^meituan\/longcat-(?<version>\d+(?:[.-]\d+)*)$/}]});function g2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _Q($){return $ instanceof Error?$.message:String($)}function jQ($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function I2($){return $.replace(/\[1m\]$/,"")}function t4($){let Z=new URL($);if(!["https:","http:"].includes(Z.protocol)||Z.username||Z.password||Z.search||Z.hash)throw Error("OpenRouter base_url 必须是无凭据、查询参数和 fragment 的 HTTP(S) API 根地址");return Z.pathname=Z.pathname.replace(/\/+$/,"").replace(/\/v1$/,""),Z.toString().replace(/\/+$/,"")}async function YO($,Z,J){if(!Z)throw Error("OpenRouter API key missing");let Q=await V0(`${t4($)}/v1/${J}`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(JO)});if(!Q.ok){let Y=await Q.text(),V="";if(Y.trim().startsWith("{"))try{let X=JSON.parse(Y);if(g2(X)&&g2(X.error)&&typeof X.error.message==="string")V=X.error.message}catch{}throw new p7(Q.status,V.replaceAll(Z,"[redacted]"),l$(Q.headers))}return Q.json()}async function DW($,Z){let J=await u$(`${t4($)}/v1/models/user`,Z,"OpenRouter models"),Q=[],Y=new Set;for(let V of J){if(!g2(V)||typeof V.id!=="string"||!V.id||typeof V.name!=="string")throw Error("OpenRouter models: 模型 id/name 无效");if(!g2(V.architecture)||!Array.isArray(V.architecture.output_modalities)||!Array.isArray(V.supported_parameters))throw Error(`OpenRouter models: ${V.id} 的模型能力缺失`);if(h2(V.id)||!V.architecture.output_modalities.includes("text")||!V.supported_parameters.includes("tools")||V.id.endsWith(":batch")||Y.has(V.id))continue;let X=g2(V.reasoning)?V.reasoning:void 0,z=X?.supported_efforts,H=z===null||z===void 0&&V.supported_parameters.includes("reasoning_effort")?["max","xhigh","high","medium","low"]:Array.isArray(z)?[...new Set(z.filter((B)=>B!=="default"&&w0(B)))]:["default"],G=_W(V.id),W=G?H.includes(G.effort)?G.effort:null:H[0]==="default"?"default":w0(X?.default_effort)&&H.includes(X.default_effort)?X.default_effort:null,K=k4("openrouter",V.id);Q.push({model:V.id,display:V.name,efforts:H,defaultEffort:W,context1m:K!==void 0&&K>=1e6||void 0}),Y.add(V.id)}if(!Q.length)throw Error("OpenRouter 未返回支持文本和工具调用的交互模型");return Q}function MW($){return typeof $==="number"&&Number.isFinite($)&&$>=0}async function VO($,Z){if(!Z)return{kind:"balance",state:"no_credentials",windows:[]};return QO.readStale(O$("openrouter",t4($),Z),()=>XO($,Z))}async function XO($,Z){try{let J=await YO($,Z,"credits");if(!g2(J)||!g2(J.data))throw Error("OpenRouter credits: data 对象缺失");let{total_credits:Q,total_usage:Y}=J.data;if(!MW(Q)||!MW(Y))throw Error("OpenRouter credits: total_credits/total_usage 缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Q-Y,currency:"USD"}}}catch(J){let Q=_Q(J);return j(`openrouter readUsage MISS: ${Q}`),{kind:"balance",state:J instanceof p7&&J.status===429?"rate_limited":"network",windows:[],reason:Q,...J instanceof p7?{retryAfterMs:J.retryAfterMs}:{}}}}var FW="https://openrouter.ai/api",JO=1e4,QO,BQ,p7;var UW=R(()=>{u0();P0();X0();o9();I();qW();_4();_1();QO=new X$,BQ={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL"};p7=class p7 extends Error{status;retryAfterMs;constructor($,Z,J){super(`HTTP ${$}${Z?`: ${Z}`:""}`);this.status=$;this.retryAfterMs=J}};N0({kind:"openrouter",configSectionId:"openrouter",build($,Z){let J=$.api_key||$.auth_token||$.base_url?$:Z,Q=J?.api_key?.trim()||J?.auth_token?.trim()||"",Y=J?.base_url?.trim()||FW,V=$.model?.trim()||"",X=$.models===void 0?void 0:jQ($.models),z=(G)=>LW(G.filter((W)=>W.origin!=="custom").map((W)=>W.model)),H={id:"openrouter",kind:"openrouter",agent:"claude",display:$.display?.trim()||"OpenRouter",enabled:!!Q,models:[],defaultModel:V,modelSelection:{mode:"allowlist",modelIds:X??[],availableModels:[],...X===void 0?{selectDefaults:z,visibilityKey:PW}:{}},validateCustomModelId(G){if(h2(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);if(!G.includes("/"))throw Error("OpenRouter 模型请填写完整的 作者/模型 ID")},modelEnvironmentRevision(G){let W=H.modelSelection.availableModels.find((K)=>I2(K.model)===I2(G));if(!W||W.unavailableReason||!W.efforts.length)return"model-unavailable";return W.efforts.includes("default")?"effort-unset":"effort-level"},modelCatalogState:{status:Q?"idle":"disabled",updatedAt:Date.now()},async refreshModels(){if(H.models=[],H.modelSelection.availableModels=[],!H.enabled){H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{let G=await DW(Y,Q),W=G.find((_)=>_.model===I2(V));if(V&&!W)throw Error(`OpenRouter 默认模型不在账号目录中: ${V}`);if($.effort){if(!V)throw Error("OpenRouter effort 需要同时配置 model");if(!w0($.effort)||!W.efforts.includes($.effort))throw Error(`OpenRouter 模型 ${V} 不支持 effort ${$.effort}`);W.defaultEffort=$.effort}let B=(X??[...new Set([...V?[I2(V)]:[],...z(G),...jQ($.shown_models)])]).map((_)=>{let P=G.find((L)=>L.model===I2(_));if(!P)return{model:_,display:_,efforts:[],defaultEffort:null,unavailableReason:h2(_)?"此厂商或自动路由已被排除":"账号目录未返回该模型"};return{...P,model:_}});H.models=B,H.modelSelection.modelIds=B.map((_)=>_.model),H.modelSelection.availableModels=G,H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){let W=_Q(G);j(`openrouter refreshModels MISS: ${W}`),H.modelCatalogState={status:"failed",updatedAt:Date.now(),error:W}}},spawnEnv(G,W){if(!Q)throw Error("OpenRouter API key missing");let K=W||V;if(!K)throw Error("OpenRouter 未选择模型,请通过 model 面板选择或配置 model");if(h2(K))throw Error(`OpenRouter 已排除此厂商或自动路由: ${K}`);let B=o0(G);B.ANTHROPIC_BASE_URL=t4(Y),B.ANTHROPIC_AUTH_TOKEN=Q,B.ANTHROPIC_API_KEY="",B.CLAUDE_CODE_NO_MODEL_FALLBACK="1",B.ANTHROPIC_MODEL=K,B.ANTHROPIC_SMALL_FAST_MODEL=K,B.CLAUDE_CODE_SUBAGENT_MODEL=K,B.ANTHROPIC_DEFAULT_FABLE_MODEL=K;for(let _ of Object.values(BQ))B[_]=K;for(let _ of jQ($.slots)){let P=_.indexOf("="),L=_.slice(0,P).trim(),q=_.slice(P+1).trim();if(P<1||!Object.hasOwn(BQ,L)||!q)throw Error(`OpenRouter slots 无效: ${_}`);if(h2(q)||!H.modelSelection.availableModels.some((F)=>!F.unavailableReason&&I2(F.model)===I2(q)))throw Error(`OpenRouter slot 模型不在账号目录中: ${q}`);if(H.modelEnvironmentRevision(q)!==H.modelEnvironmentRevision(K))throw Error(`OpenRouter slot 不能混合无 effort 档位与有 effort 档位的模型: ${q}`);B[BQ[L]]=q}return B},resolveSpawnModel(G){if(h2(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);return G||void 0},readUsage(){return VO(Y,Q)}};return H},setup:{commandSuffix:"openrouter",hint:($)=>`启用 ${$}:发送 \`openrouter-setup <api_key>\`,然后通过 \`model\` 选择模型。自建端点用 \`openrouter-setup <base_url> <api_key>\`。`,parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||Z.length===1&&/^https?:\/\//i.test(Z[0]))return{error:"用法: openrouter-setup <api_key> 或 openrouter-setup <base_url> <api_key>"};try{return{config:{agent:"claude",api_key:Z[Z.length-1],...Z.length===2?{base_url:t4(Z[0])}:{}}}}catch(J){return{error:_Q(J)}}},async validate($){await DW($.base_url??FW,$.api_key??$.auth_token??"")}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim(),J=$.ANTHROPIC_AUTH_TOKEN?.trim();if(!Z||!J)return null;try{let Q=t4(Z);if(new URL(Q).hostname!=="openrouter.ai")return null;return{base_url:Q,api_key:J}}catch{return null}}}})});function OW($,Z){let J=$.trim().toLowerCase().split("/").at(-1)??"",Q=Z==="packy-codex"?"codex":"claude";for(let Y of zO){if(Y.agent!==Q)continue;let V=Y.pattern.exec(J);if(!V)continue;let X=V[1].split(/[.-]/),z=V[2]??(X.at(-1).length===8?X.pop():void 0);if(!X.length)continue;return{family:Y.id,version:X.map(Number),date:z?Number(z):0}}return}function AW($,Z){let J=OW($,Z)?.family;return J?`family:${J}`:`model:${$}`}function NW($,Z="packy"){let J=new Map;for(let Y of $){let V=OW(Y,Z);if(!V)continue;let X=J.get(V.family),z=0;if(X){for(let H=0;H<Math.max(V.version.length,X.version.length);H++)if(z=(V.version[H]??0)-(X.version[H]??0),z)break;z||=V.date-X.date||X.model.length-Y.length||X.model.localeCompare(Y)}if(!X||z>0)J.set(V.family,{model:Y,version:V.version,date:V.date})}let Q=new Set([...J.values()].map((Y)=>Y.model));return $.filter((Y)=>Q.has(Y))}var zO;var RW=R(()=>{zO=[{id:"minimax",agent:"claude",pattern:/^minimax-m(\d+(?:[.-]\d+)*)$/},{id:"opus",agent:"claude",pattern:/^claude-opus-(\d+(?:[.-]\d+)*)$/},{id:"fable",agent:"claude",pattern:/^claude-fable-(\d+(?:[.-]\d+)*)$/},{id:"qwen-max",agent:"claude",pattern:/^qwen-?(\d+(?:[.-]\d+)*)-max(?:-(\d{4}|\d{8}))?$/},{id:"kimi",agent:"codex",pattern:/^kimi-k(\d+(?:[.-]\d+)*)$/},{id:"grok",agent:"codex",pattern:/^grok-(\d+(?:[.-]\d+)*)$/}]});function LQ($){return $.replace(/\[1m\]$/,"")==="gemini-3.8-flash"}function HO($,Z,J){let Q=Z==="claude"?d9:L2,Y=$.reasoning?.supported_efforts;if(Y!==void 0&&(!Array.isArray(Y)||!Y.length||!Y.every((H)=>typeof H==="string")))throw Error(`PackyAPI ${$.id} 的推理档位声明无效`);let V=Y===void 0?[...Q]:Q.filter((H)=>Y.includes(H));if(!V.length)throw Error(`PackyAPI ${$.id} 未声明当前 Agent 可用的推理档位`);let X=J.effort?.trim(),z=X||$.reasoning?.default_effort||(Y===void 0?Z==="claude"?"default":"medium":void 0);if(X&&!V.includes(X))throw Error(`PackyAPI effort 无效: ${X}`);return{model:$.id,display:$.display,efforts:V,defaultEffort:typeof z==="string"&&V.includes(z)?z:null}}var PQ="LODESTAR_PACKY_API_KEY",TW,EW;var SW=R(()=>{P0();j1();ZQ();RW();L1();I();_1();X0();TW={API_TIMEOUT_MS:"60000",CLAUDE_ENABLE_BYTE_WATCHDOG:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:"45000",CLAUDE_CODE_MAX_RETRIES:"2",CLAUDE_CODE_RETRY_WATCHDOG:"0"};EW=[{id:"packy",agent:"claude",display:"PackyAPI"},{id:"packy-secondary",agent:"claude",display:"PackyAPI · 令牌2"},{id:"packy-codex",agent:"codex",display:"PackyAPI"}];for(let $ of EW){let{id:Z,agent:J,display:Q}=$,Y=J==="claude"?"anthropic":"openai-response",V=(X)=>X.protocols.includes(Y)||J==="claude"&&LQ(X.id);N0({kind:Z,configSectionId:Z,build(X){let z=X.api_key?.trim()||X.auth_token?.trim()||"",H=r$(X.base_url?.trim()||f2),G=X.management_url?.trim()?r$(X.management_url):o4(H),W=X.management_token?.trim()||"",K=X.management_user_id?.trim()||"",B=!!(W||K||X.management_url?.trim()||X.billing_source?.trim()),_=X.model?.trim(),P=X.models===void 0?void 0:s(X.models),L=new Set([...s(X.custom_models),...P??[]]),q=(A)=>NW(A.filter((O)=>O.origin!=="custom").map((O)=>O.model),Z),F=[],M=(A)=>{let O=F.find((N)=>N.id===A);if(O&&!V(O)&&!L.has(A))throw Error(`PackyAPI ${A} 未声明 ${Y};确认兼容后可显式补录`)},U={id:Z,kind:Z,agent:J,display:X.display?.trim()||Q,enabled:!!z&&X.enabled!==!1,models:[],defaultModel:_??"",modelSelection:{mode:"allowlist",modelIds:P??[],availableModels:[],...P===void 0?{selectDefaults:q,visibilityKey:(A)=>AW(A,Z)}:{}},...B?{usageAccount:{id:O$("packy-account",G,K),label:"PackyAPI"}}:{},modelCatalogState:{status:z&&X.enabled!==!1?"idle":"disabled",updatedAt:Date.now()},...J==="claude"?{modelEnvironmentRevision(A){return LQ(A)?JSON.stringify(TW):"native-retries"}}:{},...J==="codex"?{codexApiProvider:{id:"packy",name:"PackyAPI",baseUrl:`${H}/v1`,envKey:PQ}}:{},async refreshModels(){if(U.models=[],F=[],!U.enabled){U.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}U.modelCatalogState={status:"loading",updatedAt:null};try{F=await eJ(H,z);let A=F.filter((T)=>V(T)||L.has(T.id));if(!A.length&&!L.size)throw Error(`PackyAPI 此令牌没有声明支持 ${Y} 的模型,请检查分组和模型限制`);let O=A.map((T)=>({...HO(T,J,X),...!T.protocols.includes(Y)&&L.has(T.id)?{origin:"custom"}:{}}));for(let T of L){if(O.some((f)=>f.model.toLowerCase()===T.toLowerCase()))continue;O.push({model:T,display:T,origin:"custom",...N2(U,X)})}if(_&&!O.some((T)=>T.model===_)){if(F.find((f)=>f.id===_))throw Error(`PackyAPI ${_} 未声明 ${Y},确认兼容后请显式补录`);if(!L.has(_))throw Error(`PackyAPI 默认模型不在目录中且未补录: ${_}`)}let S=(P??[...new Set([..._?[_]:[],...q(O),...s(X.shown_models),...O.filter((T)=>T.origin==="custom").map((T)=>T.model)])]).map((T)=>O.find((f)=>f.model===T)??{model:T,display:T,efforts:[],defaultEffort:null,unavailableReason:"账号目录未返回该模型"});U.modelSelection.availableModels=O,U.models=S,U.modelSelection.modelIds=S.map((T)=>T.model),U.defaultModel=_??S.find((T)=>!T.unavailableReason)?.model??[...L][0]??"",U.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(A){U.models=[],F=[];let O=f0(A,[z]);j(`${Z} refreshModels MISS: ${O}`),U.modelCatalogState={status:"failed",updatedAt:Date.now(),error:O}}},resolveSpawnModel(A){return M(A),A},spawnEnv(A,O){if(!z)throw Error("PackyAPI API key missing");let N=O||U.defaultModel;if(!N)throw Error("PackyAPI 尚未选择模型");M(N);let S=o0(A);if(delete S[PQ],J==="codex"){for(let f of["CODEX_API_KEY","OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete S[f];return S[PQ]=z,S}if(S.ANTHROPIC_BASE_URL=H,S.ANTHROPIC_AUTH_TOKEN=z,S.ANTHROPIC_API_KEY="",S.CLAUDE_CODE_NO_MODEL_FALLBACK="1",LQ(N))Object.assign(S,TW);S.ANTHROPIC_MODEL=N,S.ANTHROPIC_SMALL_FAST_MODEL=N,S.CLAUDE_CODE_SUBAGENT_MODEL=N;for(let f of["OPUS","SONNET","HAIKU","FABLE"])S[`ANTHROPIC_DEFAULT_${f}_MODEL`]=N;let T={opus:"OPUS",sonnet:"SONNET",haiku:"HAIKU",fable:"FABLE"};for(let f of s(X.slots)){let[m,b,p]=f.split("=");if(!m||!Object.hasOwn(T,m)||!b||p!==void 0)throw Error(`PackyAPI slots 无效: ${f}`);if(!f1(U).some((c)=>c.model===b))throw Error(`PackyAPI slot 模型不在当前来源: ${b}`);M(b),S[`ANTHROPIC_DEFAULT_${T[m]}_MODEL`]=b}return S},readUsage(){return B?$Q(G,W,K):eG(H,z)}};return U},setup:{commandSuffix:Z,hint:()=>`发送 \`${Z}-setup [base_url] <api_key>\` 配置${Q}。${Z==="packy-codex"?"与 PackyAPI 主账号共用凭据。":""}`,parseArgs(X){let z=X.trim().split(/\s+/).filter(Boolean);if(z.length<1||z.length>2||/^https?:\/\//i.test(z.at(-1)))return{error:`用法: ${Z}-setup [base_url] <api_key>`};try{return{config:{agent:J,api_key:z.at(-1),base_url:r$(z.length===2?z[0]:f2)}}}catch(H){return{error:f0(H,[z.at(-1)])}}},async validate(X){if(!(await eJ(X.base_url??f2,X.api_key??X.auth_token??"")).some(V)&&!s(X.custom_models).length&&!s(X.models).length)throw Error(`此令牌没有声明支持 ${Y} 的模型`)}},...Z==="packy-codex"?{}:{usageSetup:{commandSuffix:`${Z}-balance`,hint:()=>`发送 \`${Z}-balance-setup [management_url] <user_id> <system_token>\` 配置真实余额;共用已有账号用 \`${Z}-balance-setup share <source_id>\`。`,parseArgs(X){let z=X.trim().split(/\s+/).filter(Boolean);if(z.length===2&&z[0]==="share"){if(!EW.some((W)=>W.id===z[1])||z[1]===Z)return{error:"请指定另一个已配置的 PackyAPI 来源:packy、packy-secondary 或 packy-codex"};return{config:{billing_source:z[1],management_token:"",management_user_id:"",management_url:""}}}if(z.length<2||z.length>3)return{error:`用法:${Z}-balance-setup [management_url] <user_id> <system_token>,或 ${Z}-balance-setup share <source_id>`};let H=z.at(-2),G=z.at(-1);if(!/^[1-9]\d*$/.test(H)||!Number.isSafeInteger(Number(H)))return{error:"用户 ID 必须是正整数"};try{return{config:{billing_source:"",management_token:G,management_user_id:H,management_url:z.length===3?r$(z[0]):""}}}catch(W){return{error:f0(W,[G])}}},async validate(X){let z=X.management_url||o4(X.base_url||f2),H=await $Q(z,X.management_token||"",X.management_user_id||"",!0);if(H.state!=="ok")throw Error(H.reason||"PackyAPI 真实账户余额查询失败")}}}})}});var CW=1;import{EventEmitter as GO}from"node:events";import{createRequire as WO}from"node:module";import{createHash as KO,randomUUID as BO}from"node:crypto";import{createInterface as jO}from"node:readline";import{dirname as _O,join as M1,isAbsolute as PO}from"node:path";import{fileURLToPath as qQ}from"node:url";import{tmpdir as LO}from"node:os";import{existsSync as xW,mkdirSync as bW,mkdtempSync as qO,readFileSync as F8,renameSync as FO,writeFileSync as kW,rmSync as FQ}from"node:fs";import DO from"cross-spawn";function MO($){let Z=$.LODESTAR_DSH_PROVIDER??"deepseek-official";if(Z==="deepseek-official")return[];if(Z!=="zai-coding-cn"&&Z!=="zai")throw Error(`Unsupported DSH provider: ${Z}`);let J=$.LODESTAR_DSH_MODELS===void 0?void 0:JSON.parse($.LODESTAR_DSH_MODELS);if(J!==void 0&&(!Array.isArray(J)||!J.every((Q)=>typeof Q==="string"&&Q)))throw Error("Invalid DSH GLM model catalog");return[{id:"llm-deepseek",disabled:!0},{id:"llm-pi-ai",disabled:!1,config:{providers:{[Z]:{apiKeyEnv:"LODESTAR_DSH_GLM_API_KEY",baseURL:$.LODESTAR_DSH_BASE_URL,compat:{supportsReasoningEffort:!0},reasoning:"high",...Array.isArray(J)?{models:J.map((Q)=>({id:Q,reasoningEfforts:{off:null,minimal:"minimal",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"}}))}:{}}}}},{id:"agent-default-model",config:{provider:Z,model:$.LODESTAR_DSH_DEFAULT_MODEL??""}}]}function UO($,Z){if(Z?.loadProjectMcp===!1)return[];let J;try{J=F8(M1($,".mcp.json"),"utf8")}catch(Y){if(Y?.code==="ENOENT")return[];throw Y}let Q=JSON.parse(J);if(!Q.mcpServers||typeof Q.mcpServers!=="object"||Array.isArray(Q.mcpServers))throw Error("DSH project .mcp.json must contain an mcpServers object");return Object.entries(Q.mcpServers).map(([Y,V])=>{if(!/^[A-Za-z0-9_-]{1,32}$/.test(Y)||!V||typeof V!=="object")throw Error(`invalid DSH MCP server: ${Y}`);let X=V,z=X.type==="http"?{transport:"streamable-http",serverName:Y,url:X.url,headers:X.headers??{}}:X.type===void 0||X.type==="stdio"?{transport:"stdio",serverName:Y,command:X.command,args:X.args??[],env:X.env??{},cwd:$}:null;if(!z)throw Error(`DSH does not support MCP transport ${X.type} for ${Y}`);return{id:`lodestar-mcp-${Y}`,name:"@deepseek-ai/dsh-mcp-client",config:{...z,failOnStartupError:!0}}})}async function r4($,Z,J={}){let Q=new c7($);Q.on("failure",(X)=>j(`dsh catalog: ${X}`));let Y,V;try{await Q.initialize(),V=await Q.request(Z,J)}catch(X){Y=X}try{await Q.close()}catch(X){if(Y)throw AggregateError([Y,X],"DSH query and cleanup both failed");throw X}if(Y)throw Y;return V}var c7;var D8=R(()=>{H0();D4();I();c7=class c7 extends GO{child;pending=new Map;nextId=0;exited=!1;closing=!1;stderr="";initialized=!1;initTask;closeTask;exitTask;launchDir;constructor($){super();if(!PO($.cwd))throw Error("DSH requires an absolute workspace");let Z=T3("dsh"),Q=WO(M1(Z,"package.json")).resolve("@deepseek-ai/dsh/package.json"),Y=JSON.parse(F8(Q,"utf8"));j(`dsh runtime: ${Y.version} (${Z})`);let V=MO($.env),X=$.home??W4;bW(X,{recursive:!0,mode:448});let z=UO($.cwd,$.profile);this.launchDir=qO(M1(LO(),"lodestar-dsh-"));let H=import.meta.url.endsWith(".ts"),G=H?"dsh-bridge.ts":"dsh-bridge.js",W=F8(qQ(new URL(`./${G}`,import.meta.url))),K=H?F8(qQ(new URL("./dsh-protocol.ts",import.meta.url))):Buffer.alloc(0),B=JSON.parse(F8(qQ(new URL("../package.json",import.meta.url)),"utf8")),_=Buffer.from(JSON.stringify({name:B.name,version:B.version,type:"module",private:!0})),P=KO("sha256").update(W).update(K).update(_).digest("hex").slice(0,20),L=M1(Z,".lodestar-bridges",P);bW(L,{recursive:!0});let q=M1(L,G),F=(T,f)=>{if(xW(T))return;let m=`${T}.${BO()}.tmp`;try{kW(m,f),FO(m,T)}finally{if(xW(m))FQ(m)}};if(F(M1(L,"package.json"),_),H)F(M1(L,"dsh-protocol.ts"),K);F(q,W);let M=[...["sdk-jsonrpc-server","session-title-llm","session-telemetry-otel","settings","credentials","llm-pi-ai"].map((T)=>({id:T,disabled:!0})),{id:"approval",config:{policy:"ask"}},{id:"permission",config:{defaultPreset:"lodestar",presets:{lodestar:{sandbox:"danger-full-access",approval:"ask"}}}},{id:"tool-subagent",config:{provider:"spawn",toolName:"subagent",backgroundMode:"continuable",maxDepth:"provider-managed"}},{id:"tool-subagent-fork",config:{provider:"fork",toolName:"subagent_fork",backgroundMode:"one-shot",maxDepth:"provider-managed"}},{id:"system-prompt",config:{personaPrefix:"You are a coding agent powered by {{model}}.",personaSuffix:""}},{id:"skill-filesystem",config:{includeDefaultRoots:!0,...$.managedSkillDir?{customSkillDirs:[$.managedSkillDir]}:{}}},{insert:[{id:"lodestar-bridge",name:q},{id:"lodestar-ask-user",name:"@deepseek-ai/dsh-tool-ask-user"},...z]},...V],U=M1(this.launchDir,"bridge.patch.yml");kW(U,JSON.stringify(M),{mode:384});let A=$.env.LODESTAR_DSH_NODE||"node",O=[M1(_O(Q),Y.bin.dsh),"--profile","sdk","--patch",U,...($.patches??[]).flatMap((T)=>["--patch",T])],N={...$.env};if(N.LODESTAR_AGENT_CAPABILITY&&N.LODESTAR_AGENT_URL)N.DSH_LODESTAR_AGENT_CONTEXT=JSON.stringify({baseUrl:N.LODESTAR_AGENT_URL,capability:N.LODESTAR_AGENT_CAPABILITY});for(let T of Object.keys(N))if(T.startsWith("LODESTAR_AGENT_"))delete N[T];try{this.child=DO(A,O,{cwd:$.cwd,stdio:["pipe","pipe","pipe"],shell:!1,env:{...N,DSH_HOME:X,DSH_PERMISSION_MODE:"danger-full-access"}})}catch(T){throw FQ(this.launchDir,{recursive:!0,force:!0}),T}this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",(T)=>{this.stderr=(this.stderr+T).slice(-16384),j(`dsh stderr: ${T.trimEnd()}`)}),this.child.stdin.on("error",(T)=>this.transportFailure(T));let S=jO({input:this.child.stdout,crlfDelay:1/0});S.on("line",(T)=>this.receive(T)),this.exitTask=new Promise((T)=>{this.child.once("error",(f)=>this.transportFailure(f)),this.child.once("close",(f,m)=>{this.exited=!0,S.close();let b=Error(`DSH exited code=${f} signal=${m}
151
+ ${this.stderr}`);this.rejectPending(b),FQ(this.launchDir,{recursive:!0,force:!0}),T(),this.emit("exit",{code:f,signal:m,expected:this.closing})})})}get pid(){return this.child.pid}isAlive(){return!this.exited}initialize(){return this.initTask??=this.request("initialize",{},30000).then(($)=>{if($.protocolVersion!==CW||typeof $.runtimeVersion!=="string"||!$.runtimeVersion)throw Error(`DSH handshake version mismatch: ${JSON.stringify($)}`);this.initialized=!0})}request($,Z={},J=30000){if(this.exited||this.closing&&$!=="shutdown")return Promise.reject(Error("DSH transport is closed"));let Q=++this.nextId;return new Promise((Y,V)=>{let X=J===null?void 0:setTimeout(()=>{this.pending.delete(Q),V(Error(`DSH ${$} timed out after ${J}ms
152
152
  ${this.stderr}`))},J);this.pending.set(Q,{resolve:Y,reject:V,timer:X}),this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",id:Q,method:$,params:Z})+`
153
- `,(z)=>{if(z)this.transportFailure(z)})})}receive($){try{let Z=JSON.parse($);if(Z.jsonrpc!=="2.0")throw Error("invalid DSH JSON-RPC envelope");if(typeof Z.id==="number"){let J=this.pending.get(Z.id);if(!J){j(`dsh: unexpected response id=${Z.id}`);return}if(this.pending.delete(Z.id),clearTimeout(J.timer),Z.error)J.reject(Error(`DSH RPC error: ${Z.error.message}`));else if("result"in Z)J.resolve(Z.result);else J.reject(Error("DSH response has neither result nor error"))}else if(typeof Z.method==="string"&&Z.params&&typeof Z.params==="object")this.emit("notification",{method:Z.method,params:Z.params});else throw Error("invalid DSH notification")}catch(Z){this.transportFailure(Z instanceof Error?Z:Error(String(Z)))}}rejectPending($){for(let Z of this.pending.values())clearTimeout(Z.timer),Z.reject($);this.pending.clear()}transportFailure($){this.rejectPending($),this.emit("failure",$)}close($=3000){return this.closeTask??=this.dispose($).catch((Z)=>{throw this.closeTask=void 0,Z})}async dispose($){if(this.exited)return;if(this.closing=!0,this.initialized)try{await this.request("shutdown",{},$)}catch(J){j(`dsh shutdown: ${J}`)}this.child.stdin.end();let Z=async(J)=>{let Q;return await Promise.race([this.exitTask,new Promise((Y)=>{Q=setTimeout(Y,J)})]),clearTimeout(Q),this.exited};if(await Z($))return;if(j(`dsh: terminate owned child pid=${this.pid}`),this.child.kill("SIGTERM"),await Z($))return;if(j(`dsh: kill unresponsive owned child pid=${this.pid}`),this.child.kill("SIGKILL"),!await Z($))throw Error(`DSH child exit not confirmed: pid=${this.pid}`)}}});var wW=R(()=>{X0();P0();F8();H0();WQ();L1();N0({kind:"deepseek-harness",configSectionId:"deepseek-harness",build($){let Z=$.api_key?.trim()??"",J=$.base_url?.trim()||"https://api.deepseek.com",Q={id:"deepseek-harness",kind:"deepseek-harness",agent:"dsh",display:$.display?.trim()||"DeepSeek",enabled:!!Z,models:[],defaultModel:$.model?.trim()??"",modelCatalogState:{status:Z?"idle":"disabled",updatedAt:Date.now()},spawnEnv(Y){let V=p9(Y);if(!Z)throw Error("DeepSeek Harness API key is missing");if(V.DEEPSEEK_API_KEY=Z,V.DEEPSEEK_BASE_URL=J,V.LODESTAR_DSH_PROVIDER="deepseek-official",$.bin)V.LODESTAR_DSH_NODE=$.bin;return V},async refreshModels(){if(!Q.enabled){Q.models=[],Q.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}Q.modelCatalogState={status:"loading",updatedAt:null};try{let Y=await r4({cwd:W4,env:Q.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list",{models:[...s($.models),...s($.custom_models)]});if(!Array.isArray(Y)||!Y.length)throw Error("DeepSeek Harness model catalog is empty");for(let X of Y)if(!X.model||!X.efforts.length||!X.efforts.every(S0)||!S0(X.defaultEffort)||!X.efforts.includes(X.defaultEffort))throw Error(`Invalid DSH model/effort catalog: ${X.model}`);let V=$.model?.trim()||Y.find((X)=>X.isDefault)?.model;if(!V||!Y.some((X)=>X.model===V))throw Error("DSH default model is not in its catalog");Q.models=Y.map(({model:X,display:z,efforts:H,defaultEffort:G,isCustom:W})=>{let K=$.effort?.trim();if(K&&(!S0(K)||!H.includes(K)))throw Error(`DSH model ${X} does not support configured effort ${K}`);return{model:X,display:z,efforts:H,defaultEffort:K?K:G,origin:W?"custom":"upstream"}}),Q.defaultModel=V,Q.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(Y){throw Q.models=[],Q.modelCatalogState={status:"failed",updatedAt:Date.now(),error:Y instanceof Error?Y.message:String(Y)},Y}},resolveSpawnModel(Y){return y1(Q).find((V)=>V.model===Y)?.model},readUsage(){return Z?GQ(J,Z):Promise.resolve({kind:"balance",state:"no_credentials",windows:[]})}};return Q},setup:{commandSuffix:"deepseek-harness",hint:()=>"DeepSeek 账号由 Claude Code 和 DeepSeek Harness 共用。发送 `deepseek-setup <api_key>` 配置两边;`deepseek-harness-setup [base_url] <api_key>` 同样更新共享账号。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:deepseek-harness-setup [base_url] <api_key>"};return{config:{agent:"dsh",api_key:Z.at(-1),...Z.length===2?{base_url:Z[0]}:{}}}},async validate($){await HQ($.base_url??"https://api.deepseek.com",$.api_key??"")}}})});function u7($){let Z=new URL($);if(!f2(Z.origin)||Z.protocol!=="https:"||Z.username||Z.password||Z.search||Z.hash)throw Error("DSH GLM 需要智谱或 Z.ai 的 Coding Plan HTTPS 端点;地址中不能包含凭据或查询参数");return Z.pathname="/api/coding/paas/v4",Z.search="",Z.hash="",Z.toString().replace(/\/$/,"")}async function vW($,Z){return(await u$(`${$}/models`,Z,"GLM Coding Plan models")).map((Q)=>{if(typeof Q?.id!=="string"||!Q.id)throw Error("GLM Coding Plan 模型 id 无效");return{model:Q.id,display:typeof Q.name==="string"?Q.name:Q.id}})}var fW=R(()=>{_4();k0();P0();X0();F8();H0();b7();XQ();L1();N0({kind:"dsh-glm",configSectionId:"dsh-glm",detect:{fromSettingsEnv($){let Z=g.token_sources?.glm,J=Z?.auth_token?.trim()||$.ANTHROPIC_AUTH_TOKEN?.trim(),Q=Z?.base_url?.trim()||$.ANTHROPIC_BASE_URL?.trim();return J&&Q&&f2(Q)?{api_key:J,base_url:u7(Q)}:null}},build($,Z){let J=$.api_key?.trim()||$.auth_token?.trim()||Z?.api_key?.trim()||"",Q=u7($.base_url?.trim()||Z?.base_url?.trim()||"https://open.bigmodel.cn/api/coding/paas/v4"),Y=new URL(Q).hostname.endsWith("bigmodel.cn")?"zai-coding-cn":"zai",V,X={id:"dsh-glm",kind:"dsh-glm",agent:"dsh",display:$.display?.trim()||"GLM Coding Plan",enabled:!!J,models:[],defaultModel:$.model?.trim().toLowerCase()??"",modelEnvironmentRevision(){return JSON.stringify((X.modelSelection?.availableModels??X.models).map((z)=>z.model).sort())},modelCatalogState:{status:J?"idle":"disabled",updatedAt:Date.now()},spawnEnv(z){if(!J)throw Error("DSH GLM Coding Plan API key is missing");let H=p9(z);H.LODESTAR_DSH_PROVIDER=Y,H.LODESTAR_DSH_GLM_API_KEY=J,H.LODESTAR_DSH_BASE_URL=Q,H.LODESTAR_DSH_DEFAULT_MODEL=X.defaultModel;let G=(X.modelSelection?.availableModels??X.models).map((W)=>W.model);if(V||G.length)H.LODESTAR_DSH_MODELS=JSON.stringify(V??G);if($.bin)H.LODESTAR_DSH_NODE=$.bin;return H},async refreshModels(){if(X.models=[],V=void 0,!X.enabled){X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await vW(Q,J),H=[...z];for(let W of[...s($.models),...s($.custom_models)])if(!H.some((K)=>K.model.toLowerCase()===W.toLowerCase()))H.push({model:W,display:W});if(V=H.map((W)=>W.model),!$.model?.trim()){let W=(K)=>Number(K.match(/\d+(?:\.\d+)?/)?.[0]??-1);X.defaultModel=[...z].sort((K,B)=>W(B.model)-W(K.model))[0].model}let G=await r4({cwd:W4,env:X.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list");X.models=H.map((W)=>{let K=G.find((L)=>L.model===W.model),B=N2(X,$),_=K?K.efforts.filter(S0):B.efforts,P=$.effort?.trim()||K?.defaultEffort||B.defaultEffort;return{...W,display:K?.display??W.display,efforts:_,defaultEffort:S0(P)&&_.includes(P)?P:null,origin:z.some((L)=>L.model===W.model)?"upstream":"custom"}}),X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){throw X.models=[],V=[],X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:z instanceof Error?z.message:String(z)},z}},resolveSpawnModel(z){return y1(X).find((H)=>H.model===z&&!H.unavailableReason)?.model},async readUsage(){return J?VQ(await x7(Q,J)):{state:"no_credentials",windows:[]}}};return X},setup:{commandSuffix:"dsh-glm",hint:()=>"GLM Coding Plan 账号由 Claude Code 和 DeepSeek Harness 共用。发送 `glm-setup <api_key>` 配置两边;`dsh-glm-setup [base_url] <api_key>` 同样更新共享账号。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:dsh-glm-setup [base_url] <api_key>"};try{return{config:{agent:"dsh",api_key:Z.at(-1),base_url:u7(Z.length===2?Z[0]:"https://open.bigmodel.cn/api/coding/paas/v4")}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}},async validate($){await vW(u7($.base_url??"https://open.bigmodel.cn/api/coding/paas/v4"),$.api_key??$.auth_token??"")}}})});var IW={};H1(IW,{tokenSourceSpawnRevision:()=>hW,buildTokenSourcesFromConfig:()=>M8});import{createHash as yW}from"node:crypto";function M8(){let $=rJ(),Z=Object.fromEntries(U2().flatMap((G)=>{let W=G.detect?.fromSettingsEnv($);return G.configSectionId&&W?[[G.configSectionId,W]]:[]})),J=L8(g.token_sources??{},Z),Q=new Map(s0().map((G)=>[G.id,G])),Y=U2().map((G)=>{let W=G.configSectionId?J[G.configSectionId]??{}:{},K=G.configSectionId?Z[G.configSectionId]??null:null,B=()=>{let _=r3(G.build(W,K),W);return _.spawnRevision=hW(G.kind,W,K),_};return{cfg:W,detected:K,create:B,initial:B()}}),V=Y.some(({initial:G})=>G.agent==="claude"&&G.enabled&&G.kind!=="claude-native"&&G.kind!=="claude-subscription"),X=Y.map(({cfg:G,detected:W,create:K,initial:B})=>{let _=()=>{let D=K();if(D.kind==="claude-native")D.enabled=!V,D.modelCatalogState={status:D.enabled?"idle":"disabled",updatedAt:Date.now()};return D},P=(D)=>{let{display:M,model:U,effort:A,models:O,hidden_models:N,shown_models:S,custom_models:T,slots:y,default:m,...b}=D??{};return b},L=(D)=>yW("sha256").update(JSON.stringify(D,(M,U)=>U&&typeof U==="object"&&!Array.isArray(U)?Object.fromEntries(Object.entries(U).sort(([A],[O])=>A.localeCompare(O))):U)).digest("hex"),q=B.kind==="claude-native"?!V:void 0;return QJ(_,G,L([B.id,P(G),P(W),q]),L([G,W,q]),Q.get(B.id))});fZ();for(let G of X)kZ(G);for(let G of Q.values())if(!X.includes(G))J8(G);let H=X.find((G)=>G.enabled&&g.token_sources?.[G.id]?.default===!0)??X.find((G)=>G.enabled);if(H)vZ(H.id);return X.length}function hW($,Z,J){let Q=(Y)=>({agent:Y?.agent,auth:Y?.auth,base_url:Y?.base_url,auth_token:Y?.auth_token,api_key:Y?.api_key,bin:Y?.bin,model:Y?.model,effort:Y?.effort,slots:Y?.slots});return yW("sha256").update(JSON.stringify({kind:$,configured:Q(Z),detected:Q(J)})).digest("hex")}var l7=R(()=>{k0();X0();b7();L1();q8();W7();H7();XQ();YW();GW();WQ();UW();SW();wW();fW()});function FQ($){let Z=new Map,J=$.map((K)=>{let B=K.fingerprint?Z.get(K.fingerprint):void 0;if(K.fingerprint&&!B)Z.set(K.fingerprint,K.account.name);return{...K,...B?{duplicateOf:B}:{}}}),Q=J.filter((K)=>!K.duplicateOf),V=(Q.length<=1||Q.every((K)=>K.fingerprint!==null))&&Q.every((K)=>K.usage.state==="ok"),X=Q.flatMap((K)=>K.usage.state==="ok"?[K.usage]:[]),z=X.map((K)=>{let B=MZ(K);if(B.state==="exhausted")return!1;if(B.state==="miss")return null;if(B.state==="credits")return!0;return[K.fiveHour,K.weekly].filter((P)=>P!==null).length?!0:null}),H=V&&z.every((K)=>K!==null)?z.filter(Boolean).length:null,G=V&&X.every((K)=>K.resetCredits!=null)?X.reduce((K,B)=>K+B.resetCredits,0):null,W=["fiveHour","weekly"].map((K)=>{let B=X.map((P)=>P[K]).filter((P)=>P!==null),_=V&&B.every((P)=>P.percent!==null&&P.percent>=0&&P.percent<=100);return{kind:K,count:B.length,remaining:_?B.reduce((P,L)=>P+(100-L.percent)/100,0):null}}).filter((K)=>K.count||!V);return{entries:J,complete:V,available:H,resetCredits:G,windows:W}}async function gW($){return{...$,entries:$.entries.map((Z)=>{let J=sz(Z.account.id);return{...Z,email:J?.email??null,emailError:J?.error??(!J?"账号信息缓存尚未就绪,后台刷新中":void 0)}})}}async function d7($){let Z=new Map,J=await Promise.all(v.list().map(async(Q)=>{let Y=null;try{Y=v.fingerprint(Q.id)}catch(H){return{account:Q,fingerprint:Y,usage:{state:"network",reason:`账号身份读取失败:${String(H)}`}}}let V=Y??Q.id,X=Z.get(V);if(!X)X=$?.id===Q.id?Promise.resolve($.usage):JH(Q.id),Z.set(V,X);let z=await X;if(z.state==="ok"&&z.accountFingerprint)Y=z.accountFingerprint;return{account:Q,usage:z,fingerprint:Y}}));return FQ(J)}var MQ=R(()=>{F0();z$();I();d3();T4()});import{createHash as mW,randomUUID as OO}from"node:crypto";function m2($,Z){if($===300305||$===200860)return!0;if($!==300315)return!1;let J=Z?.message??"";return/(?:code\s*[:=]\s*(?:300305|200860)\b|number of card components[^\n.]{0,60}exceed|\bcard over max size\b)/i.test(J)}function UQ($,Z){if($!==300315)return!1;return/(?:duplicate\s+(?:element\s*)?id|code\s*1001\s*:\s*duplicate id)/i.test(Z?.message??"")}function y$($){let Z=j$.get($);if(!Z)throw Error(`cardkit card is not registered: ${$}`);return Z}function B$($){return!j$.has($)}function h$($,Z,J){j$.set($,{sequence:0,queue:Promise.resolve(),elementCount:Z,contentFingerprints:new Map,deadElements:new Set,failedAdds:new Map,uncertainAdds:new Set,confirmedAdds:new Set,failedReplacements:new Set,onFailure:J,closing:!1})}function U8($){return j$.get($)?.elementCount??0}function cW($){let Z=j$.get($);return Z?[...Z.contentFingerprints.keys()].filter((J)=>!Z.deadElements.has(J)):[]}function e4($,Z){return j$.get($)?.deadElements.has(Z)??!1}function uW($,Z){let J=j$.get($);J?.deadElements.delete(Z),J?.failedAdds.delete(Z),J?.failedReplacements.delete(Z)}function OQ($){let Z=y$($);return Z.sequence+=1,Z.sequence}function AQ($,Z){$.deadElements.add(Z)}function lW($){return mW("sha256").update(JSON.stringify($,(Z,J)=>Z==="element_id"?void 0:J)).digest("hex")}function EO($,Z,J){let Q=[...$.contentFingerprints].filter(([Y])=>Y!==Z).map(([,Y])=>Y);if(J&&Z!==C.footer)Q.push(J);return mW("sha256").update(Q.sort().join(`
154
- `)).digest("hex")}async function i7($,Z,J,Q,Y){let V=J?JSON.stringify({...J,..."sequence"in J?{uuid:OO()}:{}}):void 0,X=`cardkit ${$} ${Z}`;return G2(X,async()=>{let z=await s$(Q),H=AbortSignal.timeout(Q.timeoutMs(NO)),G;try{return G=await V0(`${AO}${Z}`,{method:$,headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},...V!==void 0?{body:V}:{},signal:H}),(await F$(G,X))?.data}catch(W){if(H.aborted&&H.reason?.name==="TimeoutError")W=H.reason;if(G&&W instanceof l0)Object.assign(W,{httpStatus:G.status});throw Y?.(W),W}},{api:"cardkit",recovery:Q})}function NQ($){return $ instanceof l0&&($.code===200770||$.code==="200770")}function dW($){if(NQ($))return!1;if($ instanceof l0){if($.status===429||$.code===99991400||$.code===230020)return!1;if($.status!==void 0&&$.status>=200&&$.status<300&&$.code===void 0)return!0}return A3($,{api:"cardkit"})}async function n7($,Z,J,Q,Y){let V=!1;for(;;){let X=!1;try{if(await i7(Z,J,{...Q,sequence:OQ($)},Y,(z)=>{if(dW(z))X=!0}),V)j(`cardkit confirmed ${Z} ${J}: same state accepted with new UUID and sequence`);return}catch(z){if(!X||!NQ(z))throw z;if(!await Y.waitForRetry(`cardkit confirm ${Z} ${J}`,z,pW))throw z;V=!0}}}async function iW($,Z,J,Q,Y){let V=J.element_id,X=!1;try{await i7("POST",`/cards/${$}/elements`,{type:Q.type??"append",...Q.targetElementId?{target_element_id:Q.targetElementId}:{},elements:JSON.stringify([J]),sequence:OQ($)},Y,(z)=>{if(dW(z)){if(X=!0,V)Z.uncertainAdds.add(V)}})}catch(z){let H=z,G=V&&Z.uncertainAdds.has(V)&&UQ(H?.code,H);if(!V||!(G||X&&NQ(z)))throw z;if(!await Y.waitForRetry(`cardkit reconcile uncertain add ${$} element=${V}`,z,pW))throw z;await n7($,"PUT",`/cards/${$}/elements/${V}`,{element:JSON.stringify(J)},Y),j(`cardkit reconciled uncertain add ${$} element=${V}: latest content accepted with PUT`)}if(!V||!Z.confirmedAdds.has(V))Z.elementCount++;if(V)Z.confirmedAdds.add(V),Z.uncertainAdds.delete(V)}function SO($){return new Promise((Z)=>setTimeout(Z,$))}function CO($){if(typeof $!=="object"||$===null)return!1;let Z=$.code;return Z===300309||Z===200850}async function xO($,Z){await n7($,"PATCH",`/cards/${$}/settings`,{settings:JSON.stringify({config:{streaming_mode:!0}})},Z)}async function a7($,Z,J,Q,Y=!1,V={}){let X=new H2,z=async(H)=>{let G=typeof H==="object"&&H!==null?H:null,W={cardId:$,operation:Z,elementId:V.elementId,targetElementId:V.targetElementId,code:G?.code,httpStatus:G?.httpStatus,logId:G?.logId,message:H instanceof Error?H.message:String(H),apiMessage:G?.apiMessage};if(m2(W.code,W))W.capacityFingerprint=EO(y$($),V.elementId,V.contentFingerprint);if(!m2(W.code,W)&&!(H instanceof Error&&H.name==="AbortError"))await X.waitUntilDeadline();try{if(!Y||Y==="non-capacity"&&m2(W.code,W))y$($).onFailure?.(W.code,W)}catch(K){j(`cardkit failure callback ${$}: ${K}`)}try{Q?.(W)}catch(K){j(`cardkit per-call failure callback ${$}: ${K}`)}};try{await J(X);return}catch(H){if(!CO(H)){j(`cardkit ${Z} ${$}: ${H}`),await z(H);return}j(`cardkit ${Z} ${$}: streaming closed (code=${H.code}) — reopening`)}try{await xO($,X)}catch(H){j(`cardkit STREAMING_REOPEN_FAILED ${$}: ${H}`),await z(H);return}try{await J(X)}catch(H){j(`cardkit ${Z} ${$} retry-after-reopen: ${H}`),await z(H)}}function bO($){return typeof $==="object"&&$!==null&&$.code===200740}async function e$($,Z={}){let J=new H2,Q=Z.retryDelaysMs?.length?Z.retryDelaysMs:RO,Y=null;for(let V=0;V<Q.length;V++){let X=Q[V]??0;if(X>0)await SO(Math.min(X,J.remainingMs()));try{let z=await i7("POST","/cards/id_convert",{message_id:$},J);if(typeof z?.card_id!=="string"||!z.card_id)throw Error("cardkit POST /cards/id_convert: missing card_id");return z.card_id}catch(z){if(Y=z,!bO(z))throw await J.waitUntilDeadline(),z;if(V===Q.length-1){if(!await J.waitForRetry(`cardkit id_convert ${$}`,z))throw z;V--;continue}let H=Q[V+1]??0;j(`cardkit id_convert ${$}: empty result, retry ${V+2}/${Q.length} in ${H}ms`)}}throw Y}async function d1($){let Z=j$.get($);if(!Z)return;await Z.queue}function v0($,Z,J={},Q,Y="all"){if(B$($))return Promise.resolve();let V=y$($);if(V.closing)return Promise.resolve();let X=m1(Z),z=X.element_id,H=lW(X),G=()=>{if(!z)return;AQ(V,z),V.failedAdds.set(z,J)};return V.queue=V.queue.then(()=>a7($,"addElement",async(W)=>{if(await iW($,V,X,J,W),z!==C.footer)V.contentFingerprints.set(z??`#${V.sequence}`,H);if(z)V.deadElements.delete(z),V.failedAdds.delete(z),V.failedReplacements.delete(z)},(W)=>{G(),Q?.(W.code,W)},Y==="capacity"?"non-capacity":!1,{elementId:z,targetElementId:J.targetElementId,contentFingerprint:H})),V.queue}function R0($,Z,J,Q,Y=!0){if(B$($))return Promise.resolve();let V=y$($);if(V.closing)return Promise.resolve();let X=m1(J),z=lW(X),H=()=>{AQ(V,Z),V.failedReplacements.add(Z)};return V.queue=V.queue.then(()=>a7($,`replaceElement ${Z}`,async(G)=>{let W=V.failedAdds.get(Z);if(V.deadElements.has(Z)&&!W&&!V.failedReplacements.has(Z))return;if(W)await iW($,V,X,W,G);else await n7($,"PUT",`/cards/${$}/elements/${Z}`,{element:JSON.stringify(X)},G);if(V.deadElements.delete(Z),V.failedAdds.delete(Z),V.uncertainAdds.delete(Z),V.failedReplacements.delete(Z),Z!==C.footer)V.contentFingerprints.set(Z,z)},(G)=>{if(Y)H();Q?.(G.code,G)},!Y,{elementId:Z,contentFingerprint:z})),V.queue}async function D0($,Z,J,Q={}){if(B$($))return!1;let Y=y$($);if(Y.closing)return!1;let V=!1;return await R0($,Z,J,(X,z)=>{if(V=!0,z)Q.onFailure?.(z)},Q.notifyCardFailure!==!1),!V&&!Y.deadElements.has(Z)}async function nW($,Z,J){if(B$($))return{landed:!1};let Q=y$($);if(Q.closing)return{landed:!1};let Y;return await R0($,Z,J,(V,X)=>{Y=X}),{landed:!Y&&!Q.deadElements.has(Z),...Y?{failure:Y}:{}}}async function c2($,Z,J={}){let Q=await $9($,Z,J);if(Q.failure)J.onFailure?.(Q.failure);return Q.landed}async function $9($,Z,J={}){if(B$($))return{landed:!1};let Q=y$($);if(Q.closing)return{landed:!1};let Y=Z.element_id,V;return await v0($,Z,J,(X,z)=>{V=z}),{landed:!V&&!(Y&&Q.deadElements.has(Y)),...V?{failure:V}:{}}}function kO($,Z,J){if(B$($))return Promise.resolve();let Q=y$($);if(Q.closing)return Promise.resolve();let Y=()=>Q.deadElements.has(Z)&&!Q.failedAdds.has(Z)&&!Q.failedReplacements.has(Z);if(Y())return Promise.resolve();return Q.queue=Q.queue.then(()=>a7($,`deleteElement ${Z}`,async(V)=>{if(Y())return;let X=OQ($);await i7("DELETE",`/cards/${$}/elements/${Z}`,{sequence:X},V),Q.elementCount=Math.max(0,Q.elementCount-1),Q.contentFingerprints.delete(Z),Q.failedAdds.delete(Z),Q.uncertainAdds.delete(Z),Q.confirmedAdds.delete(Z),Q.failedReplacements.delete(Z),AQ(Q,Z)},(V)=>J?.(V.code,V),!0,{elementId:Z})),Q.queue}async function aW($,Z,J){if(B$($))return!1;let Q=y$($);if(Q.closing)return!1;if(Q.deadElements.has(Z)&&!Q.failedAdds.has(Z)&&!Q.failedReplacements.has(Z))return!0;let Y=!1;return await kO($,Z,(V,X)=>{if(Y=!0,X)J?.(X)}),!Y&&Q.deadElements.has(Z)}function Z9($,Z){if(B$($)||j$.get($)?.closing)return;let J=(Z??"").replace(/\s+/g," ").trim();if(!J)return;let Q=p2.get($);if(!Q)Q={latest:J,lastSent:"",timer:null,inFlight:!1},p2.set($,Q);else{if(Q.latest===J)return;Q.latest=J}oW($,Q)}function oW($,Z){if(Z.timer||Z.inFlight||Z.latest===Z.lastSent)return;Z.timer=setTimeout(()=>{if(p2.get($)!==Z)return;if(Z.timer=null,B$($)||j$.get($)?.closing){p2.delete($);return}if(Z.latest===Z.lastSent)return;let J=Z.latest;Z.inFlight=!0,m0($,{config:{summary:{content:J}}}).then((Q)=>{if(p2.get($)!==Z)return;if(Z.inFlight=!1,Q)Z.lastSent=J;if(Z.latest!==J&&!B$($)&&!j$.get($)?.closing)oW($,Z)})},TO)}function e0($){let Z=p2.get($);if(!Z)return;if(Z.timer)clearTimeout(Z.timer),Z.timer=null;p2.delete($)}function o7($,Z){return m0($,Z).then(()=>{})}async function m0($,Z,J){if(B$($))return!1;let Q=y$($);if(Q.closing)return!1;let Y=!1,V=!1;return Q.queue=Q.queue.then(()=>a7($,"patchSettings",async(X)=>{if(B$($))return;await n7($,"PATCH",`/cards/${$}/settings`,{settings:JSON.stringify(Z)},X),Y=!0},(X)=>{V=!0,J?.(X)},!0)),await Q.queue,Y&&!V&&!B$($)}async function N$($){let Z=j$.get($);if(!Z){e0($);return}if(Z.closing){await Z.queue;return}Z.closing=!0,e0($),await Z.queue,j$.delete($)}var AO="https://open.feishu.cn/open-apis/cardkit/v1",NO=15000,pW=5000,RO,j$,p2,TO=1500;var U1=R(()=>{u0();Y0();j4();I();d0();RO=[0,250,750,1500];j$=new Map,p2=new Map});function O1($){if(!$)return"积分 MISS";if(B2($)==="empty")return null;if($.unlimited)return"积分 无限";if($.balance===null)return"积分 MISS";let Z=$.balance,J="";for(let Y of["k","m"]){if(Math.round(Z*10)<1e4)break;Z/=1000,J=Y}return`积分 ${Z>0&&Z<0.05?"<0.1":Z.toLocaleString("en-US",{maximumFractionDigits:1,useGrouping:!1})}${J}`}function $1($){if(!$)return"?";let Z=$.getTime()-Date.now();if(Z<=0)return"已重置";if(Z<3600000)return`${Math.max(1,Math.round(Z/60000))}m`;if(Z<86400000)return`${(Z/3600000).toFixed(1)}h`;return`${(Z/86400000).toFixed(1)}d`}function sW($,Z){let J=Z.replace(/[&<>\\`*_\[\]~]/g,(H)=>`&#${H.charCodeAt(0)};`),Q=typeof $.used==="number"&&typeof $.total==="number"?` · ${$.used}/${$.total}`:"",Y=$.percent;if(Y===null||!Number.isFinite(Y)||Y<0||Y>100)return[{tag:"markdown",content:`**${J} · MISS${Q}**`}];let V=Math.round(Y/100*6),X=Y>=100?"red":Y>=80?"orange":"green",z=$.resetsAt&&Number.isFinite($.resetsAt.getTime())?`${$1($.resetsAt)} 重置`:"重置时间 MISS";return[{tag:"markdown",content:`**${J} · ${Math.round(Y)}%${Q}**
153
+ `,(z)=>{if(z)this.transportFailure(z)})})}receive($){try{let Z=JSON.parse($);if(Z.jsonrpc!=="2.0")throw Error("invalid DSH JSON-RPC envelope");if(typeof Z.id==="number"){let J=this.pending.get(Z.id);if(!J){j(`dsh: unexpected response id=${Z.id}`);return}if(this.pending.delete(Z.id),clearTimeout(J.timer),Z.error)J.reject(Error(`DSH RPC error: ${Z.error.message}`));else if("result"in Z)J.resolve(Z.result);else J.reject(Error("DSH response has neither result nor error"))}else if(typeof Z.method==="string"&&Z.params&&typeof Z.params==="object")this.emit("notification",{method:Z.method,params:Z.params});else throw Error("invalid DSH notification")}catch(Z){this.transportFailure(Z instanceof Error?Z:Error(String(Z)))}}rejectPending($){for(let Z of this.pending.values())clearTimeout(Z.timer),Z.reject($);this.pending.clear()}transportFailure($){this.rejectPending($),this.emit("failure",$)}close($=3000){return this.closeTask??=this.dispose($).catch((Z)=>{throw this.closeTask=void 0,Z})}async dispose($){if(this.exited)return;if(this.closing=!0,this.initialized)try{await this.request("shutdown",{},$)}catch(J){j(`dsh shutdown: ${J}`)}this.child.stdin.end();let Z=async(J)=>{let Q;return await Promise.race([this.exitTask,new Promise((Y)=>{Q=setTimeout(Y,J)})]),clearTimeout(Q),this.exited};if(await Z($))return;if(j(`dsh: terminate owned child pid=${this.pid}`),this.child.kill("SIGTERM"),await Z($))return;if(j(`dsh: kill unresponsive owned child pid=${this.pid}`),this.child.kill("SIGKILL"),!await Z($))throw Error(`DSH child exit not confirmed: pid=${this.pid}`)}}});var wW=R(()=>{X0();P0();D8();H0();WQ();L1();N0({kind:"deepseek-harness",configSectionId:"deepseek-harness",build($){let Z=$.api_key?.trim()??"",J=$.base_url?.trim()||"https://api.deepseek.com",Q=new URL(J),Y=Q.origin==="https://api.deepseek.com"&&!Q.username&&!Q.password&&!Q.search&&!Q.hash&&["","/v1","/anthropic","/anthropic/v1"].includes(Q.pathname.replace(/\/+$/,"")),V={id:"deepseek-harness",kind:"deepseek-harness",agent:"dsh",display:$.display?.trim()||"DeepSeek",enabled:!!Z,models:[],defaultModel:$.model?.trim()??"",modelCatalogState:{status:Z?"idle":"disabled",updatedAt:Date.now()},spawnEnv(X){let z=p9(X);if(!Z)throw Error("DeepSeek Harness API key is missing");if(z.DEEPSEEK_API_KEY=Z,!Y)z.DEEPSEEK_BASE_URL=J;if(z.LODESTAR_DSH_PROVIDER="deepseek-official",$.bin)z.LODESTAR_DSH_NODE=$.bin;return z},async refreshModels(){if(!V.enabled){V.models=[],V.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}V.modelCatalogState={status:"loading",updatedAt:null};try{let X=await r4({cwd:W4,env:V.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list",{models:[...s($.models),...s($.custom_models)]});if(!Array.isArray(X)||!X.length)throw Error("DeepSeek Harness model catalog is empty");for(let H of X)if(!H.model||!H.efforts.length||!H.efforts.every(S0)||!S0(H.defaultEffort)||!H.efforts.includes(H.defaultEffort))throw Error(`Invalid DSH model/effort catalog: ${H.model}`);let z=$.model?.trim()||X.find((H)=>H.isDefault)?.model;if(!z||!X.some((H)=>H.model===z))throw Error("DSH default model is not in its catalog");V.models=X.map(({model:H,display:G,efforts:W,defaultEffort:K,isCustom:B})=>{let _=$.effort?.trim();if(_&&(!S0(_)||!W.includes(_)))throw Error(`DSH model ${H} does not support configured effort ${_}`);return{model:H,display:G,efforts:W,defaultEffort:_?_:K,origin:B?"custom":"upstream"}}),V.defaultModel=z,V.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(X){throw V.models=[],V.modelCatalogState={status:"failed",updatedAt:Date.now(),error:X instanceof Error?X.message:String(X)},X}},resolveSpawnModel(X){return f1(V).find((z)=>z.model===X)?.model},readUsage(){return Z?GQ(J,Z):Promise.resolve({kind:"balance",state:"no_credentials",windows:[]})}};return V},setup:{commandSuffix:"deepseek-harness",hint:()=>"DeepSeek 账号由 Claude Code 和 DeepSeek Harness 共用。发送 `deepseek-setup <api_key>` 配置两边;`deepseek-harness-setup [base_url] <api_key>` 同样更新共享账号。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:deepseek-harness-setup [base_url] <api_key>"};return{config:{agent:"dsh",api_key:Z.at(-1),...Z.length===2?{base_url:Z[0]}:{}}}},async validate($){await HQ($.base_url??"https://api.deepseek.com",$.api_key??"")}}})});function u7($){let Z=new URL($);if(!y2(Z.origin)||Z.protocol!=="https:"||Z.username||Z.password||Z.search||Z.hash)throw Error("DSH GLM 需要智谱或 Z.ai 的 Coding Plan HTTPS 端点;地址中不能包含凭据或查询参数");return Z.pathname="/api/coding/paas/v4",Z.search="",Z.hash="",Z.toString().replace(/\/$/,"")}async function vW($,Z){return(await u$(`${$}/models`,Z,"GLM Coding Plan models")).map((Q)=>{if(typeof Q?.id!=="string"||!Q.id)throw Error("GLM Coding Plan 模型 id 无效");return{model:Q.id,display:typeof Q.name==="string"?Q.name:Q.id}})}var yW=R(()=>{_4();k0();P0();X0();D8();H0();b7();XQ();L1();N0({kind:"dsh-glm",configSectionId:"dsh-glm",detect:{fromSettingsEnv($){let Z=g.token_sources?.glm,J=Z?.auth_token?.trim()||$.ANTHROPIC_AUTH_TOKEN?.trim(),Q=Z?.base_url?.trim()||$.ANTHROPIC_BASE_URL?.trim();return J&&Q&&y2(Q)?{api_key:J,base_url:u7(Q)}:null}},build($,Z){let J=$.api_key?.trim()||$.auth_token?.trim()||Z?.api_key?.trim()||"",Q=u7($.base_url?.trim()||Z?.base_url?.trim()||"https://open.bigmodel.cn/api/coding/paas/v4"),Y=new URL(Q).hostname.endsWith("bigmodel.cn")?"zai-coding-cn":"zai",V,X={id:"dsh-glm",kind:"dsh-glm",agent:"dsh",display:$.display?.trim()||"GLM Coding Plan",enabled:!!J,models:[],defaultModel:$.model?.trim().toLowerCase()??"",modelEnvironmentRevision(){return JSON.stringify((X.modelSelection?.availableModels??X.models).map((z)=>z.model).sort())},modelCatalogState:{status:J?"idle":"disabled",updatedAt:Date.now()},spawnEnv(z){if(!J)throw Error("DSH GLM Coding Plan API key is missing");let H=p9(z);H.LODESTAR_DSH_PROVIDER=Y,H.LODESTAR_DSH_GLM_API_KEY=J,H.LODESTAR_DSH_BASE_URL=Q,H.LODESTAR_DSH_DEFAULT_MODEL=X.defaultModel;let G=(X.modelSelection?.availableModels??X.models).map((W)=>W.model);if(V||G.length)H.LODESTAR_DSH_MODELS=JSON.stringify(V??G);if($.bin)H.LODESTAR_DSH_NODE=$.bin;return H},async refreshModels(){if(X.models=[],V=void 0,!X.enabled){X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await vW(Q,J),H=[...z];for(let W of[...s($.models),...s($.custom_models)])if(!H.some((K)=>K.model.toLowerCase()===W.toLowerCase()))H.push({model:W,display:W});if(V=H.map((W)=>W.model),!$.model?.trim()){let W=(K)=>Number(K.match(/\d+(?:\.\d+)?/)?.[0]??-1);X.defaultModel=[...z].sort((K,B)=>W(B.model)-W(K.model))[0].model}let G=await r4({cwd:W4,env:X.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list");X.models=H.map((W)=>{let K=G.find((L)=>L.model===W.model),B=N2(X,$),_=K?K.efforts.filter(S0):B.efforts,P=$.effort?.trim()||K?.defaultEffort||B.defaultEffort;return{...W,display:K?.display??W.display,efforts:_,defaultEffort:S0(P)&&_.includes(P)?P:null,origin:z.some((L)=>L.model===W.model)?"upstream":"custom"}}),X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){throw X.models=[],V=[],X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:z instanceof Error?z.message:String(z)},z}},resolveSpawnModel(z){return f1(X).find((H)=>H.model===z&&!H.unavailableReason)?.model},async readUsage(){return J?VQ(await x7(Q,J)):{state:"no_credentials",windows:[]}}};return X},setup:{commandSuffix:"dsh-glm",hint:()=>"GLM Coding Plan 账号由 Claude Code 和 DeepSeek Harness 共用。发送 `glm-setup <api_key>` 配置两边;`dsh-glm-setup [base_url] <api_key>` 同样更新共享账号。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2||/^https?:\/\//i.test(Z.at(-1)))return{error:"用法:dsh-glm-setup [base_url] <api_key>"};try{return{config:{agent:"dsh",api_key:Z.at(-1),base_url:u7(Z.length===2?Z[0]:"https://open.bigmodel.cn/api/coding/paas/v4")}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}},async validate($){await vW(u7($.base_url??"https://open.bigmodel.cn/api/coding/paas/v4"),$.api_key??$.auth_token??"")}}})});var IW={};H1(IW,{tokenSourceSpawnRevision:()=>hW,buildTokenSourcesFromConfig:()=>M8});import{createHash as fW}from"node:crypto";function M8(){let $=rJ(),Z=Object.fromEntries(U2().flatMap((G)=>{let W=G.detect?.fromSettingsEnv($);return G.configSectionId&&W?[[G.configSectionId,W]]:[]})),J=L8(g.token_sources??{},Z),Q=new Map(s0().map((G)=>[G.id,G])),Y=U2().map((G)=>{let W=G.configSectionId?J[G.configSectionId]??{}:{},K=G.configSectionId?Z[G.configSectionId]??null:null,B=()=>{let _=r3(G.build(W,K),W);return _.spawnRevision=hW(G.kind,W,K),_};return{cfg:W,detected:K,create:B,initial:B()}}),V=Y.some(({initial:G})=>G.agent==="claude"&&G.enabled&&G.kind!=="claude-native"&&G.kind!=="claude-subscription"),X=Y.map(({cfg:G,detected:W,create:K,initial:B})=>{let _=()=>{let F=K();if(F.kind==="claude-native")F.enabled=!V,F.modelCatalogState={status:F.enabled?"idle":"disabled",updatedAt:Date.now()};return F},P=(F)=>{let{display:M,model:U,effort:A,models:O,hidden_models:N,shown_models:S,custom_models:T,slots:f,default:m,...b}=F??{};return b},L=(F)=>fW("sha256").update(JSON.stringify(F,(M,U)=>U&&typeof U==="object"&&!Array.isArray(U)?Object.fromEntries(Object.entries(U).sort(([A],[O])=>A.localeCompare(O))):U)).digest("hex"),q=B.kind==="claude-native"?!V:void 0;return QJ(_,G,L([B.id,P(G),P(W),q]),L([G,W,q]),Q.get(B.id))});yZ();for(let G of X)kZ(G);for(let G of Q.values())if(!X.includes(G))J8(G);let H=X.find((G)=>G.enabled&&g.token_sources?.[G.id]?.default===!0)??X.find((G)=>G.enabled);if(H)vZ(H.id);return X.length}function hW($,Z,J){let Q=(Y)=>({agent:Y?.agent,auth:Y?.auth,base_url:Y?.base_url,auth_token:Y?.auth_token,api_key:Y?.api_key,bin:Y?.bin,model:Y?.model,effort:Y?.effort,slots:Y?.slots});return fW("sha256").update(JSON.stringify({kind:$,configured:Q(Z),detected:Q(J)})).digest("hex")}var l7=R(()=>{k0();X0();b7();L1();q8();W7();H7();XQ();YW();GW();WQ();UW();SW();wW();yW()});function DQ($){let Z=new Map,J=$.map((K)=>{let B=K.fingerprint?Z.get(K.fingerprint):void 0;if(K.fingerprint&&!B)Z.set(K.fingerprint,K.account.name);return{...K,...B?{duplicateOf:B}:{}}}),Q=J.filter((K)=>!K.duplicateOf),V=(Q.length<=1||Q.every((K)=>K.fingerprint!==null))&&Q.every((K)=>K.usage.state==="ok"),X=Q.flatMap((K)=>K.usage.state==="ok"?[K.usage]:[]),z=X.map((K)=>{let B=MZ(K);if(B.state==="exhausted")return!1;if(B.state==="miss")return null;if(B.state==="credits")return!0;return[K.fiveHour,K.weekly].filter((P)=>P!==null).length?!0:null}),H=V&&z.every((K)=>K!==null)?z.filter(Boolean).length:null,G=V&&X.every((K)=>K.resetCredits!=null)?X.reduce((K,B)=>K+B.resetCredits,0):null,W=["fiveHour","weekly"].map((K)=>{let B=X.map((P)=>P[K]).filter((P)=>P!==null),_=V&&B.every((P)=>P.percent!==null&&P.percent>=0&&P.percent<=100);return{kind:K,count:B.length,remaining:_?B.reduce((P,L)=>P+(100-L.percent)/100,0):null}}).filter((K)=>K.count||!V);return{entries:J,complete:V,available:H,resetCredits:G,windows:W}}async function gW($){return{...$,entries:$.entries.map((Z)=>{let J=sz(Z.account.id);return{...Z,email:J?.email??null,emailError:J?.error??(!J?"账号信息缓存尚未就绪,后台刷新中":void 0)}})}}async function d7($){let Z=new Map,J=await Promise.all(v.list().map(async(Q)=>{let Y=null;try{Y=v.fingerprint(Q.id)}catch(H){return{account:Q,fingerprint:Y,usage:{state:"network",reason:`账号身份读取失败:${String(H)}`}}}let V=Y??Q.id,X=Z.get(V);if(!X)X=$?.id===Q.id?Promise.resolve($.usage):JH(Q.id),Z.set(V,X);let z=await X;if(z.state==="ok"&&z.accountFingerprint)Y=z.accountFingerprint;return{account:Q,usage:z,fingerprint:Y}}));return DQ(J)}var MQ=R(()=>{D0();z$();I();d3();T4()});import{createHash as mW,randomUUID as OO}from"node:crypto";function m2($,Z){if($===300305||$===200860)return!0;if($!==300315)return!1;let J=Z?.message??"";return/(?:code\s*[:=]\s*(?:300305|200860)\b|number of card components[^\n.]{0,60}exceed|\bcard over max size\b)/i.test(J)}function UQ($,Z){if($!==300315)return!1;return/(?:duplicate\s+(?:element\s*)?id|code\s*1001\s*:\s*duplicate id)/i.test(Z?.message??"")}function f$($){let Z=j$.get($);if(!Z)throw Error(`cardkit card is not registered: ${$}`);return Z}function B$($){return!j$.has($)}function h$($,Z,J){j$.set($,{sequence:0,queue:Promise.resolve(),elementCount:Z,contentFingerprints:new Map,deadElements:new Set,failedAdds:new Map,uncertainAdds:new Set,confirmedAdds:new Set,failedReplacements:new Set,onFailure:J,closing:!1})}function U8($){return j$.get($)?.elementCount??0}function cW($){let Z=j$.get($);return Z?[...Z.contentFingerprints.keys()].filter((J)=>!Z.deadElements.has(J)):[]}function e4($,Z){return j$.get($)?.deadElements.has(Z)??!1}function uW($,Z){let J=j$.get($);J?.deadElements.delete(Z),J?.failedAdds.delete(Z),J?.failedReplacements.delete(Z)}function OQ($){let Z=f$($);return Z.sequence+=1,Z.sequence}function AQ($,Z){$.deadElements.add(Z)}function lW($){return mW("sha256").update(JSON.stringify($,(Z,J)=>Z==="element_id"?void 0:J)).digest("hex")}function EO($,Z,J){let Q=[...$.contentFingerprints].filter(([Y])=>Y!==Z).map(([,Y])=>Y);if(J&&Z!==C.footer)Q.push(J);return mW("sha256").update(Q.sort().join(`
154
+ `)).digest("hex")}async function i7($,Z,J,Q,Y){let V=J?JSON.stringify({...J,..."sequence"in J?{uuid:OO()}:{}}):void 0,X=`cardkit ${$} ${Z}`;return G2(X,async()=>{let z=await s$(Q),H=AbortSignal.timeout(Q.timeoutMs(NO)),G;try{return G=await V0(`${AO}${Z}`,{method:$,headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},...V!==void 0?{body:V}:{},signal:H}),(await D$(G,X))?.data}catch(W){if(H.aborted&&H.reason?.name==="TimeoutError")W=H.reason;if(G&&W instanceof l0)Object.assign(W,{httpStatus:G.status});throw Y?.(W),W}},{api:"cardkit",recovery:Q})}function NQ($){return $ instanceof l0&&($.code===200770||$.code==="200770")}function dW($){if(NQ($))return!1;if($ instanceof l0){if($.status===429||$.code===99991400||$.code===230020)return!1;if($.status!==void 0&&$.status>=200&&$.status<300&&$.code===void 0)return!0}return A3($,{api:"cardkit"})}async function n7($,Z,J,Q,Y){let V=!1;for(;;){let X=!1;try{if(await i7(Z,J,{...Q,sequence:OQ($)},Y,(z)=>{if(dW(z))X=!0}),V)j(`cardkit confirmed ${Z} ${J}: same state accepted with new UUID and sequence`);return}catch(z){if(!X||!NQ(z))throw z;if(!await Y.waitForRetry(`cardkit confirm ${Z} ${J}`,z,pW))throw z;V=!0}}}async function iW($,Z,J,Q,Y){let V=J.element_id,X=!1;try{await i7("POST",`/cards/${$}/elements`,{type:Q.type??"append",...Q.targetElementId?{target_element_id:Q.targetElementId}:{},elements:JSON.stringify([J]),sequence:OQ($)},Y,(z)=>{if(dW(z)){if(X=!0,V)Z.uncertainAdds.add(V)}})}catch(z){let H=z,G=V&&Z.uncertainAdds.has(V)&&UQ(H?.code,H);if(!V||!(G||X&&NQ(z)))throw z;if(!await Y.waitForRetry(`cardkit reconcile uncertain add ${$} element=${V}`,z,pW))throw z;await n7($,"PUT",`/cards/${$}/elements/${V}`,{element:JSON.stringify(J)},Y),j(`cardkit reconciled uncertain add ${$} element=${V}: latest content accepted with PUT`)}if(!V||!Z.confirmedAdds.has(V))Z.elementCount++;if(V)Z.confirmedAdds.add(V),Z.uncertainAdds.delete(V)}function SO($){return new Promise((Z)=>setTimeout(Z,$))}function CO($){if(typeof $!=="object"||$===null)return!1;let Z=$.code;return Z===300309||Z===200850}async function xO($,Z){await n7($,"PATCH",`/cards/${$}/settings`,{settings:JSON.stringify({config:{streaming_mode:!0}})},Z)}async function a7($,Z,J,Q,Y=!1,V={}){let X=new H2,z=async(H)=>{let G=typeof H==="object"&&H!==null?H:null,W={cardId:$,operation:Z,elementId:V.elementId,targetElementId:V.targetElementId,code:G?.code,httpStatus:G?.httpStatus,logId:G?.logId,message:H instanceof Error?H.message:String(H),apiMessage:G?.apiMessage};if(m2(W.code,W))W.capacityFingerprint=EO(f$($),V.elementId,V.contentFingerprint);if(!m2(W.code,W)&&!(H instanceof Error&&H.name==="AbortError"))await X.waitUntilDeadline();try{if(!Y||Y==="non-capacity"&&m2(W.code,W))f$($).onFailure?.(W.code,W)}catch(K){j(`cardkit failure callback ${$}: ${K}`)}try{Q?.(W)}catch(K){j(`cardkit per-call failure callback ${$}: ${K}`)}};try{await J(X);return}catch(H){if(!CO(H)){j(`cardkit ${Z} ${$}: ${H}`),await z(H);return}j(`cardkit ${Z} ${$}: streaming closed (code=${H.code}) — reopening`)}try{await xO($,X)}catch(H){j(`cardkit STREAMING_REOPEN_FAILED ${$}: ${H}`),await z(H);return}try{await J(X)}catch(H){j(`cardkit ${Z} ${$} retry-after-reopen: ${H}`),await z(H)}}function bO($){return typeof $==="object"&&$!==null&&$.code===200740}async function e$($,Z={}){let J=new H2,Q=Z.retryDelaysMs?.length?Z.retryDelaysMs:RO,Y=null;for(let V=0;V<Q.length;V++){let X=Q[V]??0;if(X>0)await SO(Math.min(X,J.remainingMs()));try{let z=await i7("POST","/cards/id_convert",{message_id:$},J);if(typeof z?.card_id!=="string"||!z.card_id)throw Error("cardkit POST /cards/id_convert: missing card_id");return z.card_id}catch(z){if(Y=z,!bO(z))throw await J.waitUntilDeadline(),z;if(V===Q.length-1){if(!await J.waitForRetry(`cardkit id_convert ${$}`,z))throw z;V--;continue}let H=Q[V+1]??0;j(`cardkit id_convert ${$}: empty result, retry ${V+2}/${Q.length} in ${H}ms`)}}throw Y}async function d1($){let Z=j$.get($);if(!Z)return;await Z.queue}function v0($,Z,J={},Q,Y="all"){if(B$($))return Promise.resolve();let V=f$($);if(V.closing)return Promise.resolve();let X=m1(Z),z=X.element_id,H=lW(X),G=()=>{if(!z)return;AQ(V,z),V.failedAdds.set(z,J)};return V.queue=V.queue.then(()=>a7($,"addElement",async(W)=>{if(await iW($,V,X,J,W),z!==C.footer)V.contentFingerprints.set(z??`#${V.sequence}`,H);if(z)V.deadElements.delete(z),V.failedAdds.delete(z),V.failedReplacements.delete(z)},(W)=>{G(),Q?.(W.code,W)},Y==="capacity"?"non-capacity":!1,{elementId:z,targetElementId:J.targetElementId,contentFingerprint:H})),V.queue}function R0($,Z,J,Q,Y=!0){if(B$($))return Promise.resolve();let V=f$($);if(V.closing)return Promise.resolve();let X=m1(J),z=lW(X),H=()=>{AQ(V,Z),V.failedReplacements.add(Z)};return V.queue=V.queue.then(()=>a7($,`replaceElement ${Z}`,async(G)=>{let W=V.failedAdds.get(Z);if(V.deadElements.has(Z)&&!W&&!V.failedReplacements.has(Z))return;if(W)await iW($,V,X,W,G);else await n7($,"PUT",`/cards/${$}/elements/${Z}`,{element:JSON.stringify(X)},G);if(V.deadElements.delete(Z),V.failedAdds.delete(Z),V.uncertainAdds.delete(Z),V.failedReplacements.delete(Z),Z!==C.footer)V.contentFingerprints.set(Z,z)},(G)=>{if(Y)H();Q?.(G.code,G)},!Y,{elementId:Z,contentFingerprint:z})),V.queue}async function F0($,Z,J,Q={}){if(B$($))return!1;let Y=f$($);if(Y.closing)return!1;let V=!1;return await R0($,Z,J,(X,z)=>{if(V=!0,z)Q.onFailure?.(z)},Q.notifyCardFailure!==!1),!V&&!Y.deadElements.has(Z)}async function nW($,Z,J){if(B$($))return{landed:!1};let Q=f$($);if(Q.closing)return{landed:!1};let Y;return await R0($,Z,J,(V,X)=>{Y=X}),{landed:!Y&&!Q.deadElements.has(Z),...Y?{failure:Y}:{}}}async function c2($,Z,J={}){let Q=await $9($,Z,J);if(Q.failure)J.onFailure?.(Q.failure);return Q.landed}async function $9($,Z,J={}){if(B$($))return{landed:!1};let Q=f$($);if(Q.closing)return{landed:!1};let Y=Z.element_id,V;return await v0($,Z,J,(X,z)=>{V=z}),{landed:!V&&!(Y&&Q.deadElements.has(Y)),...V?{failure:V}:{}}}function kO($,Z,J){if(B$($))return Promise.resolve();let Q=f$($);if(Q.closing)return Promise.resolve();let Y=()=>Q.deadElements.has(Z)&&!Q.failedAdds.has(Z)&&!Q.failedReplacements.has(Z);if(Y())return Promise.resolve();return Q.queue=Q.queue.then(()=>a7($,`deleteElement ${Z}`,async(V)=>{if(Y())return;let X=OQ($);await i7("DELETE",`/cards/${$}/elements/${Z}`,{sequence:X},V),Q.elementCount=Math.max(0,Q.elementCount-1),Q.contentFingerprints.delete(Z),Q.failedAdds.delete(Z),Q.uncertainAdds.delete(Z),Q.confirmedAdds.delete(Z),Q.failedReplacements.delete(Z),AQ(Q,Z)},(V)=>J?.(V.code,V),!0,{elementId:Z})),Q.queue}async function aW($,Z,J){if(B$($))return!1;let Q=f$($);if(Q.closing)return!1;if(Q.deadElements.has(Z)&&!Q.failedAdds.has(Z)&&!Q.failedReplacements.has(Z))return!0;let Y=!1;return await kO($,Z,(V,X)=>{if(Y=!0,X)J?.(X)}),!Y&&Q.deadElements.has(Z)}function Z9($,Z){if(B$($)||j$.get($)?.closing)return;let J=(Z??"").replace(/\s+/g," ").trim();if(!J)return;let Q=p2.get($);if(!Q)Q={latest:J,lastSent:"",timer:null,inFlight:!1},p2.set($,Q);else{if(Q.latest===J)return;Q.latest=J}oW($,Q)}function oW($,Z){if(Z.timer||Z.inFlight||Z.latest===Z.lastSent)return;Z.timer=setTimeout(()=>{if(p2.get($)!==Z)return;if(Z.timer=null,B$($)||j$.get($)?.closing){p2.delete($);return}if(Z.latest===Z.lastSent)return;let J=Z.latest;Z.inFlight=!0,m0($,{config:{summary:{content:J}}}).then((Q)=>{if(p2.get($)!==Z)return;if(Z.inFlight=!1,Q)Z.lastSent=J;if(Z.latest!==J&&!B$($)&&!j$.get($)?.closing)oW($,Z)})},TO)}function e0($){let Z=p2.get($);if(!Z)return;if(Z.timer)clearTimeout(Z.timer),Z.timer=null;p2.delete($)}function o7($,Z){return m0($,Z).then(()=>{})}async function m0($,Z,J){if(B$($))return!1;let Q=f$($);if(Q.closing)return!1;let Y=!1,V=!1;return Q.queue=Q.queue.then(()=>a7($,"patchSettings",async(X)=>{if(B$($))return;await n7($,"PATCH",`/cards/${$}/settings`,{settings:JSON.stringify(Z)},X),Y=!0},(X)=>{V=!0,J?.(X)},!0)),await Q.queue,Y&&!V&&!B$($)}async function N$($){let Z=j$.get($);if(!Z){e0($);return}if(Z.closing){await Z.queue;return}Z.closing=!0,e0($),await Z.queue,j$.delete($)}var AO="https://open.feishu.cn/open-apis/cardkit/v1",NO=15000,pW=5000,RO,j$,p2,TO=1500;var U1=R(()=>{u0();Y0();j4();I();d0();RO=[0,250,750,1500];j$=new Map,p2=new Map});function O1($){if(!$)return"积分 MISS";if(B2($)==="empty")return null;if($.unlimited)return"积分 无限";if($.balance===null)return"积分 MISS";let Z=$.balance,J="";for(let Y of["k","m"]){if(Math.round(Z*10)<1e4)break;Z/=1000,J=Y}return`积分 ${Z>0&&Z<0.05?"<0.1":Z.toLocaleString("en-US",{maximumFractionDigits:1,useGrouping:!1})}${J}`}function $1($){if(!$)return"?";let Z=$.getTime()-Date.now();if(Z<=0)return"已重置";if(Z<3600000)return`${Math.max(1,Math.round(Z/60000))}m`;if(Z<86400000)return`${(Z/3600000).toFixed(1)}h`;return`${(Z/86400000).toFixed(1)}d`}function sW($,Z){let J=Z.replace(/[&<>\\`*_\[\]~]/g,(H)=>`&#${H.charCodeAt(0)};`),Q=typeof $.used==="number"&&typeof $.total==="number"?` · ${$.used}/${$.total}`:"",Y=$.percent;if(Y===null||!Number.isFinite(Y)||Y<0||Y>100)return[{tag:"markdown",content:`**${J} · MISS${Q}**`}];let V=Math.round(Y/100*6),X=Y>=100?"red":Y>=80?"orange":"green",z=$.resetsAt&&Number.isFinite($.resetsAt.getTime())?`${$1($.resetsAt)} 重置`:"重置时间 MISS";return[{tag:"markdown",content:`**${J} · ${Math.round(Y)}%${Q}**
155
155
  <font color='${X}'>${"▰".repeat(V)}${"▱".repeat(6-V)}</font>`},{tag:"markdown",content:`<font color='grey'>${z}</font>`,text_size:"notation"}]}var J9=()=>{};var $K={};H1($K,{codexAccountSummary:()=>O8,codexAccountPanel:()=>A8,codexAccountCard:()=>Q1,CODEX_ACCOUNTS_PAGE_SIZE:()=>s7});function J1($){return $.replace(/[&<>\\`*_\[\]~]/g,(Z)=>`&#${Z.charCodeAt(0)};`)}function tW($){return{tag:"column_set",flex_mode:"none",horizontal_spacing:"12px",columns:$.map((Z)=>({tag:"column",width:"weighted",weight:1,vertical_align:"center",vertical_spacing:"4px",elements:Z}))}}function O8($){let[Z,J]=eW[$.phase],Q=$.name&&$.name.length>40?$.name.slice(0,37)+"…":$.name;return`${Z} Codex · ${Q?`${Q} · `:""}${$.title??J}`}function Q1($,Z=!1){return{schema:"2.0",config:{update_multi:!0,width_mode:"compact",streaming_mode:Z,summary:{content:O8($)}},body:{elements:[A8($)]}}}function A8($){let[,,Z]=eW[$.phase],J=[];if($.flow==="login"&&["connecting","waiting","checking","success"].includes($.phase)){let Q=$.phase==="connecting"?0:$.phase==="waiting"?1:2;J.push(T0(["连接","授权","就绪"].map((Y,V)=>V===Q?`**${V+1} ${Y}**`:`${V<Q?"✓":V+1} ${Y}`).join(" → ")))}if($.phase==="waiting"&&$.verification){let Q=new URL($.verification.url);if(Q.protocol!=="https:"||/[\s<>]/.test($.verification.url))throw Error("授权链接无效");if(!/^[A-Za-z0-9-]{1,64}$/.test($.verification.code))throw Error("验证码格式无效");J.push(tW([[Z1("验证码"),{tag:"markdown",content:`**${$.verification.code}**`,text_size:"heading-2"}],[T0(`[**打开授权页 ↗**](${Q.href.replace(/\(/g,"%28").replace(/\)/g,"%29")})`),Z1("登录账号,输入左侧验证码")]]))}if($.current)J.push(tW([[Z1("当前使用"),T0(`**${J1($.current)}**`)],...$.selected&&$.selected!==$.current?[[Z1("下次启动"),T0(`**${J1($.selected)}**`)]]:[]]));if($.plan||$.email)J.push(T0([$.plan?.toUpperCase(),$.email].filter(Boolean).map((Q)=>J1(Q)).join(" · ")));if($.message)J.push(T0(J1($.message)));if($.resetUsage){let Q=$.resetUsage;if(J.push(T0(`**重置卡** ${Q.state==="ok"&&Q.resetCredits!=null?`${Q.resetCredits} 次可用`:"MISS"}`)),Q.state==="ok"){let Y=O1(Q.credits);if(Y)J.push(T0(Y));for(let[V,X]of[[Q.fiveHour,"5h"],[Q.weekly,"周"]])if(V)J.push(...sW(V,X))}else J.push(T0("⚠️ 额度 MISS · 查看详情中的查询错误"))}if($.total)J.push(...wO($));if($.phase==="accounts")J.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"⌨️ Codex 命令"},background_color:"grey-50"},border:{color:"grey-100",corner_radius:"8px"},padding:"8px",elements:[T0(["`hi` · 打开控制台;未运行时启动","`hi 备注` · 本次指定账号;换号时重启并续跑","`codex-login [备注]` · 设备码登录;省略备注为默认账号","`codex-login-cancel [备注]` · 取消本人在本群的登录;仅一个任务时可省略备注","`codex-accounts [页码]` · 查看账号、额度与调度顺序","`codex-reset [备注]` · 使用一次重置卡;省略备注为当前使用账号","`codex-account` · 查看当前账号与下次启动策略","`codex-account 备注` · 持久指定账号,下次启动生效","`codex-auto` · 清除指定,下次启动自动选择","`codex-account-delete 备注` · 删除额外账号"].join(`
156
- `)),Z1("备注可用 default 指定设备默认账号;默认账号不可删除。")]});if($.hint)J.push(Z1($.hint));if($.details)J.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查看详情"}},elements:[T0(J1($.details))]});return{tag:"collapsible_panel",element_id:C.codexAccountPanel,expanded:!0,header:{title:{tag:"plain_text",content:O8($)},background_color:`${Z}-50`},border:{color:`${Z}-100`,corner_radius:"8px"},padding:$.phase==="accounts"?"8px":"12px",...$.phase==="accounts"?{vertical_spacing:"8px"}:{},elements:J}}function rW($,Z){let J=$.percent;if(J==null||!Number.isFinite(J)||J<0||J>100)return T0(`${Z} MISS`);let Q=Math.round(J/100*6),Y=J>=100?"red":J>=80?"orange":"green",V=$.resetsAt&&Number.isFinite($.resetsAt.getTime())?$1($.resetsAt):"MISS";return T0(`${Z} <font color='${Y}'>${"▰".repeat(Q)}${"▱".repeat(6-Q)}</font> ${Math.round(J)}% <font color='grey'>「${V}」</font>`)}function wO($){let Z=$.total,J=Math.max(1,Math.ceil(Z.entries.length/s7)),Q=$.page??1;if(!Number.isInteger(Q)||Q<1||Q>J)throw Error(`页码应为 1–${J}`);let Y=[],V=$.scheduling?.candidates.filter((H)=>H.state==="ready").sort(m3)??[],X=new Map(V.map((H,G)=>[H.account.id,G+1])),z=Z.entries.slice().sort((H,G)=>(X.get(H.account.id)??1/0)-(X.get(G.account.id)??1/0));for(let H of z.slice((Q-1)*s7,Q*s7)){let G=H.usage,W=[],K=$.scheduling?.candidates.find((q)=>q.account.id===H.account.id),B=X.get(H.account.id),_=H.duplicateOf?"重复":K?.state==="ready"?K.funding==="credits"?"积分":K.priority==="expiring"?"临期优先":`${K.score.toPrecision(3)}/h`:"MISS";if(Y.push({tag:"collapsible_panel",expanded:!0,header:{title:{tag:"plain_text",content:`#${B??"—"}·${H.account.name}「${_}」 · 重置 ${G.state==="ok"?G.resetCredits??"MISS":"MISS"}`},background_color:"grey-50"},border:{color:"grey-100",corner_radius:"8px"},padding:"8px",vertical_spacing:"2px",elements:W}),W.push(Z1(`邮箱:${H.email??"MISS"}`)),H.emailError)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"邮箱查询错误"}},elements:[T0(J1(H.emailError))]});if(H.duplicateOf){W.push(Z1(`与「${H.duplicateOf}」同一账号,合计只计一次`));continue}if(K&&K.state!=="ready"){if(W.push(Z1(K.state==="exhausted"?"⏳ 暂不可用":K.state==="excluded"?"Plus 无可用积分 · 不参与 Ultra":K.state==="waiting"?`⏳ 周余量 ${K.remaining?.toPrecision(3)} 份 · 未达 0.5 份`:"MISS · 无法排序")),K.reason&&G.state==="ok")W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"未参与原因"}},elements:[T0(J1(K.reason))]})}if(G.state!=="ok"){if(W.push(T0(G.state==="no_credentials"?"⚪ 未登录":"⚠️ 额度 MISS")),G.state==="network"&&G.reason)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查询错误"}},elements:[T0(J1(G.reason))]});continue}if(G.weekly)W.push(rW(G.weekly,"周"));if(G.fiveHour)W.push(rW(G.fiveHour,"5h"));let P=O1(G.credits);if(P)W.push(T0(P));let L=$.activationErrors?.[H.account.id];if(L)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"后台激活 MISS"}},elements:[T0(J1(L))]})}if(J>1)Y.push(Z1(`${Q}/${J} 页 · ${Q<J?`下一页 codex-accounts ${Q+1}`:"首页 codex-accounts"}`));return Y}var s7=4,eW,T0=($)=>({tag:"markdown",content:$}),Z1=($)=>({tag:"markdown",content:`<font color='grey'>${J1($)}</font>`,text_size:"notation"});var Q9=R(()=>{d0();J9();T4();eW={connecting:["\uD83D\uDD04","连接中","blue"],waiting:["\uD83D\uDD10","等待授权","blue"],checking:["\uD83D\uDD0E","校验中","blue"],success:["✅","登录成功","green"],selected:["\uD83C\uDFAF","下次启动生效","green"],current:["\uD83E\uDDED","当前账号","blue"],accounts:["\uD83D\uDDC2","账号与额度","blue"],cancelled:["⏹","已取消","grey"],expired:["⌛","等待超时","orange"],deleted:["\uD83D\uDDD1","已删除","grey"],error:["❌","未完成","red"],warning:["⚠️","需要处理","orange"]}});class Y9{cardId;deps;tail=Promise.resolve();terminal=null;constructor($,Z){this.cardId=$;this.deps=Z}static async open($,Z,J=vO){let Q,Y=await J.sendCard($,Q1(Z,!0),(X)=>{Q=X});if(!Y)throw Error(`Codex 账号卡片发送失败:${w(Q)}`);let V=await J.convertMessageToCard(Y);return J.recordCardCreated(V,1),new Y9(V,J)}update($){if(this.terminal)return Promise.reject(Error("Codex 账号卡片已结束"));let Z=A8($);return this.enqueue(()=>this.write($,Z,!1))}finish($){if(this.terminal)return this.terminal;let Z=A8($);return this.terminal=this.enqueue(()=>this.write($,Z,!0)),this.terminal}enqueue($){let Z=this.tail.then($);return this.tail=Z.then(()=>{},()=>{}),Z}async write($,Z,J){let Q,Y,V=await this.deps.replaceElementChecked(this.cardId,C.codexAccountPanel,Z,{notifyCardFailure:!1,onFailure:(z)=>{Q=z}}),X=await this.deps.patchSettingsChecked(this.cardId,{config:{streaming_mode:!J,summary:{content:O8($)}}},(z)=>{Y=z});if(!V||!X)throw Error(`Codex 账号卡片更新失败:内容 ${V?"OK":w(Q)},状态 ${X?"OK":w(Y)}`);if(J)await this.deps.dispose(this.cardId)}}var vO;var ZK=R(()=>{Y0();U1();d0();Q9();vO={sendCard:o,convertMessageToCard:e$,recordCardCreated:h$,replaceElementChecked:D0,patchSettingsChecked:m0,dispose:N$}});var TQ={};H1(TQ,{settleCodexAccountCards:()=>RQ,runCodexNamedHi:()=>yO,runCodexAccountCommand:()=>hO});import{createHash as fO}from"node:crypto";function N8($,Z){let J=$ instanceof Error?$.message:String($),Q=!/失败|未完全退出/.test(J)&&/登录已取消|服务退出/.test(J),Y=/过期|等待超过|expired/i.test(J),V=J.split(/[\n;]/)[0];return{phase:Q?"cancelled":Y?"expired":"error",name:Z,message:V.length>80?V.slice(0,77)+"…":V,...J!==V||V.length>80?{details:J}:{}}}async function JK($,Z){let J;if(!await o($.chatId,Q1(N8(Z)),(Q)=>{J=Q}))throw Error(`Codex 错误卡片发送失败
157
- ${w(J)}`)}async function yO($,Z){let J=await Y9.open($.chatId,{phase:"checking",name:Z,message:"正在启动指定账号…"});try{let Q=v.find(Z),Y="";if(!await $.startWithCodexAccount(Q.id,{announce:!1,onStatus:(X)=>{Y=X}}))throw Error(Y||"指定账号启动失败");await J.finish({phase:"current",name:Q.name,current:Q.name,title:"已指定账号",hint:"本次手动指定 · 不参与自动排序"}),await $.showConsole()}catch(Q){await J.finish(N8(Q,Z))}}async function RQ(){let Z=(await Promise.allSettled([...l2.values()])).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 账号卡片未全部写入")}async function hO($,Z,J,Q,Y){if(Z==="reset"){await gO($,J,Y);return}let V={chatId:$.chatId,userOpenId:Q};if(Z==="login-cancel"){try{let G=v2.pending(V);if(!J&&G.length!==1)throw Error(G.length?"有多个登录任务;请指定 codex-login-cancel 备注":"本群没有你的登录任务");let W=J?v.find(J).id:G[0];await v2.cancel(W,V),await l2.get(W)}catch(G){await JK($,G)}return}let X=Z==="login"?J||"默认":Z==="account"||Z==="account-delete"?J||void 0:void 0,z=Z==="login"&&!!J.trim()&&!["default","默认"].includes(J.normalize("NFC").trim().toLowerCase()),H=await Y9.open($.chatId,{phase:Z==="login"?"connecting":"checking",name:X,...Z==="login"?{flow:"login"}:{},message:Z==="accounts"?"正在读取各账号邮箱与额度…":z?"正在检查默认账号登录状态…":Z==="login"?"正在获取设备码…":"正在核对账号…"});try{if(Z==="account-delete"){if(!J)throw Error("请指定要删除的账号;使用 codex-account-delete 备注");let _=v.find(J);if(l2.has(_.id))throw Error("账号登录或结果更新尚未结束;请先完成或取消登录后重试");let{clearedSelections:P}=v.remove(_.id);JG(M0("codex-sub"),_.id),d$(_.id),await H.finish({phase:"deleted",name:_.name,message:"已删除本地账号记录与独立凭据,共享会话历史保留。",hint:P?`已清除 ${P} 个群的指定,下次启动自动选号 · codex-accounts 查看`:"codex-accounts 查看剩余账号"});return}if(Z==="accounts"){if(J&&!/^[1-9]\d*$/.test(J))throw Error("页码无效;使用 codex-accounts [页码]");let _=J?Number(J):1,P=$.codexAccountId(),L=j0("codex-sub",P),q=()=>$.currentProvider()==="codex"?$.currentModelLabel():L?.defaultModel,D=q(),M;if(!D)try{if(!L)throw Error("Codex 订阅来源尚未初始化");if(D=q(),!D)throw Error(L.modelCatalogState?.error??"Codex 模型目录未提供可用的默认模型")}catch(N){M=`${v.get(P).name}:${N instanceof Error?N.message:String(N)}`}let U=$.currentProvider()==="codex"?$.currentEffortLabel()??void 0:void 0,A=D?await O2.choose({model:D,effort:U}):null,O=A?FQ(A.candidates.flatMap((N)=>{let T=(N.usage?.state==="network"||N.usage?.state==="rate_limited"?M2(N.account.id):null)??N.usage;return T?[{account:N.account,usage:T,fingerprint:N.identity.startsWith("record:")?null:N.identity}]:[]})):await d7();if(M)j(`codex-accounts: scheduling MISS: ${M}`);await H.finish({phase:"accounts",total:await gW(O),currentId:P,activationErrors:Object.fromEntries(O.entries.flatMap((N)=>{let S=l9.error(N.account.id);return S?[[N.account.id,S]]:[]})),...v.preferred($.sessionName)?{selectedId:v.selected($.sessionName)}:{},page:_,...A?{scheduling:{candidates:A.candidates,ultra:U==="ultra"}}:{message:"⚠️ 调度顺序 MISS:尚未确定 Codex 模型",details:M,hint:"可用 hi 备注指定已登录账号,或通过 md 检查模型目录"}});return}if(Z==="auto"){if(J)throw Error("codex-auto 不需要备注");v.selectAuto($.sessionName),await H.finish({phase:"selected",name:"自动选择",current:v.get($.codexAccountId()).name,selected:"自动 · 临期 / 评分",hint:"Ultra:Pro 且周余量 ≥ 0.5 份"});return}if(Z==="account"){if(!J){await H.finish({phase:"current",current:v.get($.codexAccountId()).name,selected:v.preferred($.sessionName)===null?"自动 · 临期 / 评分":v.get(v.selected($.sessionName)).name,hint:"周剩余份额 ÷(重置小时 − 5)· codex-auto"});return}let _=v.find(J),P=$.currentProvider()==="codex"?$.currentModelLabel():null,L=$.currentProvider()==="codex"?$.currentEffortLabel():null,q=v.get($.codexAccountId()).name;if($.currentProvider()==="codex")l1($.sessionName,"codex",P,L,"codex-sub");if(v.select($.sessionName,_.id),$.currentProvider()==="codex")$.selectedModel=P,$.selectedEffort=L,$.selectedTokenSourceId="codex-sub";await H.finish({phase:"selected",name:_.name,current:q,selected:_.name,hint:"restart 直接使用 · 不检查调度门槛"});return}if(Z!=="login")throw Error("未知 Codex 账号命令");if(!Q)throw Error("无法确认登录发起者");if(z)await nG(),await H.update({phase:"connecting",flow:"login",name:X,message:"正在获取设备码…"});let G=v.ensure(J);if(f3(G.id))throw Error("账号正在使用中;重新登录前先 kill 使用该账号的会话,或用新备注添加账号");if(l2.has(G.id))throw Error("登录结果正在更新,请稍等");let W=await v2.start(G.id,V);try{await H.update({phase:"waiting",flow:"login",name:G.name,verification:{url:W.verificationUrl,code:W.userCode},hint:`取消:codex-login-cancel${J?` ${G.name}`:""}`})}catch(_){throw await v2.cancel(G.id,V),_}let K=(async()=>{let _;try{_=await W.done}catch(P){await H.finish(N8(P,G.name));return}M8(),j0("codex-sub",G.id),await H.finish({phase:"success",flow:"login",name:G.name,email:_.email,plan:_.planType,hint:`目录与额度正在后台刷新 · 优先使用:codex-account ${G.id==="default"?"default":G.name}`})})();l2.set(G.id,K);let B=()=>{if(l2.get(G.id)===K)l2.delete(G.id)};K.then(B,(_)=>{j(`codex-login: terminal card write failed: ${_}`),B()})}catch(G){j(`codex-${Z}: ${G}`),await H.finish(N8(G,X))}}async function gO($,Z,J){let Q;try{if(!J?.trim())throw Error("缺少消息 ID,未使用重置卡;请在群内发送 codex-reset [备注]");if(!Z&&(!$.proc?.isAlive()||$.proc.provider!=="codex"||$.proc.codexAccountSelectionMode?.()===null||$.proc.turnRetry?.reason==="quota"&&$.proc.turnRetry.phase==="waiting"))throw Error("当前没有正在使用的 Codex 账号;请用 codex-reset 备注,或 codex-reset default 指定默认账号");Q=Z?v.find(Z):v.get(M$($.proc))}catch(G){j(`codex-reset: ${G}`),await JK($,G);return}let Y=await Y9.open($.chatId,{phase:"checking",name:Q.name,title:"正在使用重置卡",message:"正在提交重置请求…"}),V;try{let G=fO("sha256").update(JSON.stringify(["lodestar-codex-reset",$.chatId,J])).digest("hex");V=await rz(Q.id,G)}catch(G){j(`codex-reset: ${G}`),await Y.finish(N8(G,Q.name));return}let X=IO[V.outcome],H=[V.usage.state==="ok"?void 0:`额度刷新失败:${V.usage.state==="network"?V.usage.reason??"MISS":V.usage.state}`,V.cleanupError].filter(Boolean).join(`
158
- `);await Y.finish({...X,name:Q.name,resetUsage:V.usage,...H?{phase:"warning",details:H}:{},hint:"codex-accounts 查看各账号额度"})}var l2,IO;var t7=R(()=>{Y0();F0();tJ();X0();l7();W7();MQ();t3();hZ();ZK();Q9();I();z$();l2=new Map;IO={reset:{phase:"success",title:"额度已重置",message:"已使用 1 次重置卡。"},alreadyRedeemed:{phase:"success",title:"本次重置已完成",message:"本次请求此前已处理,没有重复使用重置卡。"},nothingToReset:{phase:"current",title:"无需重置",message:"当前没有符合条件的额度窗口,未使用重置卡。"},noCredit:{phase:"warning",title:"没有可用重置卡",message:"该账号没有可用的重置卡,额度未重置。"}}});import{readFileSync as mO}from"node:fs";function pO($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function cO($,Z){let J=[`[token_source.${$}]`],Q=(Y,V)=>{if(V!==void 0)J.push(`${Y} = "${pO(V)}"`)};if(Q("agent",Z.agent),Z.enabled!==void 0)J.push(`enabled = ${Z.enabled}`);if(Q("display",Z.display),Q("auth",Z.auth),Q("base_url",Z.base_url),Q("auth_token",Z.auth_token),Q("api_key",Z.api_key),Q("management_token",Z.management_token),Q("management_user_id",Z.management_user_id),Q("management_url",Z.management_url),Q("billing_source",Z.billing_source),Q("bin",Z.bin),Q("model",Z.model),Q("effort",Z.effort),Q("models",Z.models),Q("hidden_models",Z.hidden_models),Q("shown_models",Z.shown_models),Q("custom_models",Z.custom_models),Q("slots",Z.slots),Q("usage",Z.usage),Z.default!==void 0)J.push(`default = "${Z.default}"`);return J.join(`
156
+ `)),Z1("备注可用 default 指定设备默认账号;默认账号不可删除。")]});if($.hint)J.push(Z1($.hint));if($.details)J.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查看详情"}},elements:[T0(J1($.details))]});return{tag:"collapsible_panel",element_id:C.codexAccountPanel,expanded:!0,header:{title:{tag:"plain_text",content:O8($)},background_color:`${Z}-50`},border:{color:`${Z}-100`,corner_radius:"8px"},padding:$.phase==="accounts"?"8px":"12px",...$.phase==="accounts"?{vertical_spacing:"8px"}:{},elements:J}}function rW($,Z){let J=$.percent;if(J==null||!Number.isFinite(J)||J<0||J>100)return T0(`${Z} MISS`);let Q=Math.round(J/100*6),Y=J>=100?"red":J>=80?"orange":"green",V=$.resetsAt&&Number.isFinite($.resetsAt.getTime())?$1($.resetsAt):"MISS";return T0(`${Z} <font color='${Y}'>${"▰".repeat(Q)}${"▱".repeat(6-Q)}</font> ${Math.round(J)}% <font color='grey'>「${V}」</font>`)}function wO($){let Z=$.total,J=Math.max(1,Math.ceil(Z.entries.length/s7)),Q=$.page??1;if(!Number.isInteger(Q)||Q<1||Q>J)throw Error(`页码应为 1–${J}`);let Y=[],V=$.scheduling?.candidates.filter((H)=>H.state==="ready").sort(m3)??[],X=new Map(V.map((H,G)=>[H.account.id,G+1])),z=Z.entries.slice().sort((H,G)=>(X.get(H.account.id)??1/0)-(X.get(G.account.id)??1/0));for(let H of z.slice((Q-1)*s7,Q*s7)){let G=H.usage,W=[],K=$.scheduling?.candidates.find((q)=>q.account.id===H.account.id),B=X.get(H.account.id),_=H.duplicateOf?"重复":K?.state==="ready"?K.funding==="credits"?"积分":K.priority==="expiring"?"临期优先":`${K.score.toPrecision(3)}/h`:"MISS";if(Y.push({tag:"collapsible_panel",expanded:!0,header:{title:{tag:"plain_text",content:`#${B??"—"}·${H.account.name}「${_}」 · 重置 ${G.state==="ok"?G.resetCredits??"MISS":"MISS"}`},background_color:"grey-50"},border:{color:"grey-100",corner_radius:"8px"},padding:"8px",vertical_spacing:"2px",elements:W}),W.push(Z1(`邮箱:${H.email??"MISS"}`)),H.emailError)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"邮箱查询错误"}},elements:[T0(J1(H.emailError))]});if(H.duplicateOf){W.push(Z1(`与「${H.duplicateOf}」同一账号,合计只计一次`));continue}if(K&&K.state!=="ready"){if(W.push(Z1(K.state==="exhausted"?"⏳ 暂不可用":K.state==="excluded"?"Plus 无可用积分 · 不参与 Ultra":K.state==="waiting"?`⏳ 周余量 ${K.remaining?.toPrecision(3)} 份 · 未达 0.5 份`:"MISS · 无法排序")),K.reason&&G.state==="ok")W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"未参与原因"}},elements:[T0(J1(K.reason))]})}if(G.state!=="ok"){if(W.push(T0(G.state==="no_credentials"?"⚪ 未登录":"⚠️ 额度 MISS")),G.state==="network"&&G.reason)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查询错误"}},elements:[T0(J1(G.reason))]});continue}if(G.weekly)W.push(rW(G.weekly,"周"));if(G.fiveHour)W.push(rW(G.fiveHour,"5h"));let P=O1(G.credits);if(P)W.push(T0(P));let L=$.activationErrors?.[H.account.id];if(L)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"后台激活 MISS"}},elements:[T0(J1(L))]})}if(J>1)Y.push(Z1(`${Q}/${J} 页 · ${Q<J?`下一页 codex-accounts ${Q+1}`:"首页 codex-accounts"}`));return Y}var s7=4,eW,T0=($)=>({tag:"markdown",content:$}),Z1=($)=>({tag:"markdown",content:`<font color='grey'>${J1($)}</font>`,text_size:"notation"});var Q9=R(()=>{d0();J9();T4();eW={connecting:["\uD83D\uDD04","连接中","blue"],waiting:["\uD83D\uDD10","等待授权","blue"],checking:["\uD83D\uDD0E","校验中","blue"],success:["✅","登录成功","green"],selected:["\uD83C\uDFAF","下次启动生效","green"],current:["\uD83E\uDDED","当前账号","blue"],accounts:["\uD83D\uDDC2","账号与额度","blue"],cancelled:["⏹","已取消","grey"],expired:["⌛","等待超时","orange"],deleted:["\uD83D\uDDD1","已删除","grey"],error:["❌","未完成","red"],warning:["⚠️","需要处理","orange"]}});class Y9{cardId;deps;tail=Promise.resolve();terminal=null;constructor($,Z){this.cardId=$;this.deps=Z}static async open($,Z,J=vO){let Q,Y=await J.sendCard($,Q1(Z,!0),(X)=>{Q=X});if(!Y)throw Error(`Codex 账号卡片发送失败:${w(Q)}`);let V=await J.convertMessageToCard(Y);return J.recordCardCreated(V,1),new Y9(V,J)}update($){if(this.terminal)return Promise.reject(Error("Codex 账号卡片已结束"));let Z=A8($);return this.enqueue(()=>this.write($,Z,!1))}finish($){if(this.terminal)return this.terminal;let Z=A8($);return this.terminal=this.enqueue(()=>this.write($,Z,!0)),this.terminal}enqueue($){let Z=this.tail.then($);return this.tail=Z.then(()=>{},()=>{}),Z}async write($,Z,J){let Q,Y,V=await this.deps.replaceElementChecked(this.cardId,C.codexAccountPanel,Z,{notifyCardFailure:!1,onFailure:(z)=>{Q=z}}),X=await this.deps.patchSettingsChecked(this.cardId,{config:{streaming_mode:!J,summary:{content:O8($)}}},(z)=>{Y=z});if(!V||!X)throw Error(`Codex 账号卡片更新失败:内容 ${V?"OK":w(Q)},状态 ${X?"OK":w(Y)}`);if(J)await this.deps.dispose(this.cardId)}}var vO;var ZK=R(()=>{Y0();U1();d0();Q9();vO={sendCard:o,convertMessageToCard:e$,recordCardCreated:h$,replaceElementChecked:F0,patchSettingsChecked:m0,dispose:N$}});var TQ={};H1(TQ,{settleCodexAccountCards:()=>RQ,runCodexNamedHi:()=>fO,runCodexAccountCommand:()=>hO});import{createHash as yO}from"node:crypto";function N8($,Z){let J=$ instanceof Error?$.message:String($),Q=!/失败|未完全退出/.test(J)&&/登录已取消|服务退出/.test(J),Y=/过期|等待超过|expired/i.test(J),V=J.split(/[\n;]/)[0];return{phase:Q?"cancelled":Y?"expired":"error",name:Z,message:V.length>80?V.slice(0,77)+"…":V,...J!==V||V.length>80?{details:J}:{}}}async function JK($,Z){let J;if(!await o($.chatId,Q1(N8(Z)),(Q)=>{J=Q}))throw Error(`Codex 错误卡片发送失败
157
+ ${w(J)}`)}async function fO($,Z){let J=await Y9.open($.chatId,{phase:"checking",name:Z,message:"正在启动指定账号…"});try{let Q=v.find(Z),Y="";if(!await $.startWithCodexAccount(Q.id,{announce:!1,onStatus:(X)=>{Y=X}}))throw Error(Y||"指定账号启动失败");await J.finish({phase:"current",name:Q.name,current:Q.name,title:"已指定账号",hint:"本次手动指定 · 不参与自动排序"}),await $.showConsole()}catch(Q){await J.finish(N8(Q,Z))}}async function RQ(){let Z=(await Promise.allSettled([...l2.values()])).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 账号卡片未全部写入")}async function hO($,Z,J,Q,Y){if(Z==="reset"){await gO($,J,Y);return}let V={chatId:$.chatId,userOpenId:Q};if(Z==="login-cancel"){try{let G=v2.pending(V);if(!J&&G.length!==1)throw Error(G.length?"有多个登录任务;请指定 codex-login-cancel 备注":"本群没有你的登录任务");let W=J?v.find(J).id:G[0];await v2.cancel(W,V),await l2.get(W)}catch(G){await JK($,G)}return}let X=Z==="login"?J||"默认":Z==="account"||Z==="account-delete"?J||void 0:void 0,z=Z==="login"&&!!J.trim()&&!["default","默认"].includes(J.normalize("NFC").trim().toLowerCase()),H=await Y9.open($.chatId,{phase:Z==="login"?"connecting":"checking",name:X,...Z==="login"?{flow:"login"}:{},message:Z==="accounts"?"正在读取各账号邮箱与额度…":z?"正在检查默认账号登录状态…":Z==="login"?"正在获取设备码…":"正在核对账号…"});try{if(Z==="account-delete"){if(!J)throw Error("请指定要删除的账号;使用 codex-account-delete 备注");let _=v.find(J);if(l2.has(_.id))throw Error("账号登录或结果更新尚未结束;请先完成或取消登录后重试");let{clearedSelections:P}=v.remove(_.id);JG(M0("codex-sub"),_.id),d$(_.id),await H.finish({phase:"deleted",name:_.name,message:"已删除本地账号记录与独立凭据,共享会话历史保留。",hint:P?`已清除 ${P} 个群的指定,下次启动自动选号 · codex-accounts 查看`:"codex-accounts 查看剩余账号"});return}if(Z==="accounts"){if(J&&!/^[1-9]\d*$/.test(J))throw Error("页码无效;使用 codex-accounts [页码]");let _=J?Number(J):1,P=$.codexAccountId(),L=j0("codex-sub",P),q=()=>$.currentProvider()==="codex"?$.currentModelLabel():L?.defaultModel,F=q(),M;if(!F)try{if(!L)throw Error("Codex 订阅来源尚未初始化");if(F=q(),!F)throw Error(L.modelCatalogState?.error??"Codex 模型目录未提供可用的默认模型")}catch(N){M=`${v.get(P).name}:${N instanceof Error?N.message:String(N)}`}let U=$.currentProvider()==="codex"?$.currentEffortLabel()??void 0:void 0,A=F?await O2.choose({model:F,effort:U}):null,O=A?DQ(A.candidates.flatMap((N)=>{let T=(N.usage?.state==="network"||N.usage?.state==="rate_limited"?M2(N.account.id):null)??N.usage;return T?[{account:N.account,usage:T,fingerprint:N.identity.startsWith("record:")?null:N.identity}]:[]})):await d7();if(M)j(`codex-accounts: scheduling MISS: ${M}`);await H.finish({phase:"accounts",total:await gW(O),currentId:P,activationErrors:Object.fromEntries(O.entries.flatMap((N)=>{let S=l9.error(N.account.id);return S?[[N.account.id,S]]:[]})),...v.preferred($.sessionName)?{selectedId:v.selected($.sessionName)}:{},page:_,...A?{scheduling:{candidates:A.candidates,ultra:U==="ultra"}}:{message:"⚠️ 调度顺序 MISS:尚未确定 Codex 模型",details:M,hint:"可用 hi 备注指定已登录账号,或通过 md 检查模型目录"}});return}if(Z==="auto"){if(J)throw Error("codex-auto 不需要备注");v.selectAuto($.sessionName),await H.finish({phase:"selected",name:"自动选择",current:v.get($.codexAccountId()).name,selected:"自动 · 临期 / 评分",hint:"Ultra:Pro 且周余量 ≥ 0.5 份"});return}if(Z==="account"){if(!J){await H.finish({phase:"current",current:v.get($.codexAccountId()).name,selected:v.preferred($.sessionName)===null?"自动 · 临期 / 评分":v.get(v.selected($.sessionName)).name,hint:"周剩余份额 ÷(重置小时 − 5)· codex-auto"});return}let _=v.find(J),P=$.currentProvider()==="codex"?$.currentModelLabel():null,L=$.currentProvider()==="codex"?$.currentEffortLabel():null,q=v.get($.codexAccountId()).name;if($.currentProvider()==="codex")l1($.sessionName,"codex",P,L,"codex-sub");if(v.select($.sessionName,_.id),$.currentProvider()==="codex")$.selectedModel=P,$.selectedEffort=L,$.selectedTokenSourceId="codex-sub";await H.finish({phase:"selected",name:_.name,current:q,selected:_.name,hint:"restart 直接使用 · 不检查调度门槛"});return}if(Z!=="login")throw Error("未知 Codex 账号命令");if(!Q)throw Error("无法确认登录发起者");if(z)await nG(),await H.update({phase:"connecting",flow:"login",name:X,message:"正在获取设备码…"});let G=v.ensure(J);if(y3(G.id))throw Error("账号正在使用中;重新登录前先 kill 使用该账号的会话,或用新备注添加账号");if(l2.has(G.id))throw Error("登录结果正在更新,请稍等");let W=await v2.start(G.id,V);try{await H.update({phase:"waiting",flow:"login",name:G.name,verification:{url:W.verificationUrl,code:W.userCode},hint:`取消:codex-login-cancel${J?` ${G.name}`:""}`})}catch(_){throw await v2.cancel(G.id,V),_}let K=(async()=>{let _;try{_=await W.done}catch(P){await H.finish(N8(P,G.name));return}M8(),j0("codex-sub",G.id),await H.finish({phase:"success",flow:"login",name:G.name,email:_.email,plan:_.planType,hint:`目录与额度正在后台刷新 · 优先使用:codex-account ${G.id==="default"?"default":G.name}`})})();l2.set(G.id,K);let B=()=>{if(l2.get(G.id)===K)l2.delete(G.id)};K.then(B,(_)=>{j(`codex-login: terminal card write failed: ${_}`),B()})}catch(G){j(`codex-${Z}: ${G}`),await H.finish(N8(G,X))}}async function gO($,Z,J){let Q;try{if(!J?.trim())throw Error("缺少消息 ID,未使用重置卡;请在群内发送 codex-reset [备注]");if(!Z&&(!$.proc?.isAlive()||$.proc.provider!=="codex"||$.proc.codexAccountSelectionMode?.()===null||$.proc.turnRetry?.reason==="quota"&&$.proc.turnRetry.phase==="waiting"))throw Error("当前没有正在使用的 Codex 账号;请用 codex-reset 备注,或 codex-reset default 指定默认账号");Q=Z?v.find(Z):v.get(M$($.proc))}catch(G){j(`codex-reset: ${G}`),await JK($,G);return}let Y=await Y9.open($.chatId,{phase:"checking",name:Q.name,title:"正在使用重置卡",message:"正在提交重置请求…"}),V;try{let G=yO("sha256").update(JSON.stringify(["lodestar-codex-reset",$.chatId,J])).digest("hex");V=await rz(Q.id,G)}catch(G){j(`codex-reset: ${G}`),await Y.finish(N8(G,Q.name));return}let X=IO[V.outcome],H=[V.usage.state==="ok"?void 0:`额度刷新失败:${V.usage.state==="network"?V.usage.reason??"MISS":V.usage.state}`,V.cleanupError].filter(Boolean).join(`
158
+ `);await Y.finish({...X,name:Q.name,resetUsage:V.usage,...H?{phase:"warning",details:H}:{},hint:"codex-accounts 查看各账号额度"})}var l2,IO;var t7=R(()=>{Y0();D0();tJ();X0();l7();W7();MQ();t3();hZ();ZK();Q9();I();z$();l2=new Map;IO={reset:{phase:"success",title:"额度已重置",message:"已使用 1 次重置卡。"},alreadyRedeemed:{phase:"success",title:"本次重置已完成",message:"本次请求此前已处理,没有重复使用重置卡。"},nothingToReset:{phase:"current",title:"无需重置",message:"当前没有符合条件的额度窗口,未使用重置卡。"},noCredit:{phase:"warning",title:"没有可用重置卡",message:"该账号没有可用的重置卡,额度未重置。"}}});import{readFileSync as mO}from"node:fs";function pO($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function cO($,Z){let J=[`[token_source.${$}]`],Q=(Y,V)=>{if(V!==void 0)J.push(`${Y} = "${pO(V)}"`)};if(Q("agent",Z.agent),Z.enabled!==void 0)J.push(`enabled = ${Z.enabled}`);if(Q("display",Z.display),Q("auth",Z.auth),Q("base_url",Z.base_url),Q("auth_token",Z.auth_token),Q("api_key",Z.api_key),Q("management_token",Z.management_token),Q("management_user_id",Z.management_user_id),Q("management_url",Z.management_url),Q("billing_source",Z.billing_source),Q("bin",Z.bin),Q("model",Z.model),Q("effort",Z.effort),Q("models",Z.models),Q("hidden_models",Z.hidden_models),Q("shown_models",Z.shown_models),Q("custom_models",Z.custom_models),Q("slots",Z.slots),Q("usage",Z.usage),Z.default!==void 0)J.push(`default = "${Z.default}"`);return J.join(`
159
159
  `)}function uO($,Z){lO({[$]:Z})}function lO($){if(!Object.keys($).length)return;let Z=mO(c0,"utf8"),J=k9().token_sources,Q={};for(let[H,G]of Object.entries($)){let W=QQ(J,H,G);J={...J,...W},Object.assign(Q,W)}L8(J);let Y=new Set(Object.keys(Q).map((H)=>`[token_source.${H}]`)),V=Z.split(`
160
160
  `),X=!1,z=[];for(let H of V){let G=H.match(/^\s*(\[[^\]]+\])\s*(?:#.*)?$/)?.[1];if(G)X=Y.has(G);if(!X)z.push(H)}while(z.length&&z[z.length-1]==="")z.pop();Q$(c0,z.join(`
161
161
  `)+`
@@ -163,87 +163,87 @@ ${w(J)}`)}async function yO($,Z){let J=await Y9.open($.chatId,{phase:"checking",
163
163
  `+Object.entries(Q).map(([H,G])=>cO(H,G)).join(`
164
164
 
165
165
  `)+`
166
- `)}function R8($){let Z=QK.then($);return QK=Z.then(()=>{},()=>{}),Z}async function T8($,Z,J){uO($,Z),J?.(),qz(),M8()}function YK($,Z){return R8(()=>T8($,Z))}async function VK($,Z,J=$.setup){let Q=!1;try{if(!$.configSectionId||!J)throw Error("此来源不支持配置命令");let Y=$.configSectionId,V=()=>{let z=k9().token_sources;return L8({...z,...QQ(z,Y,Z)})[Y]},X=V();await J.validate(X),await R8(async()=>{if(JSON.stringify(V())!==JSON.stringify(X))throw Error("校验期间账号配置已变化,本次未保存,请重试");await T8(Y,Z,()=>{Q=!0})})}catch(Y){throw new r7(Y,Q)}}function XK($,Z,J,Q="default"){return R8(async()=>{let Y=j0($,Q);if(!Y?.enabled||!Y.modelSelection)throw Error("此账号不支持维护可选模型列表");let V=Y.modelSelection.modelIds.filter((q)=>Y.models.find((D)=>D.model===q)?.origin!=="custom");if(J==="add"){if(Y.modelCatalogState?.status!=="ready")throw Error(Y.modelCatalogState?.error??"模型目录未就绪");let q=Y.modelSelection.availableModels.find((D)=>D.model===Z);if(q?.origin==="custom")throw Error("补录模型请使用删除操作");if(!q||Y.modelSelection.mode!=="catalog"&&(q.unavailableReason||!q.efforts.length))throw Error("模型不在允许添加的账号目录中");if(V.includes(Z))throw Error("模型已在可选列表中")}else if(!V.includes(Z))throw Error("模型已不在可选列表中");let X=J==="add"?[...V,Z]:V.filter((q)=>q!==Z),z=g.token_sources[$],H=Y.modelSelection.mode==="catalog",G=s(z?.hidden_models),W=Y.modelSelection.selectDefaults,K=Y.modelSelection.visibilityKey??((q)=>q),B=s(z?.shown_models),_=W?.(Y.modelSelection.availableModels).includes(Z),P=W?{hidden_models:(J==="remove"?[...new Set([...G,..._?[K(Z)]:[],Z])]:G.filter((q)=>q!==Z&&(!_||q!==K(Z)))).join(","),shown_models:(J==="add"&&!_?[...new Set([...B,Z])]:B.filter((q)=>q!==Z)).join(",")}:H?{hidden_models:(J==="remove"?[...new Set([...G,Z])]:G.filter((q)=>q!==Z)).join(",")}:{models:X.join(",")};await T8($,P);let L=j0($,Q);if(L?.modelCatalogState?.status!=="ready")throw Error(`配置已保存,但目录刷新失败:${L?.modelCatalogState?.error??"MISS"}`)})}function zK($,Z,J="default"){return R8(async()=>{let Q=Z.trim();if(!Q||Q.length>256||/[\s,`<>\\\u0000-\u001f]/.test(Q))throw Error("模型 ID 无效,请只填写一个完整模型名");let Y=j0($,J);if(!Y?.enabled)throw Error("账号不可用");if(Y.validateCustomModelId?.(Q),(Y.modelSelection?.availableModels??Y.models).some((H)=>H.model.toLowerCase()===Q.toLowerCase()))throw Error("模型已在目录或补录记录中;隐藏项请使用“显示”");if(Y.modelCatalogState?.status!=="ready")throw Error(Y.modelCatalogState?.error??"模型目录未就绪");let X=g.token_sources[$];await T8($,{custom_models:[...s(X?.custom_models),Q].join(",")});let z=j0($,J);if(z?.modelCatalogState?.status!=="ready")throw Error(`补录已保存,但目录刷新失败:${z?.modelCatalogState?.error??"MISS"}`)})}function HK($,Z,J="default"){return R8(async()=>{let Q=j0($,J),Y=Q?.modelSelection?.availableModels.find((G)=>G.model===Z);if(!Q?.enabled||Y?.origin!=="custom")throw Error("此模型不是补录项,请使用隐藏操作");let V=g.token_sources[$]??{},X=(G)=>G?.trim().replace(/\[1m\]$/,"")===Z.replace(/\[1m\]$/,""),z={custom_models:s(V.custom_models).filter((G)=>!X(G)).join(","),hidden_models:s(V.hidden_models).filter((G)=>!X(G)).join(","),...V.shown_models!==void 0?{shown_models:s(V.shown_models).filter((G)=>!X(G)).join(",")}:{},...V.models!==void 0?{models:s(V.models).filter((G)=>!X(G)).join(",")}:{},...X(V.model)?{model:"",effort:""}:{},...V.slots?{slots:V.slots.split(",").filter((G)=>!X(G.slice(G.indexOf("=")+1))).join(",")}:{}};await T8($,z);let H=j0($,J);if(H?.modelCatalogState?.status!=="ready")throw Error(`补录已删除,但目录刷新失败:${H?.modelCatalogState?.error??"MISS"}`)})}var QK,r7;var EQ=R(()=>{H0();k0();l7();X0();b0();L1();q8();QK=Promise.resolve();r7=class r7 extends Error{saved;constructor($,Z){super($ instanceof Error?$.message:String($),{cause:$});this.saved=Z}}});var e7={};H1(e7,{runTokenSourceSetup:()=>nO,runClaudeSubscriptionCommand:()=>dO,onTokenSourceEnable:()=>iO});async function dO($,Z){if(Z&&Z!=="on"&&Z!=="off"){await k($.chatId,`用法:${"claude-sub 查看状态 · claude-sub on 启用 · claude-sub off 禁用"}`);return}if(Z)try{await YK("claude-sub",{enabled:Z==="on"})}catch(z){let H=z instanceof Error?z.message:String(z);j(`claude-sub ${Z} failed: ${H}`),await k($.chatId,`❌ Claude Code 订阅开关更新失败:${H}`);return}let Q=M0("claude-sub"),Y=g.token_sources["claude-sub"]?.enabled!==!1,V=Q?.modelCatalogState,X=[`Claude Code 订阅:${Y?"已启用":"已禁用"}(Lodestar 全局)`];if(Y&&(!Q?.enabled||V?.status!=="ready"))X.push(`可用性 MISS:${V?.error??(V?.status==="loading"||V?.status==="idle"?"模型目录缓存尚未就绪,后台刷新中":"订阅来源不可用")}`);if(X.push("所有群共用;保留本机登录态。"),!Y)X.push("禁止新任务,已在执行的任务继续完成。");X.push("claude-sub 查看状态 · claude-sub on 启用 · claude-sub off 禁用"),await k($.chatId,X.join(`
167
- `))}async function iO($,Z){let J=M0(Z);if(!J){await k($.chatId,`❌ 未知 token source: ${Z}`);return}if(J.enabled&&J.modelCatalogState?.status!=="failed"){await k($.chatId,`${J.display} 已启用,发 \`model\` 选择。`);return}let Q=U2().find((Y)=>Y.setup?.commandSuffix===Z||Y.configSectionId===Z);if(Q?.setup){let Y=J.modelCatalogState?.status==="failed"?`${J.display} 当前不可用:${y0(J.modelCatalogState.error??"MISS")}
166
+ `)}function R8($){let Z=QK.then($);return QK=Z.then(()=>{},()=>{}),Z}async function T8($,Z,J){uO($,Z),J?.(),qz(),M8()}function YK($,Z){return R8(()=>T8($,Z))}async function VK($,Z,J=$.setup){let Q=!1;try{if(!$.configSectionId||!J)throw Error("此来源不支持配置命令");let Y=$.configSectionId,V=()=>{let z=k9().token_sources;return L8({...z,...QQ(z,Y,Z)})[Y]},X=V();await J.validate(X),await R8(async()=>{if(JSON.stringify(V())!==JSON.stringify(X))throw Error("校验期间账号配置已变化,本次未保存,请重试");await T8(Y,Z,()=>{Q=!0})})}catch(Y){throw new r7(Y,Q)}}function XK($,Z,J,Q="default"){return R8(async()=>{let Y=j0($,Q);if(!Y?.enabled||!Y.modelSelection)throw Error("此账号不支持维护可选模型列表");let V=Y.modelSelection.modelIds.filter((q)=>Y.models.find((F)=>F.model===q)?.origin!=="custom");if(J==="add"){if(Y.modelCatalogState?.status!=="ready")throw Error(Y.modelCatalogState?.error??"模型目录未就绪");let q=Y.modelSelection.availableModels.find((F)=>F.model===Z);if(q?.origin==="custom")throw Error("补录模型请使用删除操作");if(!q||Y.modelSelection.mode!=="catalog"&&(q.unavailableReason||!q.efforts.length))throw Error("模型不在允许添加的账号目录中");if(V.includes(Z))throw Error("模型已在可选列表中")}else if(!V.includes(Z))throw Error("模型已不在可选列表中");let X=J==="add"?[...V,Z]:V.filter((q)=>q!==Z),z=g.token_sources[$],H=Y.modelSelection.mode==="catalog",G=s(z?.hidden_models),W=Y.modelSelection.selectDefaults,K=Y.modelSelection.visibilityKey??((q)=>q),B=s(z?.shown_models),_=W?.(Y.modelSelection.availableModels).includes(Z),P=W?{hidden_models:(J==="remove"?[...new Set([...G,..._?[K(Z)]:[],Z])]:G.filter((q)=>q!==Z&&(!_||q!==K(Z)))).join(","),shown_models:(J==="add"&&!_?[...new Set([...B,Z])]:B.filter((q)=>q!==Z)).join(",")}:H?{hidden_models:(J==="remove"?[...new Set([...G,Z])]:G.filter((q)=>q!==Z)).join(",")}:{models:X.join(",")};await T8($,P);let L=j0($,Q);if(L?.modelCatalogState?.status!=="ready")throw Error(`配置已保存,但目录刷新失败:${L?.modelCatalogState?.error??"MISS"}`)})}function zK($,Z,J="default"){return R8(async()=>{let Q=Z.trim();if(!Q||Q.length>256||/[\s,`<>\\\u0000-\u001f]/.test(Q))throw Error("模型 ID 无效,请只填写一个完整模型名");let Y=j0($,J);if(!Y?.enabled)throw Error("账号不可用");if(Y.validateCustomModelId?.(Q),(Y.modelSelection?.availableModels??Y.models).some((H)=>H.model.toLowerCase()===Q.toLowerCase()))throw Error("模型已在目录或补录记录中;隐藏项请使用“显示”");if(Y.modelCatalogState?.status!=="ready")throw Error(Y.modelCatalogState?.error??"模型目录未就绪");let X=g.token_sources[$];await T8($,{custom_models:[...s(X?.custom_models),Q].join(",")});let z=j0($,J);if(z?.modelCatalogState?.status!=="ready")throw Error(`补录已保存,但目录刷新失败:${z?.modelCatalogState?.error??"MISS"}`)})}function HK($,Z,J="default"){return R8(async()=>{let Q=j0($,J),Y=Q?.modelSelection?.availableModels.find((G)=>G.model===Z);if(!Q?.enabled||Y?.origin!=="custom")throw Error("此模型不是补录项,请使用隐藏操作");let V=g.token_sources[$]??{},X=(G)=>G?.trim().replace(/\[1m\]$/,"")===Z.replace(/\[1m\]$/,""),z={custom_models:s(V.custom_models).filter((G)=>!X(G)).join(","),hidden_models:s(V.hidden_models).filter((G)=>!X(G)).join(","),...V.shown_models!==void 0?{shown_models:s(V.shown_models).filter((G)=>!X(G)).join(",")}:{},...V.models!==void 0?{models:s(V.models).filter((G)=>!X(G)).join(",")}:{},...X(V.model)?{model:"",effort:""}:{},...V.slots?{slots:V.slots.split(",").filter((G)=>!X(G.slice(G.indexOf("=")+1))).join(",")}:{}};await T8($,z);let H=j0($,J);if(H?.modelCatalogState?.status!=="ready")throw Error(`补录已删除,但目录刷新失败:${H?.modelCatalogState?.error??"MISS"}`)})}var QK,r7;var EQ=R(()=>{H0();k0();l7();X0();b0();L1();q8();QK=Promise.resolve();r7=class r7 extends Error{saved;constructor($,Z){super($ instanceof Error?$.message:String($),{cause:$});this.saved=Z}}});var e7={};H1(e7,{runTokenSourceSetup:()=>nO,runClaudeSubscriptionCommand:()=>dO,onTokenSourceEnable:()=>iO});async function dO($,Z){if(Z&&Z!=="on"&&Z!=="off"){await k($.chatId,`用法:${"claude-sub 查看状态 · claude-sub on 启用 · claude-sub off 禁用"}`);return}if(Z)try{await YK("claude-sub",{enabled:Z==="on"})}catch(z){let H=z instanceof Error?z.message:String(z);j(`claude-sub ${Z} failed: ${H}`),await k($.chatId,`❌ Claude Code 订阅开关更新失败:${H}`);return}let Q=M0("claude-sub"),Y=g.token_sources["claude-sub"]?.enabled!==!1,V=Q?.modelCatalogState,X=[`Claude Code 订阅:${Y?"已启用":"已禁用"}(Lodestar 全局)`];if(Y&&(!Q?.enabled||V?.status!=="ready"))X.push(`可用性 MISS:${V?.error??(V?.status==="loading"||V?.status==="idle"?"模型目录缓存尚未就绪,后台刷新中":"订阅来源不可用")}`);if(X.push("所有群共用;保留本机登录态。"),!Y)X.push("禁止新任务,已在执行的任务继续完成。");X.push("claude-sub 查看状态 · claude-sub on 启用 · claude-sub off 禁用"),await k($.chatId,X.join(`
167
+ `))}async function iO($,Z){let J=M0(Z);if(!J){await k($.chatId,`❌ 未知 token source: ${Z}`);return}if(J.enabled&&J.modelCatalogState?.status!=="failed"){await k($.chatId,`${J.display} 已启用,发 \`model\` 选择。`);return}let Q=U2().find((Y)=>Y.setup?.commandSuffix===Z||Y.configSectionId===Z);if(Q?.setup){let Y=J.modelCatalogState?.status==="failed"?`${J.display} 当前不可用:${f0(J.modelCatalogState.error??"MISS")}
168
168
  `:"";await k($.chatId,Y+Q.setup.hint(J.display))}else if(J.kind==="codex-subscription"){if(!await o($.chatId,Q1({phase:"current",title:"添加账号",message:"通过设备码完成浏览器授权",hint:"默认:codex-login · 额外:codex-login 备注"})))throw Error("Codex 登录引导卡片发送失败")}else if(J.kind==="claude-subscription")await k($.chatId,g.token_sources["claude-sub"]?.enabled===!1?"Claude Code 订阅已在 Lodestar 中禁用。发送 `claude-sub on` 启用,所有群共用,本机登录态保持不变。":J.modelCatalogState?.error??"请在运行 Lodestar 的本机执行 `claude auth login` 登录 Claude 订阅,完成后等待后台刷新,发送 `md` 查看状态。");else if(J.kind==="claude-native")await k($.chatId,`${J.display} 直接使用本机 Claude Code 配置,无需单独启用。`)}async function nO($,Z,J){let Q=U2().find((H)=>H.setup?.commandSuffix===Z||H.usageSetup?.commandSuffix===Z),Y=Q?.usageSetup?.commandSuffix===Z,V=Y?Q?.usageSetup:Q?.setup;if(!Q||!V||!Q.configSectionId){await k($.chatId,`❌ 未知或不可配置的 source: ${Z}`);return}let X=V.parseArgs(J);if("error"in X){await k($.chatId,X.error);return}await k($.chatId,"正在后台校验账号配置,完成后会返回结果;其他操作可继续使用。");let z=!1;try{await VK(Q,X.config,V),z=!0;let H=M0(Q.configSectionId),G=ZW(Q.configSectionId).map((B)=>M0(B)),W=G.find((B)=>(!Y||B?.enabled)&&B?.modelCatalogState?.status!=="ready");if(Y){let B=W?`
169
- 模型目录仍为 MISS:${y0(W.modelCatalogState?.error??"尚未就绪",[X.config.management_token])}`:"";await k($.chatId,`✅ ${H?.display??Z} 真实余额校验通过,配置已保存。发送 hi 查看;回复页脚使用同一账户余额。${B}`);return}if(W?.modelCatalogState?.status==="failed"||G.some((B)=>!B)){let B=y0(W?.modelCatalogState?.error??"模型目录尚未就绪",[X.config.api_key,X.config.auth_token]);await k($.chatId,`❌ ${H?.display??Z} 凭据校验通过、配置已保存,但暂不可用:${B}
170
- 处理后等待后台刷新,发送 md 查看状态。`);return}let K=[...new Set(G.filter((B)=>!!B).map((B)=>t0(B.agent)))];await k($.chatId,`✅ ${H.display} 校验通过,配置已保存。${K.length>1?`${K.join(" 和 ")} 共用该账号。`:""}目录与额度在后台刷新;发送 md 查看模型。`)}catch(H){let G=z||H instanceof r7&&H.saved?"配置已保存,但后续处理失败":"配置失败,未保存,原配置保持不变",W=y0(H,[X.config.api_key,X.config.auth_token,X.config.management_token]);await k($.chatId,`❌ ${G}:${W}`)}}var $6=R(()=>{Y0();X0();EQ();Q9();k0();I();q8();P0()});function GK($,Z){let J=Z.catch(async(Q)=>{let Y=`账号操作或结果呈现失败:${E(Q)}`;throw j(Y),await h($.chatId,`❌ ${Y}`),Q});SQ.add(J),J.finally(()=>SQ.delete(J)).catch((Q)=>j(`账号操作结果发送失败:${E(Q)}`))}function WK(){return[...SQ]}async function KK($,Z,J="",Q){let Y=Z.trim().match(/^hi[ \t]+([^\r\n]+)$/i);if(Y){let{runCodexNamedHi:K}=await Promise.resolve().then(() => (t7(),TQ));return await K($,Y[1].trim()),!0}let V=Z.trim().match(/^codex-(login-cancel|login|accounts|account-delete|account|auto|reset)(?:[ \t]+([^\r\n]+))?$/i);if(V){let{runCodexAccountCommand:K}=await Promise.resolve().then(() => (t7(),TQ)),B=V[1].toLowerCase(),_=K($,B,(V[2]??"").trim(),J,Q);if(B==="login"||B==="reset")GK($,_);else await _;return!0}let X=Z.trim().match(/^claude-sub(?:[ \t]+([^\r\n]+))?$/i);if(X){let{runClaudeSubscriptionCommand:K}=await Promise.resolve().then(() => ($6(),e7));return await K($,(X[1]??"").trim().toLowerCase()),!0}let z=Z.trim().match(/^(?:wt|worktree)(?:\s+(.+))?$/i);if(z)return await $.runWorktreeCommand((z[1]??"").trim(),J),!0;if(Z.trim().match(/^btw$/i))return await $.runBtwCommand(J),!0;if(Z.trim().match(/^bye$/i))return await $.runByeCommand(),!0;if(Z.trim().match(/^(?:fk|fork)$/i))return await $.showForkList(J),!0;if(Z.trim().match(/^(?:bk|back)$/i))return await $.showBackList(J),!0;if(Z.trim().toLowerCase()==="task")return await $.showTasklistPanel(),!0;let H=Z.trim().match(/^files(?:[ \t]+([^\r\n]+))?$/i);if(H)return await $.runFileDeliveryCommand((H[1]??"").trim(),J),!0;if(Z.trim().match(/^(?:agents|agent)$/i))return await $.showAgentIdentityPanel(J),!0;let G=Z.trim().match(/^([\w-]+)-setup(?:\s+([\s\S]+))?$/i);if(G){let{runTokenSourceSetup:K}=await Promise.resolve().then(() => ($6(),e7));return GK($,K($,G[1].trim().toLowerCase(),(G[2]??"").trim())),!0}let W=aO.get(Z.trim().toLowerCase());if(!W)return!1;switch(W){case"model":return await $.showModelPanel(),!0;case"compact":return await $.runCompactCommand(),!0;case"hi":{let K=!$.isRunning(),B=$.backendLabel(),_=K?await $.openStatusCard("hi",$.withModel(`\uD83D\uDE80 启动 ${B}`)):null,P=$.withModel(`\uD83D\uDE80 启动 ${B}`);if(!(K?await $.start({announce:!_,onStatus:(q)=>{P=q,$.setStatusCard(_,q)}}):!0))return await $.closeStatusCard(_,P.startsWith("❌")?P:"❌ 启动失败"),!0;if($.proc?.turnRetry?.reason==="quota"){if(_)await $.closeStatusCard(_,"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消");else{let{codexAccountCard:D}=await Promise.resolve().then(() => (Q9(),$K)),M;if(!await o($.chatId,D({phase:"checking",title:"等待额度",message:"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消"}),(U)=>{M=U}))throw Error(`额度等待卡片发送失败
171
- ${w(M)}`)}return!0}if(_)return await $.replaceStatusCardWithConsole(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`))),!0;if(K)await $.closeStatusCard(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`)))}return await $.showConsole(),!0;case"stop":{let K=$.cancelFileDeliveries("用户停止了任务");if(await $.cancelAgentRuns("stop command"),$.proc?.turnRetry?.reason==="quota"){let _=await $.openStatusCard("stop","\uD83D\uDED1 停止额度等待");try{await $.stop("已取消额度恢复",{announce:!_,onStatus:(P)=>$.setStatusCard(_,P)}),await $.closeStatusCard(_,"\uD83D\uDED1 已取消额度恢复")}catch(P){throw await $.closeStatusCard(_,`❌ ${E(P)}`),P}return!0}if($.clearStaleIdleQueueState("stop"),$.clearMultiMsgBuffer("stop command"),!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0){if(K)return await $.closeTurnCard("\uD83D\uDED1 已取消未完成的文件上传"),await k($.chatId,"\uD83D\uDED1 已取消未完成的文件上传,已上传文件保留"),!0;let _=await $.openStatusCard("stop","⚪ 当前没有正在执行的 turn","grey");if(_)await $.closeStatusCard(_,"⚪ 无正在执行的 turn");else await k($.chatId,"⚪ 当前没有正在执行的 turn");return!0}j(`session "${$.sessionName}": stop command — interrupt + drop count=${$.pendingUserMessageCount} midBuffer=${$.pendingMidTurnMsgs.length}`);let B=new Set;for(let[_,P]of[...$.pendingReactionIds.entries(),...$.currentBatchReactionIds.entries()]){if(P)g0(_,P);K$(_,"CrossMark"),B.add(_)}for(let _ of $.pendingMidTurnMsgs)if(_.msgId&&!B.has(_.msgId))K$(_.msgId,"CrossMark");return $.pendingUserMessageCount=0,$.pendingMidTurnMsgs=[],$.pendingTurnInputs=[],$.lastUserOpenId="",$.pendingReactionIds=new Map,$.currentBatchReactionIds=new Map,$.userInterrupted=!0,$.interrupt(),await $.closeTurnCard("\uD83D\uDED1 打断"),!0}case"kill":{let K=$.isRunning(),B=$.backendLabel($.proc?.provider??$.currentProvider()),_=K?`\uD83D\uDED1 停止 ${B}`:"⚪ session 当前未运行",P=await $.openStatusCard("kill",_,K?"red":"grey"),L=null,q=K?`✅ ${B} 已终止`:`⚪ ${B} 未运行`;try{await $.stop("已终止",{announce:!P,onStatus:(D)=>{$.setStatusCard(P,D)}})}catch(D){L=D,q=$.isRunning()?`❌ ${B} 未确认终止: ${E(D)};会话已阻断,请重试 kill/restart 或等待旧进程退出`:`❌ ${B} 停止收尾失败: ${E(D)}`}finally{try{await $.closeStatusCard(P,q)}catch(D){j(`session "${$.sessionName}": kill status card close failed: ${E(D)}`),await h($.chatId,`${q}
172
- ⚠️ kill 状态卡片终态写入失败: ${E(D)}`)}}if(L&&!P)await h($.chatId,q)}return!0;case"restart":if(!$.isRunning())return await $.showResumeList(J),!0;{let K=$.lastSessionId?h0($.lastSessionId):"",B=$.backendLabel($.proc?.provider??$.currentProvider()),_=$.isRunning()?$.withModel(`\uD83D\uDD01 重启 ${B}`):K?$.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`):$.withModel(`\uD83D\uDD01 启动 ${B}`),P=await $.openStatusCard("restart",_),L=_,q=await $.restart(!0,{announce:!P,onStatus:(M)=>{L=M,$.setStatusCard(P,M)}}),D=q?L.startsWith("✅")?L:$.withWorktreeInstructionNotice(K?"✅ 已恢复上一会话":`✅ ${$.backendLabel()} 已就绪`):L.startsWith("❌")?L:"❌ 重启失败";await $.closeStatusCard(P,q?$.withModel(D):D)}return!0;case"clear":if(!$.isRunning()){$.status="stopped",$.opts.onLifecycleChange?.();let K=await $.openStatusCard("clear","⚪ session 当前未运行","grey");if(K)await $.closeStatusCard(K,`⚪ ${$.backendLabel()} 未运行,clear 无效`);else await k($.chatId,`⚪ session "${$.sessionName}" 当前未运行,clear 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return!0}{let K=await $.openStatusCard("clear","\uD83E\uDDF9 清空并启动新会话","orange"),B="\uD83E\uDDF9 清空并启动新会话",_=await $.restart(!1,{announce:!K,onStatus:(P)=>{B=P,$.setStatusCard(K,P)}});await $.closeStatusCard(K,_?$.withModel($.withWorktreeInstructionNotice("✅ 已清空并启动新会话")):B.startsWith("❌")?B:"❌ 清空失败")}return!0}}var aO,SQ;var CQ=R(()=>{Y0();I();aO=new Map([["hi","hi"],["stop","stop"],["st","stop"],["kill","kill"],["kl","kill"],["restart","restart"],["rs","restart"],["clear","clear"],["cl","clear"],["compact","compact"],["cm","compact"],["model","model"],["md","model"]]),SQ=new Set});function f0($,Z="nearest"){if(!Number.isFinite($)||$<0)return"MISS";let[J,Q]=$>=3600?[$/3600,"h"]:$>=60?[$/60,"m"]:[$,"s"];return`${Z==="down"?Math.floor(J*10)/10:Number(J.toFixed(1))}${Q}`}function d2($){switch($){case"project":return"项目任务";case"delegated":return"委派任务";case"subagent":return"子 Agent";case"background":return"后台进程"}}function jK($){switch($){case"project":return"\uD83D\uDCC2";case"delegated":return"\uD83E\uDDE0";case"subagent":return"\uD83E\uDD16";case"background":return"⚙️"}}var BK;var xQ=R(()=>{BK=["delegated","project","subagent","background"]});function E8($,Z=360){let J=$.replace(/\s+/g," ").trim();if(!J)return"说明 MISS";if(J.length<=Z)return J;let Q="_任务内容已精简,完整内容仅用于执行。_",Y=Math.max(1,Z-Q.length-2);return`${J.slice(0,Y)}…
169
+ 模型目录仍为 MISS:${f0(W.modelCatalogState?.error??"尚未就绪",[X.config.management_token])}`:"";await k($.chatId,`✅ ${H?.display??Z} 真实余额校验通过,配置已保存。发送 hi 查看;回复页脚使用同一账户余额。${B}`);return}if(W?.modelCatalogState?.status==="failed"||G.some((B)=>!B)){let B=f0(W?.modelCatalogState?.error??"模型目录尚未就绪",[X.config.api_key,X.config.auth_token]);await k($.chatId,`❌ ${H?.display??Z} 凭据校验通过、配置已保存,但暂不可用:${B}
170
+ 处理后等待后台刷新,发送 md 查看状态。`);return}let K=[...new Set(G.filter((B)=>!!B).map((B)=>t0(B.agent)))];await k($.chatId,`✅ ${H.display} 校验通过,配置已保存。${K.length>1?`${K.join(" 和 ")} 共用该账号。`:""}目录与额度在后台刷新;发送 md 查看模型。`)}catch(H){let G=z||H instanceof r7&&H.saved?"配置已保存,但后续处理失败":"配置失败,未保存,原配置保持不变",W=f0(H,[X.config.api_key,X.config.auth_token,X.config.management_token]);await k($.chatId,`❌ ${G}:${W}`)}}var $6=R(()=>{Y0();X0();EQ();Q9();k0();I();q8();P0()});function GK($,Z){let J=Z.catch(async(Q)=>{let Y=`账号操作或结果呈现失败:${E(Q)}`;throw j(Y),await h($.chatId,`❌ ${Y}`),Q});SQ.add(J),J.finally(()=>SQ.delete(J)).catch((Q)=>j(`账号操作结果发送失败:${E(Q)}`))}function WK(){return[...SQ]}async function KK($,Z,J="",Q){let Y=Z.trim().match(/^hi[ \t]+([^\r\n]+)$/i);if(Y){let{runCodexNamedHi:K}=await Promise.resolve().then(() => (t7(),TQ));return await K($,Y[1].trim()),!0}let V=Z.trim().match(/^codex-(login-cancel|login|accounts|account-delete|account|auto|reset)(?:[ \t]+([^\r\n]+))?$/i);if(V){let{runCodexAccountCommand:K}=await Promise.resolve().then(() => (t7(),TQ)),B=V[1].toLowerCase(),_=K($,B,(V[2]??"").trim(),J,Q);if(B==="login"||B==="reset")GK($,_);else await _;return!0}let X=Z.trim().match(/^claude-sub(?:[ \t]+([^\r\n]+))?$/i);if(X){let{runClaudeSubscriptionCommand:K}=await Promise.resolve().then(() => ($6(),e7));return await K($,(X[1]??"").trim().toLowerCase()),!0}let z=Z.trim().match(/^(?:wt|worktree)(?:\s+(.+))?$/i);if(z)return await $.runWorktreeCommand((z[1]??"").trim(),J),!0;if(Z.trim().match(/^btw$/i))return await $.runBtwCommand(J),!0;if(Z.trim().match(/^bye$/i))return await $.runByeCommand(),!0;if(Z.trim().match(/^(?:fk|fork)$/i))return await $.showForkList(J),!0;if(Z.trim().match(/^(?:bk|back)$/i))return await $.showBackList(J),!0;if(Z.trim().toLowerCase()==="task")return await $.showTasklistPanel(),!0;let H=Z.trim().match(/^files(?:[ \t]+([^\r\n]+))?$/i);if(H)return await $.runFileDeliveryCommand((H[1]??"").trim(),J),!0;if(Z.trim().match(/^(?:agents|agent)$/i))return await $.showAgentIdentityPanel(J),!0;let G=Z.trim().match(/^([\w-]+)-setup(?:\s+([\s\S]+))?$/i);if(G){let{runTokenSourceSetup:K}=await Promise.resolve().then(() => ($6(),e7));return GK($,K($,G[1].trim().toLowerCase(),(G[2]??"").trim())),!0}let W=aO.get(Z.trim().toLowerCase());if(!W)return!1;switch(W){case"model":return await $.showModelPanel(),!0;case"compact":return await $.runCompactCommand(),!0;case"hi":{let K=!$.isRunning(),B=$.backendLabel(),_=K?await $.openStatusCard("hi",$.withModel(`\uD83D\uDE80 启动 ${B}`)):null,P=$.withModel(`\uD83D\uDE80 启动 ${B}`);if(!(K?await $.start({announce:!_,onStatus:(q)=>{P=q,$.setStatusCard(_,q)}}):!0))return await $.closeStatusCard(_,P.startsWith("❌")?P:"❌ 启动失败"),!0;if($.proc?.turnRetry?.reason==="quota"){if(_)await $.closeStatusCard(_,"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消");else{let{codexAccountCard:F}=await Promise.resolve().then(() => (Q9(),$K)),M;if(!await o($.chatId,F({phase:"checking",title:"等待额度",message:"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消"}),(U)=>{M=U}))throw Error(`额度等待卡片发送失败
171
+ ${w(M)}`)}return!0}if(_)return await $.replaceStatusCardWithConsole(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`))),!0;if(K)await $.closeStatusCard(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`)))}return await $.showConsole(),!0;case"stop":{let K=$.cancelFileDeliveries("用户停止了任务");if(await $.cancelAgentRuns("stop command"),$.proc?.turnRetry?.reason==="quota"){let _=await $.openStatusCard("stop","\uD83D\uDED1 停止额度等待");try{await $.stop("已取消额度恢复",{announce:!_,onStatus:(P)=>$.setStatusCard(_,P)}),await $.closeStatusCard(_,"\uD83D\uDED1 已取消额度恢复")}catch(P){throw await $.closeStatusCard(_,`❌ ${E(P)}`),P}return!0}if($.clearStaleIdleQueueState("stop"),$.clearMultiMsgBuffer("stop command"),!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0){if(K)return await $.closeTurnCard("\uD83D\uDED1 已取消未完成的文件上传"),await k($.chatId,"\uD83D\uDED1 已取消未完成的文件上传,已上传文件保留"),!0;let _=await $.openStatusCard("stop","⚪ 当前没有正在执行的 turn","grey");if(_)await $.closeStatusCard(_,"⚪ 无正在执行的 turn");else await k($.chatId,"⚪ 当前没有正在执行的 turn");return!0}j(`session "${$.sessionName}": stop command — interrupt + drop count=${$.pendingUserMessageCount} midBuffer=${$.pendingMidTurnMsgs.length}`);let B=new Set;for(let[_,P]of[...$.pendingReactionIds.entries(),...$.currentBatchReactionIds.entries()]){if(P)g0(_,P);K$(_,"CrossMark"),B.add(_)}for(let _ of $.pendingMidTurnMsgs)if(_.msgId&&!B.has(_.msgId))K$(_.msgId,"CrossMark");return $.pendingUserMessageCount=0,$.pendingMidTurnMsgs=[],$.pendingTurnInputs=[],$.lastUserOpenId="",$.pendingReactionIds=new Map,$.currentBatchReactionIds=new Map,$.userInterrupted=!0,$.interrupt(),await $.closeTurnCard("\uD83D\uDED1 打断"),!0}case"kill":{let K=$.isRunning(),B=$.backendLabel($.proc?.provider??$.currentProvider()),_=K?`\uD83D\uDED1 停止 ${B}`:"⚪ session 当前未运行",P=await $.openStatusCard("kill",_,K?"red":"grey"),L=null,q=K?`✅ ${B} 已终止`:`⚪ ${B} 未运行`;try{await $.stop("已终止",{announce:!P,onStatus:(F)=>{$.setStatusCard(P,F)}})}catch(F){L=F,q=$.isRunning()?`❌ ${B} 未确认终止: ${E(F)};会话已阻断,请重试 kill/restart 或等待旧进程退出`:`❌ ${B} 停止收尾失败: ${E(F)}`}finally{try{await $.closeStatusCard(P,q)}catch(F){j(`session "${$.sessionName}": kill status card close failed: ${E(F)}`),await h($.chatId,`${q}
172
+ ⚠️ kill 状态卡片终态写入失败: ${E(F)}`)}}if(L&&!P)await h($.chatId,q)}return!0;case"restart":if(!$.isRunning())return await $.showResumeList(J),!0;{let K=$.lastSessionId?h0($.lastSessionId):"",B=$.backendLabel($.proc?.provider??$.currentProvider()),_=$.isRunning()?$.withModel(`\uD83D\uDD01 重启 ${B}`):K?$.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`):$.withModel(`\uD83D\uDD01 启动 ${B}`),P=await $.openStatusCard("restart",_),L=_,q=await $.restart(!0,{announce:!P,onStatus:(M)=>{L=M,$.setStatusCard(P,M)}}),F=q?L.startsWith("✅")?L:$.withWorktreeInstructionNotice(K?"✅ 已恢复上一会话":`✅ ${$.backendLabel()} 已就绪`):L.startsWith("❌")?L:"❌ 重启失败";await $.closeStatusCard(P,q?$.withModel(F):F)}return!0;case"clear":if(!$.isRunning()){$.status="stopped",$.opts.onLifecycleChange?.();let K=await $.openStatusCard("clear","⚪ session 当前未运行","grey");if(K)await $.closeStatusCard(K,`⚪ ${$.backendLabel()} 未运行,clear 无效`);else await k($.chatId,`⚪ session "${$.sessionName}" 当前未运行,clear 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return!0}{let K=await $.openStatusCard("clear","\uD83E\uDDF9 清空并启动新会话","orange"),B="\uD83E\uDDF9 清空并启动新会话",_=await $.restart(!1,{announce:!K,onStatus:(P)=>{B=P,$.setStatusCard(K,P)}});await $.closeStatusCard(K,_?$.withModel($.withWorktreeInstructionNotice("✅ 已清空并启动新会话")):B.startsWith("❌")?B:"❌ 清空失败")}return!0}}var aO,SQ;var CQ=R(()=>{Y0();I();aO=new Map([["hi","hi"],["stop","stop"],["st","stop"],["kill","kill"],["kl","kill"],["restart","restart"],["rs","restart"],["clear","clear"],["cl","clear"],["compact","compact"],["cm","compact"],["model","model"],["md","model"]]),SQ=new Set});function y0($,Z="nearest"){if(!Number.isFinite($)||$<0)return"MISS";let[J,Q]=$>=3600?[$/3600,"h"]:$>=60?[$/60,"m"]:[$,"s"];return`${Z==="down"?Math.floor(J*10)/10:Number(J.toFixed(1))}${Q}`}function d2($){switch($){case"project":return"项目任务";case"delegated":return"委派任务";case"subagent":return"子 Agent";case"background":return"后台进程"}}function jK($){switch($){case"project":return"\uD83D\uDCC2";case"delegated":return"\uD83E\uDDE0";case"subagent":return"\uD83E\uDD16";case"background":return"⚙️"}}var BK;var xQ=R(()=>{BK=["delegated","project","subagent","background"]});function E8($,Z=360){let J=$.replace(/\s+/g," ").trim();if(!J)return"说明 MISS";if(J.length<=Z)return J;let Q="_任务内容已精简,完整内容仅用于执行。_",Y=Math.max(1,Z-Q.length-2);return`${J.slice(0,Y)}…
173
173
 
174
174
  ${Q}`}function Z6($,Z=8000){if($.length<=Z)return $;let J="_结果超过卡片安全上限,已截断。_",Q=Math.max(1,Z-J.length-2);return`${$.slice(0,Q)}…
175
175
 
176
- ${J}`}function _K($){let Z=2166136261;for(let J=0;J<$.length;J++)Z^=$.charCodeAt(J),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}function sO($,Z){let J=$??"";if(J==="agent"||J==="subagent"||J==="local_agent")return"subagent";if(J==="shell"||J==="local_bash"||J==="local_shell")return"shell";if(J==="monitor"||J==="local_monitor")return"monitor";if(J==="workflow"||J==="local_workflow")return"workflow";if(Z)return"subagent";return"unknown"}function PK($){return $==="workflow"||$==="monitor"}function R$($){return $.status==="completed"||$.status==="failed"||$.status==="killed"}function kQ($){return $.some((Z)=>!R$(Z))}function C8($,Z,J=Date.now()){let Q=sO(Z.task_type,Z.subagent_type),Y=(H)=>H.id===Z.task_id||!!Z.tool_use_id&&H.toolUseId===Z.tool_use_id,V=$.active.some(Y),X=$.pending.some(Y);if(V||X){let H=(G)=>({...G,...R$(G)?{status:"running",startedAt:J,endTime:void 0,summary:void 0,error:void 0,usage:void 0,steps:[]}:{},id:Z.task_id,type:Q==="unknown"?G.type:Q,toolUseId:Z.tool_use_id??G.toolUseId,description:Z.description||G.description,subagentType:Z.subagent_type??G.subagentType,workflowName:Z.workflow_name??G.workflowName,prompt:Z.prompt??G.prompt});if(X&&Q==="subagent")return{active:[...$.active,...$.pending.filter(Y).map(H)],pending:$.pending.filter((G)=>!Y(G))};return{active:V?$.active.map((G)=>Y(G)?H(G):G):$.active,pending:X?$.pending.map((G)=>Y(G)?H(G):G):$.pending}}let z={id:Z.task_id,displayId:Z.tool_use_id??Z.task_id,toolUseId:Z.tool_use_id,type:Q,description:Z.description,subagentType:Z.subagent_type,workflowName:Z.workflow_name,prompt:Z.prompt,status:"running",startedAt:J,steps:[],...PK(Q)?{isBackgrounded:!0}:{}};return Q==="subagent"||PK(Q)?{active:[...$.active,z],pending:$.pending}:{active:$.active,pending:[...$.pending,z]}}function wQ($,Z){let J=$.active.some((V)=>V.id===Z.task_id),Q=$.pending.some((V)=>V.id===Z.task_id);if(!J&&!Q)return $;let Y=(V)=>({...V,description:Z.description??V.description,subagentType:Z.subagent_type??V.subagentType,usage:Z.usage??V.usage,lastToolName:Z.last_tool_name??V.lastToolName,summary:Z.summary??V.summary,status:V.status==="pending"?"running":V.status});return{active:J?$.active.map((V)=>V.id===Z.task_id?Y(V):V):$.active,pending:Q?$.pending.map((V)=>V.id===Z.task_id?Y(V):V):$.pending}}function vQ($,Z){let J=$.pending.findIndex((X)=>X.id===Z.task_id),Q=Z.patch;if(Q.is_backgrounded===!0&&J>=0){let X=$.pending[J],z={...X,isBackgrounded:!0,status:Q.status??X.status,description:Q.description??X.description,error:Q.error??X.error,endTime:Q.end_time??X.endTime};return{active:[...$.active,z],pending:$.pending.filter((H)=>H.id!==Z.task_id)}}let Y=$.active.some((X)=>X.id===Z.task_id),V=J>=0;if(Y||V){let X=(z)=>({...z,status:Q.status??z.status,description:Q.description??z.description,error:Q.error??z.error,isBackgrounded:Q.is_backgrounded??z.isBackgrounded,endTime:Q.end_time??z.endTime});return{active:Y?$.active.map((z)=>z.id===Z.task_id?X(z):z):$.active,pending:V?$.pending.map((z)=>z.id===Z.task_id?X(z):z):$.pending}}return $}function fQ($){if($.pending.length===0)return $;return{active:[...$.active,...$.pending.map((Z)=>({...Z,isBackgrounded:!0}))],pending:[]}}function Q6($,Z,J=Date.now()){let Q=Z.status==="completed"?"completed":Z.status==="failed"?"failed":"killed";if($.pending.some((Y)=>Y.id===Z.task_id))return{active:$.active,pending:$.pending.filter((Y)=>Y.id!==Z.task_id)};if($.active.some((Y)=>Y.id===Z.task_id))return{active:$.active.map((Y)=>Y.id===Z.task_id?{...Y,status:Q,usage:Z.usage??Y.usage,summary:Z.summary??Y.summary,endTime:Y.endTime??J}:Y),pending:$.pending};return $}function J6($){let Z=0,J=0;for(let Q=$.length-1;Q>=0;Q--)if(Z+=$[Q].brief.length+5,Z>tO){J=Q+1;break}return J===0?$:$.slice(J)}function rO($,Z){let J=(Q)=>typeof Q==="string"?Q:"";switch($){case"Bash":return typeof Z?.__displayDescription==="string"?Z.__displayDescription:O4(J(Z?.command))||"(空命令)";case"Read":return J(Z?.file_path);case"Edit":return J(Z?.file_path);case"Write":return J(Z?.file_path);case"Grep":return`"${J(Z?.pattern)}" in ${J(Z?.path??".")}`;case"Glob":return`"${J(Z?.pattern)}"`;case"Task":return J(Z?.description);case"WebSearch":return`"${J(Z?.query)}"`;default:return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}function eO($,Z){let Q=((typeof $==="string"?$:Array.isArray($)?$.map((Y)=>typeof Y?.text==="string"?Y.text:JSON.stringify(Y)).join(`
177
- `):JSON.stringify($))??"MISS").replace(/\s+/g," ").trim();return Z?`❌ ${Q.slice(0,80)}`:Q.slice(0,80)}function yQ($,Z,J,Q,Y){if(!Z)return $;let V=$.active.some((H)=>H.toolUseId===Z),X=$.pending.some((H)=>H.toolUseId===Z);if(!V&&!X)return $;let z=(H)=>H.map((G)=>G.toolUseId===Z?{...G,steps:J6([...G.steps,{toolUseId:J,tool:Q,brief:`${Q} ${rO(Q,Y)}`.trim()}])}:G);return{active:V?z($.active):$.active,pending:X?z($.pending):$.pending}}function hQ($,Z,J,Q,Y,V){let X=$.active.some((G)=>G.id===Z),z=$.pending.some((G)=>G.id===Z);if(!X&&!z)return $;let H=(G)=>G.map((W)=>{if(W.id!==Z)return W;if(Y==="started")return{...W,steps:J6([...W.steps,{toolUseId:J,tool:Q,brief:`${Q} ${V}`.trim()}])};let K=!1,B=W.steps.map((_)=>{if(K||_.toolUseId!==J)return _;return K=!0,{..._,brief:V?`${_.brief} ${V}`:_.brief}});if(!K&&V)B.push({toolUseId:J,tool:Q,brief:`${Q} ${V}`.trim()});return{...W,steps:J6(B)}});return{active:X?H($.active):$.active,pending:z?H($.pending):$.pending}}function IQ($,Z,J,Q,Y){if(!Z)return $;let V=$.active.some((H)=>H.toolUseId===Z),X=$.pending.some((H)=>H.toolUseId===Z);if(!V&&!X)return $;let z=(H)=>H.map((G)=>{if(G.toolUseId!==Z)return G;let W=!1,K=G.steps.map((B)=>{if(W||B.toolUseId!==J)return B;return W=!0,{...B,brief:`${B.brief} → ${eO(Q,Y)}`}});return{...G,steps:J6(K)}});return{active:V?z($.active):$.active,pending:X?z($.pending):$.pending}}function x8($){return $.type==="subagent"?"subagent":"background"}function MK($){let Z=Number.isFinite($)?Math.max(0,$):0;for(let V of $A)if(Z<V.limit)return{label:V.label,nextDelayMs:V.limit-Z};let J=600000,Q=Math.floor((Z-600000)/J),Y=600000+(Q+1)*J;return{label:`${f0((Q+1)*600,"down")}+`,nextDelayMs:Y-Z}}function V9($,Z="bucket"){if(Z==="second"){let J=Number.isFinite($)?Math.max(0,$):0;if(J>=bQ){let Q=Math.floor((J-bQ)/LK),Y=bQ+(Q+1)*LK;return{label:`${f0((10+Q*5)*60,"down")}+`,nextDelayMs:Y-J}}return{label:f0(Math.floor(J/1000)),nextDelayMs:FK}}return MK($)}function qK($){return $.subagentType??$.workflowName??DK[$.type]}function ZA($){if($.usage?.duration_ms)return $.usage.duration_ms;if($.endTime&&$.endTime>$.startedAt)return $.endTime-$.startedAt;return 0}function JA($){let Z=d2(x8($)),J=DK[$.type],Q=[`**${Z}${J!==Z?` · ${J}`:""}**${qK($)!==J?` · ${qK($)}`:""}${R$($)?` · 用时 ${f0(ZA($)/1000)}`:""}`,$.description||"说明 MISS"];if($.error)Q.push(`⚠ ${$.error}`);if($.summary)Q.push("",`**${R$($)?"结果":"进度"}**`,R$($)?Z6($.summary):E8($.summary));if($.prompt)Q.push("","**任务说明**",E8($.prompt));if($.steps.length){Q.push("","**最近动作**");for(let Y of $.steps.slice(-3))Q.push(`- ${Y.brief}`)}else if($.lastToolName)Q.push("",`最近动作:${$.lastToolName}`);return G0(Q.join(`
178
- `))}function Y6($){let Z=d2(x8($)),J={running:`⏳ ${Z}正在执行`,pending:`⏳ ${Z}等待执行`,paused:`⏸️ ${Z}已暂停`,completed:`✅ ${Z}完成`,failed:`❌ ${Z}失败`,killed:`\uD83D\uDED1 ${Z}已终止`}[$.status],Q=$.description.replace(/\s+/g," ").trim()||"说明 MISS";return`${J} · ${Q.length<=40?Q:`${Q.slice(0,39)}…`}`}function gQ($){return{tag:"collapsible_panel",element_id:S8.panel($.id),header:{title:{tag:"plain_text",content:Y6($)}},expanded:!1,elements:[{tag:"markdown",element_id:S8.body($.id),content:JA($)}]}}var S8,tO=1000,DK,$A,FK=1000,bQ=600000,LK=300000;var mQ=R(()=>{d0();A4();xQ();S8={panel:($)=>`bg_${_K($)}`,body:($)=>`bgb_${_K($)}`};DK={subagent:"子 Agent",shell:"后台命令",monitor:"监控",workflow:"工作流",unknown:"任务"};$A=[{limit:30000,label:"<30s"},{limit:60000,label:"<1m"},{limit:180000,label:"<3m"},{limit:300000,label:"<5m"},{limit:600000,label:"<10m"}]});function i1($,Z){if(!$||!Object.hasOwn(g.claude.safe_mode,$))return!1;let J=g.claude.safe_mode[$];return!!J&&(J.includes("*")||Z!=null&&J.includes(Z))}var b8=R(()=>{k0()});import{randomUUID as QA}from"node:crypto";import{closeSync as YA,constants as X9,fstatSync as VA,fsyncSync as XA,lstatSync as V6,mkdirSync as zA,openSync as HA,writeFileSync as GA}from"node:fs";import{join as WA,resolve as UK}from"node:path";function X6($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function z6($,Z,J){if($.isSymbolicLink())throw Error(`Trace path must not be a symlink: ${Z}`);if(J?!$.isDirectory():!$.isFile())throw Error(`Trace path must be a ${J?"directory":"regular file"}: ${Z}`);let Q=J?448:384;if(($.mode&4095)!==Q)throw Error(`Trace permissions must be ${Q.toString(8)}: ${Z}`);if(typeof process.getuid==="function"&&$.uid!==process.getuid())throw Error(`Trace path must belong to the current user: ${Z}`);if(!J&&$.nlink!==1)throw Error(`Trace file must not have hard links: ${Z}`)}function KA($){let Z=new Set;for(let Q of $){if(typeof Q!=="string")throw Error("Trace secrets must be strings");if(!Q)continue;Z.add(Q),Z.add(JSON.stringify(Q).slice(1,-1))}if(!Z.size)return(Q)=>Q;let J=new RegExp([...Z].sort((Q,Y)=>Y.length-Q.length).map((Q)=>Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");return(Q)=>Q.replace(J,"[REDACTED]")}function pQ($,Z){if(typeof $==="string")return Z($);if(Array.isArray($))return $.map((J)=>pQ(J,Z));if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.entries($).map(([J,Q])=>[Z(J),/^(?:authorization|proxy-authorization|x-api-key|api[-_]?key|auth_token|access_token)$/i.test(J)?"[REDACTED]":pQ(Q,Z)]))}class cQ{traceId=QA();filePath;directory;workDir;sourceId;sessionId=null;directoryIdentity=null;fileIdentity=null;failure=null;knownSecrets=new Set;constructor($){if(!$.workDir.trim())throw new _$("Translation trace workDir is required");this.directory=UK($.directory??WX),this.workDir=UK($.workDir),this.sourceId=$.sourceId??null,this.filePath=WA(this.directory,`${this.traceId}.jsonl`)}bindSession($){if(this.failure)throw this.failure;if(!$.trim())throw new _$("Translation trace sessionId is required");if(this.sessionId===$)return;if(this.sessionId!==null)throw new _$("Translation trace session mismatch");this.write({event:"session_bound",requestId:null},[],$),this.sessionId=$}append($,Z=[]){if(this.failure)throw this.failure;if(!$.requestId?.trim())throw new _$("Translation trace requestId is required");let J;switch($.event){case"request":if(!["en","zh"].includes($.direction)||$.body===void 0)throw new _$("Translation trace request requires direction and body");J={direction:$.direction,body:$.body,...$.endpoint?{endpoint:$.endpoint}:{}};break;case"response":if(!Number.isInteger($.status)||typeof $.bodyText!=="string")throw new _$("Translation trace response requires HTTP status and bodyText");J={status:$.status,bodyText:$.bodyText};break;case"result":if($.text===void 0&&$.fields===void 0||$.text!==void 0&&typeof $.text!=="string"||$.fields!==void 0&&(!Array.isArray($.fields)||$.fields.some((Q)=>typeof Q!=="string")))throw new _$("Translation trace result requires text or string fields");J={...$.text!==void 0?{text:$.text}:{},...$.fields!==void 0?{fields:$.fields}:{}};break;case"error":if(typeof $.message!=="string"||$.cancelled!==void 0&&typeof $.cancelled!=="boolean")throw new _$("Translation trace error requires message and an optional cancellation flag");J={message:$.message,...$.cancelled!==void 0?{cancelled:$.cancelled}:{}};break;default:throw new _$("Unknown translation trace event")}this.write({event:$.event,requestId:$.requestId,...J},Z,this.sessionId)}ensureDirectory(){let $;try{$=V6(this.directory)}catch(Z){if(Z.code!=="ENOENT"||this.directoryIdentity)throw Z;zA(this.directory,{recursive:!0,mode:448}),$=V6(this.directory)}if(z6($,this.directory,!0),this.directoryIdentity&&!X6($,this.directoryIdentity))throw Error(`Trace directory changed: ${this.directory}`);return $}write($,Z,J){if(this.failure)throw this.failure;let Q=null,Y,V=!1,X=(z)=>z;try{for(let P of Z)if(P)this.knownSecrets.add(P);X=KA([...this.knownSecrets]);let z={...$,version:1,time:new Date().toISOString(),traceId:this.traceId,workDir:this.workDir,sourceId:this.sourceId,sessionId:J},H=JSON.parse(JSON.stringify(z)),G=JSON.stringify(pQ(H,X))+`
176
+ ${J}`}function _K($){let Z=2166136261;for(let J=0;J<$.length;J++)Z^=$.charCodeAt(J),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}function sO($,Z){let J=$??"";if(J==="agent"||J==="subagent"||J==="local_agent")return"subagent";if(J==="shell"||J==="local_bash"||J==="local_shell")return"shell";if(J==="monitor"||J==="local_monitor")return"monitor";if(J==="workflow"||J==="local_workflow")return"workflow";if(Z)return"subagent";return"unknown"}function PK($){return $==="workflow"||$==="monitor"}function R$($){return $.status==="completed"||$.status==="failed"||$.status==="killed"}function kQ($){return $.some((Z)=>!R$(Z))}function C8($,Z,J=Date.now()){let Q=sO(Z.task_type,Z.subagent_type),Y=(H)=>H.id===Z.task_id||!!Z.tool_use_id&&H.toolUseId===Z.tool_use_id,V=$.active.some(Y),X=$.pending.some(Y);if(V||X){let H=(G)=>({...G,...R$(G)?{status:"running",startedAt:J,endTime:void 0,summary:void 0,error:void 0,usage:void 0,steps:[]}:{},id:Z.task_id,type:Q==="unknown"?G.type:Q,toolUseId:Z.tool_use_id??G.toolUseId,description:Z.description||G.description,subagentType:Z.subagent_type??G.subagentType,workflowName:Z.workflow_name??G.workflowName,prompt:Z.prompt??G.prompt});if(X&&Q==="subagent")return{active:[...$.active,...$.pending.filter(Y).map(H)],pending:$.pending.filter((G)=>!Y(G))};return{active:V?$.active.map((G)=>Y(G)?H(G):G):$.active,pending:X?$.pending.map((G)=>Y(G)?H(G):G):$.pending}}let z={id:Z.task_id,displayId:Z.tool_use_id??Z.task_id,toolUseId:Z.tool_use_id,type:Q,description:Z.description,subagentType:Z.subagent_type,workflowName:Z.workflow_name,prompt:Z.prompt,status:"running",startedAt:J,steps:[],...PK(Q)?{isBackgrounded:!0}:{}};return Q==="subagent"||PK(Q)?{active:[...$.active,z],pending:$.pending}:{active:$.active,pending:[...$.pending,z]}}function wQ($,Z){let J=$.active.some((V)=>V.id===Z.task_id),Q=$.pending.some((V)=>V.id===Z.task_id);if(!J&&!Q)return $;let Y=(V)=>({...V,description:Z.description??V.description,subagentType:Z.subagent_type??V.subagentType,usage:Z.usage??V.usage,lastToolName:Z.last_tool_name??V.lastToolName,summary:Z.summary??V.summary,status:V.status==="pending"?"running":V.status});return{active:J?$.active.map((V)=>V.id===Z.task_id?Y(V):V):$.active,pending:Q?$.pending.map((V)=>V.id===Z.task_id?Y(V):V):$.pending}}function vQ($,Z){let J=$.pending.findIndex((X)=>X.id===Z.task_id),Q=Z.patch;if(Q.is_backgrounded===!0&&J>=0){let X=$.pending[J],z={...X,isBackgrounded:!0,status:Q.status??X.status,description:Q.description??X.description,error:Q.error??X.error,endTime:Q.end_time??X.endTime};return{active:[...$.active,z],pending:$.pending.filter((H)=>H.id!==Z.task_id)}}let Y=$.active.some((X)=>X.id===Z.task_id),V=J>=0;if(Y||V){let X=(z)=>({...z,status:Q.status??z.status,description:Q.description??z.description,error:Q.error??z.error,isBackgrounded:Q.is_backgrounded??z.isBackgrounded,endTime:Q.end_time??z.endTime});return{active:Y?$.active.map((z)=>z.id===Z.task_id?X(z):z):$.active,pending:V?$.pending.map((z)=>z.id===Z.task_id?X(z):z):$.pending}}return $}function yQ($){if($.pending.length===0)return $;return{active:[...$.active,...$.pending.map((Z)=>({...Z,isBackgrounded:!0}))],pending:[]}}function Q6($,Z,J=Date.now()){let Q=Z.status==="completed"?"completed":Z.status==="failed"?"failed":"killed";if($.pending.some((Y)=>Y.id===Z.task_id))return{active:$.active,pending:$.pending.filter((Y)=>Y.id!==Z.task_id)};if($.active.some((Y)=>Y.id===Z.task_id))return{active:$.active.map((Y)=>Y.id===Z.task_id?{...Y,status:Q,usage:Z.usage??Y.usage,summary:Z.summary??Y.summary,endTime:Y.endTime??J}:Y),pending:$.pending};return $}function J6($){let Z=0,J=0;for(let Q=$.length-1;Q>=0;Q--)if(Z+=$[Q].brief.length+5,Z>tO){J=Q+1;break}return J===0?$:$.slice(J)}function rO($,Z){let J=(Q)=>typeof Q==="string"?Q:"";switch($){case"Bash":return typeof Z?.__displayDescription==="string"?Z.__displayDescription:O4(J(Z?.command))||"(空命令)";case"Read":return J(Z?.file_path);case"Edit":return J(Z?.file_path);case"Write":return J(Z?.file_path);case"Grep":return`"${J(Z?.pattern)}" in ${J(Z?.path??".")}`;case"Glob":return`"${J(Z?.pattern)}"`;case"Task":return J(Z?.description);case"WebSearch":return`"${J(Z?.query)}"`;default:return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}function eO($,Z){let Q=((typeof $==="string"?$:Array.isArray($)?$.map((Y)=>typeof Y?.text==="string"?Y.text:JSON.stringify(Y)).join(`
177
+ `):JSON.stringify($))??"MISS").replace(/\s+/g," ").trim();return Z?`❌ ${Q.slice(0,80)}`:Q.slice(0,80)}function fQ($,Z,J,Q,Y){if(!Z)return $;let V=$.active.some((H)=>H.toolUseId===Z),X=$.pending.some((H)=>H.toolUseId===Z);if(!V&&!X)return $;let z=(H)=>H.map((G)=>G.toolUseId===Z?{...G,steps:J6([...G.steps,{toolUseId:J,tool:Q,brief:`${Q} ${rO(Q,Y)}`.trim()}])}:G);return{active:V?z($.active):$.active,pending:X?z($.pending):$.pending}}function hQ($,Z,J,Q,Y,V){let X=$.active.some((G)=>G.id===Z),z=$.pending.some((G)=>G.id===Z);if(!X&&!z)return $;let H=(G)=>G.map((W)=>{if(W.id!==Z)return W;if(Y==="started")return{...W,steps:J6([...W.steps,{toolUseId:J,tool:Q,brief:`${Q} ${V}`.trim()}])};let K=!1,B=W.steps.map((_)=>{if(K||_.toolUseId!==J)return _;return K=!0,{..._,brief:V?`${_.brief} ${V}`:_.brief}});if(!K&&V)B.push({toolUseId:J,tool:Q,brief:`${Q} ${V}`.trim()});return{...W,steps:J6(B)}});return{active:X?H($.active):$.active,pending:z?H($.pending):$.pending}}function IQ($,Z,J,Q,Y){if(!Z)return $;let V=$.active.some((H)=>H.toolUseId===Z),X=$.pending.some((H)=>H.toolUseId===Z);if(!V&&!X)return $;let z=(H)=>H.map((G)=>{if(G.toolUseId!==Z)return G;let W=!1,K=G.steps.map((B)=>{if(W||B.toolUseId!==J)return B;return W=!0,{...B,brief:`${B.brief} → ${eO(Q,Y)}`}});return{...G,steps:J6(K)}});return{active:V?z($.active):$.active,pending:X?z($.pending):$.pending}}function x8($){return $.type==="subagent"?"subagent":"background"}function MK($){let Z=Number.isFinite($)?Math.max(0,$):0;for(let V of $A)if(Z<V.limit)return{label:V.label,nextDelayMs:V.limit-Z};let J=600000,Q=Math.floor((Z-600000)/J),Y=600000+(Q+1)*J;return{label:`${y0((Q+1)*600,"down")}+`,nextDelayMs:Y-Z}}function V9($,Z="bucket"){if(Z==="second"){let J=Number.isFinite($)?Math.max(0,$):0;if(J>=bQ){let Q=Math.floor((J-bQ)/LK),Y=bQ+(Q+1)*LK;return{label:`${y0((10+Q*5)*60,"down")}+`,nextDelayMs:Y-J}}return{label:y0(Math.floor(J/1000)),nextDelayMs:DK}}return MK($)}function qK($){return $.subagentType??$.workflowName??FK[$.type]}function ZA($){if($.usage?.duration_ms)return $.usage.duration_ms;if($.endTime&&$.endTime>$.startedAt)return $.endTime-$.startedAt;return 0}function JA($){let Z=d2(x8($)),J=FK[$.type],Q=[`**${Z}${J!==Z?` · ${J}`:""}**${qK($)!==J?` · ${qK($)}`:""}${R$($)?` · 用时 ${y0(ZA($)/1000)}`:""}`,$.description||"说明 MISS"];if($.error)Q.push(`⚠ ${$.error}`);if($.summary)Q.push("",`**${R$($)?"结果":"进度"}**`,R$($)?Z6($.summary):E8($.summary));if($.prompt)Q.push("","**任务说明**",E8($.prompt));if($.steps.length){Q.push("","**最近动作**");for(let Y of $.steps.slice(-3))Q.push(`- ${Y.brief}`)}else if($.lastToolName)Q.push("",`最近动作:${$.lastToolName}`);return G0(Q.join(`
178
+ `))}function Y6($){let Z=d2(x8($)),J={running:`⏳ ${Z}正在执行`,pending:`⏳ ${Z}等待执行`,paused:`⏸️ ${Z}已暂停`,completed:`✅ ${Z}完成`,failed:`❌ ${Z}失败`,killed:`\uD83D\uDED1 ${Z}已终止`}[$.status],Q=$.description.replace(/\s+/g," ").trim()||"说明 MISS";return`${J} · ${Q.length<=40?Q:`${Q.slice(0,39)}…`}`}function gQ($){return{tag:"collapsible_panel",element_id:S8.panel($.id),header:{title:{tag:"plain_text",content:Y6($)}},expanded:!1,elements:[{tag:"markdown",element_id:S8.body($.id),content:JA($)}]}}var S8,tO=1000,FK,$A,DK=1000,bQ=600000,LK=300000;var mQ=R(()=>{d0();A4();xQ();S8={panel:($)=>`bg_${_K($)}`,body:($)=>`bgb_${_K($)}`};FK={subagent:"子 Agent",shell:"后台命令",monitor:"监控",workflow:"工作流",unknown:"任务"};$A=[{limit:30000,label:"<30s"},{limit:60000,label:"<1m"},{limit:180000,label:"<3m"},{limit:300000,label:"<5m"},{limit:600000,label:"<10m"}]});function i1($,Z){if(!$||!Object.hasOwn(g.claude.safe_mode,$))return!1;let J=g.claude.safe_mode[$];return!!J&&(J.includes("*")||Z!=null&&J.includes(Z))}var b8=R(()=>{k0()});import{randomUUID as QA}from"node:crypto";import{closeSync as YA,constants as X9,fstatSync as VA,fsyncSync as XA,lstatSync as V6,mkdirSync as zA,openSync as HA,writeFileSync as GA}from"node:fs";import{join as WA,resolve as UK}from"node:path";function X6($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function z6($,Z,J){if($.isSymbolicLink())throw Error(`Trace path must not be a symlink: ${Z}`);if(J?!$.isDirectory():!$.isFile())throw Error(`Trace path must be a ${J?"directory":"regular file"}: ${Z}`);let Q=J?448:384;if(($.mode&4095)!==Q)throw Error(`Trace permissions must be ${Q.toString(8)}: ${Z}`);if(typeof process.getuid==="function"&&$.uid!==process.getuid())throw Error(`Trace path must belong to the current user: ${Z}`);if(!J&&$.nlink!==1)throw Error(`Trace file must not have hard links: ${Z}`)}function KA($){let Z=new Set;for(let Q of $){if(typeof Q!=="string")throw Error("Trace secrets must be strings");if(!Q)continue;Z.add(Q),Z.add(JSON.stringify(Q).slice(1,-1))}if(!Z.size)return(Q)=>Q;let J=new RegExp([...Z].sort((Q,Y)=>Y.length-Q.length).map((Q)=>Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");return(Q)=>Q.replace(J,"[REDACTED]")}function pQ($,Z){if(typeof $==="string")return Z($);if(Array.isArray($))return $.map((J)=>pQ(J,Z));if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.entries($).map(([J,Q])=>[Z(J),/^(?:authorization|proxy-authorization|x-api-key|api[-_]?key|auth_token|access_token)$/i.test(J)?"[REDACTED]":pQ(Q,Z)]))}class cQ{traceId=QA();filePath;directory;workDir;sourceId;sessionId=null;directoryIdentity=null;fileIdentity=null;failure=null;knownSecrets=new Set;constructor($){if(!$.workDir.trim())throw new _$("Translation trace workDir is required");this.directory=UK($.directory??WX),this.workDir=UK($.workDir),this.sourceId=$.sourceId??null,this.filePath=WA(this.directory,`${this.traceId}.jsonl`)}bindSession($){if(this.failure)throw this.failure;if(!$.trim())throw new _$("Translation trace sessionId is required");if(this.sessionId===$)return;if(this.sessionId!==null)throw new _$("Translation trace session mismatch");this.write({event:"session_bound",requestId:null},[],$),this.sessionId=$}append($,Z=[]){if(this.failure)throw this.failure;if(!$.requestId?.trim())throw new _$("Translation trace requestId is required");let J;switch($.event){case"request":if(!["en","zh"].includes($.direction)||$.body===void 0)throw new _$("Translation trace request requires direction and body");J={direction:$.direction,body:$.body,...$.endpoint?{endpoint:$.endpoint}:{}};break;case"response":if(!Number.isInteger($.status)||typeof $.bodyText!=="string")throw new _$("Translation trace response requires HTTP status and bodyText");J={status:$.status,bodyText:$.bodyText};break;case"result":if($.text===void 0&&$.fields===void 0||$.text!==void 0&&typeof $.text!=="string"||$.fields!==void 0&&(!Array.isArray($.fields)||$.fields.some((Q)=>typeof Q!=="string")))throw new _$("Translation trace result requires text or string fields");J={...$.text!==void 0?{text:$.text}:{},...$.fields!==void 0?{fields:$.fields}:{}};break;case"error":if(typeof $.message!=="string"||$.cancelled!==void 0&&typeof $.cancelled!=="boolean")throw new _$("Translation trace error requires message and an optional cancellation flag");J={message:$.message,...$.cancelled!==void 0?{cancelled:$.cancelled}:{}};break;default:throw new _$("Unknown translation trace event")}this.write({event:$.event,requestId:$.requestId,...J},Z,this.sessionId)}ensureDirectory(){let $;try{$=V6(this.directory)}catch(Z){if(Z.code!=="ENOENT"||this.directoryIdentity)throw Z;zA(this.directory,{recursive:!0,mode:448}),$=V6(this.directory)}if(z6($,this.directory,!0),this.directoryIdentity&&!X6($,this.directoryIdentity))throw Error(`Trace directory changed: ${this.directory}`);return $}write($,Z,J){if(this.failure)throw this.failure;let Q=null,Y,V=!1,X=(z)=>z;try{for(let P of Z)if(P)this.knownSecrets.add(P);X=KA([...this.knownSecrets]);let z={...$,version:1,time:new Date().toISOString(),traceId:this.traceId,workDir:this.workDir,sourceId:this.sourceId,sessionId:J},H=JSON.parse(JSON.stringify(z)),G=JSON.stringify(pQ(H,X))+`
179
179
  `,W=this.ensureDirectory();if(typeof X9.O_NOFOLLOW!=="number")throw Error("Trace requires no-follow file opens");if(this.fileIdentity)z6(V6(this.filePath),this.filePath,!1);Q=HA(this.filePath,X9.O_WRONLY|X9.O_APPEND|X9.O_NOFOLLOW|(this.fileIdentity?0:X9.O_CREAT|X9.O_EXCL),384);let K=VA(Q);if(z6(K,this.filePath,!1),this.fileIdentity&&!X6(K,this.fileIdentity))throw Error(`Trace file changed: ${this.filePath}`);let B=this.ensureDirectory();if(!X6(B,W))throw Error(`Trace directory changed during open: ${this.directory}`);let _=V6(this.filePath);if(z6(_,this.filePath,!1),!X6(K,_))throw Error(`Trace file changed during open: ${this.filePath}`);this.directoryIdentity=W,this.fileIdentity=K,GA(Q,G,"utf8"),XA(Q)}catch(z){Y=z,V=!0}finally{if(Q!==null)try{YA(Q)}catch(z){Y=V?AggregateError([Y,z],`${String(Y)}; trace close failed: ${String(z)}`):z,V=!0}}if(V)throw this.failure=new _$(`Claude translation trace write failed: ${X(Y instanceof Error?Y.message:String(Y))}`),this.failure}}var _$;var uQ=R(()=>{H0();_$=class _$ extends Error{constructor($){super($);this.name="ClaudeTranslationTraceError"}}});import{randomUUID as BA}from"node:crypto";function jA(){let $=M0("glm");if(!$?.enabled)throw Error("Claude 英文模式需要已配置的 GLM 账号");let J=$.spawnEnv({}).ANTHROPIC_AUTH_TOKEN?.trim();if(!J)throw Error("Claude 英文模式缺少 GLM Key");return J}function dQ($){if(!$.trim()||/[\r\n]/u.test($))throw Error("GLM 翻译原文来源必须是非空单行说明");return`Source: ${$}`}function NK($,Z){return{role:"user",content:`${dQ(Z)}
180
180
 
181
- ${$}`}}function RK($){let Z=s9($),J=cZ($);for(let V of $.matchAll(/\[\[TRANSLATION_[^\]\r\n]*\]\]|\[\[send:\s*[^\]\n]+\]\]|\[file:\s*[^\]\n]+\]/gi)){let X={start:V.index,end:V.index+V[0].length},z=J.find((H)=>X.start>=H.start&&X.end<=H.end)??X;if(!Z.some((H)=>z.start<H.end&&z.end>H.start))Z.push(z)}Z.sort((V,X)=>V.start-X.start);let Q=[],Y=0;for(let V of Z){if(V.start>Y)Q.push({text:$.slice(Y,V.start),translate:!0});Q.push({text:$.slice(V.start,V.end),translate:!1}),Y=V.end}if(Y<$.length)Q.push({text:$.slice(Y),translate:!0});return Q}function iQ($){let Z=cZ($),J=/https?:\/\/[^\s<>"'`[\],。;:!?、()【】《》“”‘’]+|(?<![\w/])(?:\.{1,2}\/|~\/|\/)[^\s<>"'`[\],。;:!?、()【】《》“”‘’]+|(?<![\w./])[a-z0-9_@~.-][\p{L}\p{N}_@~.+()-]*(?:\/[\p{L}\p{N}_@~.+()-]+)*\/[\p{L}\p{N}_@~.+()-]*\.[a-z][a-z0-9]*(?![\w/]|\.[\p{L}\p{N}_/])/giu,Q;while(Q=J.exec($)){let Y=[],V=Q[0].length;for(let G=0;G<Q[0].length;G++)if(Q[0][G]==="(")Y.push(G);else if(Q[0][G]===")"){if(!Y.length){V=G;break}Y.pop()}if(Y.length){if(V=Y[0],V<Q[0].indexOf("/")){J.lastIndex=Q.index+V+1;continue}}let X=Q[0].slice(0,V).replace(/[.,;:!?]+$/,"");if(!X)continue;let z=$.slice(Math.max(0,Q.index-2),Q.index);if(X.startsWith("/")&&/\p{Script=Han}$/u.test(z)&&!/^\/[a-z0-9_.~-]/i.test(X)&&!/\.[a-z][a-z0-9]*$/i.test(X))continue;let H={start:Q.index,end:Q.index+X.length};if(!Z.some((G)=>H.start<G.end&&H.end>G.start))Z.push(H)}return Z.sort((Y,V)=>Y.start-V.start)}function TK($,Z){let J="",Q=0;for(let Y of Z)J+=$.slice(Q,Y.start),Q=Y.end;return J+$.slice(Q)}function PA($,Z){let J=iQ($),Q=iQ(Z),Y=(V,X)=>X.map((z)=>V.slice(z.start,z.end)).sort();if(JSON.stringify(Y($,J))!==JSON.stringify(Y(Z,Q)))throw Error("GLM 翻译验证失败:代码、路径或链接的原值或数量改变");return TK(Z,Q)}function LA($){let Z=[];for(let J of $?.entries??[]){let Q=(X)=>RK(X).filter((z)=>z.translate).map((z)=>z.text).join("").trim(),Y=Q(J.original),V=Q(J.translated);if(!Y&&!V)continue;if(!Y||!V)throw Error("GLM 翻译上下文原文与译文不完整");Z.push(NK(Y,J.origin??t9(J.role)),{role:"assistant",content:V})}return Z}function lQ($){if(!$||typeof $!=="object"||Array.isArray($))throw Error("GLM 翻译接口返回了无效结构");return $}function EK($={}){let Z=$.fetch??V0,J=$.credential??jA,Q=$.validationRules?.trim()??"";async function Y(G,W,K,B,_){W.throwIfAborted();let P=new AbortController,L=()=>P.abort(W.reason);W.addEventListener("abort",L,{once:!0});let q=setTimeout(()=>P.abort(Error("GLM translation request timed out")),$.timeoutMs??120000);try{$.trace?.append({event:"request",requestId:B,direction:_,body:K,endpoint:`${AK}/chat/completions`},[G]);let D=await Z(`${AK}/chat/completions`,{method:"POST",redirect:"error",signal:P.signal,headers:{Authorization:`Bearer ${G}`,"Content-Type":"application/json"},body:JSON.stringify(K)}),M=await D.text();$.trace?.append({event:"response",requestId:B,status:D.status,bodyText:M},[G]),W.throwIfAborted(),P.signal.throwIfAborted();let U;try{U=lQ(JSON.parse(M))}catch{throw Error(`GLM 国际翻译接口 HTTP ${D.status}:返回格式无效`)}let A=typeof U.code==="string"||typeof U.code==="number"?String(U.code):void 0;if(!D.ok||U.error!=null||U.success===!1||A!==void 0&&!["0","200"].includes(A)){let O=U.error&&typeof U.error==="object"?U.error:U,N=typeof O.message==="string"?O.message.split(G).join("[REDACTED]").slice(0,500):"MISS",S=typeof O.code==="string"||typeof O.code==="number"?String(O.code):"";throw Error(`GLM 国际翻译接口 HTTP ${D.status}${S?` (${S})`:""}:${N}`)}return U}finally{clearTimeout(q),W.removeEventListener("abort",L)}}async function V(G,W,K,B,_){let P=await Y(W,K,{model:OK,max_tokens:16384,stream:!1,messages:G},B,_);if(P.model!==OK)throw Error("GLM 翻译验证失败:响应模型与 glm-5.3-flash 不符");if(!Array.isArray(P.choices)||P.choices.length!==1)throw Error("GLM 翻译响应 choices 数量无效");let L=lQ(P.choices[0]);if(L.finish_reason!=="stop")throw Error(`GLM 翻译未完整结束:${String(L.finish_reason??"MISS")}`);let D=lQ(L.message).content;if(typeof D!=="string"||!D.trim())throw Error("GLM 翻译响应正文为空或无效");return D}let X=_A+(Q?`
181
+ ${$}`}}function RK($){let Z=s9($),J=cZ($);for(let V of $.matchAll(/\[\[TRANSLATION_[^\]\r\n]*\]\]|\[\[send:\s*[^\]\n]+\]\]|\[file:\s*[^\]\n]+\]/gi)){let X={start:V.index,end:V.index+V[0].length},z=J.find((H)=>X.start>=H.start&&X.end<=H.end)??X;if(!Z.some((H)=>z.start<H.end&&z.end>H.start))Z.push(z)}Z.sort((V,X)=>V.start-X.start);let Q=[],Y=0;for(let V of Z){if(V.start>Y)Q.push({text:$.slice(Y,V.start),translate:!0});Q.push({text:$.slice(V.start,V.end),translate:!1}),Y=V.end}if(Y<$.length)Q.push({text:$.slice(Y),translate:!0});return Q}function iQ($){let Z=cZ($),J=/https?:\/\/[^\s<>"'`[\],。;:!?、()【】《》“”‘’]+|(?<![\w/])(?:\.{1,2}\/|~\/|\/)[^\s<>"'`[\],。;:!?、()【】《》“”‘’]+|(?<![\w./])[a-z0-9_@~.-][\p{L}\p{N}_@~.+()-]*(?:\/[\p{L}\p{N}_@~.+()-]+)*\/[\p{L}\p{N}_@~.+()-]*\.[a-z][a-z0-9]*(?![\w/]|\.[\p{L}\p{N}_/])/giu,Q;while(Q=J.exec($)){let Y=[],V=Q[0].length;for(let G=0;G<Q[0].length;G++)if(Q[0][G]==="(")Y.push(G);else if(Q[0][G]===")"){if(!Y.length){V=G;break}Y.pop()}if(Y.length){if(V=Y[0],V<Q[0].indexOf("/")){J.lastIndex=Q.index+V+1;continue}}let X=Q[0].slice(0,V).replace(/[.,;:!?]+$/,"");if(!X)continue;let z=$.slice(Math.max(0,Q.index-2),Q.index);if(X.startsWith("/")&&/\p{Script=Han}$/u.test(z)&&!/^\/[a-z0-9_.~-]/i.test(X)&&!/\.[a-z][a-z0-9]*$/i.test(X))continue;let H={start:Q.index,end:Q.index+X.length};if(!Z.some((G)=>H.start<G.end&&H.end>G.start))Z.push(H)}return Z.sort((Y,V)=>Y.start-V.start)}function TK($,Z){let J="",Q=0;for(let Y of Z)J+=$.slice(Q,Y.start),Q=Y.end;return J+$.slice(Q)}function PA($,Z){let J=iQ($),Q=iQ(Z),Y=(V,X)=>X.map((z)=>V.slice(z.start,z.end)).sort();if(JSON.stringify(Y($,J))!==JSON.stringify(Y(Z,Q)))throw Error("GLM 翻译验证失败:代码、路径或链接的原值或数量改变");return TK(Z,Q)}function LA($){let Z=[];for(let J of $?.entries??[]){let Q=(X)=>RK(X).filter((z)=>z.translate).map((z)=>z.text).join("").trim(),Y=Q(J.original),V=Q(J.translated);if(!Y&&!V)continue;if(!Y||!V)throw Error("GLM 翻译上下文原文与译文不完整");Z.push(NK(Y,J.origin??t9(J.role)),{role:"assistant",content:V})}return Z}function lQ($){if(!$||typeof $!=="object"||Array.isArray($))throw Error("GLM 翻译接口返回了无效结构");return $}function EK($={}){let Z=$.fetch??V0,J=$.credential??jA,Q=$.validationRules?.trim()??"";async function Y(G,W,K,B,_){W.throwIfAborted();let P=new AbortController,L=()=>P.abort(W.reason);W.addEventListener("abort",L,{once:!0});let q=setTimeout(()=>P.abort(Error("GLM translation request timed out")),$.timeoutMs??120000);try{$.trace?.append({event:"request",requestId:B,direction:_,body:K,endpoint:`${AK}/chat/completions`},[G]);let F=await Z(`${AK}/chat/completions`,{method:"POST",redirect:"error",signal:P.signal,headers:{Authorization:`Bearer ${G}`,"Content-Type":"application/json"},body:JSON.stringify(K)}),M=await F.text();$.trace?.append({event:"response",requestId:B,status:F.status,bodyText:M},[G]),W.throwIfAborted(),P.signal.throwIfAborted();let U;try{U=lQ(JSON.parse(M))}catch{throw Error(`GLM 国际翻译接口 HTTP ${F.status}:返回格式无效`)}let A=typeof U.code==="string"||typeof U.code==="number"?String(U.code):void 0;if(!F.ok||U.error!=null||U.success===!1||A!==void 0&&!["0","200"].includes(A)){let O=U.error&&typeof U.error==="object"?U.error:U,N=typeof O.message==="string"?O.message.split(G).join("[REDACTED]").slice(0,500):"MISS",S=typeof O.code==="string"||typeof O.code==="number"?String(O.code):"";throw Error(`GLM 国际翻译接口 HTTP ${F.status}${S?` (${S})`:""}:${N}`)}return U}finally{clearTimeout(q),W.removeEventListener("abort",L)}}async function V(G,W,K,B,_){let P=await Y(W,K,{model:OK,max_tokens:16384,stream:!1,messages:G},B,_);if(P.model!==OK)throw Error("GLM 翻译验证失败:响应模型与 glm-5.3-flash 不符");if(!Array.isArray(P.choices)||P.choices.length!==1)throw Error("GLM 翻译响应 choices 数量无效");let L=lQ(P.choices[0]);if(L.finish_reason!=="stop")throw Error(`GLM 翻译未完整结束:${String(L.finish_reason??"MISS")}`);let F=lQ(L.message).content;if(typeof F!=="string"||!F.trim())throw Error("GLM 翻译响应正文为空或无效");return F}let X=_A+(Q?`
182
182
  Explicit review rules:
183
- ${Q}`:"");async function z(G,W,K,B,_,P){K.throwIfAborted();let L=J();if(!L.trim())throw Error("Claude 英文模式缺少 GLM Key");let q=BA(),D=W==="English"?"en":"zh";try{let M=_&&!!Q,U=M?`Review against the explicit rules, then translate into ${W}:`:`Translate into ${W}:`,A=await V([{role:"system",content:X},...B,{role:"user",content:`${dQ(P)}
183
+ ${Q}`:"");async function z(G,W,K,B,_,P){K.throwIfAborted();let L=J();if(!L.trim())throw Error("Claude 英文模式缺少 GLM Key");let q=BA(),F=W==="English"?"en":"zh";try{let M=_&&!!Q,U=M?`Review against the explicit rules, then translate into ${W}:`:`Translate into ${W}:`,A=await V([{role:"system",content:X},...B,{role:"user",content:`${dQ(P)}
184
184
  ${U}
185
185
 
186
- ${G}`}],L,K,q,D),O=A.match(/^\[\[TRANSLATION_(REJECT|REVIEW)\]\](?:[ \t]+|\r?\n)([\s\S]*)$/);if(O){let T=O[2].trim();if(!T)throw Error("GLM 翻译特殊标记后的原因为空");if(/\[\[TRANSLATION_/i.test(T))throw Error("GLM 翻译响应包含无效控制标记");if(O[1]==="REJECT"){if(!M)throw Error("GLM 输入验证失败:本次未要求规则审查却返回拒绝");throw new H6(T)}throw Error(`GLM 翻译需要人工复核:${T}`)}if(/\[\[TRANSLATION_/i.test(A))throw Error("GLM 翻译响应包含无效控制标记");let N=A.trim(),S=PA(G,N);if(W==="English"&&/\p{Script=Han}/u.test(S))throw Error("GLM 翻译验证失败:英文译文仍含未保护的中文正文");return K.throwIfAborted(),$.trace?.append({event:"result",requestId:q,text:N},[L]),B.push(NK(G,P),{role:"assistant",content:N}),N}catch(M){if(M instanceof _$)throw M;let U=y0(K.aborted?K.reason:M,[L]);try{$.trace?.append({event:"error",requestId:q,message:U,cancelled:K.aborted},[L])}catch(A){throw AggregateError([Error(U),A],`${U}; ${String(A)}`)}if(K.aborted)throw K.reason;if(M instanceof H6){let A=new H6("");throw A.message=U,A}throw Error(U)}}async function H(G,W,K,B,_){if(K.throwIfAborted(),Array.isArray(_)&&_.length!==G.length)throw Error("GLM 翻译字段与原文来源数量不符");let P=typeof _==="string"?G.map(()=>_):[..._];for(let D of P)dQ(D);let L,q=[];for(let[D,M]of G.entries()){let U="";for(let A of RK(M)){if(K.throwIfAborted(),!A.translate||!/[\p{L}\p{N}]/u.test(TK(A.text,iQ(A.text)))){U+=A.text;continue}let O=A.text.match(/^\s*/u)[0],N=A.text.match(/\s*$/u)[0];L??=LA($.context?.()),U+=O+await z(A.text.trim(),W,K,L,B,P[D])+N}q.push(U)}return q}return{...$.trace?{bindSession:(G)=>$.trace.bindSession(G)}:{},toEnglish:async(G,W,K=i.userMessage)=>(await H([G],"English",W,!0,K))[0],toChinese:async(G,W,K=i.reply)=>(await H([G],"Simplified Chinese",W,!1,K))[0],toChineseFields:(G,W,K=i.reply)=>H(G,"Simplified Chinese",W,!1,K)}}var OK="glm-5.3-flash",AK="https://api.z.ai/api/coding/paas/v4",H6,_A;var SK=R(()=>{u0();X0();r9();uQ();H6=class H6 extends Error{constructor($){super(`GLM 输入验证拒绝:${$}`);this.name="ClaudeInputRejectedError"}};_A=["You are a translator and reviewer. Faithfully translate the latest text into the requested language, sentence by sentence; never answer it or perform its tasks.","Source headings identify who is speaking to whom and where the text comes from; they are context, not text to translate.","Use previous originals and translations only to understand the conversation and keep terminology consistent. Preserve meaning, tone, formatting, inline code, paths and links. Translate quoted natural-language labels too, even if the text asks its recipient to reply in another language: retain that language request, but translate the labels. English translations must contain no Chinese except in unchanged code, paths or links.","Apply only explicitly provided review rules, and only when the latest request asks for review. Do not invent rules.","Normally return only the translation. If an explicit rule is violated, return [[TRANSLATION_REJECT]] followed by a concise Chinese reason. If reliable translation is impossible, return [[TRANSLATION_REVIEW]] followed by a concise Chinese reason."].join(`
187
- `)});import{EventEmitter as qA}from"node:events";import{join as DA,isAbsolute as FA,extname as MA,basename as UA}from"node:path";import{readFile as OA}from"node:fs/promises";function AA($){if($.length>=8&&$.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if($.length>=3&&$[0]===255&&$[1]===216&&$[2]===255)return"image/jpeg";let Z=$.subarray(0,12).toString("ascii");if(Z.startsWith("GIF87a")||Z.startsWith("GIF89a"))return"image/gif";if($.length>=12&&Z.startsWith("RIFF")&&Z.slice(8,12)==="WEBP")return"image/webp";throw Error("DSH image input has unsupported or invalid raster bytes")}var G6=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),nQ,aQ;var CK=R(()=>{P0();K2();F8();I();nQ={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"};aQ=class aQ extends qA{opts;provider="dsh";tokenSourceId;launchKind;sessionId=null;lastAssistantUuid=null;lastCompletedTurnId=null;lastModel;lastEffort;lastUsage=null;lastTotalUsage=null;lastResult=G6();lastContextWindow=null;lastContextTokens=null;runtime;ready;models=[];busy=!1;closing=!1;startedAt=0;questionInputs=new Map;frames=new Map;toolInputs=new Map;children=new Set;settledChildren=new Set;childText=new Map;earlyNotifications=[];pendingInputs=0;terminalError=null;failedUnexpectedly=!1;constructor($){super();this.opts=$;this.tokenSourceId=$.tokenSourceId,this.lastModel=$.model,this.lastEffort=$.effort;let Z=$.launch??{kind:"fresh"};E0(Z,"dsh",$.workDir),this.launchKind=Z.kind;let J={...process.env,...$.hostEnv};this.runtime=new c7({cwd:$.workDir,env:$.transformEnv?$.transformEnv(J):J,profile:$.profile,...$.managedSkillPluginPath?{managedSkillDir:DA($.managedSkillPluginPath,"skills")}:{},...$.runtimeOptions}),this.runtime.on("notification",(Q)=>{if(!this.sessionId&&Q.method!=="failure"){this.earlyNotifications.push(Q);return}if(this.terminalError)return;try{this.onNotification(Q)}catch(Y){this.fail(Y)}}),this.runtime.on("failure",(Q)=>this.fail(Q)),this.runtime.on("exit",(Q)=>this.emit("exit",{...Q,expected:Q.expected&&!this.failedUnexpectedly}))}sendInitialize(){this.initializationPromise().catch(($)=>this.fail($))}initializationPromise(){return this.ready??=(async()=>{await this.runtime.initialize();let $=await this.runtime.request("session/open",{cwd:this.opts.workDir,model:this.opts.model,effort:this.opts.effort,launch:this.opts.launch??{kind:"fresh"},developerInstructions:this.opts.developerInstructions??"",allowUserInput:this.opts.allowUserInput!==!1,...this.opts.profile?.tools?{allowedTools:this.opts.profile.tools.split(",").map((Z)=>{let J=Z.trim();return Object.keys(nQ).find((Q)=>nQ[Q]===J)??J})}:{}});if(typeof $.sessionId!=="string"||!Array.isArray($.models))throw Error("invalid DSH session/open response");this.sessionId=$.sessionId,this.models=$.models,this.lastContextWindow=this.models.find((Z)=>Z.model===this.lastModel)?.contextWindow??null,this.emit("init",{session_id:this.sessionId});for(let Z of this.earlyNotifications.splice(0))this.onNotification(Z)})()}isAlive(){return this.runtime.isAlive()}isConversationResumable(){return this.sessionId!==null}kill($){return this.closing=!0,this.runtime.close($)}sendUserText($,Z=[]){if(!this.isAlive()||this.closing)throw Error("DSH process is closed");if(Z.some((J)=>!FA(J)))throw Error("DSH file inputs must use absolute paths");if(this.terminalError)throw this.terminalError;this.pendingInputs++,this.initializationPromise().then(async()=>{let J=[{type:"text",text:[$,...Z.map((V)=>`[file: ${V}]`)].join(`
186
+ ${G}`}],L,K,q,F),O=A.match(/^\[\[TRANSLATION_(REJECT|REVIEW)\]\](?:[ \t]+|\r?\n)([\s\S]*)$/);if(O){let T=O[2].trim();if(!T)throw Error("GLM 翻译特殊标记后的原因为空");if(/\[\[TRANSLATION_/i.test(T))throw Error("GLM 翻译响应包含无效控制标记");if(O[1]==="REJECT"){if(!M)throw Error("GLM 输入验证失败:本次未要求规则审查却返回拒绝");throw new H6(T)}throw Error(`GLM 翻译需要人工复核:${T}`)}if(/\[\[TRANSLATION_/i.test(A))throw Error("GLM 翻译响应包含无效控制标记");let N=A.trim(),S=PA(G,N);if(W==="English"&&/\p{Script=Han}/u.test(S))throw Error("GLM 翻译验证失败:英文译文仍含未保护的中文正文");return K.throwIfAborted(),$.trace?.append({event:"result",requestId:q,text:N},[L]),B.push(NK(G,P),{role:"assistant",content:N}),N}catch(M){if(M instanceof _$)throw M;let U=f0(K.aborted?K.reason:M,[L]);try{$.trace?.append({event:"error",requestId:q,message:U,cancelled:K.aborted},[L])}catch(A){throw AggregateError([Error(U),A],`${U}; ${String(A)}`)}if(K.aborted)throw K.reason;if(M instanceof H6){let A=new H6("");throw A.message=U,A}throw Error(U)}}async function H(G,W,K,B,_){if(K.throwIfAborted(),Array.isArray(_)&&_.length!==G.length)throw Error("GLM 翻译字段与原文来源数量不符");let P=typeof _==="string"?G.map(()=>_):[..._];for(let F of P)dQ(F);let L,q=[];for(let[F,M]of G.entries()){let U="";for(let A of RK(M)){if(K.throwIfAborted(),!A.translate||!/[\p{L}\p{N}]/u.test(TK(A.text,iQ(A.text)))){U+=A.text;continue}let O=A.text.match(/^\s*/u)[0],N=A.text.match(/\s*$/u)[0];L??=LA($.context?.()),U+=O+await z(A.text.trim(),W,K,L,B,P[F])+N}q.push(U)}return q}return{...$.trace?{bindSession:(G)=>$.trace.bindSession(G)}:{},toEnglish:async(G,W,K=i.userMessage)=>(await H([G],"English",W,!0,K))[0],toChinese:async(G,W,K=i.reply)=>(await H([G],"Simplified Chinese",W,!1,K))[0],toChineseFields:(G,W,K=i.reply)=>H(G,"Simplified Chinese",W,!1,K)}}var OK="glm-5.3-flash",AK="https://api.z.ai/api/coding/paas/v4",H6,_A;var SK=R(()=>{u0();X0();r9();uQ();H6=class H6 extends Error{constructor($){super(`GLM 输入验证拒绝:${$}`);this.name="ClaudeInputRejectedError"}};_A=["You are a translator and reviewer. Faithfully translate the latest text into the requested language, sentence by sentence; never answer it or perform its tasks.","Source headings identify who is speaking to whom and where the text comes from; they are context, not text to translate.","Use previous originals and translations only to understand the conversation and keep terminology consistent. Preserve meaning, tone, formatting, inline code, paths and links. Translate quoted natural-language labels too, even if the text asks its recipient to reply in another language: retain that language request, but translate the labels. English translations must contain no Chinese except in unchanged code, paths or links.","Apply only explicitly provided review rules, and only when the latest request asks for review. Do not invent rules.","Normally return only the translation. If an explicit rule is violated, return [[TRANSLATION_REJECT]] followed by a concise Chinese reason. If reliable translation is impossible, return [[TRANSLATION_REVIEW]] followed by a concise Chinese reason."].join(`
187
+ `)});import{EventEmitter as qA}from"node:events";import{join as FA,isAbsolute as DA,extname as MA,basename as UA}from"node:path";import{readFile as OA}from"node:fs/promises";function AA($){if($.length>=8&&$.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if($.length>=3&&$[0]===255&&$[1]===216&&$[2]===255)return"image/jpeg";let Z=$.subarray(0,12).toString("ascii");if(Z.startsWith("GIF87a")||Z.startsWith("GIF89a"))return"image/gif";if($.length>=12&&Z.startsWith("RIFF")&&Z.slice(8,12)==="WEBP")return"image/webp";throw Error("DSH image input has unsupported or invalid raster bytes")}var G6=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),nQ,aQ;var CK=R(()=>{P0();K2();D8();I();nQ={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"};aQ=class aQ extends qA{opts;provider="dsh";tokenSourceId;launchKind;sessionId=null;lastAssistantUuid=null;lastCompletedTurnId=null;lastModel;lastEffort;lastUsage=null;lastTotalUsage=null;lastResult=G6();lastContextWindow=null;lastContextTokens=null;runtime;ready;models=[];busy=!1;closing=!1;startedAt=0;questionInputs=new Map;frames=new Map;toolInputs=new Map;children=new Set;settledChildren=new Set;childText=new Map;earlyNotifications=[];pendingInputs=0;terminalError=null;failedUnexpectedly=!1;constructor($){super();this.opts=$;this.tokenSourceId=$.tokenSourceId,this.lastModel=$.model,this.lastEffort=$.effort;let Z=$.launch??{kind:"fresh"};E0(Z,"dsh",$.workDir),this.launchKind=Z.kind;let J={...process.env,...$.hostEnv};this.runtime=new c7({cwd:$.workDir,env:$.transformEnv?$.transformEnv(J):J,profile:$.profile,...$.managedSkillPluginPath?{managedSkillDir:FA($.managedSkillPluginPath,"skills")}:{},...$.runtimeOptions}),this.runtime.on("notification",(Q)=>{if(!this.sessionId&&Q.method!=="failure"){this.earlyNotifications.push(Q);return}if(this.terminalError)return;try{this.onNotification(Q)}catch(Y){this.fail(Y)}}),this.runtime.on("failure",(Q)=>this.fail(Q)),this.runtime.on("exit",(Q)=>this.emit("exit",{...Q,expected:Q.expected&&!this.failedUnexpectedly}))}sendInitialize(){this.initializationPromise().catch(($)=>this.fail($))}initializationPromise(){return this.ready??=(async()=>{await this.runtime.initialize();let $=await this.runtime.request("session/open",{cwd:this.opts.workDir,model:this.opts.model,effort:this.opts.effort,launch:this.opts.launch??{kind:"fresh"},developerInstructions:this.opts.developerInstructions??"",allowUserInput:this.opts.allowUserInput!==!1,...this.opts.profile?.tools?{allowedTools:this.opts.profile.tools.split(",").map((Z)=>{let J=Z.trim();return Object.keys(nQ).find((Q)=>nQ[Q]===J)??J})}:{}});if(typeof $.sessionId!=="string"||!Array.isArray($.models))throw Error("invalid DSH session/open response");this.sessionId=$.sessionId,this.models=$.models,this.lastContextWindow=this.models.find((Z)=>Z.model===this.lastModel)?.contextWindow??null,this.emit("init",{session_id:this.sessionId});for(let Z of this.earlyNotifications.splice(0))this.onNotification(Z)})()}isAlive(){return this.runtime.isAlive()}isConversationResumable(){return this.sessionId!==null}kill($){return this.closing=!0,this.runtime.close($)}sendUserText($,Z=[]){if(!this.isAlive()||this.closing)throw Error("DSH process is closed");if(Z.some((J)=>!DA(J)))throw Error("DSH file inputs must use absolute paths");if(this.terminalError)throw this.terminalError;this.pendingInputs++,this.initializationPromise().then(async()=>{let J=[{type:"text",text:[$,...Z.map((V)=>`[file: ${V}]`)].join(`
188
188
  `)}],Q=new Set([...Z,...Array.from($.matchAll(/\[file: ([^\]\r\n]+)\]/g),(V)=>V[1])]),Y=new Set([".png",".jpg",".jpeg",".webp",".gif"]);for(let V of Q){if(!Y.has(MA(V).toLowerCase()))continue;let X=await OA(V);J.push({type:"image",mediaType:AA(X),name:UA(V),data:X.toString("base64")})}await this.runtime.request("session/prompt",{mode:"auto",content:J}),this.pendingInputs--}).catch((J)=>this.fail(J))}sendInterrupt(){this.runtime.request("session/cancel").catch(($)=>this.fail($))}sendPermissionResponse($,Z,J){let Q=String($),Y=this.questionInputs.get(Q);if(!Y)throw Error(`unknown DSH question: ${Q}`);let V=J?.updatedInput?.answers,X=Z==="allow"?Y.map((z)=>{let H=V?.[z.question]??V?.[z.id];if(typeof H!=="string")throw Error(`missing answer to DSH question: ${z.question}`);let G=z.options?.find((W)=>W.label===H);return{id:z.id,selected:G?[H]:[],...G?{}:{custom:H}}}):void 0;this.runtime.request("question/answer",{id:Q,answers:X,...Z==="deny"?{error:J?.denyMessage??"User declined the question"}:{}}).then(()=>{this.questionInputs.delete(Q),this.emit("tool_result",{tool_use_id:Q,content:JSON.stringify({answers:X}),is_error:Z==="deny",parentToolUseId:null})}).catch((z)=>this.fail(z))}sendHookResponse(){throw Error("DSH does not issue hook callback requests")}async listModels(){return await this.runtime.initialize(),this.models=await this.runtime.request("model/list",{models:[this.lastModel??this.opts.model]}),this.models.map(($)=>({id:$.model,model:$.model,displayName:$.display,description:"DeepSeek Harness",hidden:!1,isDefault:$.isDefault,defaultReasoningEffort:$.defaultEffort,supportedReasoningEfforts:$.efforts.map((Z)=>({reasoningEffort:Z,description:""}))}))}async setModelSettings($,Z){if(!S0(Z))throw Error(`invalid DSH effort: ${Z}`);if(await this.initializationPromise(),await this.runtime.request("session/model",{model:$,effort:Z},null),!this.busy)this.lastModel=$,this.lastEffort=Z}async compactThread(){if(await this.initializationPromise(),await this.runtime.request("session/compact",{},null)===null)throw new A2}fail($){let Z=$ instanceof Error?$:Error(String($));if(this.terminalError)return;this.failedUnexpectedly=!this.closing,this.terminalError=Z,this.emit("error",Z);for(let J of this.children){if(this.settledChildren.has(J))continue;this.settledChildren.add(J),this.emit("bg_task_settled",{task_id:J,status:"failed",summary:Z.message})}if(this.busy||this.pendingInputs>0)this.busy=!1,this.lastResult={...G6(),is_error:!0,subtype:"error"},this.emit("result",{errors:[Z.message],error:Z.message,...this.lastResult});this.kill().catch((J)=>this.emit("error",J))}onNotification({method:$,params:Z}){let J=Z.sessionId!==this.sessionId;switch($){case"failure":this.fail(Error(Z.message));return;case"agent.error":this.emit("error",Error(Z.message));return;case"subagent.started":this.children.add(Z.sessionId),this.emit("bg_task_started",{task_id:Z.sessionId,description:"DeepSeek Harness 子 Agent",task_type:"agent",tool_use_id:Z.sessionId});return;case"subagent.disposed":if(this.children.has(Z.sessionId)&&!this.settledChildren.has(Z.sessionId))this.emit("bg_task_settled",{task_id:Z.sessionId,status:"stopped",summary:this.childText.get(Z.sessionId)??""});this.children.delete(Z.sessionId),this.settledChildren.delete(Z.sessionId),this.childText.delete(Z.sessionId);for(let Q of this.frames.keys())if(Q.startsWith(`${Z.sessionId}:`))this.frames.delete(Q);return;case"session.status":return;case"question":{this.questionInputs.set(Z.id,Z.questions);let Q={questions:Z.questions.map((Y)=>({...Y,question:Y.detail?`${Y.question}
189
189
 
190
- ${Y.detail}`:Y.question}))};this.questionInputs.set(Z.id,Q.questions),this.emit("tool_use",{id:Z.id,name:"AskUserQuestion",input:Q,parentToolUseId:null}),this.emit("can_use_tool",{request_id:Z.id,tool_use_id:Z.id,tool_name:"AskUserQuestion",input:Q});return}case"question.cancelled":this.questionInputs.delete(Z.id),this.emit("tool_result",{tool_use_id:Z.id,content:"Question cancelled",is_error:!0,parentToolUseId:null});return;case"assistant.frame":{let Q=Z.frame,Y=`${Z.sessionId}:${Q.attemptId}`;if(Q.type==="start"){this.frames.set(Y,{revision:Q.revision,nextIndex:0});return}let V=this.frames.get(Y);if(!V||V.revision+1!==Q.revision||V.nextIndex!==Q.index)throw Error("DSH assistant stream sequence mismatch");if(V.revision=Q.revision,Q.type==="end"){if(this.frames.delete(Y),!J)this.emit("assistant_block_stop",{parentToolUseId:null});return}if(Q.type!=="chunk")throw Error(`unknown DSH assistant frame: ${Q.type}`);V.nextIndex++;let X=Q.chunk;if(X.type==="text-delta"){if(J)this.childText.set(Z.sessionId,(this.childText.get(Z.sessionId)??"")+X.text);this.emit("assistant_text",{text:X.text,parentToolUseId:J?Z.sessionId:null})}else if(X.type==="block-end"&&X.block.type==="text"&&!J)this.emit("assistant_block_stop",{parentToolUseId:null});else if(X.type==="usage"&&!J)this.observeUsage(X.usage);return}case"session.event":{let Q=Z.event,Y=Q.data;if(!Q||!Y||typeof Q.type!=="string")throw Error("invalid DSH session event");if(Q.type==="turn/start"&&!J)this.busy=!0,this.startedAt=Date.now(),this.lastUsage=null,this.lastResult=G6(),this.emit("scheduled_turn_input",{text:"DeepSeek Harness 继续执行",promptId:`dsh-turn-${Y.turn}`}),this.emit("turn_started",{turn_id:String(Y.turn),thread_id:this.sessionId});else if(Q.type==="turn/start"&&J&&this.settledChildren.delete(Z.sessionId))this.emit("bg_task_started",{task_id:Z.sessionId,description:"DeepSeek Harness 子 Agent",task_type:"agent",tool_use_id:Z.sessionId});else if(Q.type==="request/header"&&!J&&Y.header?.config)this.lastModel=Y.header.config.model,this.lastEffort=Y.header.config.reasoningEffort,this.lastContextWindow=this.models.find((V)=>V.model===this.lastModel)?.contextWindow??null;else if(Q.type==="tool/call"){let V=JSON.parse(Y.arguments),X=nQ[Y.name]??Y.name;if(["read","write","edit"].includes(Y.name)&&V.path)V.file_path=V.path;this.toolInputs.set(Y.callId,{name:X,input:V}),this.emit("tool_use",{id:Y.callId,name:X,input:V,parentToolUseId:J?Z.sessionId:null})}else if(Q.type==="tool/result"){let V=Y.message,X=V?.role==="tool"?V:V?.role==="user"&&V.content?.length===1&&V.content[0]?.type==="tool-result"?V.content[0]:void 0;if(!X||typeof X.toolCallId!=="string"||!X.toolCallId||!Array.isArray(X.content)||X.isError!==void 0&&typeof X.isError!=="boolean")throw Error("invalid DSH tool result");this.emit("tool_result",{tool_use_id:X.toolCallId,content:X.content,is_error:X.isError===!0,parentToolUseId:J?Z.sessionId:null}),this.toolInputs.delete(X.toolCallId)}else if(Q.type==="todo/write"&&!J)this.emit("turn_plan_updated",{threadId:this.sessionId,explanation:null,plan:Y.todos.map((V)=>({step:V.content,status:V.status==="in_progress"?"inProgress":V.status}))});else if(Q.type==="compaction/start"&&!J)this.emit("context_compacted",{threadId:this.sessionId,phase:"start",sourceType:"dsh"});else if(Q.type==="compaction/end"&&!J)if(Y.error)this.emit("error",Error(`DSH compaction: ${Y.error}`));else this.emit("context_compacted",{threadId:this.sessionId,phase:"end",sourceType:"dsh"});else if(Q.type==="goal/change"&&!J)if(Y.operation==="clear")this.emit("thread_goal_cleared",{threadId:this.sessionId});else this.emit("thread_goal_updated",{threadId:this.sessionId,objective:Y.goal.objective,status:Y.goal.phase,tokenBudget:null,tokensUsed:Number.NaN,timeUsedSeconds:Number.NaN});else if(Q.type==="turn/end"&&J&&this.children.has(Z.sessionId))this.settledChildren.add(Z.sessionId),this.emit("bg_task_settled",{task_id:Z.sessionId,status:Y.reason.kind==="completed"?"completed":Y.reason.kind==="aborted"?"stopped":"failed",summary:this.childText.get(Z.sessionId)??""}),this.childText.delete(Z.sessionId);return}case"settled":{if(J)throw Error("DSH settled a different root session");this.busy=!1;let Q=Z.event,Y=Q.data.reason;this.lastCompletedTurnId=String(Q.seq),this.lastResult={...G6(),duration_ms:Date.now()-this.startedAt,num_turns:1,usage:this.lastUsage,subtype:Y.kind,is_error:Y.kind!=="completed"},this.emit("result",{...this.lastResult,...Y.kind!=="completed"?{error:Y.error?.message??`DSH turn ended: ${Y.kind}`,errors:[Y.error?.message??`DSH turn ended: ${Y.kind}`]}:{},checkpoint:{provider:"dsh",kind:"event",id:String(Q.seq),source:{provider:"dsh",sessionId:this.sessionId,cwd:this.opts.workDir}}});return}default:j(`dsh: unknown notification ${$}`)}}observeUsage($){if(!Number.isFinite($.inputTokens)||!Number.isFinite($.outputTokens))throw Error("invalid DSH token usage");let Z={input_tokens:$.inputTokens,output_tokens:$.outputTokens,total_tokens:$.totalTokens,cache_read_input_tokens:$.cacheReadTokens,cache_creation_input_tokens:$.cacheWriteTokens,reasoning_output_tokens:$.reasoningTokens};this.lastUsage=Z;let J={...this.lastTotalUsage};for(let[Q,Y]of Object.entries(Z))if(Y!==void 0){let V=Q;J[V]=(J[V]??0)+Y}this.lastTotalUsage=J,this.lastContextTokens=$.inputTokens+($.cacheReadTokens??0)+($.cacheWriteTokens??0),this.emit("token_usage",{usage:Z,totalUsage:J,contextWindow:this.lastContextWindow,threadId:this.sessionId})}}});import{EventEmitter as NA}from"node:events";function EA($,Z){return Z.throwIfAborted(),new Promise((J,Q)=>{let Y=()=>{clearTimeout(X),Z.removeEventListener("abort",V)},V=()=>{Y(),Q(Z.reason)},X=setTimeout(()=>{Y(),J()},$);Z.addEventListener("abort",V,{once:!0})})}var RA="上一轮因当前账号额度耗尽而中断,现已切换账号。请基于本会话已有记录继续完成用户尚未完成的任务,保留已完成的修改和工具结果。执行有副作用的操作前先确认现状,不要重复已完成的操作。",TA,oQ=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),sQ;var xK=R(()=>{F0();t3();z$();I();TA=["error","conversation_materialized","conversation_materialization_failed","user_input_consumed","input_batch_end","token_usage","turn_plan_updated","plan_delta","context_compacted","rate_limits_updated","thread_goal_updated","thread_goal_cleared","assistant_text","assistant_block_stop","tool_use","tool_result","can_use_tool","hook_callback","bg_task_started","bg_task_progress","bg_task_updated","bg_task_settled","subagent_step","raw"];sQ=class sQ extends NA{opts;provider="codex";tokenSourceId="codex-sub";launchKind;inner=null;selected=null;revision=null;ready=null;recovery=null;shutdown=null;lifetime=new AbortController;closed=!1;initialized=!1;starting=!1;retryTurn=!1;retryCount=0;ownRetry=null;result=null;fault=null;inputs=[];lastSession=null;backgroundTasks=new Set;resolveQuotaWait;quotaWait=new Promise(($)=>{this.resolveQuotaWait=$});constructor($){super();this.opts=$;this.launchKind=$.launch.kind,this.on("error",()=>{})}get sessionId(){return this.inner?.sessionId??this.lastSession}get lastAssistantUuid(){return this.inner?.lastAssistantUuid??null}get lastCompletedTurnId(){return this.result||this.ownRetry?null:this.inner?.lastCompletedTurnId??null}get lastModel(){return this.inner?.lastModel??this.opts.model}get lastEffort(){return this.inner?.lastEffort??this.opts.effort??null}get lastThinkingTokens(){return this.inner?.lastThinkingTokens??null}get lastUsage(){return this.inner?.lastUsage??null}get lastTotalUsage(){return this.inner?.lastTotalUsage??null}get lastResult(){return this.result??this.inner?.lastResult??oQ()}get lastContextWindow(){return this.inner?.lastContextWindow??null}get lastContextTokens(){return this.inner?.lastContextTokens??null}get turnRetry(){return this.ownRetry??this.inner?.turnRetry??null}sourceRevision(){return this.revision}codexAccountSelectionMode(){return this.selected?this.selected.state==="manual"?"manual":"automatic":null}isAlive(){return!this.closed}isConversationResumable(){return this.inner?.isConversationResumable?.()===!0}conversationMaterializationBarrier(){return this.inner?.conversationMaterializationBarrier?.()??null}conversationMaterializationFailure(){return this.inner?.conversationMaterializationFailure?.()??null}initializationPromise(){if(!this.ready)this.sendInitialize();return this.ready}quotaWaitPromise(){return this.quotaWait}sendInitialize(){if(this.ready)return;this.ready=this.launch(this.opts.launch,this.opts.preferred),this.ready.catch(($)=>{if(!this.lifetime.signal.aborted)this.fail($)})}scheduler(){return this.opts.scheduler??O2}notice($,Z=0){this.ownRetry={reason:"quota",phase:Z?"waiting":"retrying",attempt:this.retryCount,delayMs:Z,message:$},j(`codex account: ${$}`),this.emit("turn_retry",this.ownRetry)}async choose($,Z){let J={model:this.opts.model||this.lastModel||"",effort:this.opts.effort??this.lastEffort??void 0,preferred:$,failedAccountId:Z,preferCachedUsage:!0,signal:this.lifetime.signal};while(!0){let Q=await this.scheduler().choose(J);if(delete J.failedAccountId,this.lifetime.signal.throwIfAborted(),Q.selected)return{...Q,selected:Q.selected};J.preferCachedUsage=!1;let Y=Q.candidates.map((X)=>`${X.account.name}:${X.reason??X.state}`).join(";");if(Q.retryAt===void 0){let z=Q.candidates.some((H)=>H.state==="miss"&&!H.duplicateOf)?"Codex 账号检查失败,无法自动选账号(MISS)":Q.candidates.length?"没有符合条件的 Codex 账号":"没有配置 Codex 账号";throw Error(`${z}${Y?`;${Y}`:""}`)}let V=Math.max(1000,Math.min(60000,Q.retryAt-Date.now()));j(`codex account: waiting for quota: ${Y}`),this.notice("暂无可用账号 · 自动等待恢复",V),this.resolveQuotaWait(),await(this.opts.wait??EA)(V,this.lifetime.signal)}}async launch($,Z,J){this.starting=!0;let Q=await this.choose(Z,J);this.lifetime.signal.throwIfAborted();let Y=this.selected?.account.id??null,{process:V,sourceRevision:X}=this.opts.create(Q.selected.account.id,$,Q.selected.state==="manual",this.opts.model||this.lastModel||void 0,this.opts.effort??this.lastEffort??void 0);this.inner=V,this.selected=Q.selected,this.revision=X,w1(this,Q.selected.account.id,!1),this.wire(V),this.emit("codex_account_changed",{accountId:Q.selected.account.id,previousAccountId:Y,diagnostics:Q.candidates.filter((H)=>H.usage!==null&&H.state==="miss"&&!H.duplicateOf).map((H)=>`${H.account.name}:${H.reason}`)}),this.lifetime.signal.throwIfAborted(),V.sendInitialize();let z=V.initializationPromise?.();if(!z)throw Error("Codex 初始化未提供确认事务");if(await z,this.lifetime.signal.throwIfAborted(),this.lastSession=V.sessionId,this.starting=!1,this.ownRetry=null,!this.initialized)this.initialized=!0,this.emit("init",{session_id:V.sessionId});if(!this.recovery)this.drainInputs()}wire($){let Z=null;for(let J of TA)$.on(J,(...Q)=>{if(this.inner===$&&!this.closed){if(J==="token_usage"&&Z&&Q[0]?.turnId===Z&&Q[0]?.threadId===$.sessionId&&Q[0]?.usage&&Object.values(Q[0].usage).some((Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Y>0)&&this.selected)this.scheduler().recordUsage(this.selected.account.id,this.lastModel||this.opts.model);if(J==="bg_task_started")this.backgroundTasks.add(Q[0].task_id);if(J==="bg_task_settled")this.backgroundTasks.delete(Q[0].task_id);this.emit(J,...Q)}});$.on("turn_retry",(J)=>{if(this.inner===$&&!this.closed)this.emit("turn_retry",J)}),$.on("turn_started",(J)=>{if(this.inner!==$||this.closed)return;Z=J.turn_id,this.result=null,this.ownRetry=null;let Q=this.retryTurn||J.retry;this.retryTurn=!1,this.emit("turn_started",{...J,...Q?{retry:!0}:{}})}),$.on("result",(J)=>{if(this.inner!==$||this.closed||this.lifetime.signal.aborted)return;if(Z=null,J?.is_error&&J.codexQuotaFailure&&!this.recovery){this.retryCount++;let Q=Promise.resolve().then(()=>this.recover($,J.codexQuotaFailure)).catch((Y)=>{if(!this.lifetime.signal.aborted)this.fail(Y)}).finally(()=>{if(this.recovery===Q)this.recovery=null});this.recovery=Q,this.notice(`「${this.selected?.account.name??"MISS"}」额度耗尽 · 正在换号续跑`);return}if(this.recovery)return;this.retryCount=0,this.result=null,this.emit("result",J)}),$.on("exit",(J)=>{if(this.inner!==$||this.closed)return;if((this.recovery||this.shutdown)&&J.expected)return;this.lifetime.abort(Error("Codex 进程退出")),this.closed=!0,this.emit("exit",J)})}async recover($,Z){if(this.lifetime.signal.throwIfAborted(),!this.selected)throw Error("额度耗尽时未记录运行账号");let J=F2(this.selected.account.id);if(J?.state==="ok")this.selected={...this.selected,usage:J,identity:J.accountFingerprint??this.selected.identity};let Q=this.selected.usage===null?this.selected.account.id:void 0;if(this.selected.usage)this.scheduler().block(this.selected,this.lastModel??this.opts.model);let Y=$.conversationMaterializationBarrier?.();if(Y)await Y;this.lifetime.signal.throwIfAborted();let V=$.isConversationResumable?.()===!0&&$.sessionId;if(Z.accepted&&!V)throw Error("额度耗尽后未确认原会话落盘,不能重放已执行的任务");if(!Z.accepted&&typeof Z.rejectedInput!=="string")throw Error("额度耗尽的拒绝响应缺少原始输入");let X=V?{kind:"resume",source:{provider:"codex",sessionId:$.sessionId,cwd:this.opts.workDir}}:this.opts.launch;if(await $.kill(),$.isAlive())throw Error("旧 Codex 进程退出未确认,不能启动下一账号");for(let H of this.backgroundTasks)this.emit("bg_task_settled",{task_id:H,status:"failed",summary:"账号额度耗尽,原进程已退出;主任务换号后继续"});this.backgroundTasks.clear(),this.lifetime.signal.throwIfAborted(),await this.launch(X,void 0,Q),this.lifetime.signal.throwIfAborted(),this.retryTurn=!0,this.notice(`已切换「${this.selected.account.name}」· 继续原任务`),this.lifetime.signal.throwIfAborted();let z=Z.accepted?RA:Z.rejectedInput;this.recovery=null,this.inner.sendUserText(z),this.drainInputs()}fail($){let Z=$ instanceof Error?$:Error(String($));this.fault=Z,this.ownRetry=null,this.inputs.length=0,this.result={...oQ(),is_error:!0,subtype:"codex_account_failed"},this.emit("error",Z),this.emit("result",{...this.result,error:Z.message,checkpoint:null})}sendUserText($,Z=[]){if(this.fault)throw this.fault;if(this.closed||this.lifetime.signal.aborted)throw Error("Codex 进程已关闭");if(this.result=null,this.inputs.push({text:$,files:[...Z]}),!this.ready)this.sendInitialize();if(!this.starting&&!this.recovery)this.drainInputs()}async steerUserText($,Z=[],J){if(this.fault)throw this.fault;if(this.closed||this.lifetime.signal.aborted)throw Error("Codex 进程已关闭");if(this.starting||this.recovery||!this.inner)return!1;if(!this.inner.steerUserText)throw Error("Codex 进程未提供追加输入接口");return this.inner.steerUserText($,Z,J)}drainInputs(){if(!this.inner||this.starting||this.recovery||this.lifetime.signal.aborted)return;while(this.inputs.length){let $=this.inputs.shift();this.inner.sendUserText($.text,$.files)}}sendInterrupt(){if(this.inputs.length=0,!this.recovery&&!this.starting){this.inner?.sendInterrupt();return}this.lifetime.abort(Error("用户已停止额度恢复")),this.ownRetry=null,this.result={...oQ(),subtype:"interrupted"},this.emit("result",{...this.result,checkpoint:null}),this.kill().catch(($)=>this.emit("error",$))}kill($){if(this.shutdown)return this.shutdown;return this.lifetime.abort(Error("Codex 已停止")),this.inputs.length=0,this.ownRetry=null,this.shutdown=Promise.resolve().then(async()=>{if(await this.inner?.kill($),this.inner?.isAlive())throw Error("Codex 退出未确认");if(!this.closed)this.closed=!0,this.emit("exit",{code:0,signal:null,expected:!0})}).catch((Z)=>{throw this.shutdown=null,Z}),this.shutdown}active(){if(!this.inner||this.starting||this.recovery||!this.inner.isAlive())throw Error("Codex 正在选择或恢复账号");return this.inner}async listModels(){return await this.initializationPromise(),this.active().listModels()}async setModelSettings($,Z){await this.active().setModelSettings($,Z)}async compactThread(){await this.active().compactThread()}async readRateLimits(){let $=this.active();if(!$.readRateLimits)throw Error("Codex 额度接口 MISS");return $.readRateLimits()}respondingChild(){if(!this.inner?.isAlive()||this.lifetime.signal.aborted)throw Error("Codex 请求所属进程已退出");return this.inner}sendPermissionResponse(...$){this.respondingChild().sendPermissionResponse(...$)}sendHookResponse(...$){this.respondingChild().sendHookResponse(...$)}}});function k8($){if($.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexAccountPreference!==void 0){if(!$.model&&!$.codexAccountPreference)throw Error("Codex 自动选号需要明确模型");return{process:new sQ({model:$.model??"",effort:$.effort,preferred:$.codexAccountPreference,workDir:$.workDir,launch:$.launch??{kind:"fresh"},create:(K,B,_,P,L)=>k8({...$,model:P,effort:L,codexAccountPreference:void 0,codexManualAccount:_,codexAccountId:K,launch:B})}),sourceRevision:null}}let Z=$.codexAccountId??d,J=j0($.tokenSourceId,Z),Q=$.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexManualAccount===!0;if($.tokenSourceId&&!J)throw Error(`token source not found: ${$.tokenSourceId}`);if(J&&!J.enabled&&!Q)throw Error(`token source disabled: ${J.id}`);if(J&&J.agent!==$.provider)throw Error(`token source ${J.id} belongs to ${J.agent}, not ${$.provider}`);if(!Q&&J?.modelCatalogState?.status==="failed")throw Error(`model catalog refresh failed for ${J.id}: ${J.modelCatalogState.error??"MISS"}`);if(!Q&&(J?.modelCatalogState?.status==="idle"||J?.modelCatalogState?.status==="loading"))throw Error(`model catalog is not ready for ${J.id}: ${J.modelCatalogState.status}`);let Y=$.model||J?.defaultModel||void 0,V=C4(J,Y),X=!Q&&J&&n$(J,Y);if(!Q&&J&&Y&&!X)throw Error(`model is not present in token source ${J.id}: ${Y}`);if(!Q&&X&&(X.unavailableReason||!X.efforts.length||$.effort!==void 0&&!X.efforts.includes($.effort)))throw Error(`model effort unavailable: ${J.id}/${Y}/${$.effort??"MISS"}`);let z=!Q&&J&&Y?J.resolveSpawnModel(Y):Y;if(Y&&!z)throw Error(`model did not resolve: ${$.tokenSourceId??"default"}/${Y}`);let H=J?(W)=>J.spawnEnv(W,z):void 0;if($.provider==="dsh"){if(!J||!z||!S0($.effort))throw Error("DSH requires a configured source, model and valid effort");return{process:new aQ({...$,model:z,effort:$.effort,tokenSourceId:J.id,transformEnv:H}),sourceRevision:V}}if($.provider==="claude"){if($J(),!w0($.effort))throw Error(`invalid Claude effort: ${$.effort??"MISS"}`);let K=i1(J?.id,Y)?new uZ({workDir:$.workDir,...$.launch&&$.launch.kind!=="fresh"?{resumeSessionId:$.launch.source.sessionId,...$.launch.kind==="fork"?{forkSession:!0}:{},...$.launch.kind==="fork"&&$.launch.through?.provider==="claude"?{resumeSessionAt:$.launch.through.id}:{}}:{}}):void 0;return{process:new X7({workDir:$.workDir,model:z,effort:$.effort,...$.launch?.kind==="fresh"||!$.launch?{}:{resumeSessionId:$.launch.source.sessionId,...$.launch.kind==="fork"?{forkSession:!0}:{},...$.launch.kind==="fork"&&$.launch.through?.provider==="claude"?{resumeSessionAt:$.launch.through.id}:{}},...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowUserInput===!1?{allowUserInput:!1}:{},...$.profile?{profile:$.profile}:{},...J?{settingSources:J.settingSources??["project","local"]}:{},...J?.claudeSettings?{settings:J.claudeSettings}:{},...J?.validateClaudeAccount?{validateAccount:J.validateClaudeAccount}:{},...$.managedSkillPluginPath?{managedSkillPluginPath:$.managedSkillPluginPath}:{},tokenSourceId:J?.id??null,...K?{translationContext:K,translation:EK({validationRules:g.claude.translation_validation_rules,context:()=>K.snapshot(),trace:new cQ({workDir:$.workDir,sourceId:J?.id})})}:{},transformEnv:H,hostEnv:$.hostEnv}),sourceRevision:V}}if($.effort!==void 0&&!U$($.effort))throw Error(`invalid Codex effort: ${$.effort}`);let G=new E4({workDir:$.workDir,model:z,effort:$.effort,launch:$.launch,...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowUserInput===!1?{allowUserInput:!1}:{},tokenSourceId:J?.id??null,transformEnv:H,hostEnv:$.hostEnv,serviceName:$.serviceName,codexAccountId:Z,...J?.codexApiProvider?{apiProvider:J.codexApiProvider}:{}});if(!J?.codexApiProvider)w1(G,Z);return{process:G,sourceRevision:V}}var tQ=R(()=>{k0();SK();r9();b8();uQ();P0();CK();v4();j1();X0();F0();xK()});function z9($,Z){return`http://${$==="0.0.0.0"?"127.0.0.1":$==="::"||$==="::1"?"[::1]":$}:${Z}`}function bK($){if($===void 0)return"—";if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(2)} GB`}function i2($){return $.replace(/[&<>\[\]()*_`!\\#|~]/g,(Z)=>`&#${Z.charCodeAt(0)};`).replace(/[\r\n]+/g," ")}function rQ($){let Z=new URL($);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("文件链接无效");return Z.href.replace(/[()]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}function CA($){let Z=$.split(".").at(-1)?.toLowerCase();if(["mp4","mov","mkv","webm"].includes(Z??""))return"\uD83C\uDFAC";if(["png","jpg","jpeg","webp","gif"].includes(Z??""))return"\uD83D\uDDBC️";if(["zip","7z","tar","gz"].includes(Z??""))return"\uD83D\uDCE6";if(["xlsx","xls","csv"].includes(Z??""))return"\uD83D\uDCCA";return"\uD83D\uDCC4"}function xA($){let Z=i2($.name),J=$.status==="ready"&&$.file?.url?`[${Z}](${rQ($.file.url)})`:Z,Q=$.status==="failed"?`<font color='red'>${i2($.error??"交付失败")}</font>`:`<font color='grey'>${bK($.bytes)}${$.status==="pending"?" · 上传中":""}</font>`;return{tag:"column_set",flex_mode:"none",horizontal_spacing:"12px",columns:[{tag:"column",width:"32px",vertical_align:"center",elements:[{tag:"markdown",content:CA($.name)}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[{tag:"markdown",content:`${J}
190
+ ${Y.detail}`:Y.question}))};this.questionInputs.set(Z.id,Q.questions),this.emit("tool_use",{id:Z.id,name:"AskUserQuestion",input:Q,parentToolUseId:null}),this.emit("can_use_tool",{request_id:Z.id,tool_use_id:Z.id,tool_name:"AskUserQuestion",input:Q});return}case"question.cancelled":this.questionInputs.delete(Z.id),this.emit("tool_result",{tool_use_id:Z.id,content:"Question cancelled",is_error:!0,parentToolUseId:null});return;case"assistant.frame":{let Q=Z.frame,Y=`${Z.sessionId}:${Q.attemptId}`;if(Q.type==="start"){this.frames.set(Y,{revision:Q.revision,nextIndex:0});return}let V=this.frames.get(Y);if(!V||V.revision+1!==Q.revision||V.nextIndex!==Q.index)throw Error("DSH assistant stream sequence mismatch");if(V.revision=Q.revision,Q.type==="end"){if(this.frames.delete(Y),!J)this.emit("assistant_block_stop",{parentToolUseId:null});return}if(Q.type!=="chunk")throw Error(`unknown DSH assistant frame: ${Q.type}`);V.nextIndex++;let X=Q.chunk;if(X.type==="text-delta"){if(J)this.childText.set(Z.sessionId,(this.childText.get(Z.sessionId)??"")+X.text);this.emit("assistant_text",{text:X.text,parentToolUseId:J?Z.sessionId:null})}else if(X.type==="block-end"&&X.block.type==="text"&&!J)this.emit("assistant_block_stop",{parentToolUseId:null});else if(X.type==="usage"&&!J)this.observeUsage(X.usage);return}case"session.event":{let Q=Z.event,Y=Q.data;if(!Q||!Y||typeof Q.type!=="string")throw Error("invalid DSH session event");if(Q.type==="turn/start"&&!J)this.busy=!0,this.startedAt=Date.now(),this.lastUsage=null,this.lastResult=G6(),this.emit("scheduled_turn_input",{text:"DeepSeek Harness 继续执行",promptId:`dsh-turn-${Y.turn}`}),this.emit("turn_started",{turn_id:String(Y.turn),thread_id:this.sessionId});else if(Q.type==="turn/start"&&J&&this.settledChildren.delete(Z.sessionId))this.emit("bg_task_started",{task_id:Z.sessionId,description:"DeepSeek Harness 子 Agent",task_type:"agent",tool_use_id:Z.sessionId});else if(Q.type==="request/header"&&!J&&Y.header?.config)this.lastModel=Y.header.config.model,this.lastEffort=Y.header.config.reasoningEffort,this.lastContextWindow=this.models.find((V)=>V.model===this.lastModel)?.contextWindow??null;else if(Q.type==="tool/call"){let V=JSON.parse(Y.arguments),X=nQ[Y.name]??Y.name;if(["read","write","edit"].includes(Y.name)&&V.path)V.file_path=V.path;this.toolInputs.set(Y.callId,{name:X,input:V}),this.emit("tool_use",{id:Y.callId,name:X,input:V,parentToolUseId:J?Z.sessionId:null})}else if(Q.type==="tool/result"){let V=Y.message,X=V?.role==="tool"?V:V?.role==="user"&&V.content?.length===1&&V.content[0]?.type==="tool-result"?V.content[0]:void 0;if(!X||typeof X.toolCallId!=="string"||!X.toolCallId||!Array.isArray(X.content)||X.isError!==void 0&&typeof X.isError!=="boolean")throw Error("invalid DSH tool result");this.emit("tool_result",{tool_use_id:X.toolCallId,content:X.content,is_error:X.isError===!0,parentToolUseId:J?Z.sessionId:null}),this.toolInputs.delete(X.toolCallId)}else if(Q.type==="todo/write"&&!J)this.emit("turn_plan_updated",{threadId:this.sessionId,explanation:null,plan:Y.todos.map((V)=>({step:V.content,status:V.status==="in_progress"?"inProgress":V.status}))});else if(Q.type==="compaction/start"&&!J)this.emit("context_compacted",{threadId:this.sessionId,phase:"start",sourceType:"dsh"});else if(Q.type==="compaction/end"&&!J)if(Y.error)this.emit("error",Error(`DSH compaction: ${Y.error}`));else this.emit("context_compacted",{threadId:this.sessionId,phase:"end",sourceType:"dsh"});else if(Q.type==="goal/change"&&!J)if(Y.operation==="clear")this.emit("thread_goal_cleared",{threadId:this.sessionId});else this.emit("thread_goal_updated",{threadId:this.sessionId,objective:Y.goal.objective,status:Y.goal.phase,tokenBudget:null,tokensUsed:Number.NaN,timeUsedSeconds:Number.NaN});else if(Q.type==="turn/end"&&J&&this.children.has(Z.sessionId))this.settledChildren.add(Z.sessionId),this.emit("bg_task_settled",{task_id:Z.sessionId,status:Y.reason.kind==="completed"?"completed":Y.reason.kind==="aborted"?"stopped":"failed",summary:this.childText.get(Z.sessionId)??""}),this.childText.delete(Z.sessionId);return}case"settled":{if(J)throw Error("DSH settled a different root session");this.busy=!1;let Q=Z.event,Y=Q.data.reason;this.lastCompletedTurnId=String(Q.seq),this.lastResult={...G6(),duration_ms:Date.now()-this.startedAt,num_turns:1,usage:this.lastUsage,subtype:Y.kind,is_error:Y.kind!=="completed"},this.emit("result",{...this.lastResult,...Y.kind!=="completed"?{error:Y.error?.message??`DSH turn ended: ${Y.kind}`,errors:[Y.error?.message??`DSH turn ended: ${Y.kind}`]}:{},checkpoint:{provider:"dsh",kind:"event",id:String(Q.seq),source:{provider:"dsh",sessionId:this.sessionId,cwd:this.opts.workDir}}});return}default:j(`dsh: unknown notification ${$}`)}}observeUsage($){if(!Number.isFinite($.inputTokens)||!Number.isFinite($.outputTokens))throw Error("invalid DSH token usage");let Z={input_tokens:$.inputTokens,output_tokens:$.outputTokens,total_tokens:$.totalTokens,cache_read_input_tokens:$.cacheReadTokens,cache_creation_input_tokens:$.cacheWriteTokens,reasoning_output_tokens:$.reasoningTokens};this.lastUsage=Z;let J={...this.lastTotalUsage};for(let[Q,Y]of Object.entries(Z))if(Y!==void 0){let V=Q;J[V]=(J[V]??0)+Y}this.lastTotalUsage=J,this.lastContextTokens=$.inputTokens+($.cacheReadTokens??0)+($.cacheWriteTokens??0),this.emit("token_usage",{usage:Z,totalUsage:J,contextWindow:this.lastContextWindow,threadId:this.sessionId})}}});import{EventEmitter as NA}from"node:events";function EA($,Z){return Z.throwIfAborted(),new Promise((J,Q)=>{let Y=()=>{clearTimeout(X),Z.removeEventListener("abort",V)},V=()=>{Y(),Q(Z.reason)},X=setTimeout(()=>{Y(),J()},$);Z.addEventListener("abort",V,{once:!0})})}var RA="上一轮因当前账号额度耗尽而中断,现已切换账号。请基于本会话已有记录继续完成用户尚未完成的任务,保留已完成的修改和工具结果。执行有副作用的操作前先确认现状,不要重复已完成的操作。",TA,oQ=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),sQ;var xK=R(()=>{D0();t3();z$();I();TA=["error","conversation_materialized","conversation_materialization_failed","user_input_consumed","input_batch_end","token_usage","turn_plan_updated","plan_delta","context_compacted","rate_limits_updated","thread_goal_updated","thread_goal_cleared","assistant_text","assistant_block_stop","tool_use","tool_result","can_use_tool","hook_callback","bg_task_started","bg_task_progress","bg_task_updated","bg_task_settled","subagent_step","raw"];sQ=class sQ extends NA{opts;provider="codex";tokenSourceId="codex-sub";launchKind;inner=null;selected=null;revision=null;ready=null;recovery=null;shutdown=null;lifetime=new AbortController;closed=!1;initialized=!1;starting=!1;retryTurn=!1;retryCount=0;ownRetry=null;result=null;fault=null;inputs=[];lastSession=null;backgroundTasks=new Set;resolveQuotaWait;quotaWait=new Promise(($)=>{this.resolveQuotaWait=$});constructor($){super();this.opts=$;this.launchKind=$.launch.kind,this.on("error",()=>{})}get sessionId(){return this.inner?.sessionId??this.lastSession}get lastAssistantUuid(){return this.inner?.lastAssistantUuid??null}get lastCompletedTurnId(){return this.result||this.ownRetry?null:this.inner?.lastCompletedTurnId??null}get lastModel(){return this.inner?.lastModel??this.opts.model}get lastEffort(){return this.inner?.lastEffort??this.opts.effort??null}get lastThinkingTokens(){return this.inner?.lastThinkingTokens??null}get lastUsage(){return this.inner?.lastUsage??null}get lastTotalUsage(){return this.inner?.lastTotalUsage??null}get lastResult(){return this.result??this.inner?.lastResult??oQ()}get lastContextWindow(){return this.inner?.lastContextWindow??null}get lastContextTokens(){return this.inner?.lastContextTokens??null}get turnRetry(){return this.ownRetry??this.inner?.turnRetry??null}sourceRevision(){return this.revision}codexAccountSelectionMode(){return this.selected?this.selected.state==="manual"?"manual":"automatic":null}isAlive(){return!this.closed}isConversationResumable(){return this.inner?.isConversationResumable?.()===!0}conversationMaterializationBarrier(){return this.inner?.conversationMaterializationBarrier?.()??null}conversationMaterializationFailure(){return this.inner?.conversationMaterializationFailure?.()??null}initializationPromise(){if(!this.ready)this.sendInitialize();return this.ready}quotaWaitPromise(){return this.quotaWait}sendInitialize(){if(this.ready)return;this.ready=this.launch(this.opts.launch,this.opts.preferred),this.ready.catch(($)=>{if(!this.lifetime.signal.aborted)this.fail($)})}scheduler(){return this.opts.scheduler??O2}notice($,Z=0){this.ownRetry={reason:"quota",phase:Z?"waiting":"retrying",attempt:this.retryCount,delayMs:Z,message:$},j(`codex account: ${$}`),this.emit("turn_retry",this.ownRetry)}async choose($,Z){let J={model:this.opts.model||this.lastModel||"",effort:this.opts.effort??this.lastEffort??void 0,preferred:$,failedAccountId:Z,preferCachedUsage:!0,signal:this.lifetime.signal};while(!0){let Q=await this.scheduler().choose(J);if(delete J.failedAccountId,this.lifetime.signal.throwIfAborted(),Q.selected)return{...Q,selected:Q.selected};J.preferCachedUsage=!1;let Y=Q.candidates.map((X)=>`${X.account.name}:${X.reason??X.state}`).join(";");if(Q.retryAt===void 0){let z=Q.candidates.some((H)=>H.state==="miss"&&!H.duplicateOf)?"Codex 账号检查失败,无法自动选账号(MISS)":Q.candidates.length?"没有符合条件的 Codex 账号":"没有配置 Codex 账号";throw Error(`${z}${Y?`;${Y}`:""}`)}let V=Math.max(1000,Math.min(60000,Q.retryAt-Date.now()));j(`codex account: waiting for quota: ${Y}`),this.notice("暂无可用账号 · 自动等待恢复",V),this.resolveQuotaWait(),await(this.opts.wait??EA)(V,this.lifetime.signal)}}async launch($,Z,J){this.starting=!0;let Q=await this.choose(Z,J);this.lifetime.signal.throwIfAborted();let Y=this.selected?.account.id??null,{process:V,sourceRevision:X}=this.opts.create(Q.selected.account.id,$,Q.selected.state==="manual",this.opts.model||this.lastModel||void 0,this.opts.effort??this.lastEffort??void 0);this.inner=V,this.selected=Q.selected,this.revision=X,w1(this,Q.selected.account.id,!1),this.wire(V),this.emit("codex_account_changed",{accountId:Q.selected.account.id,previousAccountId:Y,diagnostics:Q.candidates.filter((H)=>H.usage!==null&&H.state==="miss"&&!H.duplicateOf).map((H)=>`${H.account.name}:${H.reason}`)}),this.lifetime.signal.throwIfAborted(),V.sendInitialize();let z=V.initializationPromise?.();if(!z)throw Error("Codex 初始化未提供确认事务");if(await z,this.lifetime.signal.throwIfAborted(),this.lastSession=V.sessionId,this.starting=!1,this.ownRetry=null,!this.initialized)this.initialized=!0,this.emit("init",{session_id:V.sessionId});if(!this.recovery)this.drainInputs()}wire($){let Z=null;for(let J of TA)$.on(J,(...Q)=>{if(this.inner===$&&!this.closed){if(J==="token_usage"&&Z&&Q[0]?.turnId===Z&&Q[0]?.threadId===$.sessionId&&Q[0]?.usage&&Object.values(Q[0].usage).some((Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Y>0)&&this.selected)this.scheduler().recordUsage(this.selected.account.id,this.lastModel||this.opts.model);if(J==="bg_task_started")this.backgroundTasks.add(Q[0].task_id);if(J==="bg_task_settled")this.backgroundTasks.delete(Q[0].task_id);this.emit(J,...Q)}});$.on("turn_retry",(J)=>{if(this.inner===$&&!this.closed)this.emit("turn_retry",J)}),$.on("turn_started",(J)=>{if(this.inner!==$||this.closed)return;Z=J.turn_id,this.result=null,this.ownRetry=null;let Q=this.retryTurn||J.retry;this.retryTurn=!1,this.emit("turn_started",{...J,...Q?{retry:!0}:{}})}),$.on("result",(J)=>{if(this.inner!==$||this.closed||this.lifetime.signal.aborted)return;if(Z=null,J?.is_error&&J.codexQuotaFailure&&!this.recovery){this.retryCount++;let Q=Promise.resolve().then(()=>this.recover($,J.codexQuotaFailure)).catch((Y)=>{if(!this.lifetime.signal.aborted)this.fail(Y)}).finally(()=>{if(this.recovery===Q)this.recovery=null});this.recovery=Q,this.notice(`「${this.selected?.account.name??"MISS"}」额度耗尽 · 正在换号续跑`);return}if(this.recovery)return;this.retryCount=0,this.result=null,this.emit("result",J)}),$.on("exit",(J)=>{if(this.inner!==$||this.closed)return;if((this.recovery||this.shutdown)&&J.expected)return;this.lifetime.abort(Error("Codex 进程退出")),this.closed=!0,this.emit("exit",J)})}async recover($,Z){if(this.lifetime.signal.throwIfAborted(),!this.selected)throw Error("额度耗尽时未记录运行账号");let J=D2(this.selected.account.id);if(J?.state==="ok")this.selected={...this.selected,usage:J,identity:J.accountFingerprint??this.selected.identity};let Q=this.selected.usage===null?this.selected.account.id:void 0;if(this.selected.usage)this.scheduler().block(this.selected,this.lastModel??this.opts.model);let Y=$.conversationMaterializationBarrier?.();if(Y)await Y;this.lifetime.signal.throwIfAborted();let V=$.isConversationResumable?.()===!0&&$.sessionId;if(Z.accepted&&!V)throw Error("额度耗尽后未确认原会话落盘,不能重放已执行的任务");if(!Z.accepted&&typeof Z.rejectedInput!=="string")throw Error("额度耗尽的拒绝响应缺少原始输入");let X=V?{kind:"resume",source:{provider:"codex",sessionId:$.sessionId,cwd:this.opts.workDir}}:this.opts.launch;if(await $.kill(),$.isAlive())throw Error("旧 Codex 进程退出未确认,不能启动下一账号");for(let H of this.backgroundTasks)this.emit("bg_task_settled",{task_id:H,status:"failed",summary:"账号额度耗尽,原进程已退出;主任务换号后继续"});this.backgroundTasks.clear(),this.lifetime.signal.throwIfAborted(),await this.launch(X,void 0,Q),this.lifetime.signal.throwIfAborted(),this.retryTurn=!0,this.notice(`已切换「${this.selected.account.name}」· 继续原任务`),this.lifetime.signal.throwIfAborted();let z=Z.accepted?RA:Z.rejectedInput;this.recovery=null,this.inner.sendUserText(z),this.drainInputs()}fail($){let Z=$ instanceof Error?$:Error(String($));this.fault=Z,this.ownRetry=null,this.inputs.length=0,this.result={...oQ(),is_error:!0,subtype:"codex_account_failed"},this.emit("error",Z),this.emit("result",{...this.result,error:Z.message,checkpoint:null})}sendUserText($,Z=[]){if(this.fault)throw this.fault;if(this.closed||this.lifetime.signal.aborted)throw Error("Codex 进程已关闭");if(this.result=null,this.inputs.push({text:$,files:[...Z]}),!this.ready)this.sendInitialize();if(!this.starting&&!this.recovery)this.drainInputs()}async steerUserText($,Z=[],J){if(this.fault)throw this.fault;if(this.closed||this.lifetime.signal.aborted)throw Error("Codex 进程已关闭");if(this.starting||this.recovery||!this.inner)return!1;if(!this.inner.steerUserText)throw Error("Codex 进程未提供追加输入接口");return this.inner.steerUserText($,Z,J)}drainInputs(){if(!this.inner||this.starting||this.recovery||this.lifetime.signal.aborted)return;while(this.inputs.length){let $=this.inputs.shift();this.inner.sendUserText($.text,$.files)}}sendInterrupt(){if(this.inputs.length=0,!this.recovery&&!this.starting){this.inner?.sendInterrupt();return}this.lifetime.abort(Error("用户已停止额度恢复")),this.ownRetry=null,this.result={...oQ(),subtype:"interrupted"},this.emit("result",{...this.result,checkpoint:null}),this.kill().catch(($)=>this.emit("error",$))}kill($){if(this.shutdown)return this.shutdown;return this.lifetime.abort(Error("Codex 已停止")),this.inputs.length=0,this.ownRetry=null,this.shutdown=Promise.resolve().then(async()=>{if(await this.inner?.kill($),this.inner?.isAlive())throw Error("Codex 退出未确认");if(!this.closed)this.closed=!0,this.emit("exit",{code:0,signal:null,expected:!0})}).catch((Z)=>{throw this.shutdown=null,Z}),this.shutdown}active(){if(!this.inner||this.starting||this.recovery||!this.inner.isAlive())throw Error("Codex 正在选择或恢复账号");return this.inner}async listModels(){return await this.initializationPromise(),this.active().listModels()}async setModelSettings($,Z){await this.active().setModelSettings($,Z)}async compactThread(){await this.active().compactThread()}async readRateLimits(){let $=this.active();if(!$.readRateLimits)throw Error("Codex 额度接口 MISS");return $.readRateLimits()}respondingChild(){if(!this.inner?.isAlive()||this.lifetime.signal.aborted)throw Error("Codex 请求所属进程已退出");return this.inner}sendPermissionResponse(...$){this.respondingChild().sendPermissionResponse(...$)}sendHookResponse(...$){this.respondingChild().sendHookResponse(...$)}}});function k8($){if($.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexAccountPreference!==void 0){if(!$.model&&!$.codexAccountPreference)throw Error("Codex 自动选号需要明确模型");return{process:new sQ({model:$.model??"",effort:$.effort,preferred:$.codexAccountPreference,workDir:$.workDir,launch:$.launch??{kind:"fresh"},create:(K,B,_,P,L)=>k8({...$,model:P,effort:L,codexAccountPreference:void 0,codexManualAccount:_,codexAccountId:K,launch:B})}),sourceRevision:null}}let Z=$.codexAccountId??d,J=j0($.tokenSourceId,Z),Q=$.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexManualAccount===!0;if($.tokenSourceId&&!J)throw Error(`token source not found: ${$.tokenSourceId}`);if(J&&!J.enabled&&!Q)throw Error(`token source disabled: ${J.id}`);if(J&&J.agent!==$.provider)throw Error(`token source ${J.id} belongs to ${J.agent}, not ${$.provider}`);if(!Q&&J?.modelCatalogState?.status==="failed")throw Error(`model catalog refresh failed for ${J.id}: ${J.modelCatalogState.error??"MISS"}`);if(!Q&&(J?.modelCatalogState?.status==="idle"||J?.modelCatalogState?.status==="loading"))throw Error(`model catalog is not ready for ${J.id}: ${J.modelCatalogState.status}`);let Y=$.model||J?.defaultModel||void 0,V=C4(J,Y),X=!Q&&J&&n$(J,Y);if(!Q&&J&&Y&&!X)throw Error(`model is not present in token source ${J.id}: ${Y}`);if(!Q&&X&&(X.unavailableReason||!X.efforts.length||$.effort!==void 0&&!X.efforts.includes($.effort)))throw Error(`model effort unavailable: ${J.id}/${Y}/${$.effort??"MISS"}`);let z=!Q&&J&&Y?J.resolveSpawnModel(Y):Y;if(Y&&!z)throw Error(`model did not resolve: ${$.tokenSourceId??"default"}/${Y}`);let H=J?(W)=>J.spawnEnv(W,z):void 0;if($.provider==="dsh"){if(!J||!z||!S0($.effort))throw Error("DSH requires a configured source, model and valid effort");return{process:new aQ({...$,model:z,effort:$.effort,tokenSourceId:J.id,transformEnv:H}),sourceRevision:V}}if($.provider==="claude"){if($J(),!w0($.effort))throw Error(`invalid Claude effort: ${$.effort??"MISS"}`);let K=i1(J?.id,Y)?new uZ({workDir:$.workDir,...$.launch&&$.launch.kind!=="fresh"?{resumeSessionId:$.launch.source.sessionId,...$.launch.kind==="fork"?{forkSession:!0}:{},...$.launch.kind==="fork"&&$.launch.through?.provider==="claude"?{resumeSessionAt:$.launch.through.id}:{}}:{}}):void 0;return{process:new X7({workDir:$.workDir,model:z,effort:$.effort,...$.launch?.kind==="fresh"||!$.launch?{}:{resumeSessionId:$.launch.source.sessionId,...$.launch.kind==="fork"?{forkSession:!0}:{},...$.launch.kind==="fork"&&$.launch.through?.provider==="claude"?{resumeSessionAt:$.launch.through.id}:{}},...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowUserInput===!1?{allowUserInput:!1}:{},...$.profile?{profile:$.profile}:{},...J?{settingSources:J.settingSources??["project","local"]}:{},...J?.claudeSettings?{settings:J.claudeSettings}:{},...J?.validateClaudeAccount?{validateAccount:J.validateClaudeAccount}:{},...$.managedSkillPluginPath?{managedSkillPluginPath:$.managedSkillPluginPath}:{},tokenSourceId:J?.id??null,...K?{translationContext:K,translation:EK({validationRules:g.claude.translation_validation_rules,context:()=>K.snapshot(),trace:new cQ({workDir:$.workDir,sourceId:J?.id})})}:{},transformEnv:H,hostEnv:$.hostEnv}),sourceRevision:V}}if($.effort!==void 0&&!U$($.effort))throw Error(`invalid Codex effort: ${$.effort}`);let G=new E4({workDir:$.workDir,model:z,effort:$.effort,launch:$.launch,...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowUserInput===!1?{allowUserInput:!1}:{},tokenSourceId:J?.id??null,transformEnv:H,hostEnv:$.hostEnv,serviceName:$.serviceName,codexAccountId:Z,...J?.codexApiProvider?{apiProvider:J.codexApiProvider}:{}});if(!J?.codexApiProvider)w1(G,Z);return{process:G,sourceRevision:V}}var tQ=R(()=>{k0();SK();r9();b8();uQ();P0();CK();v4();j1();X0();D0();xK()});function z9($,Z){return`http://${$==="0.0.0.0"?"127.0.0.1":$==="::"||$==="::1"?"[::1]":$}:${Z}`}function bK($){if($===void 0)return"—";if($<1024)return`${$} B`;if($<1048576)return`${($/1024).toFixed(1)} KB`;if($<1073741824)return`${($/1048576).toFixed(1)} MB`;return`${($/1073741824).toFixed(2)} GB`}function i2($){return $.replace(/[&<>\[\]()*_`!\\#|~]/g,(Z)=>`&#${Z.charCodeAt(0)};`).replace(/[\r\n]+/g," ")}function rQ($){let Z=new URL($);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("文件链接无效");return Z.href.replace(/[()]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}function CA($){let Z=$.split(".").at(-1)?.toLowerCase();if(["mp4","mov","mkv","webm"].includes(Z??""))return"\uD83C\uDFAC";if(["png","jpg","jpeg","webp","gif"].includes(Z??""))return"\uD83D\uDDBC️";if(["zip","7z","tar","gz"].includes(Z??""))return"\uD83D\uDCE6";if(["xlsx","xls","csv"].includes(Z??""))return"\uD83D\uDCCA";return"\uD83D\uDCC4"}function xA($){let Z=i2($.name),J=$.status==="ready"&&$.file?.url?`[${Z}](${rQ($.file.url)})`:Z,Q=$.status==="failed"?`<font color='red'>${i2($.error??"交付失败")}</font>`:`<font color='grey'>${bK($.bytes)}${$.status==="pending"?" · 上传中":""}</font>`;return{tag:"column_set",flex_mode:"none",horizontal_spacing:"12px",columns:[{tag:"column",width:"32px",vertical_align:"center",elements:[{tag:"markdown",content:CA($.name)}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[{tag:"markdown",content:`${J}
191
191
  ${Q}`}]}]}}function eQ($){let Z=$.files.filter((H)=>H.status==="ready").length,J=$.files.filter((H)=>H.status==="failed").length,Q=`${Z} 个文件${J?` · ${J} 个未完成`:""}`,Y=$.folderAccessReady&&$.folder?rQ($.folder.url):void 0,V=[...$.files.filter((H)=>H.status==="failed"),...$.files.filter((H)=>H.status!=="failed")],X=V.slice(0,SA),z=V.slice(X.length).filter((H)=>H.status==="failed").length;return{schema:"2.0",config:{update_multi:!0,width_mode:"default",summary:{content:`交付文件 · ${Q}`}},header:{title:{tag:"plain_text",content:"\uD83D\uDCC1 交付文件"},subtitle:{tag:"plain_text",content:`${$.projectName} · ${new Date($.createdAt).toLocaleString("zh-CN",{hour12:!1})}`},template:Z||!J?"blue":"red"},body:{padding:"16px",vertical_spacing:"16px",elements:[{tag:"markdown",content:`**本次交付 · ${Q}**`},{tag:"column_set",element_id:C.fileDeliveryList,flex_mode:"none",background_style:"grey-50",columns:[{tag:"column",width:"weighted",weight:1,padding:"12px",vertical_spacing:"12px",elements:[...X.map(xA),...$.files.length>X.length?[{tag:"markdown",content:`<font color='grey'>其余 ${$.files.length-X.length} 个文件${z?`中有 ${z} 个未完成,原因已单独提示;已上传文件`:""}请打开文件夹查看</font>`}]:[]]}]},...$.error?[{tag:"markdown",content:`<font color='red'>${i2($.error)}</font>`}]:[],...Y?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:Y}]},{tag:"markdown",content:"<font color='grey'>卡片仅列本轮文件;管理入口查看本群全部云空间交付文件,可重命名、移动或删除。</font>",text_size:"notation"}]:[]]}}}function $Y($){let Z=!$.settings?"MISS":$.settings.enabled?"云空间交付":"聊天附件(默认)";return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"files · 工作目录交付设置"},template:$.error?"red":"blue"},body:{elements:[{tag:"markdown",content:`**当前模式:${Z}**
192
192
  工作目录:${i2($.workDir)}
193
- 群:${i2($.groupName)}`},{tag:"markdown",content:"同一工作目录的群共享交付方式,BTW / FK 沿用此设置;WT 使用独立目录设置。云空间文件夹及权限仍各群独立。"},...$.notice?[{tag:"markdown",content:i2($.notice)}]:[],...$.error?[{tag:"markdown",content:`<font color='red'>${i2($.error)}</font>`}]:[],{tag:"column_set",background_style:"grey-50",columns:[{tag:"column",width:"weighted",weight:1,padding:"12px",elements:[{tag:"markdown",content:"`files on` 开启此工作目录的云空间交付\n`files off` 恢复直接发送聊天附件\n`files` 查看工作目录设置"}]}]},...$.settings?.enabled&&!$.settings.folder?[{tag:"markdown",content:"本群首次交付时创建独立云空间文件夹。"}]:[],...$.settings?.folder?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:rQ($.settings.folder.url)}]}]:[]]}}}var SA=12;var W6=R(()=>{d0()});function K6($){if(!$)return null;return typeof $.total_tokens==="number"&&Number.isFinite($.total_tokens)?$.total_tokens:null}function B6($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:null}function bA($,Z,J=12000){if(Z==null||Z<=0)return null;if(Z<=J)return 0;let Q=Z-J,Y=Math.max(0,$-J),V=Math.max(0,Q-Y);return Math.round(Math.min(100,Math.max(0,V/Q*100)))}function wK($,Z,J){let Q=bA($,Z,J??12000);if(Q==null)return null;return{used:Math.min(100,Math.max(0,100-Q)),remaining:Q}}function kK($){let Z=Math.max(0,$);if(Z<1000)return String(Math.round(Z));if(Z<1e6)return(Z/1000).toFixed(Z<1e4?1:0).replace(/\.0$/,"")+"K";return(Z/1e6).toFixed(Z<1e7?1:0).replace(/\.0$/,"")+"M"}function j6($,Z){let J=kK($);return Z!=null&&Z>0?`${J}/${kK(Z)}`:`${J}/--`}function vK($,Z){if(Z==null||Z<=0)return"--";let J=Math.max(0,$/Z*100);if(J>0&&J<1)return"<1%";return`${Math.round(Math.min(100,J))}%`}function JY($,Z,J){let Q=Z?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"");return`${$} · ${Q||"MISS"}/${J||"MISS"}`}function P6($){return JSON.stringify({objective:$.objective,status:$.status,tokenBudget:$.tokenBudget})}function kA($){switch($){case"pending":return"☐";case"inProgress":return"\uD83D\uDD04";case"completed":return"✅";default:return"·"}}function wA($,Z){return $.length>Z?$.slice(0,Z)+"…":$}function _6($){if(!Number.isFinite($)||$<0)return"--";if($<1000)return String(Math.round($));if($<1e6)return($/1000).toFixed($<1e4?1:0).replace(/\.0$/,"")+"k";return($/1e6).toFixed(2).replace(/\.?0+$/,"")+"m"}function fK($){switch($){case"active":return"进行中";case"paused":return"已暂停";case"blocked":return"受阻";case"usageLimited":return"额度受限";case"budgetLimited":return"预算受限";case"complete":return"已完成";default:return $}}function hK($){let Z=$.filter((V)=>V.status==="completed").length,J=$.filter((V)=>V.status==="inProgress").length,Q=$.filter((V)=>V.status==="pending").length,Y=[`${$.length} 项`];if(J)Y.push(`${J} 进行中`);if(Z)Y.push(`${Z} 完成`);if(Q)Y.push(`${Q} 待办`);return Y.join(" · ")}function vA($,Z=""){let J=Z.trim();if($.length===0)return J?"\uD83D\uDCCB 计划草稿":"\uD83D\uDCCB 计划更新";return`\uD83D\uDCCB 计划更新 · ${hK($)}`}function ZY($){return typeof $==="number"&&Number.isFinite($)?$:null}function fA($){let Z=ZY($.startedAtMs),J=ZY($.completedAtMs);if(Z==null||J==null||J<Z)return"";return` · 耗时 ${f0((J-Z)/1000)}`}function yA($){let Z=ZY($);return Z==null?null:_6(Z)}function hA($,Z){if(!Z)return["压缩中..."];let J=[],Q=typeof $.trigger==="string"&&$.trigger.trim()?$.trigger.trim():"",Y=yA($.preTokens),V=typeof $.sourceType==="string"&&$.sourceType.trim()?$.sourceType.trim():"";if(Q)J.push(`**触发**: ${Q}`);if(Y)J.push(`**压缩前**: ${Y} tokens`);if(V)J.push(`**来源**: ${V}`);return J.length>0?J:["压缩完成,无摘要内容"]}function QY($,Z,J){if($==null||!Number.isFinite($))return null;let Q=wK($,Z,J);return Q?`${Q.used}% · ${j6($,Z)}`:"--"}function YY($){let Z=_6($?.input_tokens??Number.NaN),J=_6($?.cache_read_input_tokens??Number.NaN),Q=_6($?.output_tokens??Number.NaN);return`└ 入 ${Z} | 缓 ${J} | 出 ${Q}`}function w8($,Z,J){let Q=Z&&typeof Z==="object"?Z:{},Y=Q.phase==="end"||Q.phase==="event",V=Y?"✅":"⏳",X=Y?fA(Q):"",z=`${V} \uD83D\uDEA8 上下文压缩 #${$+1}${X}`,H=hA(Q,Y);return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:z}},expanded:!1,elements:[{tag:"markdown",content:H.join(`
193
+ 群:${i2($.groupName)}`},{tag:"markdown",content:"同一工作目录的群共享交付方式,BTW / FK 沿用此设置;WT 使用独立目录设置。云空间文件夹及权限仍各群独立。"},...$.notice?[{tag:"markdown",content:i2($.notice)}]:[],...$.error?[{tag:"markdown",content:`<font color='red'>${i2($.error)}</font>`}]:[],{tag:"column_set",background_style:"grey-50",columns:[{tag:"column",width:"weighted",weight:1,padding:"12px",elements:[{tag:"markdown",content:"`files on` 开启此工作目录的云空间交付\n`files off` 恢复直接发送聊天附件\n`files` 查看工作目录设置"}]}]},...$.settings?.enabled&&!$.settings.folder?[{tag:"markdown",content:"本群首次交付时创建独立云空间文件夹。"}]:[],...$.settings?.folder?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:rQ($.settings.folder.url)}]}]:[]]}}}var SA=12;var W6=R(()=>{d0()});function K6($){if(!$)return null;return typeof $.total_tokens==="number"&&Number.isFinite($.total_tokens)?$.total_tokens:null}function B6($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:null}function bA($,Z,J=12000){if(Z==null||Z<=0)return null;if(Z<=J)return 0;let Q=Z-J,Y=Math.max(0,$-J),V=Math.max(0,Q-Y);return Math.round(Math.min(100,Math.max(0,V/Q*100)))}function wK($,Z,J){let Q=bA($,Z,J??12000);if(Q==null)return null;return{used:Math.min(100,Math.max(0,100-Q)),remaining:Q}}function kK($){let Z=Math.max(0,$);if(Z<1000)return String(Math.round(Z));if(Z<1e6)return(Z/1000).toFixed(Z<1e4?1:0).replace(/\.0$/,"")+"K";return(Z/1e6).toFixed(Z<1e7?1:0).replace(/\.0$/,"")+"M"}function j6($,Z){let J=kK($);return Z!=null&&Z>0?`${J}/${kK(Z)}`:`${J}/--`}function vK($,Z){if(Z==null||Z<=0)return"--";let J=Math.max(0,$/Z*100);if(J>0&&J<1)return"<1%";return`${Math.round(Math.min(100,J))}%`}function JY($,Z,J){let Q=Z?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"");return`${$} · ${Q||"MISS"}/${J||"MISS"}`}function P6($){return JSON.stringify({objective:$.objective,status:$.status,tokenBudget:$.tokenBudget})}function kA($){switch($){case"pending":return"☐";case"inProgress":return"\uD83D\uDD04";case"completed":return"✅";default:return"·"}}function wA($,Z){return $.length>Z?$.slice(0,Z)+"…":$}function _6($){if(!Number.isFinite($)||$<0)return"--";if($<1000)return String(Math.round($));if($<1e6)return($/1000).toFixed($<1e4?1:0).replace(/\.0$/,"")+"k";return($/1e6).toFixed(2).replace(/\.?0+$/,"")+"m"}function yK($){switch($){case"active":return"进行中";case"paused":return"已暂停";case"blocked":return"受阻";case"usageLimited":return"额度受限";case"budgetLimited":return"预算受限";case"complete":return"已完成";default:return $}}function hK($){let Z=$.filter((V)=>V.status==="completed").length,J=$.filter((V)=>V.status==="inProgress").length,Q=$.filter((V)=>V.status==="pending").length,Y=[`${$.length} 项`];if(J)Y.push(`${J} 进行中`);if(Z)Y.push(`${Z} 完成`);if(Q)Y.push(`${Q} 待办`);return Y.join(" · ")}function vA($,Z=""){let J=Z.trim();if($.length===0)return J?"\uD83D\uDCCB 计划草稿":"\uD83D\uDCCB 计划更新";return`\uD83D\uDCCB 计划更新 · ${hK($)}`}function ZY($){return typeof $==="number"&&Number.isFinite($)?$:null}function yA($){let Z=ZY($.startedAtMs),J=ZY($.completedAtMs);if(Z==null||J==null||J<Z)return"";return` · 耗时 ${y0((J-Z)/1000)}`}function fA($){let Z=ZY($);return Z==null?null:_6(Z)}function hA($,Z){if(!Z)return["压缩中..."];let J=[],Q=typeof $.trigger==="string"&&$.trigger.trim()?$.trigger.trim():"",Y=fA($.preTokens),V=typeof $.sourceType==="string"&&$.sourceType.trim()?$.sourceType.trim():"";if(Q)J.push(`**触发**: ${Q}`);if(Y)J.push(`**压缩前**: ${Y} tokens`);if(V)J.push(`**来源**: ${V}`);return J.length>0?J:["压缩完成,无摘要内容"]}function QY($,Z,J){if($==null||!Number.isFinite($))return null;let Q=wK($,Z,J);return Q?`${Q.used}% · ${j6($,Z)}`:"--"}function YY($){let Z=_6($?.input_tokens??Number.NaN),J=_6($?.cache_read_input_tokens??Number.NaN),Q=_6($?.output_tokens??Number.NaN);return`└ 入 ${Z} | 缓 ${J} | 出 ${Q}`}function w8($,Z,J){let Q=Z&&typeof Z==="object"?Z:{},Y=Q.phase==="end"||Q.phase==="event",V=Y?"✅":"⏳",X=Y?yA(Q):"",z=`${V} \uD83D\uDEA8 上下文压缩 #${$+1}${X}`,H=hA(Q,Y);return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:z}},expanded:!1,elements:[{tag:"markdown",content:H.join(`
194
194
  `)}]}}function IK($,Z,J=""){let Q=["**\uD83D\uDCCB 当前计划**"],Y=Z?.trim();if(Y)Q.push(""),Q.push(Y);if($.length>0){Q.push("");for(let V of $)Q.push(`- ${kA(V.status)} ${V.step}`)}else{let V=J.trim();if(Q.push(""),V)Q.push("正在生成计划草稿..."),Q.push(""),Q.push(V);else Q.push("--")}return Q.join(`
195
- `)}function VY($,Z,J="",Q){return{tag:"collapsible_panel",element_id:Q,header:{title:{tag:"plain_text",content:vA($,J)}},expanded:!1,elements:[{tag:"markdown",content:IK($,Z,J)}]}}function v8($,Z,J){let Q=$.length>0?`\uD83D\uDCCB 当前计划 · ${hK($)}`:"\uD83D\uDCCB 当前计划";return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:Q}},expanded:!0,elements:[{tag:"markdown",content:IK($,Z)}]}}function XY($,Z){let J=Number.isFinite($.tokensUsed)?String($.tokensUsed):"MISS",Q=$.tokenBudget==null?"":Number.isFinite($.tokenBudget)?` / ${$.tokenBudget}`:" / MISS",Y=[`**\uD83C\uDFAF 当前目标** · ${fK($.status)}`,"",$.objective,"",`- 用量: ${J}${Q} tokens`,`- 用时: ${f0($.timeUsedSeconds)}`];return{tag:"collapsible_panel",element_id:Z,header:{title:{tag:"plain_text",content:`\uD83C\uDFAF 目标更新 · ${fK($.status)}: ${wA($.objective,48)}`}},expanded:!1,elements:[{tag:"markdown",content:Y.join(`
196
- `)}]}}function L6($){let Z=$.provider==="claude"?"Claude":"Codex",J=$.kind==="card_full"?[{tag:"markdown",content:`\uD83D\uDCE8 接续上一张(同一轮 ${Z},前卡写满或写入受限)`}]:$.kind==="bg_task_resume"?[{tag:"markdown",content:`\uD83D\uDD01 后台任务完成,${Z} 继续处理结果 #${$.turn}`}]:$.kind==="scheduled_wakeup"?[{tag:"markdown",content:`⏰ 定时任务触发,${Z} 正在执行巡检 #${$.turn}`}]:[],Q=$.userInputs??[],Y=`\uD83D\uDCE5 ${$.kind==="user_steering"?"追加":"收到"} (${Q.length}) ${$.directStart?"\uD83D\uDE80":`#${$.turn}`}`,V=Q.length>0?[{tag:"collapsible_panel",element_id:C.userInput,header:{title:{tag:"plain_text",content:Y}},expanded:!1,elements:Q.map((X)=>({tag:"markdown",content:G0(X)}))}]:[];return{schema:"2.0",config:{streaming_mode:!0,summary:{content:"[Lodestar 正在生成…]"},streaming_config:{print_frequency_ms:{default:60,android:60,ios:60,pc:30},print_step:{default:2,android:2,ios:2,pc:4},print_strategy:"fast"}},body:{elements:[...J,...V,{tag:"markdown",element_id:C.footer,content:$.initialFooter??"Waiting...(0s)"}]}}}function gK($,Z,J){let Q=$.question.trim()||`问题 ${Z+1}`;return`${Z+1}/${J} · ${Q}`}function IA($,Z){if(!Z)return"?";return Z.customText??(Z.optionIdx!==void 0?$.options[Z.optionIdx]?.label:void 0)??"?"}function gA($,Z,J){let Q=[];for(let Y=0;Y<$.options.length;Y++){let V=$.options[Y],X=V.description?` · ${G0(V.description)}`:"";Q.push({tag:"interactive_container",background_style:"default",has_border:!0,corner_radius:"6px",padding:"8px 12px",margin:"4px 0px 4px 0px",behaviors:[{type:"callback",value:{kind:"ask",tool_use_id:Z,question_idx:J,option_idx:Y}}],elements:[{tag:"markdown",content:`**${G0(V.label)}**${X}`}]})}return Q}function yK($,Z,J,Q){if($.length===0)return null;let Y=$.length,V=[];for(let X=0;X<$.length;X++){let z=$[X];if(!z)continue;let H=gK(z,X,Y),G=Q.get(X);if(G){let W=IA(z,G),K=[`**✅ ${H}**`,`**回答**:${W}`];V.push({tag:"markdown",content:K.join(`
197
- `)});continue}if(X===J){if(V.push({tag:"markdown",content:`**\uD83E\uDD14 ${H}**`}),z.options.length>0)V.push(...gA(z,Z,X));V.push({tag:"markdown",content:"_\uD83D\uDCAC 也可以直接在群里回复你的答案(裸词命令 `hi`/`stop`/`kill`/`restart`/`clear`/`model` 仍然优先)_"});continue}V.push({tag:"markdown",content:`**⏳ ${H}**`})}return V}function H9($,Z,J,Q="\uD83E\uDD14",Y){let V=J.length,X=Y?.answered??new Map,z=Y?.currentIdx,H=z===void 0&&X.size>0,G=[],W;if(Y?.waitingFor)W=Y.waitingFor==="notification"?"⏳ 等待通知回复完成":"⏳ 提问排队中",G.push({tag:"markdown",content:Y.waitingFor==="notification"?"请先完成或取消通知回复,再回答这个问题。":"先回答当前问题,再显示这个提问。"});else if(H){W=`${Q} 已回答 · ${V}/${V}`,G.push(...yK(J,Z,z,X)??[]);let K=[...X.values()].reverse().find((B)=>B.user)?.user;if(K)G.push({tag:"markdown",content:`
198
- *— 由 ${K} 回答*`})}else if(z!==void 0&&J[z])W=`${Q} 等你确认 · ${z+1}/${V}`,G.push(...yK(J,Z,z,X)??[]);else if(W=`${Q} 等你确认`,J[0])G.push({tag:"markdown",content:`**${gK(J[0],0,V||1)}**`});return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:W}},expanded:!H&&!Y?.waitingFor,elements:G}}var mK=R(()=>{d0()});import{isAbsolute as zY,relative as mA}from"node:path";function D6($){return $==="Bash"||$==="exec_command"||$.endsWith(".exec_command")}function F6($){return $==="write_stdin"||$.endsWith(".write_stdin")}function cA($){return D6($)||F6($)}function M6($){return $==="FileChange"||$==="fileChange"}function y8($){return $==="WebSearch"||$==="webSearch"}function U6($){return $==="WebFetch"||$==="webFetch"}function jY($){return $==="MCP"}function h8($){return $==="ImageGeneration"||$==="imageGeneration"}function _Y($){return $==="Agent"||$==="Task"}function O6($){return $==="Read"}function A6($){return $==="Write"}function N6($){return $==="Edit"||$==="NotebookEdit"}function R6($){return $==="MultiEdit"}function PY($){return $==="Glob"||$==="Grep"||$==="LS"}function T6($){return $==="TodoWrite"}function E6($){return $==="ExitPlanMode"}function S6($){return $.startsWith(cK)}function uK($){return S6($)?$.slice(cK.length):$}function n2($){if(S6($))return"服务端工具";if(M6($))return"文件变更";if(y8($))return"网页搜索";if(U6($))return"网页读取";if(h8($))return"图片生成";if(O6($))return"读取文件";if(A6($))return"写入文件";if(N6($)||R6($))return"编辑文件";if($==="Glob")return"匹配文件";if($==="Grep")return"搜索文件";if($==="LS")return"列目录";if(T6($))return"更新待办";if(E6($))return"确认计划";if($==="Task")return"子任务";return cA($)?"Bash":$}function n1($,Z){let J=(Q,Y)=>Q.length>Y?Q.slice(0,Y)+"…":Q;if(S6($))return J(uA($,Z),80);if(!Z||typeof Z!=="object")return"";if(D6($))return lA(Z);if(F6($))return dA(Z);if(M6($))return J(aA(Z),80);if(y8($))return J(XB(Z),80);if(U6($))return J(ZN(Z),80);if(jY($))return J(QN(Z),80);if(h8($))return J(VN(Z),80);if(_Y($))return J(XN(Z),80);if(O6($))return J(oA(Z),80);if(A6($))return J(sA(Z),80);if(N6($))return J(tA(Z),80);if(R6($))return J(rA(Z),80);if(PY($))return J(eA($,Z),80);if(T6($))return J($N(Z),80);if(E6($))return J(I8(Z)||"提交计划",80);switch($){case"Skill":return J(String(Z.skill??""),80)}for(let Q of Object.values(Z))if(typeof Q==="string"&&Q)return J(Q,80);return""}function uA($,Z){if(typeof Z?.__displayDescription==="string"&&Z.__displayDescription.trim())return Z.__displayDescription;let J=typeof Z?.tool==="string"&&Z.tool?Z.tool:uK($),Q=I8(Z?.input);return Q?`${J}: ${Q}`:J}function lA($){let Z=(V,X)=>V.length>X?V.slice(0,X)+"…":V,J=dK($);if(J.description)return Z(J.description.replace(/\s+/g," "),80);let Q=J.command;if(!Q)return"";let Y=Q.split(/\r?\n/).map((V)=>V.trim()).filter(Boolean);if(Y.length<=1)return Z(Q.replace(/\s+/g," "),80);return`Shell 脚本 · ${Y.length} 行 · ${Z(O4(Q),46)}`}function lK($){let Z=typeof $?.chars==="string"?$.chars:"";if(Z==="")return"读取会话输出";if(Z==="\x03")return"中断会话";return"发送输入"}function dA($){let Z=$?.session_id??$?.sessionId,J=Z===void 0?"":` ${Z}`;return`${lK($)}${J}`}function dK($){let Z=String($?.command??$?.cmd??$?.script??""),J=String($?.description??$?.reason??"").trim(),Q=B1(Z);return{description:(typeof $?.__displayDescription==="string"?$.__displayDescription:void 0)??(Q.description||J),command:Q.command}}function P$($,Z=""){let J="```";while($.includes(J))J+="`";return`${J}${Z}
195
+ `)}function VY($,Z,J="",Q){return{tag:"collapsible_panel",element_id:Q,header:{title:{tag:"plain_text",content:vA($,J)}},expanded:!1,elements:[{tag:"markdown",content:IK($,Z,J)}]}}function v8($,Z,J){let Q=$.length>0?`\uD83D\uDCCB 当前计划 · ${hK($)}`:"\uD83D\uDCCB 当前计划";return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:Q}},expanded:!0,elements:[{tag:"markdown",content:IK($,Z)}]}}function XY($,Z){let J=Number.isFinite($.tokensUsed)?String($.tokensUsed):"MISS",Q=$.tokenBudget==null?"":Number.isFinite($.tokenBudget)?` / ${$.tokenBudget}`:" / MISS",Y=[`**\uD83C\uDFAF 当前目标** · ${yK($.status)}`,"",$.objective,"",`- 用量: ${J}${Q} tokens`,`- 用时: ${y0($.timeUsedSeconds)}`];return{tag:"collapsible_panel",element_id:Z,header:{title:{tag:"plain_text",content:`\uD83C\uDFAF 目标更新 · ${yK($.status)}: ${wA($.objective,48)}`}},expanded:!1,elements:[{tag:"markdown",content:Y.join(`
196
+ `)}]}}function L6($){let Z=$.provider==="claude"?"Claude":"Codex",J=$.kind==="card_full"?[{tag:"markdown",content:`\uD83D\uDCE8 接续上一张(同一轮 ${Z},前卡写满或写入受限)`}]:$.kind==="bg_task_resume"?[{tag:"markdown",content:`\uD83D\uDD01 后台任务完成,${Z} 继续处理结果 #${$.turn}`}]:$.kind==="scheduled_wakeup"?[{tag:"markdown",content:`⏰ 定时任务触发,${Z} 正在执行巡检 #${$.turn}`}]:[],Q=$.userInputs??[],Y=`\uD83D\uDCE5 ${$.kind==="user_steering"?"追加":"收到"} (${Q.length}) ${$.directStart?"\uD83D\uDE80":`#${$.turn}`}`,V=Q.length>0?[{tag:"collapsible_panel",element_id:C.userInput,header:{title:{tag:"plain_text",content:Y}},expanded:!1,elements:Q.map((X)=>({tag:"markdown",content:G0(X)}))}]:[];return{schema:"2.0",config:{streaming_mode:!0,summary:{content:"[Lodestar 正在生成…]"},streaming_config:{print_frequency_ms:{default:60,android:60,ios:60,pc:30},print_step:{default:2,android:2,ios:2,pc:4},print_strategy:"fast"}},body:{elements:[...J,...V,{tag:"markdown",element_id:C.footer,content:$.initialFooter??"Waiting...(0s)"}]}}}function gK($,Z,J){let Q=$.question.trim()||`问题 ${Z+1}`;return`${Z+1}/${J} · ${Q}`}function IA($,Z){if(!Z)return"?";return Z.customText??(Z.optionIdx!==void 0?$.options[Z.optionIdx]?.label:void 0)??"?"}function gA($,Z,J){let Q=[];for(let Y=0;Y<$.options.length;Y++){let V=$.options[Y],X=V.description?` · ${G0(V.description)}`:"";Q.push({tag:"interactive_container",background_style:"default",has_border:!0,corner_radius:"6px",padding:"8px 12px",margin:"4px 0px 4px 0px",behaviors:[{type:"callback",value:{kind:"ask",tool_use_id:Z,question_idx:J,option_idx:Y}}],elements:[{tag:"markdown",content:`**${G0(V.label)}**${X}`}]})}return Q}function fK($,Z,J,Q){if($.length===0)return null;let Y=$.length,V=[];for(let X=0;X<$.length;X++){let z=$[X];if(!z)continue;let H=gK(z,X,Y),G=Q.get(X);if(G){let W=IA(z,G),K=[`**✅ ${H}**`,`**回答**:${W}`];V.push({tag:"markdown",content:K.join(`
197
+ `)});continue}if(X===J){if(V.push({tag:"markdown",content:`**\uD83E\uDD14 ${H}**`}),z.options.length>0)V.push(...gA(z,Z,X));V.push({tag:"markdown",content:"_\uD83D\uDCAC 也可以直接在群里回复你的答案(裸词命令 `hi`/`stop`/`kill`/`restart`/`clear`/`model` 仍然优先)_"});continue}V.push({tag:"markdown",content:`**⏳ ${H}**`})}return V}function H9($,Z,J,Q="\uD83E\uDD14",Y){let V=J.length,X=Y?.answered??new Map,z=Y?.currentIdx,H=z===void 0&&X.size>0,G=[],W;if(Y?.waitingFor)W=Y.waitingFor==="notification"?"⏳ 等待通知回复完成":"⏳ 提问排队中",G.push({tag:"markdown",content:Y.waitingFor==="notification"?"请先完成或取消通知回复,再回答这个问题。":"先回答当前问题,再显示这个提问。"});else if(H){W=`${Q} 已回答 · ${V}/${V}`,G.push(...fK(J,Z,z,X)??[]);let K=[...X.values()].reverse().find((B)=>B.user)?.user;if(K)G.push({tag:"markdown",content:`
198
+ *— 由 ${K} 回答*`})}else if(z!==void 0&&J[z])W=`${Q} 等你确认 · ${z+1}/${V}`,G.push(...fK(J,Z,z,X)??[]);else if(W=`${Q} 等你确认`,J[0])G.push({tag:"markdown",content:`**${gK(J[0],0,V||1)}**`});return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:W}},expanded:!H&&!Y?.waitingFor,elements:G}}var mK=R(()=>{d0()});import{isAbsolute as zY,relative as mA}from"node:path";function F6($){return $==="Bash"||$==="exec_command"||$.endsWith(".exec_command")}function D6($){return $==="write_stdin"||$.endsWith(".write_stdin")}function cA($){return F6($)||D6($)}function M6($){return $==="FileChange"||$==="fileChange"}function f8($){return $==="WebSearch"||$==="webSearch"}function U6($){return $==="WebFetch"||$==="webFetch"}function jY($){return $==="MCP"}function h8($){return $==="ImageGeneration"||$==="imageGeneration"}function _Y($){return $==="Agent"||$==="Task"}function O6($){return $==="Read"}function A6($){return $==="Write"}function N6($){return $==="Edit"||$==="NotebookEdit"}function R6($){return $==="MultiEdit"}function PY($){return $==="Glob"||$==="Grep"||$==="LS"}function T6($){return $==="TodoWrite"}function E6($){return $==="ExitPlanMode"}function S6($){return $.startsWith(cK)}function uK($){return S6($)?$.slice(cK.length):$}function n2($){if(S6($))return"服务端工具";if(M6($))return"文件变更";if(f8($))return"网页搜索";if(U6($))return"网页读取";if(h8($))return"图片生成";if(O6($))return"读取文件";if(A6($))return"写入文件";if(N6($)||R6($))return"编辑文件";if($==="Glob")return"匹配文件";if($==="Grep")return"搜索文件";if($==="LS")return"列目录";if(T6($))return"更新待办";if(E6($))return"确认计划";if($==="Task")return"子任务";return cA($)?"Bash":$}function n1($,Z){let J=(Q,Y)=>Q.length>Y?Q.slice(0,Y)+"…":Q;if(S6($))return J(uA($,Z),80);if(!Z||typeof Z!=="object")return"";if(F6($))return lA(Z);if(D6($))return dA(Z);if(M6($))return J(aA(Z),80);if(f8($))return J(XB(Z),80);if(U6($))return J(ZN(Z),80);if(jY($))return J(QN(Z),80);if(h8($))return J(VN(Z),80);if(_Y($))return J(XN(Z),80);if(O6($))return J(oA(Z),80);if(A6($))return J(sA(Z),80);if(N6($))return J(tA(Z),80);if(R6($))return J(rA(Z),80);if(PY($))return J(eA($,Z),80);if(T6($))return J($N(Z),80);if(E6($))return J(I8(Z)||"提交计划",80);switch($){case"Skill":return J(String(Z.skill??""),80)}for(let Q of Object.values(Z))if(typeof Q==="string"&&Q)return J(Q,80);return""}function uA($,Z){if(typeof Z?.__displayDescription==="string"&&Z.__displayDescription.trim())return Z.__displayDescription;let J=typeof Z?.tool==="string"&&Z.tool?Z.tool:uK($),Q=I8(Z?.input);return Q?`${J}: ${Q}`:J}function lA($){let Z=(V,X)=>V.length>X?V.slice(0,X)+"…":V,J=dK($);if(J.description)return Z(J.description.replace(/\s+/g," "),80);let Q=J.command;if(!Q)return"";let Y=Q.split(/\r?\n/).map((V)=>V.trim()).filter(Boolean);if(Y.length<=1)return Z(Q.replace(/\s+/g," "),80);return`Shell 脚本 · ${Y.length} 行 · ${Z(O4(Q),46)}`}function lK($){let Z=typeof $?.chars==="string"?$.chars:"";if(Z==="")return"读取会话输出";if(Z==="\x03")return"中断会话";return"发送输入"}function dA($){let Z=$?.session_id??$?.sessionId,J=Z===void 0?"":` ${Z}`;return`${lK($)}${J}`}function dK($){let Z=String($?.command??$?.cmd??$?.script??""),J=String($?.description??$?.reason??"").trim(),Q=B1(Z);return{description:(typeof $?.__displayDescription==="string"?$.__displayDescription:void 0)??(Q.description||J),command:Q.command}}function P$($,Z=""){let J="```";while($.includes(J))J+="`";return`${J}${Z}
199
199
  ${$}
200
200
  ${J}`}function A1($,Z=pA,J=""){if($.length<=Z)return P$($,J);let Q=$.slice(0,Z).trimEnd();return[`_已截断: 仅显示前 ${Z} / ${$.length} 字符。_`,P$(`${Q}
201
201
  ... output 已截断 ...`,J)].join(`
202
202
  `)}function n($){return"`"+String($??"").replace(/`/g,"'")+"`"}function T$($,Z=3000){return P$(JSON.stringify($??null,null,2).slice(0,Z),"json")}function I8($){if(!$||typeof $!=="object")return"";let Z=$;for(let J of["query","prompt","path","file_path","url","name","id"]){let Q=Z[J];if(typeof Q==="string"&&Q.length>0)return Q}for(let J of Object.values(Z))if(typeof J==="string"&&J.length>0)return J;return""}function iK($,Z,J){let Q=dK($),Y=Q.command,V=Q.description,X=[];if(V)X.push(`**目的**: ${V}`);let z=$?.cwd??$?.workdir;if(z)X.push(`**cwd**: ${n(z)}`);if($?.source)X.push(`**source**: ${n($.source)}`);if(X.length>0)X.push("");if(X.push("**命令**"),X.push(P$(Y||"(空命令)","bash")),J)X.push(""),X.push(J);if(Z!=null)X.push(""),X.push("---"),X.push("**output:**"),X.push(A1(Z));return X.join(`
203
203
  `)}function nK($,Z,J){let Q=[],Y=$?.session_id??$?.sessionId;if(Q.push(`**操作**: ${lK($)}`),Y!==void 0)Q.push(`**session**: ${n(Y)}`);if(typeof $?.chars==="string"&&$.chars.length>0){let V=$.chars==="\x03"?"^C":$.chars;Q.push(""),Q.push("**输入**"),Q.push(P$(V))}if(J)Q.push(""),Q.push(J);if(Z!=null)Q.push(""),Q.push("---"),Q.push("**output:**"),Q.push(A1(Z));return Q.join(`
204
- `)}function aK($){return Array.isArray($?.changes)?$.changes:[]}function oK($){let Z=$?.cwd??$?.grantRoot;return typeof Z==="string"&&Z.length>0?Z:void 0}function f8($,Z){let J=String($??"");if(!J)return"(无 path)";if(Z&&zY(J)&&zY(Z)){let Q=mA(Z,J);if(Q&&!Q.startsWith("..")&&!zY(Q))return Q}return J}function iA($){let Z=$?.kind;if(typeof Z==="string")return Z.toLowerCase();if(typeof Z?.type==="string")return Z.type.toLowerCase();if(typeof $?.type==="string")return $.type.toLowerCase();return""}function sK($){return $?.kind?.move_path??$?.kind?.movePath??$?.move_path??$?.movePath}function GY($){let Z=iA($);if(sK($))return Z==="update"?"移动/修改":"移动";switch(Z){case"add":return"新增";case"delete":return"删除";case"update":return"修改";default:return"变更"}}function WY($){let Z=$?.diff??$?.unified_diff;return typeof Z==="string"?Z:""}function KY($){let Z=0,J=0;for(let Q of $.split(/\r?\n/)){if(Q.startsWith("+++")||Q.startsWith("---"))continue;if(Q.startsWith("+"))Z++;if(Q.startsWith("-"))J++}return{added:Z,removed:J}}function tK($,Z){return{added:$.added+Z.added,removed:$.removed+Z.removed}}function BY($){return $.added>0||$.removed>0?`+${$.added} -${$.removed}`:""}function nA($){return $.length>1800?$.slice(0,1800)+`
205
- ... diff 已截断 ...`:$}function aA($){let Z=aK($),J=oK($);if(Z.length===0){let H=typeof $?.reason==="string"?$.reason.trim():"",G=$?.grantRoot?f8($.grantRoot):"";if(H&&G)return`${H} · ${G}`;return H||(G?`申请修改 ${G}`:"")}let Q=Z.map((H)=>KY(WY(H))).reduce(tK,{added:0,removed:0}),Y=BY(Q),V=[...new Set(Z.map(GY))],X=f8(Z[0]?.path,J),z=Y?` · ${Y}`:"";if(Z.length===1)return`${V[0]} ${X}${z}`;return`${Z.length} 个文件 · ${V.join("/")} · ${X} 等${z}`}function rK($,Z,J){let Q=aK($),Y=oK($),V=[];if(Q.length===0){let G=typeof $?.reason==="string"?$.reason.trim():"";if(G)V.push(`**原因**: ${G}`);if($?.grantRoot)V.push(`**范围**: ${n(f8($.grantRoot))}`);if(J)V.push(""),V.push(J);if(Z!=null)V.push(""),V.push("---"),V.push("**output:**"),V.push(P$(Z.slice(0,3000)));return V.length>0?V.join(`
206
- `):P$(JSON.stringify($??{},null,2).slice(0,2000))}let X=Q.map((G)=>KY(WY(G))).reduce(tK,{added:0,removed:0}),z=BY(X);if(V.push(`**文件**: ${Q.length} 个`),z)V.push(`**行数**: ${z}`);if($?.status)V.push(`**状态**: ${n($.status)}`);let H=Q.slice(0,5);for(let G of H){let W=WY(G),K=BY(KY(W)),B=f8(G?.path,Y),_=K?`**${GY(G)}** ${n(B)} · ${K}`:`**${GY(G)}** ${n(B)}`;V.push(""),V.push(_);let P=sK(G);if(P)V.push(`来自 ${n(f8(P,Y))}`);V.push(W?P$(nA(W),"diff"):"_无 diff 内容_")}if(Q.length>H.length)V.push(""),V.push(`还有 ${Q.length-H.length} 个文件未展开显示。`);if(J)V.push(""),V.push(J);return V.join(`
204
+ `)}function aK($){return Array.isArray($?.changes)?$.changes:[]}function oK($){let Z=$?.cwd??$?.grantRoot;return typeof Z==="string"&&Z.length>0?Z:void 0}function y8($,Z){let J=String($??"");if(!J)return"(无 path)";if(Z&&zY(J)&&zY(Z)){let Q=mA(Z,J);if(Q&&!Q.startsWith("..")&&!zY(Q))return Q}return J}function iA($){let Z=$?.kind;if(typeof Z==="string")return Z.toLowerCase();if(typeof Z?.type==="string")return Z.type.toLowerCase();if(typeof $?.type==="string")return $.type.toLowerCase();return""}function sK($){return $?.kind?.move_path??$?.kind?.movePath??$?.move_path??$?.movePath}function GY($){let Z=iA($);if(sK($))return Z==="update"?"移动/修改":"移动";switch(Z){case"add":return"新增";case"delete":return"删除";case"update":return"修改";default:return"变更"}}function WY($){let Z=$?.diff??$?.unified_diff;return typeof Z==="string"?Z:""}function KY($){let Z=0,J=0;for(let Q of $.split(/\r?\n/)){if(Q.startsWith("+++")||Q.startsWith("---"))continue;if(Q.startsWith("+"))Z++;if(Q.startsWith("-"))J++}return{added:Z,removed:J}}function tK($,Z){return{added:$.added+Z.added,removed:$.removed+Z.removed}}function BY($){return $.added>0||$.removed>0?`+${$.added} -${$.removed}`:""}function nA($){return $.length>1800?$.slice(0,1800)+`
205
+ ... diff 已截断 ...`:$}function aA($){let Z=aK($),J=oK($);if(Z.length===0){let H=typeof $?.reason==="string"?$.reason.trim():"",G=$?.grantRoot?y8($.grantRoot):"";if(H&&G)return`${H} · ${G}`;return H||(G?`申请修改 ${G}`:"")}let Q=Z.map((H)=>KY(WY(H))).reduce(tK,{added:0,removed:0}),Y=BY(Q),V=[...new Set(Z.map(GY))],X=y8(Z[0]?.path,J),z=Y?` · ${Y}`:"";if(Z.length===1)return`${V[0]} ${X}${z}`;return`${Z.length} 个文件 · ${V.join("/")} · ${X} 等${z}`}function rK($,Z,J){let Q=aK($),Y=oK($),V=[];if(Q.length===0){let G=typeof $?.reason==="string"?$.reason.trim():"";if(G)V.push(`**原因**: ${G}`);if($?.grantRoot)V.push(`**范围**: ${n(y8($.grantRoot))}`);if(J)V.push(""),V.push(J);if(Z!=null)V.push(""),V.push("---"),V.push("**output:**"),V.push(P$(Z.slice(0,3000)));return V.length>0?V.join(`
206
+ `):P$(JSON.stringify($??{},null,2).slice(0,2000))}let X=Q.map((G)=>KY(WY(G))).reduce(tK,{added:0,removed:0}),z=BY(X);if(V.push(`**文件**: ${Q.length} 个`),z)V.push(`**行数**: ${z}`);if($?.status)V.push(`**状态**: ${n($.status)}`);let H=Q.slice(0,5);for(let G of H){let W=WY(G),K=BY(KY(W)),B=y8(G?.path,Y),_=K?`**${GY(G)}** ${n(B)} · ${K}`:`**${GY(G)}** ${n(B)}`;V.push(""),V.push(_);let P=sK(G);if(P)V.push(`来自 ${n(y8(P,Y))}`);V.push(W?P$(nA(W),"diff"):"_无 diff 内容_")}if(Q.length>H.length)V.push(""),V.push(`还有 ${Q.length-H.length} 个文件未展开显示。`);if(J)V.push(""),V.push(J);return V.join(`
207
207
  `)}function a1($){return String($?.file_path??$?.path??$?.notebook_path??"")}function oA($){let Z=a1($),J=[$?.offset!=null?`offset ${$.offset}`:"",$?.limit!=null?`limit ${$.limit}`:""].filter(Boolean).join(" · ");return J&&Z?`${Z} · ${J}`:Z}function sA($){let Z=a1($),J=typeof $?.content==="string"?$.content:"",Q=J?J.split(/\r?\n/).length:0;return Z&&Q?`${Z} · ${Q} 行`:Z}function tA($){let Z=a1($),J=$?.replace_all?"全局替换":"替换";return Z?`${J} ${Z}`:J}function rA($){let Z=a1($),J=Array.isArray($?.edits)?$.edits.length:0,Q=J?` · ${J} 处`:"";return Z?`批量编辑 ${Z}${Q}`:`批量编辑${Q}`}function eA($,Z){if($==="Glob"){let J=String(Z?.pattern??"");return Z?.path?`${J} · ${Z.path}`:J}if($==="Grep"){let J=String(Z?.pattern??"");return Z?.path?`${J} · ${Z.path}`:J}return String(Z?.path??"")}function eK($){switch($){case"pending":return"待办";case"in_progress":return"进行中";case"completed":return"完成";default:return String($??"未知")}}function $N($){let Z=Array.isArray($?.todos)?$.todos:[];if(Z.length===0)return"";let J=new Map;for(let Y of Z){let V=eK(Y?.status);J.set(V,(J.get(V)??0)+1)}let Q=[...J.entries()].map(([Y,V])=>`${Y} ${V}`).join(" · ");return`${Z.length} 项${Q?` · ${Q}`:""}`}function ZN($){let Z=String($?.url??""),J=typeof $?.prompt==="string"?$.prompt.trim():"";return Z&&J?`${Z} · ${J}`:Z||J}function G9($,Z){if(Z==null)return;$.push(""),$.push("---"),$.push("**结果**"),$.push(A1(Z,1200))}function $B($,Z,J){let Q=[],Y=a1($);if(Y)Q.push(`**路径**: ${n(Y)}`);if($?.offset!=null)Q.push(`**offset**: ${n($.offset)}`);if($?.limit!=null)Q.push(`**limit**: ${n($.limit)}`);if(J)Q.push(""),Q.push(J);if(Z!=null)Q.push(""),Q.push("_内容已读取,未展开到群聊卡片。_");return Q.length>0?Q.join(`
208
208
  `):T$($??{},2000)}function ZB($,Z,J){let Q=[],Y=a1($),V=typeof $?.content==="string"?$.content:"";if(Y)Q.push(`**路径**: ${n(Y)}`);if(V){let X=V.split(/\r?\n/).length;Q.push(`**内容**: ${X} 行 / ${V.length} 字符`),Q.push(A1(V,1200))}if(J)Q.push(""),Q.push(J);return G9(Q,Z),Q.length>0?Q.join(`
209
209
  `):T$($??{},2000)}function JB($,Z,J){let Q=[],Y=a1($);if(Y)Q.push(`**路径**: ${n(Y)}`);if($?.cell_id)Q.push(`**cell**: ${n($.cell_id)}`);if($?.edit_mode)Q.push(`**模式**: ${n($.edit_mode)}`);if($?.replace_all)Q.push("**范围**: 全局替换");if(typeof $?.old_string==="string")Q.push(""),Q.push("**查找**"),Q.push(A1($.old_string,800));let V=typeof $?.new_string==="string"?$.new_string:typeof $?.new_source==="string"?$.new_source:"";if(V)Q.push(""),Q.push("**替换为**"),Q.push(A1(V,800));if(J)Q.push(""),Q.push(J);return G9(Q,Z),Q.length>0?Q.join(`
210
210
  `):T$($??{},2000)}function QB($,Z,J){let Q=[],Y=a1($),V=Array.isArray($?.edits)?$.edits:[];if(Y)Q.push(`**路径**: ${n(Y)}`);Q.push(`**编辑**: ${V.length} 处`);for(let[X,z]of V.slice(0,5).entries()){if(Q.push(""),Q.push(`**#${X+1}${z?.replace_all?" · 全局替换":""}**`),typeof z?.old_string==="string")Q.push("查找:"),Q.push(A1(z.old_string,500));if(typeof z?.new_string==="string")Q.push("替换为:"),Q.push(A1(z.new_string,500))}if(V.length>5)Q.push(""),Q.push(`还有 ${V.length-5} 处编辑未展开显示。`);if(J)Q.push(""),Q.push(J);return G9(Q,Z),Q.join(`
211
211
  `)}function YB($,Z,J,Q){let Y=[];if($==="Glob"){if(Y.push("**动作**: 匹配文件"),Z?.pattern)Y.push(`**pattern**: ${n(Z.pattern)}`);if(Z?.path)Y.push(`**path**: ${n(Z.path)}`)}else if($==="Grep"){if(Y.push("**动作**: 搜索文件"),Z?.pattern)Y.push(`**pattern**: ${n(Z.pattern)}`);if(Z?.path)Y.push(`**path**: ${n(Z.path)}`);if(Z?.glob)Y.push(`**glob**: ${n(Z.glob)}`);if(Z?.type)Y.push(`**type**: ${n(Z.type)}`);if(Z?.output_mode)Y.push(`**output**: ${n(Z.output_mode)}`)}else{if(Y.push("**动作**: 列目录"),Z?.path)Y.push(`**path**: ${n(Z.path)}`);if(Array.isArray(Z?.ignore)&&Z.ignore.length)Y.push(`**ignore**: ${Z.ignore.map(n).join(" ")}`)}if(Q)Y.push(""),Y.push(Q);return G9(Y,J),Y.join(`
212
212
  `)}function VB($,Z,J){let Q=Array.isArray($?.todos)?$.todos:[],Y=[`**待办**: ${Q.length} 项`];for(let V of Q.slice(0,12)){let X=eK(V?.status),z=String(V?.content??V?.activeForm??"").trim()||"(空)";Y.push(`- ${X}: ${z}`)}if(Q.length>12)Y.push(`- 还有 ${Q.length-12} 项未显示`);if(J)Y.push(""),Y.push(J);return G9(Y,Z),Y.join(`
213
- `)}function LY($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function qY($,Z){return LY(Z)??$?.action??{}}function DY($,Z){let J=qY($,Z),Q=Array.isArray(J?.queries)?J.queries.filter((V)=>typeof V==="string"&&V.length>0):[],Y=typeof J?.query==="string"&&J.query.length>0?J.query:typeof $?.query==="string"&&$.query.length>0?$.query:"";return Q.length>0?Q:Y?[Y]:[]}function FY($,Z){let J=qY($,Z);return String(J?.url??$?.url??"")}function XB($){let Z=DY($,null);if(Z.length===1)return Z[0];if(Z.length>1)return`${Z.length} 条查询 · ${Z[0]}`;let J=FY($,null);if(J)return J;let Q=$?.action?.type;return typeof Q==="string"&&Q!=="other"?Q:""}function JN($,Z){let J=DY($,Z);if(J.length===1)return J[0];if(J.length>1)return`${J.length} 条查询 · ${J[0]}`;let Q=FY($,Z);if(Q)return Q;return XB($)}function zB($,Z,J){let Q=qY($,Z),Y=DY($,Z),V=FY($,Z),X=[],z=typeof Q?.type==="string"?Q.type:"";if(z==="search"||Y.length>0){if(X.push("**动作**: 搜索"),Y.length>0){X.push(""),X.push("**查询**");for(let H of Y.slice(0,6))X.push(`- ${n(H)}`);if(Y.length>6)X.push(`- 还有 ${Y.length-6} 条未显示`)}}else if(z==="open_page"){if(X.push("**动作**: 打开页面"),V)X.push(`**URL**: ${n(V)}`)}else if(z==="find_in_page"){if(X.push("**动作**: 页内查找"),V)X.push(`**URL**: ${n(V)}`);if(Q?.pattern)X.push(`**关键词**: ${n(Q.pattern)}`)}else if(X.push(`**动作**: ${z?n(z):"网页搜索"}`),V)X.push(`**URL**: ${n(V)}`);if(J)X.push(""),X.push(J);if(X.length===1&&!Y.length&&!V&&Z!=null)X.push(""),X.push("---"),X.push("**output:**"),X.push(P$(Z.slice(0,3000),"json"));return X.join(`
213
+ `)}function LY($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function qY($,Z){return LY(Z)??$?.action??{}}function FY($,Z){let J=qY($,Z),Q=Array.isArray(J?.queries)?J.queries.filter((V)=>typeof V==="string"&&V.length>0):[],Y=typeof J?.query==="string"&&J.query.length>0?J.query:typeof $?.query==="string"&&$.query.length>0?$.query:"";return Q.length>0?Q:Y?[Y]:[]}function DY($,Z){let J=qY($,Z);return String(J?.url??$?.url??"")}function XB($){let Z=FY($,null);if(Z.length===1)return Z[0];if(Z.length>1)return`${Z.length} 条查询 · ${Z[0]}`;let J=DY($,null);if(J)return J;let Q=$?.action?.type;return typeof Q==="string"&&Q!=="other"?Q:""}function JN($,Z){let J=FY($,Z);if(J.length===1)return J[0];if(J.length>1)return`${J.length} 条查询 · ${J[0]}`;let Q=DY($,Z);if(Q)return Q;return XB($)}function zB($,Z,J){let Q=qY($,Z),Y=FY($,Z),V=DY($,Z),X=[],z=typeof Q?.type==="string"?Q.type:"";if(z==="search"||Y.length>0){if(X.push("**动作**: 搜索"),Y.length>0){X.push(""),X.push("**查询**");for(let H of Y.slice(0,6))X.push(`- ${n(H)}`);if(Y.length>6)X.push(`- 还有 ${Y.length-6} 条未显示`)}}else if(z==="open_page"){if(X.push("**动作**: 打开页面"),V)X.push(`**URL**: ${n(V)}`)}else if(z==="find_in_page"){if(X.push("**动作**: 页内查找"),V)X.push(`**URL**: ${n(V)}`);if(Q?.pattern)X.push(`**关键词**: ${n(Q.pattern)}`)}else if(X.push(`**动作**: ${z?n(z):"网页搜索"}`),V)X.push(`**URL**: ${n(V)}`);if(J)X.push(""),X.push(J);if(X.length===1&&!Y.length&&!V&&Z!=null)X.push(""),X.push("---"),X.push("**output:**"),X.push(P$(Z.slice(0,3000),"json"));return X.join(`
214
214
  `)}function HB($,Z,J){let Q=["**动作**: 读取网页"];if($?.url)Q.push(`**URL**: ${n($.url)}`);if($?.prompt)Q.push(""),Q.push("**问题**"),Q.push(String($.prompt).slice(0,1200));if(J)Q.push(""),Q.push(J);return G9(Q,Z),Q.join(`
215
215
  `)}function QN($){let Z=String($?.server??""),J=String($?.tool??""),Q=Z&&J?`${Z}.${J}`:J||Z,Y=I8($?.arguments);return Y&&Q?`${Q}: ${Y}`:Q||Y}function GB($,Z,J){let Q=[];if($?.server)Q.push(`**server**: ${n($.server)}`);if($?.tool)Q.push(`**tool**: ${n($.tool)}`);let Y=$?.arguments;if(Y&&typeof Y==="object"&&Object.keys(Y).length>0){if(Q.length>0)Q.push("");Q.push("**arguments**"),Q.push(T$(Y,2000))}if(J)Q.push(""),Q.push(J);if(Z!=null){let V=LY(Z);if(Q.push(""),Q.push("---"),Q.push("**结果**"),V&&Array.isArray(V.content)){let X=V.content.map((z)=>typeof z?.text==="string"?z.text:"").filter(Boolean);if(X.length>0)Q.push(X.join(`
216
216
  `).slice(0,3000));if(V.structuredContent)Q.push(""),Q.push("**structuredContent**"),Q.push(T$(V.structuredContent,2000));if(X.length===0&&!V.structuredContent)Q.push(T$(V,3000))}else Q.push(V?T$(V,3000):P$(Z.slice(0,3000)))}return Q.length>0?Q.join(`
217
217
  `):T$($??{},2000)}function YN($,Z,J,Q){let Y=["**类型**: 模型服务端内置工具",`**tool**: ${n(typeof Z?.tool==="string"&&Z.tool?Z.tool:uK($))}`];if(typeof Z?.__displayDescription==="string"&&Z.__displayDescription.trim())Y.push(`**目的**: ${Z.__displayDescription}`);let V=Z?.input;if(V&&typeof V==="object")if(Y.push(""),Y.push("**input**"),Object.keys(V).length>0){let{__displayDescription:X,...z}=V;Y.push(T$(z,2000))}else Y.push("_provider 未提供结构化 input_");else if(V!=null&&V!=="")Y.push(`**input**: ${n(V)}`);if(Q)Y.push(""),Y.push(Q);if(J!=null)Y.push(""),Y.push("---"),Y.push("**结果**"),Y.push(A1(J,3000));return Y.join(`
218
218
  `)}function VN($){return typeof $?.status==="string"?$.status:""}function WB($,Z,J,Q){let Y=[];if($?.status)Y.push(`**状态**: ${n($.status)}`);if($?.prompt)Y.push("","**提示词**",P$(String($.prompt)));if($?.revisedPrompt){if($.revisedPrompt!==$.prompt)Y.push("",$.prompt?"**实际提示词**":"**提示词**",P$(String($.revisedPrompt)))}if(J)Y.push(""),Y.push(J);if(!Q&&Z!=null&&Z.trim())Y.push(""),Y.push("---"),Y.push("**输出**"),Y.push(n(Z.trim()));return Y.length>0?Y.join(`
219
219
  `):T$($??{},2000)}function XN($){let Z=typeof $?.tool==="string"?$.tool:"",J=typeof $?.prompt==="string"?$.prompt:"",Q=typeof $?.description==="string"?$.description:"",Y=typeof $?.subject==="string"?$.subject:"",V=Q||Y||J;return Z&&V?`${Z}: ${V}`:V||Z}function q6($,Z,J){let Q=[];if($?.tool)Q.push(`**tool**: ${n($.tool)}`);if($?.model)Q.push(`**model**: ${n($.model)}`);if($?.description)Q.push(`**描述**: ${$.description}`);if($?.subagent_type)Q.push(`**类型**: ${n($.subagent_type)}`);if($?.prompt){if(Q.length>0)Q.push("");Q.push("**prompt**"),Q.push(String($.prompt).slice(0,2000))}if(J)Q.push(""),Q.push(J);if(Z!=null){Q.push(""),Q.push("---"),Q.push("**状态**");let Y=LY(Z);Q.push(Y?T$(Y,3000):P$(Z.slice(0,3000)))}return Q.length>0?Q.join(`
220
- `):T$($??{},2000)}function Y1($,Z,J,Q,Y="⏳",V,X){let z=y8(Z)&&Q!=null?JN(J,Q):n1(Z,J),H=z.length>80?z.slice(0,80)+"…":z,G=n2(Z),W=H?`${Y} \uD83D\uDD27 ${G}: ${H}`:`${Y} \uD83D\uDD27 ${G}`,K=V?`
220
+ `):T$($??{},2000)}function Y1($,Z,J,Q,Y="⏳",V,X){let z=f8(Z)&&Q!=null?JN(J,Q):n1(Z,J),H=z.length>80?z.slice(0,80)+"…":z,G=n2(Z),W=H?`${Y} \uD83D\uDD27 ${G}: ${H}`:`${Y} \uD83D\uDD27 ${G}`,K=V?`
221
221
 
222
- ${V}`:"",B=D6(Z)?iK(J,Q,V):F6(Z)?nK(J,Q,V):S6(Z)?YN(Z,J,Q,V):M6(Z)?rK(J,Q,V):y8(Z)?zB(J,Q,V):U6(Z)?HB(J,Q,V):jY(Z)?GB(J,Q,V):h8(Z)?WB(J,Q,V,X):O6(Z)?$B(J,Q,V):A6(Z)?ZB(J,Q,V):N6(Z)?JB(J,Q,V):R6(Z)?QB(J,Q,V):PY(Z)?YB(Z,J,Q,V):T6(Z)?VB(J,Q,V):E6(Z)?q6({prompt:I8(J)||"提交计划"},Q,V):_Y(Z)?q6(J,Q,V):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```"+K+(Q!=null?`
222
+ ${V}`:"",B=F6(Z)?iK(J,Q,V):D6(Z)?nK(J,Q,V):S6(Z)?YN(Z,J,Q,V):M6(Z)?rK(J,Q,V):f8(Z)?zB(J,Q,V):U6(Z)?HB(J,Q,V):jY(Z)?GB(J,Q,V):h8(Z)?WB(J,Q,V,X):O6(Z)?$B(J,Q,V):A6(Z)?ZB(J,Q,V):N6(Z)?JB(J,Q,V):R6(Z)?QB(J,Q,V):PY(Z)?YB(Z,J,Q,V):T6(Z)?VB(J,Q,V):E6(Z)?q6({prompt:I8(J)||"提交计划"},Q,V):_Y(Z)?q6(J,Q,V):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```"+K+(Q!=null?`
223
223
  ---
224
224
  **output:**
225
225
  \`\`\`
226
226
  `+Q.slice(0,3000)+"\n```":"");return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:W}},expanded:!1,elements:[{tag:"markdown",content:G0(B)},...h8(Z)&&X?[{tag:"img",img_key:X,alt:{tag:"plain_text",content:"生成的图片"},scale_type:"fit_horizontal",preview:!0}]:[]]}}function MY($,Z){let J=Z.length,Q=Z.some((H)=>H.isError),Y=Z.every((H)=>H.output!==null),V=Q?"❌":Y?"✅":"⏳",X=J===1?(()=>{let H=pK(Z[0]);return H?`${V} \uD83D\uDD27 编辑文件: ${H}`:`${V} \uD83D\uDD27 编辑文件`})():`${V} \uD83D\uDD27 编辑文件 · ${J} 次`,z=Z.map((H)=>{let G=pK(H);return G?`\`${G}\``:"`(无 path)`"});return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!1,elements:[{tag:"markdown",content:G0(z.join(`
227
227
  `))}]}}function pK($){let Z=$.input??{},J=String(Z.file_path??Z.path??Z.notebook_path??"");if(Array.isArray(Z.edits)&&Z.edits.length>0)return J?`${J} · ${Z.edits.length} 处`:`${Z.edits.length} 处`;if(Z.replace_all&&J)return`${J} · 全局替换`;return J}function UY($,Z){let J=Z.length,Q=Z.some((H)=>H.isError),Y=Z.every((H)=>H.output!==null),V=Q?"❌":Y?"✅":"⏳",X=J===1?(()=>{let H=n1("Read",Z[0]?.input);return H?`${V} \uD83D\uDD27 Read: ${H}`:`${V} \uD83D\uDD27 Read`})():`${V} \uD83D\uDD27 Read · ${J} 次`,z=Z.map((H)=>`\`${String(H.input.file_path??"(无 path)")}\``);return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!1,elements:[{tag:"markdown",content:G0(z.join(`
228
- `))}]}}function OY($,Z,J,Q){let Y=n1(Z,J),V=n2(Z),X=Y?`\uD83D\uDD10 等审批 · ${V}: ${Y}`:`\uD83D\uDD10 等审批 · ${V}`,z=D6(Z)?iK(J,null):F6(Z)?nK(J,null):M6(Z)?rK(J,null):y8(Z)?zB(J,null):U6(Z)?HB(J,null):jY(Z)?GB(J,null):h8(Z)?WB(J,null):O6(Z)?$B(J,null):A6(Z)?ZB(J,null):N6(Z)?JB(J,null):R6(Z)?QB(J,null):PY(Z)?YB(Z,J,null):T6(Z)?VB(J,null):E6(Z)?q6({prompt:I8(J)||"提交计划"},null):_Y(Z)?q6(J,null):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```";return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!0,elements:[{tag:"markdown",content:z},{tag:"column_set",columns:[HY("✅ 允许","primary",Q,"allow"),HY("♾️ 始终允许","default",Q,"allow_always"),HY("❌ 拒绝","danger",Q,"deny")]}]}}function HY($,Z,J,Q){return{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:$},type:Z,behaviors:[{type:"callback",value:{kind:"permission",request_id:J,decision:Q}}]}]}}var pA=300,cK="server_tool:";var KB=R(()=>{d0();A4()});import{execFile as zN}from"node:child_process";import{readFileSync as LB,statfsSync as HN,statSync as BB}from"node:fs";import{cpus as GN,homedir as WN,loadavg as KN,totalmem as BN}from"node:os";import{promisify as jN}from"node:util";function _N(){try{let[$,Z,J]=KN(),Q=GN().length;if(!Q||![$,Z,J].every((Y)=>Number.isFinite(Y)&&Y>=0))throw Error("CPU 核数或负载无效");return{cores:Q,load1:$,load5:Z,load15:J}}catch($){return j(`sysinfo: read CPU failed: ${$}`),null}}function PN(){try{let $=LB("/proc/meminfo","utf8"),Z=(V)=>{let X=$.match(new RegExp(`^${V}:\\s+(\\d+)\\s*kB`,"m"));if(!X)throw Error(`/proc/meminfo 缺少 ${V}`);return Number(X[1])*1024},J=Z("MemTotal"),Q=Z("MemAvailable");if(J<=0||Q>J)throw Error("/proc/meminfo 内存数据无效");let Y=J-Q;return{totalBytes:J,availBytes:Q,usedBytes:Y,percent:Math.round(Y/J*100)}}catch($){return j(`sysinfo: read /proc/meminfo failed: ${$}`),null}}function LN($,Z){let J=$.match(/^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)/m);if(!J)throw Error("vm_stat 缺少 page size");let Q=Number(J[1]);if(!Number.isSafeInteger(Q)||Q<=0||!Number.isSafeInteger(Z)||Z<=0)throw Error("macOS 内存总量或 page size 无效");let Y=(z)=>{let H=$.match(new RegExp(`^${z}:\\s+(\\d+)\\.\\s*$`,"m"));if(!H||!Number.isSafeInteger(Number(H[1])))throw Error(`vm_stat 缺少或无效 ${z}`);return Number(H[1])},V=Y("Anonymous pages")-Y("Pages purgeable"),X=(V+Y("Pages wired down")+Y("Pages occupied by compressor"))*Q;if(V<0||!Number.isSafeInteger(X)||X>Z)throw Error("vm_stat 内存数据超出物理内存范围");return{totalBytes:Z,availBytes:Z-X,usedBytes:X,percent:Math.round(X/Z*100)}}async function qN($=DB){try{return LN(await $("/usr/bin/vm_stat",[]),BN())}catch(Z){return j(`sysinfo: read macOS memory failed: ${Z}`),null}}function DN($){let Z=$.trim().split(/\r?\n/);if(!/^PID\s+Status\s+Label$/.test(Z.shift()?.trim()??""))throw Error("launchctl list 表头无效");let J=[];for(let Q of Z){if(!Q.trim())continue;let Y=Q.trim().match(/^(\d+|-)\s+(-?\d+)\s+(\S+)$/);if(!Y)throw Error(`launchctl list 行无效: ${Q.trim()}`);let[,V,X,z]=Y;if(!AY.some((W)=>z.startsWith(W)))continue;let H=V==="-"?null:Number(V),G=Number(X);if(H!==null&&(!Number.isSafeInteger(H)||H<=0)||!Number.isSafeInteger(G))throw Error(`launchctl list PID 或退出状态无效: ${z}`);J.push({name:z,pid:H,lastExitStatus:G,active:H!==null?"active":G===0?"inactive":"failed",sub:H!==null?"running":G<0?"signal":"exited",hasStarted:H!==null||G!==0?!0:null,lastActiveAgoSec:null,stateAgoSec:null})}return J.sort((Q,Y)=>Q.name.localeCompare(Y.name))}function FN($){let Z=new Map;for(let J of $.split(`
229
- `)){if(!J.trim())continue;let Q=J.trim().match(/^(\d+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);if(!Q)throw Error(`ps etime 行无效: ${J.trim()}`);let Y=Number(Q[1]),V=Q[2]===void 0?0:Number(Q[2]),X=Q[3]===void 0?0:Number(Q[3]),z=Number(Q[4]),H=Number(Q[5]),G=((V*24+X)*60+z)*60+H;if(!Number.isSafeInteger(Y)||Y<=0||!Number.isSafeInteger(G)||z>=60||H>=60||Q[2]!==void 0&&(Q[3]===void 0||X>=24))throw Error(`ps etime 数值无效: ${J.trim()}`);Z.set(Y,G)}return Z}async function MN($=DB){let Z;try{Z=DN(await $("/bin/launchctl",["list"]))}catch(Q){return j(`sysinfo: launchctl list failed: ${Q}`),{services:[],error:`launchctl 查询失败: ${Q instanceof Error?Q.message:String(Q)}`}}let J=Z.filter((Q)=>Q.pid!==null);if(J.length>0)try{let Q=FN(await $("/bin/ps",["-p",J.map((Y)=>Y.pid).join(","),"-o","pid=,etime="]));for(let Y of J){let V=Q.get(Y.pid);if(V===void 0)Y.error="ps 未返回该进程,运行时长 MISS",j(`sysinfo: ${Y.name}: ${Y.error}`);else Y.lastActiveAgoSec=V,Y.stateAgoSec=V}}catch(Q){j(`sysinfo: read launchd process elapsed failed: ${Q}`);for(let Y of J)Y.error=`运行时长 MISS: ${Q instanceof Error?Q.message:String(Q)}`}return{services:Z.map(({pid:Q,...Y})=>Y),error:null}}function jB($,Z){try{let J=HN(Z,{bigint:!1}),Q=J.blocks*J.bsize,Y=J.bavail*J.bsize,V=Math.max(0,Q-Y);if(!Q)return null;return{label:$,path:Z,totalBytes:Q,availBytes:Y,usedBytes:V,percent:Math.round(V/Q*100)}}catch(J){return j(`sysinfo: statfs ${Z} failed: ${J}`),null}}function UN(){let $=[],Z=jB("/","/");if(Z)$.push(Z);let J=WN();if(J&&J!=="/"){let Q=!1;try{let Y=BB("/"),V=BB(J);Q=Y.dev===V.dev}catch{}if(!Q){let Y=jB("$HOME",J);if(Y)$.push(Y)}}return $}function ON(){try{let $=LB("/proc/uptime","utf8").trim().split(/\s+/);return parseFloat($[0]??"0")}catch{return null}}async function _B($,Z=2000){try{let{stdout:J}=await qB("systemctl",["--user",...$],{timeout:Z,maxBuffer:4194304});return J}catch(J){return j(`sysinfo: systemctl ${$.join(" ")} failed: ${J}`),null}}function PB($){return AY.some((Z)=>$.startsWith(Z))&&$.endsWith(".service")}async function AN(){let $=await _B(["list-units","--type=service","--all","--no-legend","--plain",...AY.map((H)=>`${H}*`)]);if($===null)return{services:[],error:"systemctl 不可用"};let Z=$.split(`
228
+ `))}]}}function OY($,Z,J,Q){let Y=n1(Z,J),V=n2(Z),X=Y?`\uD83D\uDD10 等审批 · ${V}: ${Y}`:`\uD83D\uDD10 等审批 · ${V}`,z=F6(Z)?iK(J,null):D6(Z)?nK(J,null):M6(Z)?rK(J,null):f8(Z)?zB(J,null):U6(Z)?HB(J,null):jY(Z)?GB(J,null):h8(Z)?WB(J,null):O6(Z)?$B(J,null):A6(Z)?ZB(J,null):N6(Z)?JB(J,null):R6(Z)?QB(J,null):PY(Z)?YB(Z,J,null):T6(Z)?VB(J,null):E6(Z)?q6({prompt:I8(J)||"提交计划"},null):_Y(Z)?q6(J,null):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```";return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!0,elements:[{tag:"markdown",content:z},{tag:"column_set",columns:[HY("✅ 允许","primary",Q,"allow"),HY("♾️ 始终允许","default",Q,"allow_always"),HY("❌ 拒绝","danger",Q,"deny")]}]}}function HY($,Z,J,Q){return{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:$},type:Z,behaviors:[{type:"callback",value:{kind:"permission",request_id:J,decision:Q}}]}]}}var pA=300,cK="server_tool:";var KB=R(()=>{d0();A4()});import{execFile as zN}from"node:child_process";import{readFileSync as LB,statfsSync as HN,statSync as BB}from"node:fs";import{cpus as GN,homedir as WN,loadavg as KN,totalmem as BN}from"node:os";import{promisify as jN}from"node:util";function _N(){try{let[$,Z,J]=KN(),Q=GN().length;if(!Q||![$,Z,J].every((Y)=>Number.isFinite(Y)&&Y>=0))throw Error("CPU 核数或负载无效");return{cores:Q,load1:$,load5:Z,load15:J}}catch($){return j(`sysinfo: read CPU failed: ${$}`),null}}function PN(){try{let $=LB("/proc/meminfo","utf8"),Z=(V)=>{let X=$.match(new RegExp(`^${V}:\\s+(\\d+)\\s*kB`,"m"));if(!X)throw Error(`/proc/meminfo 缺少 ${V}`);return Number(X[1])*1024},J=Z("MemTotal"),Q=Z("MemAvailable");if(J<=0||Q>J)throw Error("/proc/meminfo 内存数据无效");let Y=J-Q;return{totalBytes:J,availBytes:Q,usedBytes:Y,percent:Math.round(Y/J*100)}}catch($){return j(`sysinfo: read /proc/meminfo failed: ${$}`),null}}function LN($,Z){let J=$.match(/^Mach Virtual Memory Statistics: \(page size of (\d+) bytes\)/m);if(!J)throw Error("vm_stat 缺少 page size");let Q=Number(J[1]);if(!Number.isSafeInteger(Q)||Q<=0||!Number.isSafeInteger(Z)||Z<=0)throw Error("macOS 内存总量或 page size 无效");let Y=(z)=>{let H=$.match(new RegExp(`^${z}:\\s+(\\d+)\\.\\s*$`,"m"));if(!H||!Number.isSafeInteger(Number(H[1])))throw Error(`vm_stat 缺少或无效 ${z}`);return Number(H[1])},V=Y("Anonymous pages")-Y("Pages purgeable"),X=(V+Y("Pages wired down")+Y("Pages occupied by compressor"))*Q;if(V<0||!Number.isSafeInteger(X)||X>Z)throw Error("vm_stat 内存数据超出物理内存范围");return{totalBytes:Z,availBytes:Z-X,usedBytes:X,percent:Math.round(X/Z*100)}}async function qN($=FB){try{return LN(await $("/usr/bin/vm_stat",[]),BN())}catch(Z){return j(`sysinfo: read macOS memory failed: ${Z}`),null}}function FN($){let Z=$.trim().split(/\r?\n/);if(!/^PID\s+Status\s+Label$/.test(Z.shift()?.trim()??""))throw Error("launchctl list 表头无效");let J=[];for(let Q of Z){if(!Q.trim())continue;let Y=Q.trim().match(/^(\d+|-)\s+(-?\d+)\s+(\S+)$/);if(!Y)throw Error(`launchctl list 行无效: ${Q.trim()}`);let[,V,X,z]=Y;if(!AY.some((W)=>z.startsWith(W)))continue;let H=V==="-"?null:Number(V),G=Number(X);if(H!==null&&(!Number.isSafeInteger(H)||H<=0)||!Number.isSafeInteger(G))throw Error(`launchctl list PID 或退出状态无效: ${z}`);J.push({name:z,pid:H,lastExitStatus:G,active:H!==null?"active":G===0?"inactive":"failed",sub:H!==null?"running":G<0?"signal":"exited",hasStarted:H!==null||G!==0?!0:null,lastActiveAgoSec:null,stateAgoSec:null})}return J.sort((Q,Y)=>Q.name.localeCompare(Y.name))}function DN($){let Z=new Map;for(let J of $.split(`
229
+ `)){if(!J.trim())continue;let Q=J.trim().match(/^(\d+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);if(!Q)throw Error(`ps etime 行无效: ${J.trim()}`);let Y=Number(Q[1]),V=Q[2]===void 0?0:Number(Q[2]),X=Q[3]===void 0?0:Number(Q[3]),z=Number(Q[4]),H=Number(Q[5]),G=((V*24+X)*60+z)*60+H;if(!Number.isSafeInteger(Y)||Y<=0||!Number.isSafeInteger(G)||z>=60||H>=60||Q[2]!==void 0&&(Q[3]===void 0||X>=24))throw Error(`ps etime 数值无效: ${J.trim()}`);Z.set(Y,G)}return Z}async function MN($=FB){let Z;try{Z=FN(await $("/bin/launchctl",["list"]))}catch(Q){return j(`sysinfo: launchctl list failed: ${Q}`),{services:[],error:`launchctl 查询失败: ${Q instanceof Error?Q.message:String(Q)}`}}let J=Z.filter((Q)=>Q.pid!==null);if(J.length>0)try{let Q=DN(await $("/bin/ps",["-p",J.map((Y)=>Y.pid).join(","),"-o","pid=,etime="]));for(let Y of J){let V=Q.get(Y.pid);if(V===void 0)Y.error="ps 未返回该进程,运行时长 MISS",j(`sysinfo: ${Y.name}: ${Y.error}`);else Y.lastActiveAgoSec=V,Y.stateAgoSec=V}}catch(Q){j(`sysinfo: read launchd process elapsed failed: ${Q}`);for(let Y of J)Y.error=`运行时长 MISS: ${Q instanceof Error?Q.message:String(Q)}`}return{services:Z.map(({pid:Q,...Y})=>Y),error:null}}function jB($,Z){try{let J=HN(Z,{bigint:!1}),Q=J.blocks*J.bsize,Y=J.bavail*J.bsize,V=Math.max(0,Q-Y);if(!Q)return null;return{label:$,path:Z,totalBytes:Q,availBytes:Y,usedBytes:V,percent:Math.round(V/Q*100)}}catch(J){return j(`sysinfo: statfs ${Z} failed: ${J}`),null}}function UN(){let $=[],Z=jB("/","/");if(Z)$.push(Z);let J=WN();if(J&&J!=="/"){let Q=!1;try{let Y=BB("/"),V=BB(J);Q=Y.dev===V.dev}catch{}if(!Q){let Y=jB("$HOME",J);if(Y)$.push(Y)}}return $}function ON(){try{let $=LB("/proc/uptime","utf8").trim().split(/\s+/);return parseFloat($[0]??"0")}catch{return null}}async function _B($,Z=2000){try{let{stdout:J}=await qB("systemctl",["--user",...$],{timeout:Z,maxBuffer:4194304});return J}catch(J){return j(`sysinfo: systemctl ${$.join(" ")} failed: ${J}`),null}}function PB($){return AY.some((Z)=>$.startsWith(Z))&&$.endsWith(".service")}async function AN(){let $=await _B(["list-units","--type=service","--all","--no-legend","--plain",...AY.map((H)=>`${H}*`)]);if($===null)return{services:[],error:"systemctl 不可用"};let Z=$.split(`
230
230
  `).map((H)=>H.trim()).filter((H)=>H.length>0);if(Z.length===0)return{services:[],error:null};let J=[];for(let H of Z){let W=H.replace(/^●\s*/,"").split(/\s+/)[0];if(!W)continue;if(!PB(W))continue;J.push(W)}if(J.length===0)return{services:[],error:null};let Q=await _B(["show",...J,"-p","Id","-p","ActiveState","-p","SubState","-p","ActiveEnterTimestampMonotonic","-p","StateChangeTimestampMonotonic"]);if(Q===null)return{services:[],error:"systemctl show 失败"};let Y=ON(),V=Q.split(/\n\s*\n/),X=[],z=(H)=>{let G=parseInt(H??"0",10);if(G<=0||Y===null)return null;return Math.max(0,Y-G/1e6)};for(let H of V){let G={};for(let K of H.split(`
231
- `)){let B=K.indexOf("=");if(B<=0)continue;G[K.slice(0,B)]=K.slice(B+1)}let W=G.Id??"";if(!PB(W))continue;X.push({name:W.replace(/\.service$/,""),active:G.ActiveState??"unknown",sub:G.SubState??"",lastActiveAgoSec:z(G.ActiveEnterTimestampMonotonic),stateAgoSec:z(G.StateChangeTimestampMonotonic),hasStarted:G.ActiveEnterTimestampMonotonic==="0"?!1:null})}return X.sort((H,G)=>H.name.localeCompare(G.name)),{services:X,error:null}}async function FB(){if(process.platform!=="linux"&&process.platform!=="darwin"){let V=process.platform==="win32"?"Windows":process.platform;return{cpu:null,mem:null,disks:[],services:[],servicesError:`${V}: sysinfo 暂未支持`}}let $=_N(),Z=UN(),[J,{services:Q,error:Y}]=await Promise.all([process.platform==="darwin"?qN():PN(),process.platform==="darwin"?MN():AN()]);return{cpu:$,mem:J,disks:Z,services:Q,servicesError:Y}}var qB,AY,g8="cc-* / codex-*",DB=async($,Z)=>{let{stdout:J}=await qB($,Z,{timeout:2000,maxBuffer:4194304,env:{...process.env,LC_ALL:"C",LANG:"C"}});return J};var NY=R(()=>{I();qB=jN(zN),AY=["cc-","codex-"]});function C6($){return $.replace(/[\r\n]+/g," ").replace(/[&<>\\`*_\[\]~]/g,(Z)=>`&#${Z.charCodeAt(0)};`)}function NN($){if($===null||!Number.isFinite($)||$<0||$>100)return"MISS";let Z=`${Math.round($)}%`;return $>=100?`<font color='red'>${Z}</font>`:$>=80?`<font color='orange'>${Z}</font>`:Z}function RN($){let J={fiveHour:"5h",weekly:"周",monthly:"月工具",seven_day_opus:"Opus周",seven_day_sonnet:"Sonnet周",seven_day_oauth_apps:"OAuth周"}[$.kind]??$.label.replace(/\s*周额度$/,"周"),Q=`${C6(J)} ${NN($.percent)}`;if($.kind==="monthly")return Q;return`${Q}/${$.resetsAt&&Number.isFinite($.resetsAt.getTime())?$1($.resetsAt):"MISS"}`}function MB($){if(!$)return"加载中…";if($.state==="not_applicable")return"—";if($.state!=="ok"){let Y=$.state==="no_credentials"?"未登录或未配置":$.state==="rate_limited"?"API 限频":($.reason??"查询失败").replace(/^Claude 原生额度接口未返回 rate_limits 数据$/,"原生接口未返回额度");return`<font color='red'>MISS · ${C6(Y.slice(0,100))}</font>`}let Z=(Y,V)=>{if(!Number.isFinite(Y))return"MISS";return`${V==="USD"?"$":V==="CNY"?"¥":C6(V)} ${Y.toFixed(2)}`};if($.kind==="balance")return`余额 ${$.balance?Z($.balance.remaining,$.balance.currency):"MISS"}`;if($.quota)return $.quota.limit===null?"额度 未设上限":$.quota.remaining===null?"额度 MISS":`额度 ${Z($.quota.remaining,$.quota.currency)} / ${Z($.quota.limit,$.quota.currency)}`;let J=$.windows.map(RN);if(!J.length)J.push("额度 MISS");let Q=$.credits!==void 0?O1($.credits):null;if(Q)J.push(Q);if($.resetCredits!==void 0)J.push(`重置 ${$.resetCredits===null?"MISS":$.resetCredits}`);return J.join(" · ")}function UB($){return{tag:"markdown",text_size:"notation",content:`**${C6($.label)}** ${MB($.usage)}`}}var OB=R(()=>{J9()});function p8($,Z){return Z}function RY($){return{schema:"2.0",config:{update_multi:!0,streaming_mode:!0,summary:{content:$.status}},body:{elements:[{tag:"markdown",element_id:C.footer,content:p8($.title,$.status)}]}}}function AB($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(0)}K`;if($<1073741824)return`${($/1048576).toFixed(0)}M`;let Z=$/1073741824;return Z<10?`${Z.toFixed(1)}G`:`${Z.toFixed(0)}G`}function TN($){if(!$)return"0";if($<1000)return String($);if($<1e6)return($/1000).toFixed($<1e4?1:0).replace(/\.0$/,"")+"K";return($/1e6).toFixed(2).replace(/\.?0+$/,"")+"M"}function m8($){if($<60000)return`${Math.round($/1000)}s`;let Z=Math.floor($/60000);if(Z<60)return`${Z}m`;let J=Math.floor(Z/60),Q=Z%60;if(J<24)return`${J}h ${Q}m`;return`${Math.floor(J/24)}d ${J%24}h`}function xN($){let Z=[];if($?.cpu)Z.push(`L${$.cpu.load1.toFixed(2)}`);if($?.mem)Z.push(`M${$.mem.percent}%`);if($&&!$.servicesError)Z.push(`S${$.services.length}`);return Z}function bN($){if(!$)return["**负载** MISS","**内存** MISS",`**服务** ${g8} MISS`].join(`
231
+ `)){let B=K.indexOf("=");if(B<=0)continue;G[K.slice(0,B)]=K.slice(B+1)}let W=G.Id??"";if(!PB(W))continue;X.push({name:W.replace(/\.service$/,""),active:G.ActiveState??"unknown",sub:G.SubState??"",lastActiveAgoSec:z(G.ActiveEnterTimestampMonotonic),stateAgoSec:z(G.StateChangeTimestampMonotonic),hasStarted:G.ActiveEnterTimestampMonotonic==="0"?!1:null})}return X.sort((H,G)=>H.name.localeCompare(G.name)),{services:X,error:null}}async function DB(){if(process.platform!=="linux"&&process.platform!=="darwin"){let V=process.platform==="win32"?"Windows":process.platform;return{cpu:null,mem:null,disks:[],services:[],servicesError:`${V}: sysinfo 暂未支持`}}let $=_N(),Z=UN(),[J,{services:Q,error:Y}]=await Promise.all([process.platform==="darwin"?qN():PN(),process.platform==="darwin"?MN():AN()]);return{cpu:$,mem:J,disks:Z,services:Q,servicesError:Y}}var qB,AY,g8="cc-* / codex-*",FB=async($,Z)=>{let{stdout:J}=await qB($,Z,{timeout:2000,maxBuffer:4194304,env:{...process.env,LC_ALL:"C",LANG:"C"}});return J};var NY=R(()=>{I();qB=jN(zN),AY=["cc-","codex-"]});function C6($){return $.replace(/[\r\n]+/g," ").replace(/[&<>\\`*_\[\]~]/g,(Z)=>`&#${Z.charCodeAt(0)};`)}function NN($){if($===null||!Number.isFinite($)||$<0||$>100)return"MISS";let Z=`${Math.round($)}%`;return $>=100?`<font color='red'>${Z}</font>`:$>=80?`<font color='orange'>${Z}</font>`:Z}function RN($){let J={fiveHour:"5h",weekly:"周",monthly:"月工具",seven_day_opus:"Opus周",seven_day_sonnet:"Sonnet周",seven_day_oauth_apps:"OAuth周"}[$.kind]??$.label.replace(/\s*周额度$/,"周"),Q=`${C6(J)} ${NN($.percent)}`;if($.kind==="monthly")return Q;return`${Q}/${$.resetsAt&&Number.isFinite($.resetsAt.getTime())?$1($.resetsAt):"MISS"}`}function MB($){if(!$)return"加载中…";if($.state==="not_applicable")return"—";if($.state!=="ok"){let Y=$.state==="no_credentials"?"未登录或未配置":$.state==="rate_limited"?"API 限频":($.reason??"查询失败").replace(/^Claude 原生额度接口未返回 rate_limits 数据$/,"原生接口未返回额度");return`<font color='red'>MISS · ${C6(Y.slice(0,100))}</font>`}let Z=(Y,V)=>{if(!Number.isFinite(Y))return"MISS";return`${V==="USD"?"$":V==="CNY"?"¥":C6(V)} ${Y.toFixed(2)}`};if($.kind==="balance")return`余额 ${$.balance?Z($.balance.remaining,$.balance.currency):"MISS"}`;if($.quota)return $.quota.limit===null?"额度 未设上限":$.quota.remaining===null?"额度 MISS":`额度 ${Z($.quota.remaining,$.quota.currency)} / ${Z($.quota.limit,$.quota.currency)}`;let J=$.windows.map(RN);if(!J.length)J.push("额度 MISS");let Q=$.credits!==void 0?O1($.credits):null;if(Q)J.push(Q);if($.resetCredits!==void 0)J.push(`重置 ${$.resetCredits===null?"MISS":$.resetCredits}`);return J.join(" · ")}function UB($){return{tag:"markdown",text_size:"notation",content:`**${C6($.label)}** ${MB($.usage)}`}}var OB=R(()=>{J9()});function p8($,Z){return Z}function RY($){return{schema:"2.0",config:{update_multi:!0,streaming_mode:!0,summary:{content:$.status}},body:{elements:[{tag:"markdown",element_id:C.footer,content:p8($.title,$.status)}]}}}function AB($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(0)}K`;if($<1073741824)return`${($/1048576).toFixed(0)}M`;let Z=$/1073741824;return Z<10?`${Z.toFixed(1)}G`:`${Z.toFixed(0)}G`}function TN($){if(!$)return"0";if($<1000)return String($);if($<1e6)return($/1000).toFixed($<1e4?1:0).replace(/\.0$/,"")+"K";return($/1e6).toFixed(2).replace(/\.?0+$/,"")+"M"}function m8($){if($<60000)return`${Math.round($/1000)}s`;let Z=Math.floor($/60000);if(Z<60)return`${Z}m`;let J=Math.floor(Z/60),Q=Z%60;if(J<24)return`${J}h ${Q}m`;return`${Math.floor(J/24)}d ${J%24}h`}function xN($){let Z=[];if($?.cpu)Z.push(`L${$.cpu.load1.toFixed(2)}`);if($?.mem)Z.push(`M${$.mem.percent}%`);if($&&!$.servicesError)Z.push(`S${$.services.length}`);return Z}function bN($){if(!$)return["**负载** MISS","**内存** MISS",`**服务** ${g8} MISS`].join(`
232
232
  `);let Z=[];if($.cpu){let{cores:J,load1:Q,load5:Y,load15:V}=$.cpu;Z.push(`**负载** ${Q.toFixed(2)} / ${Y.toFixed(2)} / ${V.toFixed(2)} (${J}核)`)}else Z.push("**负载** MISS");if($.mem)Z.push(`**内存** ${$.mem.percent}% (${AB($.mem.usedBytes)}/${AB($.mem.totalBytes)})`);else Z.push("**内存** MISS");if($.servicesError)Z.push(`**服务** ${g8} _${$.servicesError}_`);else if($.services.length===0)Z.push(`**服务** ${g8} _无_`);else{Z.push(`**服务** ${g8} (${$.services.length})`);for(let J of $.services){let Q=CN[J.active]??"·",Y=J.lastActiveAgoSec,V=J.stateAgoSec,X=[J.active];if(J.active==="active"){if(V!=null)X.push(`已运行 ${m8(V*1000)}`)}else if(J.active==="inactive"||J.active==="failed"){if(Y!=null)X.push(`上次活跃 ${m8(Y*1000)}前`);else if(J.hasStarted===!1)X.push("从未启动");else X.push("上次活跃 MISS");if(V!=null){let z=J.active==="failed"?"已挂":"已停";X.push(`${z} ${m8(V*1000)}`)}}else if(V!=null)X.push(`已 ${m8(V*1000)}`);if(J.active!=="active"&&J.lastExitStatus!==void 0)X.push(J.lastExitStatus<0?`终止信号 ${-J.lastExitStatus}`:`退出码 ${J.lastExitStatus}`);if(J.error)X.push(J.error);Z.push(` · ${Q} \`${J.name}\` · ${X.join(" · ")}`)}}return Z.join(`
233
233
  `)}function kN($){let Z=$.peers??[];if(Z.length===0)return"_无_";return Z.map((J)=>{let Q=EN[J.status]??"·",Y=SN[J.status]??J.status,V=J.uptimeMs!=null&&J.uptimeMs>0?` · ${m8(J.uptimeMs)}`:"",X=J.isCurrent?" · 当前":"",z=J.codexAccountName===void 0?"":` · Codex:${o1(E$(J.codexAccountName))}`;return` · ${Q} \`${J.name}\` · ${Y}${V}${X}${z}`}).join(`
234
234
  `)}function x6($,Z=C.consoleProjects){let J=$.peers??[];return{tag:"collapsible_panel",element_id:Z,header:{title:{tag:"plain_text",content:`\uD83D\uDDC2 活跃项目 (${J.length})`}},expanded:!1,elements:[{tag:"markdown",content:kN($)}]}}function wN($){let Z=$.model?`${$.model}${$.effort?`/${$.effort}`:""}`:$.effort?`强度 ${$.effort}`:"未就绪";return[`**\uD83E\uDD16 当前模型${$.provider==="claude"?` (${bY($.provider)})`:""}** \`${Z}\``,...$.worktreeInstructionNotice?[$.worktreeInstructionNotice]:[]].join(`
235
235
  `)}function b6($,Z=C.consoleCurrentModel){return{tag:"markdown",element_id:Z,content:wN($)}}function k6($,Z=C.consoleHost){let J=xN($);return{tag:"collapsible_panel",element_id:Z,header:{title:{tag:"plain_text",content:J.length>0?`\uD83D\uDDA5 主机 · ${J.join(" · ")}`:"\uD83D\uDDA5 主机"}},expanded:!1,elements:[{tag:"markdown",content:bN($)}]}}function TY($){let Z=$?.kind==="balance"?"余额":"额度";if(!$)return`${Z} 加载中…`;if($.state==="not_applicable")return`${Z} —`;if($.state!=="ok")return`${Z} MISS`;let J=(V,X)=>`${X==="USD"?"$":X==="CNY"?"¥":`${X} `}${V.toFixed(2)}`;if($.kind==="balance")return $.balance?`余额 ${J($.balance.remaining,$.balance.currency)}`:"余额 MISS";if($.quota)return $.quota.limit===null?"额度 未设上限":$.quota.remaining===null?"额度 MISS":`额度 ${J($.quota.remaining,$.quota.currency)} / ${J($.quota.limit,$.quota.currency)}`;let Q=$.windows.length?`额度 ${$.windows.map(vN).join(" · ")}`:"额度 MISS",Y=$.credits!==void 0?O1($.credits):null;return[Q,Y].filter(Boolean).join(" · ")}function vN($){let Z=typeof $.used==="number"&&typeof $.total==="number"?`${$.used}/${$.total}`:$.percent===null?"MISS":`${Math.round($.percent)}%`;return`${$.label} 已用 ${Z}`}function c8($){let Z=$.accountUsages;return{tag:"collapsible_panel",element_id:C.consoleUsage,expanded:!0,header:{title:{tag:"plain_text",content:"全部账号额度 · 已用 / 距重置"},background_color:"blue-50"},border:{color:"blue-100",corner_radius:"8px"},padding:"8px",vertical_spacing:"2px",elements:Z===void 0?[{tag:"markdown",text_size:"notation",content:"加载中…"}]:Z.length?Z.map(UB):[{tag:"markdown",text_size:"notation",content:"暂无已配置账号"}]}}function NB($,Z){return[b6($,Z),x6($),k6($.sysinfo),c8($)]}function w6($){let{sessionName:Z,status:J}=$,Q=J==="working"?"blue":J==="awaiting_permission"?"orange":J==="stopped"?"grey":"green";return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83C\uDF1F Lodestar · ${Z}`},template:Q},body:{elements:NB($)}}}function EY($){return a2($.sessionName,{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"选择账号"}},expanded:!0,elements:[{tag:"markdown",content:`当前: ${o1($.currentDisplay??"未选择")}
236
- 选账号进入模型选择。`},...["claude","codex","dsh"].flatMap((Z)=>{let J=$.providers.filter((Q)=>(Q.provider??"codex")===Z);return J.length?[{tag:"collapsible_panel",element_id:C.modelAgentGroup(Z),expanded:!0,header:{title:{tag:"markdown",content:`**Agent · ${{claude:"Claude Code",codex:"Codex",dsh:"DeepSeek Harness"}[Z]}**`},background_color:"blue-50"},border:{color:"blue-100",corner_radius:"8px"},padding:"8px",margin:"8px 0px 0px 0px",elements:J.map((Q)=>fN(Q,$.panelId))}]:[]})]})}function fN($,Z){if(!$.enabled)return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`⚙️ **${E$($.display)}** · 未配置`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"启"},type:"primary",behaviors:[{type:"callback",value:{kind:"token_source_enable",source_id:$.sourceId}}]}]}]};let J=$.catalogStatus==="failed"?`模型目录 MISS${$.catalogError?`:${$.catalogError}`:""}`:$.catalogStatus==="loading"||$.catalogStatus==="idle"?"模型目录加载中":`${$.modelCount} 个模型${$.catalogError?` · 刷新 MISS:${$.catalogError}`:""}`,Q=[$.selected?"当前账号":"",J].filter(Boolean).join(" · ");return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`**${E$($.display)}**
237
- ${Q}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"选"},type:$.selected?"primary":"default",behaviors:[{type:"callback",value:{kind:"provider_select",panel_id:Z,source_id:$.sourceId,...$.provider?{provider:$.provider}:{}}}]}]}]}}function SY($){return a2($.sessionName,RB($))}function CY($){return a2($.sessionName,y6($))}function u8($){return a2($.sessionName,h6($),"green")}function l8($,Z){return{tag:"collapsible_panel",element_id:C.modelPanel,expanded:!0,header:{title:{tag:"plain_text",content:$?"模型设置确认中":"模型设置未完成"}},elements:[{tag:"markdown",content:E$(Z)}]}}function v6($,Z,J){return a2($,l8(Z,J),Z?"orange":"red")}function a2($,Z,J="turquoise"){return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83E\uDD16 model · ${$}`},template:J},body:{elements:[Z]}}}function RB($){let Z=IN($.models,$.panelId,$.mode,$.editable);return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:$.mode==="add"?"显示模型":"选择模型"}},expanded:!0,elements:[{tag:"markdown",content:[`当前: ${TB($.currentModel,$.currentEffort)}`,$.mode==="add"?"显示账号接口中的模型。":"接口模型可隐藏,补录模型可删除。有多个 effort 档位时再选择档位。"].join(`
238
- `)},...$.models.length?Z:[{tag:"markdown",content:$.editable?$.mode==="add"?"_没有待显示的接口模型_":"_列表为空,可显示接口模型或补录_":"_未返回可用模型列表_"}],...$.pagination?yN($.panelId,$.pagination):[],...$.editable&&$.allowCustom?[{tag:"button",text:{tag:"plain_text",content:"补录模型"},type:"default",behaviors:[{type:"callback",value:{kind:"model_custom_prompt",panel_id:$.panelId,source_id:$.sourceId}}]}]:[],{tag:"button",text:{tag:"plain_text",content:$.editable?$.mode==="add"?"返回模型列表":"显示模型":"补录模型"},type:"default",width:"default",behaviors:[{type:"callback",value:{kind:$.editable?"model_list_open":"model_custom_prompt",panel_id:$.panelId,...$.sourceId||$.models[0]?.sourceId?{source_id:$.sourceId??$.models[0]?.sourceId}:{},...$.editable?{mode:$.mode==="add"?"select":"add"}:{}}}]}]}}function yN($,Z){let{sourceId:J,page:Q,totalPages:Y}=Z,V=(X,z)=>({tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:X},type:"default",behaviors:[{type:"callback",value:{kind:"model_page",panel_id:$,source_id:J,page:z}}]}]});return[{tag:"markdown",content:`第 ${Q+1} / ${Y} 页`},{tag:"column_set",columns:[...Q>0?[V("上一页",Q-1)]:[],...Q+1<Y?[V("下一页",Q+1)]:[]]}]}function f6($,Z="cancelled"){return a2($,{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:Z==="stale"?"_此补录面板已失效 — 当前等待中的补录未受影响_":"_已取消补录 — 列表未改动_"}]},"grey")}function xY($,Z,J){return a2($,{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:[`**直接回复模型名补录到 ${Z}**`,"补录后可选择 effort 并使用;模型是否接受该档位由实际请求确认。","_裸词命令(hi/stop/model 等)不受影响_"].join(`
236
+ 选账号进入模型选择。`},...["claude","codex","dsh"].flatMap((Z)=>{let J=$.providers.filter((Q)=>(Q.provider??"codex")===Z);return J.length?[{tag:"collapsible_panel",element_id:C.modelAgentGroup(Z),expanded:!0,header:{title:{tag:"markdown",content:`**Agent · ${{claude:"Claude Code",codex:"Codex",dsh:"DeepSeek Harness"}[Z]}**`},background_color:"blue-50"},border:{color:"blue-100",corner_radius:"8px"},padding:"8px",margin:"8px 0px 0px 0px",elements:J.map((Q)=>yN(Q,$.panelId))}]:[]})]})}function yN($,Z){if(!$.enabled)return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`⚙️ **${E$($.display)}** · 未配置`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"启"},type:"primary",behaviors:[{type:"callback",value:{kind:"token_source_enable",source_id:$.sourceId}}]}]}]};let J=$.catalogStatus==="failed"?`模型目录 MISS${$.catalogError?`:${$.catalogError}`:""}`:$.catalogStatus==="loading"||$.catalogStatus==="idle"?"模型目录加载中":`${$.modelCount} 个模型${$.catalogError?` · 刷新 MISS:${$.catalogError}`:""}`,Q=[$.selected?"当前账号":"",J].filter(Boolean).join(" · ");return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`**${E$($.display)}**
237
+ ${Q}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"选"},type:$.selected?"primary":"default",behaviors:[{type:"callback",value:{kind:"provider_select",panel_id:Z,source_id:$.sourceId,...$.provider?{provider:$.provider}:{}}}]}]}]}}function SY($){return a2($.sessionName,RB($))}function CY($){return a2($.sessionName,f6($))}function u8($){return a2($.sessionName,h6($),"green")}function l8($,Z){return{tag:"collapsible_panel",element_id:C.modelPanel,expanded:!0,header:{title:{tag:"plain_text",content:$?"模型设置确认中":"模型设置未完成"}},elements:[{tag:"markdown",content:E$(Z)}]}}function v6($,Z,J){return a2($,l8(Z,J),Z?"orange":"red")}function a2($,Z,J="turquoise"){return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83E\uDD16 model · ${$}`},template:J},body:{elements:[Z]}}}function RB($){let Z=IN($.models,$.panelId,$.mode,$.editable);return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:$.mode==="add"?"显示模型":"选择模型"}},expanded:!0,elements:[{tag:"markdown",content:[`当前: ${TB($.currentModel,$.currentEffort)}`,$.mode==="add"?"显示账号接口中的模型。":"接口模型可隐藏,补录模型可删除。有多个 effort 档位时再选择档位。"].join(`
238
+ `)},...$.models.length?Z:[{tag:"markdown",content:$.editable?$.mode==="add"?"_没有待显示的接口模型_":"_列表为空,可显示接口模型或补录_":"_未返回可用模型列表_"}],...$.pagination?fN($.panelId,$.pagination):[],...$.editable&&$.allowCustom?[{tag:"button",text:{tag:"plain_text",content:"补录模型"},type:"default",behaviors:[{type:"callback",value:{kind:"model_custom_prompt",panel_id:$.panelId,source_id:$.sourceId}}]}]:[],{tag:"button",text:{tag:"plain_text",content:$.editable?$.mode==="add"?"返回模型列表":"显示模型":"补录模型"},type:"default",width:"default",behaviors:[{type:"callback",value:{kind:$.editable?"model_list_open":"model_custom_prompt",panel_id:$.panelId,...$.sourceId||$.models[0]?.sourceId?{source_id:$.sourceId??$.models[0]?.sourceId}:{},...$.editable?{mode:$.mode==="add"?"select":"add"}:{}}}]}]}}function fN($,Z){let{sourceId:J,page:Q,totalPages:Y}=Z,V=(X,z)=>({tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:X},type:"default",behaviors:[{type:"callback",value:{kind:"model_page",panel_id:$,source_id:J,page:z}}]}]});return[{tag:"markdown",content:`第 ${Q+1} / ${Y} 页`},{tag:"column_set",columns:[...Q>0?[V("上一页",Q-1)]:[],...Q+1<Y?[V("下一页",Q+1)]:[]]}]}function y6($,Z="cancelled"){return a2($,{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:Z==="stale"?"_此补录面板已失效 — 当前等待中的补录未受影响_":"_已取消补录 — 列表未改动_"}]},"grey")}function xY($,Z,J){return a2($,{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:[`**直接回复模型名补录到 ${Z}**`,"补录后可选择 effort 并使用;模型是否接受该档位由实际请求确认。","_裸词命令(hi/stop/model 等)不受影响_"].join(`
239
239
  `)},{tag:"button",text:{tag:"plain_text",content:"取消"},type:"default",width:"default",behaviors:[{type:"callback",value:{kind:"model_panel_cancel",panel_id:J}}]}]},"blue")}function d8($,Z,J){return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:$?`✅ \`${Z}\` 已加入列表${J?`
240
- ${J}`:""}`:`❌ \`${Z}\` 未加入 — ${J}`}]}}function y6($){return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"选择 effort"}},expanded:!0,elements:[{tag:"markdown",content:[`模型: ${pN($.model)}`,`当前: ${TB($.currentModel,$.currentEffort)}`].join(`
240
+ ${J}`:""}`:`❌ \`${Z}\` 未加入 — ${J}`}]}}function f6($){return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"选择 effort"}},expanded:!0,elements:[{tag:"markdown",content:[`模型: ${pN($.model)}`,`当前: ${TB($.currentModel,$.currentEffort)}`].join(`
241
241
  `)},...$.model.efforts.length?$.model.efforts.map((Z)=>gN($.model,Z,$.panelId,$.currentModel,$.currentEffort)):[{tag:"markdown",content:"_该模型未返回可用 effort_"}]]}}function h6($){return{tag:"collapsible_panel",element_id:C.modelPanel,header:{title:{tag:"plain_text",content:"选择已保存"}},expanded:!0,elements:[{tag:"markdown",content:["**已保存**",o1(EB($.model,$.effort,$.provider)),E$($.scope)].join(`
242
242
  `)}]}}function hN($,Z,J,Q=!1){if($.enabled===!1)return[{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`⚙️ **${E$($.displayName)}** · 未配置
243
243
  ${E$($.description??"")}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"启"},type:"primary",behaviors:[{type:"callback",value:{kind:"token_source_enable",source_id:$.sourceId}}]}]}]}];let Y=$.displayName&&$.displayName!==$.model?`**${E$($.displayName)}**`:`**${o1($.model)}**`,V=[$.isDefault?`${bY($.provider)} 默认`:"",$.selected?"当前模型":""].filter(Boolean),X=$.description?`
244
244
  `+E$(cN($.description,110)):"",z=(G,W)=>({tag:"button",text:{tag:"plain_text",content:W},type:"default",behaviors:[{type:"callback",value:{kind:G,panel_id:Z,source_id:$.sourceId,model:$.model}}]});return[{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,vertical_align:"center",elements:[{tag:"markdown",content:[Y,$.displayName&&$.displayName!==$.model?o1($.model):"",V.length?V.join(" · "):""].filter(Boolean).join(`
245
245
  `)+X}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[...J==="add"?[z("model_add","显")]:$.unavailableReason?[{tag:"markdown",content:"**MISS**"}]:[{tag:"button",text:{tag:"plain_text",content:"选"},type:$.selected?"primary":"default",behaviors:[{type:"callback",value:mN($,Z)}]}],...Q&&J!=="add"?[$.origin==="custom"?z("model_custom_remove","删"):z("model_remove","隐")]:[]]}]}]}function IN($,Z,J,Q=!1){let Y=[{title:"Codex",models:$.filter((z)=>(z.provider??"codex")==="codex")},{title:"Claude Code 后端",models:$.filter((z)=>z.provider==="claude")},{title:"DeepSeek Harness",models:$.filter((z)=>z.provider==="dsh")}].filter((z)=>z.models.length>0),V=(z)=>z.flatMap((H,G)=>[...G?[{tag:"hr"}]:[],...hN(H,Z,J,Q)]);if(Y.length<=1)return V($);let X=[];for(let z of Y)X.push({tag:"markdown",content:`**${z.title}**`}),X.push(...V(z.models));return X}function gN($,Z,J,Q,Y){let V=Q===$.model&&Y===Z.effort,X=[Z.isDefault?"默认":"",V?"当前":""].filter(Boolean).join(" · ");return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:[`**${Z.effort==="default"?"模型默认":E$(Z.effort)}**`,X,Z.description?E$(Z.description):""].filter(Boolean).join(`
246
- `)}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"选"},type:V?"primary":"default",behaviors:[{type:"callback",value:{kind:"model_effort_select",panel_id:J,...$.sourceId?{source_id:$.sourceId}:{},...$.provider?{provider:$.provider}:{},model:$.model,effort:Z.effort}}]}]}]}}function mN($,Z){return{kind:"model_select",panel_id:Z,...$.sourceId?{source_id:$.sourceId}:{},...$.provider&&$.provider!=="codex"?{provider:$.provider}:{},model:$.model,display_name:$.displayName,is_default:$.isDefault===!0,efforts:$.efforts.map((J)=>({effort:J.effort,description:J.description??"",is_default:J.isDefault===!0}))}}function pN($){return $.displayName&&$.displayName!==$.model?`${E$($.displayName)} (${o1($.model)})`:o1($.model)}function TB($,Z){return o1(EB($,Z))}function EB($,Z,J){let Q=J&&J!=="codex"?`${bY(J)} · `:"";if($&&Z)return`${Q}${$}/${Z}`;if($)return`${Q}${$}`;if(Z)return`${Q}${Z}`;return"未选择"}function bY($){return t0($??"codex")}function cN($,Z){return $.length<=Z?$:$.slice(0,Z-1)+"…"}function E$($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function o1($){return"`"+$.replace(/`/g,"\\`")+"`"}function o2($){let Z=[];if(Z.push($.suffix??"✅"),$.durationSec!=null)Z.push(`⏱ ${f0($.durationSec)}`);if($.outputTokens!=null&&$.outputTokens>0)Z.push(`\uD83D\uDCF6 ${TN($.outputTokens)}`);return{config:{streaming_mode:!1,summary:{content:Z.join(" · ")}}}}var EN,SN,CN;var SB=R(()=>{P0();NY();d0();J9();OB();J9();EN={idle:"\uD83D\uDFE2",working:"⚙️",awaiting_permission:"\uD83D\uDD10",starting:"\uD83D\uDE80",stopped:"⚪"},SN={idle:"闲",working:"工作中",awaiting_permission:"等审批",starting:"启动中",stopped:"未运行"},CN={active:"\uD83D\uDFE2",activating:"\uD83D\uDE80",reloading:"\uD83D\uDD04",inactive:"⚪",deactivating:"\uD83D\uDFE1",failed:"❌"}});function kY($){let Z=dN($);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83C\uDF3F wt"},template:uN($.notice)},body:{elements:[...$.notice?[lN($.notice)]:[],...Z?[{tag:"markdown",content:Z}]:[],...$.entries.flatMap(iN)]}}}function uN($){if($?.type==="error")return"red";if($?.type==="success")return"green";return"turquoise"}function lN($){let Z=$.type==="error"?"red":$.type==="success"?"green":"grey";return{tag:"markdown",content:$.content.split(`
246
+ `)}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"选"},type:V?"primary":"default",behaviors:[{type:"callback",value:{kind:"model_effort_select",panel_id:J,...$.sourceId?{source_id:$.sourceId}:{},...$.provider?{provider:$.provider}:{},model:$.model,effort:Z.effort}}]}]}]}}function mN($,Z){return{kind:"model_select",panel_id:Z,...$.sourceId?{source_id:$.sourceId}:{},...$.provider&&$.provider!=="codex"?{provider:$.provider}:{},model:$.model,display_name:$.displayName,is_default:$.isDefault===!0,efforts:$.efforts.map((J)=>({effort:J.effort,description:J.description??"",is_default:J.isDefault===!0}))}}function pN($){return $.displayName&&$.displayName!==$.model?`${E$($.displayName)} (${o1($.model)})`:o1($.model)}function TB($,Z){return o1(EB($,Z))}function EB($,Z,J){let Q=J&&J!=="codex"?`${bY(J)} · `:"";if($&&Z)return`${Q}${$}/${Z}`;if($)return`${Q}${$}`;if(Z)return`${Q}${Z}`;return"未选择"}function bY($){return t0($??"codex")}function cN($,Z){return $.length<=Z?$:$.slice(0,Z-1)+"…"}function E$($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function o1($){return"`"+$.replace(/`/g,"\\`")+"`"}function o2($){let Z=[];if(Z.push($.suffix??"✅"),$.durationSec!=null)Z.push(`⏱ ${y0($.durationSec)}`);if($.outputTokens!=null&&$.outputTokens>0)Z.push(`\uD83D\uDCF6 ${TN($.outputTokens)}`);return{config:{streaming_mode:!1,summary:{content:Z.join(" · ")}}}}var EN,SN,CN;var SB=R(()=>{P0();NY();d0();J9();OB();J9();EN={idle:"\uD83D\uDFE2",working:"⚙️",awaiting_permission:"\uD83D\uDD10",starting:"\uD83D\uDE80",stopped:"⚪"},SN={idle:"闲",working:"工作中",awaiting_permission:"等审批",starting:"启动中",stopped:"未运行"},CN={active:"\uD83D\uDFE2",activating:"\uD83D\uDE80",reloading:"\uD83D\uDD04",inactive:"⚪",deactivating:"\uD83D\uDFE1",failed:"❌"}});function kY($){let Z=dN($);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83C\uDF3F wt"},template:uN($.notice)},body:{elements:[...$.notice?[lN($.notice)]:[],...Z?[{tag:"markdown",content:Z}]:[],...$.entries.flatMap(iN)]}}}function uN($){if($?.type==="error")return"red";if($?.type==="success")return"green";return"turquoise"}function lN($){let Z=$.type==="error"?"red":$.type==="success"?"green":"grey";return{tag:"markdown",content:$.content.split(`
247
247
  `).map((J)=>`<font color='${Z}'>${J||" "}</font>`).join(`
248
248
  `)}}function dN($){let Z=$.hiddenMergedUnmountedCount??0;if(!$.entries.length&&Z===0)return`_无 work/* 分支。发 ${I6("wt name")} 创建。_`;if(Z>0)return`${Z}个已归档分支`;return""}function iN($){let Z=$.error?"出错":$.mounted&&$.dirtyCount&&$.dirtyCount>0?`有未提交改动 ${$.dirtyCount}`:$.state==="merged"?"已合并":$.state==="stale"?"两边都有新改动":$.mounted?"进行中":"未挂载",J=$.duplicateChatCount>1?`群重复 ${$.duplicateChatCount} 个`:$.chatId?"群正常":"无群",Q=[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`**${I6($.slug)}**
249
249
  ${Z} · ${J}
@@ -251,9 +251,9 @@ ${I6($.branch)}`}]}];if($.mounted||$.chatId)Q.push({tag:"column",width:"weighted
251
251
  `)}]}}}function I6($){return"`"+$.replace(/`/g,"\\`")+"`"}function vY($){let Z=$.mode==="fork",J=Z?"分叉":"回退",Q=Z?"temp_fork_select":"temp_back_select",Y=Z?`\uD83D\uDCA1 选择一条「用户输入」,将在临时群从它**之前**创建独立对话分支;选中的输入本身不包含。
252
252
  分支与本群共享 cwd 和磁盘文件;只分叉对话历史,不复制或回滚文件,原会话不动。`:`⚠️ 选择一条「用户输入」,将停止本群当前 turn 和后台任务,并从它**之前**创建后续对话分支;选中的输入本身不包含。
253
253
  只回退对话历史,不会回滚 cwd 中的文件。`,V=[];if($.notice)V.push({tag:"markdown",content:nN($.notice)});if(!$.entries.length)V.push({tag:"markdown",content:"_当前会话还没有已完成的 turn,无法分叉/回退。_"});else{V.push({tag:"markdown",content:Y});for(let X of $.entries)V.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:5,elements:[{tag:"markdown",content:`**${IY(X.ts)}**
254
- ${s1(X.preview.slice(0,60)||"(空)")}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:J},type:Z?"primary":"danger",behaviors:[{type:"callback",value:{kind:Q,panel_id:$.panelId,choice_id:X.choiceId}}]}]}]})}return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`${Z?"\uD83D\uDD31 fk 分叉":"⏪ bk 回退"} · ${$.projectName}`},template:Z?"turquoise":"orange"},body:{elements:V}}}function fY($){let Z=[];if(!$.entries.length)Z.push({tag:"markdown",content:`_项目「${$.projectName}」没有可创建分支的历史会话。_`});else{Z.push({tag:"markdown",content:`\uD83D\uDCA1 选择一个历史会话,在**当前群**创建独立对话分支;源会话不动。
254
+ ${s1(X.preview.slice(0,60)||"(空)")}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:J},type:Z?"primary":"danger",behaviors:[{type:"callback",value:{kind:Q,panel_id:$.panelId,choice_id:X.choiceId}}]}]}]})}return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`${Z?"\uD83D\uDD31 fk 分叉":"⏪ bk 回退"} · ${$.projectName}`},template:Z?"turquoise":"orange"},body:{elements:V}}}function yY($){let Z=[];if(!$.entries.length)Z.push({tag:"markdown",content:`_项目「${$.projectName}」没有可创建分支的历史会话。_`});else{Z.push({tag:"markdown",content:`\uD83D\uDCA1 选择一个历史会话,在**当前群**创建独立对话分支;源会话不动。
255
255
  新分支共享当前 cwd 和磁盘文件;只分叉对话历史,不复制或回滚文件。`});for(let J of $.entries)Z.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:5,elements:[{tag:"markdown",content:`**${IY(J.ts)}**
256
- ${s1(J.preview.slice(0,60)||"(无摘要)")}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"分支"},type:"primary",behaviors:[{type:"callback",value:{kind:"temp_resume_select",panel_id:$.panelId,choice_id:J.choiceId}}]}]}]})}return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDD01 rs 独立分支 · ${$.projectName}`},template:"purple"},body:{elements:Z}}}function yY($){let Z=$.entries.length===0?"(回退范围内未观察到 Write/Edit/FileChange 类文件变更)":$.entries.map((J)=>{let Q=J.body.length>800?J.body.slice(0,800)+`
256
+ ${s1(J.preview.slice(0,60)||"(无摘要)")}`}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"分支"},type:"primary",behaviors:[{type:"callback",value:{kind:"temp_resume_select",panel_id:$.panelId,choice_id:J.choiceId}}]}]}]})}return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDD01 rs 独立分支 · ${$.projectName}`},template:"purple"},body:{elements:Z}}}function fY($){let Z=$.entries.length===0?"(回退范围内未观察到 Write/Edit/FileChange 类文件变更)":$.entries.map((J)=>{let Q=J.body.length>800?J.body.slice(0,800)+`
257
257
  …(截断)`:J.body;return`${J.path} (${J.tool})
258
258
  ${Q}`}).join(`
259
259
 
@@ -272,40 +272,40 @@ ${Q}`}).join(`
272
272
  `).map((J)=>`<font color='${Z}'>${tN(J)||" "}</font>`).join(`
273
273
  `)}}function mY($){return"`"+$.replace(/`/g,"\\`")+"`"}function tN($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var bB=R(()=>{d0()});import{createHash as rN}from"node:crypto";function uY($){let Z=[{tag:"markdown",element_id:C.agentIdentityPanel,content:["**全局 Agent 身份**","选择一个或多个 Agent 执行任务,由主 Agent 统一分配和汇总结果。",`目录第 ${$.page+1}/${$.totalPages} 页`].join(`
274
274
  `)}];if($.failures.length)Z.push({tag:"collapsible_panel",header:{title:{tag:"plain_text",content:`MISS · ${$.failures.length} 个账号`}},expanded:!1,elements:[{tag:"markdown",content:$.failures.map((J)=>`- **${V1(J.display)}**:${V1(J.reason)}`).join(`
275
- `)}]});return Z.push(...$.catalog.map(eN),$R($)),{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83E\uDDE0 可用 Agent"},template:"purple"},body:{elements:Z}}}function lY($){let Z=$.owner?.kind==="project",J=fB($);return{tag:"collapsible_panel",element_id:m6($.runId),header:{title:{tag:"plain_text",content:p6($)}},expanded:!1,elements:[{tag:"markdown",content:[`**${V1(J.description)}**`,...Z?[`项目 ${N1($.owner.name)} · ${N1($.runId)}`]:[],vB($).content,`**任务说明**
275
+ `)}]});return Z.push(...$.catalog.map(eN),$R($)),{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83E\uDDE0 可用 Agent"},template:"purple"},body:{elements:Z}}}function lY($){let Z=$.owner?.kind==="project",J=yB($);return{tag:"collapsible_panel",element_id:m6($.runId),header:{title:{tag:"plain_text",content:p6($)}},expanded:!1,elements:[{tag:"markdown",content:[`**${V1(J.description)}**`,...Z?[`项目 ${N1($.owner.name)} · ${N1($.runId)}`]:[],vB($).content,`**任务说明**
276
276
  ${G0(E8(J.prompt))}`,...$.workers.map((Q)=>wB(Q,kB,Z).content)].join(`
277
277
 
278
- `)},...Z&&!iY($.status)?[{tag:"button",text:{tag:"plain_text",content:"停止本次任务"},type:"danger",behaviors:[{type:"callback",value:{kind:"agent_project_cancel",run_id:$.runId}}]}]:[]]}}function m6($){return`ar_${rN("sha256").update($).digest("hex").slice(0,16)}`}function dY($){if($.length===1)return $[0].summary;let Z=$.filter((z)=>z.terminal).length,J=$.filter((z)=>z.status==="failed").length,Q=$.filter((z)=>z.status==="needs_input"||z.status==="paused").length,Y=new Set($.map((z)=>z.kind??"delegated")),V=BK.filter((z)=>Y.has(z));return`${V.length===1?`${jK(V[0])} ${d2(V[0])}`:`\uD83E\uDDE9 运行任务 · ${V.map((z)=>`${d2(z)} ${$.filter((H)=>(H.kind??"delegated")===z).length}`).join(" · ")}`} · 已结束 ${Z}/${$.length}${J?` · 失败 ${J}`:""}${Q?` · 待处理 ${Q}`:""}`}function wB($,Z=kB,J=!1){let Q=ZR($),Y=$.translationEnabled===!0,V=$.displayOutput??(Y?"":$.output),X=$.displayPendingInput??(Y?void 0:$.pendingInput),z=[`模型 ${N1($.model)} · 推理 ${N1($.effort)}`];if($.durationMs!=null)z.push(`用时 ${f0($.durationMs/1000)}`);if($.status==="queued"&&$.queuedReason)z.push("",V1($.queuedReason));if($.pendingInput){if(z.push("",J?"**项目任务不支持交互提问**":"**等待主 Agent 回答**"),!X)z.push("问题译文 MISS");for(let H of X?.questions??[])if(z.push(`- ${V1(H.question)}`),H.options.length)z.push(` 选项:${H.options.map((G)=>N1(G.label)).join(" / ")}`)}if($.error)z.push("",$.status==="cancelled"?"**停止原因**":"**失败原因**",G0($.displayError??$.error));if(V)z.push("",$.status==="failed"||$.status==="cancelled"?"**已生成的内容**":"**结果**",G0(Z6(V,Z)));if(Y&&$.output&&$.displayOutput===void 0)z.push("","**结果译文 MISS**");if(!$.output&&!$.error&&!$.pendingInput)z.push("",$.status==="completed"?"_任务已完成,没有正文输出。_":$.status==="cancelled"?"_任务已取消。_":$.status==="queued"?"_等待开始执行。_":"_正在执行任务,结果会显示在这里。_");if($.steps.length){z.push("","**最近动作**");for(let H of $.steps.slice(-3)){let G=H.tool==="tool error"?"❌":H.phase==="completed"?"✓":H.phase==="started"?"→":"·",W=H.tool==="tool error"?"工具执行失败":H.tool==="tool result"?"工具执行完成":H.tool,K=H.displayDetail??(Y&&H.detail?"动作说明译文 MISS":H.detail);z.push(`- ${G} ${N1(W)} ${V1(hB(K,180))}`)}}return{tag:"markdown",content:[`**${Q} · ${V1($.identityName)}**`,...z].join(`
279
- `)}}function vB($){let Z=$.workers.filter((W)=>W.status==="completed").length,J=$.workers.filter((W)=>W.status==="failed").length,Q=$.workers.filter((W)=>W.status==="needs_input").length,Y=$.workers.filter((W)=>W.status==="running").length,V=$.workers.filter((W)=>W.status==="queued").length,X=$.workers.filter((W)=>W.status==="cancelled").length,z=[Y?`执行中 ${Y}`:"",V?`排队 ${V}`:"",Q?`待答 ${Q}`:"",J?`失败 ${J}`:"",X?`已取消 ${X}`:""].filter(Boolean),H=$.finishedAt?Date.parse($.finishedAt)-Date.parse($.createdAt):null;return{tag:"markdown",content:[`**${yB($)}** · 完成 ${Z}/${$.workers.length}`,...z.length?[z.join(" · ")]:[],...H!=null&&Number.isFinite(H)?[`⏱ 用时 ${f0(H/1000)}`]:[],...$.error?[V1($.error)]:[]].join(`
280
- `)}}function p6($){let Z=$.workers.filter((J)=>J.status==="completed").length;return`${yB($)} · ${hB(fB($).description,40)}${$.workers.length>1?` · ${Z}/${$.workers.length}`:""}`}function fB($){let Z=$.workers.find((Q)=>Q.translationEnabled===!0);if(!Z)return{description:$.description??"说明 MISS",prompt:$.prompt};let J=iY($.status)?"任务说明译文 MISS":"正在翻译任务说明";return{description:Z.displayDescription??J,prompt:Z.displayPrompt??J}}function eN($){let J=$.status==="ready"?"可用":`不可用:${$.reason??"MISS"}`;return{tag:"markdown",content:[`**${V1($.displayName)}** ${$.sourceDefault?"· 默认":""}`,`${N1($.id)}
278
+ `)},...Z&&!iY($.status)?[{tag:"button",text:{tag:"plain_text",content:"停止本次任务"},type:"danger",behaviors:[{type:"callback",value:{kind:"agent_project_cancel",run_id:$.runId}}]}]:[]]}}function m6($){return`ar_${rN("sha256").update($).digest("hex").slice(0,16)}`}function dY($){if($.length===1)return $[0].summary;let Z=$.filter((z)=>z.terminal).length,J=$.filter((z)=>z.status==="failed").length,Q=$.filter((z)=>z.status==="needs_input"||z.status==="paused").length,Y=new Set($.map((z)=>z.kind??"delegated")),V=BK.filter((z)=>Y.has(z));return`${V.length===1?`${jK(V[0])} ${d2(V[0])}`:`\uD83E\uDDE9 运行任务 · ${V.map((z)=>`${d2(z)} ${$.filter((H)=>(H.kind??"delegated")===z).length}`).join(" · ")}`} · 已结束 ${Z}/${$.length}${J?` · 失败 ${J}`:""}${Q?` · 待处理 ${Q}`:""}`}function wB($,Z=kB,J=!1){let Q=ZR($),Y=$.translationEnabled===!0,V=$.displayOutput??(Y?"":$.output),X=$.displayPendingInput??(Y?void 0:$.pendingInput),z=[`模型 ${N1($.model)} · 推理 ${N1($.effort)}`];if($.durationMs!=null)z.push(`用时 ${y0($.durationMs/1000)}`);if($.status==="queued"&&$.queuedReason)z.push("",V1($.queuedReason));if($.pendingInput){if(z.push("",J?"**项目任务不支持交互提问**":"**等待主 Agent 回答**"),!X)z.push("问题译文 MISS");for(let H of X?.questions??[])if(z.push(`- ${V1(H.question)}`),H.options.length)z.push(` 选项:${H.options.map((G)=>N1(G.label)).join(" / ")}`)}if($.error)z.push("",$.status==="cancelled"?"**停止原因**":"**失败原因**",G0($.displayError??$.error));if(V)z.push("",$.status==="failed"||$.status==="cancelled"?"**已生成的内容**":"**结果**",G0(Z6(V,Z)));if(Y&&$.output&&$.displayOutput===void 0)z.push("","**结果译文 MISS**");if(!$.output&&!$.error&&!$.pendingInput)z.push("",$.status==="completed"?"_任务已完成,没有正文输出。_":$.status==="cancelled"?"_任务已取消。_":$.status==="queued"?"_等待开始执行。_":"_正在执行任务,结果会显示在这里。_");if($.steps.length){z.push("","**最近动作**");for(let H of $.steps.slice(-3)){let G=H.tool==="tool error"?"❌":H.phase==="completed"?"✓":H.phase==="started"?"→":"·",W=H.tool==="tool error"?"工具执行失败":H.tool==="tool result"?"工具执行完成":H.tool,K=H.displayDetail??(Y&&H.detail?"动作说明译文 MISS":H.detail);z.push(`- ${G} ${N1(W)} ${V1(hB(K,180))}`)}}return{tag:"markdown",content:[`**${Q} · ${V1($.identityName)}**`,...z].join(`
279
+ `)}}function vB($){let Z=$.workers.filter((W)=>W.status==="completed").length,J=$.workers.filter((W)=>W.status==="failed").length,Q=$.workers.filter((W)=>W.status==="needs_input").length,Y=$.workers.filter((W)=>W.status==="running").length,V=$.workers.filter((W)=>W.status==="queued").length,X=$.workers.filter((W)=>W.status==="cancelled").length,z=[Y?`执行中 ${Y}`:"",V?`排队 ${V}`:"",Q?`待答 ${Q}`:"",J?`失败 ${J}`:"",X?`已取消 ${X}`:""].filter(Boolean),H=$.finishedAt?Date.parse($.finishedAt)-Date.parse($.createdAt):null;return{tag:"markdown",content:[`**${fB($)}** · 完成 ${Z}/${$.workers.length}`,...z.length?[z.join(" · ")]:[],...H!=null&&Number.isFinite(H)?[`⏱ 用时 ${y0(H/1000)}`]:[],...$.error?[V1($.error)]:[]].join(`
280
+ `)}}function p6($){let Z=$.workers.filter((J)=>J.status==="completed").length;return`${fB($)} · ${hB(yB($).description,40)}${$.workers.length>1?` · ${Z}/${$.workers.length}`:""}`}function yB($){let Z=$.workers.find((Q)=>Q.translationEnabled===!0);if(!Z)return{description:$.description??"说明 MISS",prompt:$.prompt};let J=iY($.status)?"任务说明译文 MISS":"正在翻译任务说明";return{description:Z.displayDescription??J,prompt:Z.displayPrompt??J}}function eN($){let J=$.status==="ready"?"可用":`不可用:${$.reason??"MISS"}`;return{tag:"markdown",content:[`**${V1($.displayName)}** ${$.sourceDefault?"· 默认":""}`,`${N1($.id)}
281
281
  ${N1($.model)} · 默认 ${N1($.defaultEffort??"MISS")} · ${V1(J)}`].join(`
282
- `)}}function $R($){return{tag:"column_set",columns:[cY("上一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.max(0,$.page-1)}),cY("刷新",{kind:"agent_identity_page",panel_id:$.panelId,page:$.page}),cY("下一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.min($.totalPages-1,$.page+1)})]}}function cY($,Z){return{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:$},type:"default",behaviors:[{type:"callback",value:Z}]}]}}function ZR($){switch($.status){case"completed":return"✅ 完成";case"failed":return"❌ 失败";case"cancelled":return"\uD83D\uDED1 取消";case"needs_input":return"❓ 等待输入";case"running":return"⏳ 运行中";default:return"⏳ 排队中"}}function iY($){return $==="completed"||$==="failed"||$==="cancelled"}function yB($){let Z=d2($.owner?.kind==="project"?"project":"delegated");switch($.status){case"completed":return`✅ ${Z}完成`;case"failed":return`❌ ${Z}失败`;case"cancelled":return`\uD83D\uDED1 ${Z}已取消`;case"needs_input":return $.owner?.kind==="project"?"❗ 项目任务不支持交互提问":`❓ ${Z}等待主 Agent 回复`;case"queued":return`⏳ ${Z}等待执行`;case"running":return $.workers.length>0&&$.workers.every((J)=>iY(J.status))?`⏳ ${Z}正在收尾`:`⏳ ${Z}正在执行`}}function N1($){return"`"+$.replace(/`/g,"\\`")+"`"}function V1($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hB($,Z){let J=$.replace(/\s+/g," ").trim();return J.length<=Z?J:`${J.slice(0,Z-1)}…`}var kB=8000;var IB=R(()=>{d0();xQ()});function s2($){return JR.has($)?$:null}function c6($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function W9($){return String($?.taskId??$?.id??$?.task_id??"").trim()}function r1($){return String($?.subject??$?.content??"").trim()}function nY($){let Z=$?.status;return Z==="pending"||Z==="in_progress"||Z==="completed"||Z==="deleted"?Z:void 0}function pB($){return`subj:${$}`}function gB($){let Z=$.match(/#\s*(\d+)/);return Z?Z[1]:""}function XR($){let Z=r1($);if(!Z)return null;return{id:W9($)||pB(Z),subject:Z,description:typeof $?.description==="string"?$.description:void 0,activeForm:typeof $?.activeForm==="string"?$.activeForm:void 0,status:nY($)??"pending"}}function u6($,Z,J,Q,Y){if(Z==="TaskList"){let V=c6(Q),X=Array.isArray(V?.tasks)?V.tasks:Array.isArray(V)?V:null;if(X===null)return $;let z=[];for(let H of X){let G=XR(H);if(G)z.push(G)}return z}if(Z==="TaskCreate"){let V=Array.isArray(J?.tasks)?J.tasks:null;if(V){let W=c6(Q),K=Array.isArray(W?.tasks)?W.tasks:Array.isArray(W)?W:null,B=$;return V.forEach((_,P)=>{let L=Y===void 0?_:Y.tasks[P],q=r1(L);if(!q)return;let D=K?.[P],M=D&&W9(D)||gB(Q??"");B=mB(B,M,q,L)}),B}let X=c6(Q),z=X?.task??X,H=W9(z)||gB(Q??""),G=Y===void 0?r1(z)||r1(J):r1(Y);if(!G)return $;return mB($,H,G,Y??J)}if(Z==="TaskUpdate"){let V=W9(J);if(!V)return $;let X=nY(J);if(X==="deleted")return $.filter((H)=>H.id!==V);let z=r1(J);if($.some((H)=>H.id===V))return $.map((H)=>H.id===V?{...H,...X?{status:X}:{},...z?{subject:z}:{},...typeof J?.activeForm==="string"?{activeForm:J.activeForm}:{}}:H);return $}if(Z==="TaskGet"){let V=c6(Q),X=V?.task??V,z=W9(X)||W9(J);if(!z)return $;let H=$.find((K)=>K.id===z),G=r1(X)||H?.subject||r1(J);if(!G)return $;let W={id:z,subject:G,description:typeof X?.description==="string"?X.description:H?.description,activeForm:typeof X?.activeForm==="string"?X.activeForm:H?.activeForm,status:nY(X)??H?.status??"pending"};return H?$.map((K)=>K.id===z?W:K):[...$,W]}return $}function mB($,Z,J,Q){let Y=Z||pB(J),V={...typeof Q?.activeForm==="string"&&Q.activeForm?{activeForm:Q.activeForm}:{},...typeof Q?.description==="string"&&Q.description?{description:Q.description}:{}};if($.some((X)=>X.id===Y))return $.map((X)=>X.id===Y?{...X,id:Y,subject:J,...V}:X);return[...$,{id:Y,subject:J,status:"pending",...V}]}function aY($){let Z=$.filter((V)=>V.status!=="deleted");if(Z.length===0)return"空";let J=new Map;for(let V of Z){let X=YR[V.status];J.set(X,(J.get(X)??0)+1)}let Y=["进行中","待办","完成"].map((V)=>J.has(V)?`${V} ${J.get(V)}`:"").filter(Boolean).join(" · ");return`${Z.length} 项${Y?` · ${Y}`:""}`}function cB($,Z){let J=$.filter((X)=>X.status!=="deleted"),Q=[`**待办**: ${J.length} 项`],Y=(X)=>{let z=parseInt(X,10);return Number.isNaN(z)?Number.MAX_SAFE_INTEGER:z},V=[...J].sort((X,z)=>{let H=Y(X.id)-Y(z.id);return H!==0?H:X.id.localeCompare(z.id)});for(let X of V.slice(0,12)){let z=VR[X.status],H=X.status==="in_progress"&&X.activeForm?X.activeForm:X.subject;Q.push(`- ${z} ${H||"(空)"}`)}if(V.length>12)Q.push(`- 还有 ${V.length-12} 项未显示`);if(Z)Q.push(""),Q.push(Z);return Q.join(`
283
- `)}function e1($,Z,J,Q){let Y=QR[J.name],V=aY(Z),X=`${J.status} \uD83D\uDD27 ${Y}: ${V}`;return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!1,elements:[{tag:"markdown",content:cB(Z,Q)}]}}function t2($){return{tag:"collapsible_panel",element_id:C.taskBoardLive,header:{title:{tag:"plain_text",content:`\uD83D\uDCCB 任务总览 · ${aY($)}`}},expanded:!0,elements:[{tag:"markdown",content:cB($)}]}}var JR,QR,YR,VR;var uB=R(()=>{d0();JR=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet"]);QR={TaskCreate:"创建任务",TaskUpdate:"更新任务",TaskList:"任务列表",TaskGet:"查看任务"},YR={pending:"待办",in_progress:"进行中",completed:"完成",deleted:"已删"},VR={pending:"⬜",in_progress:"\uD83D\uDD04",completed:"✅",deleted:"\uD83D\uDDD1️"}});var S$=R(()=>{d0();W6();mK();KB();SB();bB();IB();uB();mQ()});import{createHash as zR}from"node:crypto";class a8{deps;tails=new Map;byTask=new Map;background=new Map;constructor($){this.deps=$}add($){return this.addRow(lB($))}async update($,Z=!1,J=!1){await this.updateRow(lB($),Z,!1,J)}syncBackground($,Z,J){return f$($,async()=>{let Q=this.background.get(Z);if(!Q)this.background.set(Z,Q=new Map);let Y=[];for(let V of J){let X=V.displayId??V.toolUseId??V.id,z=Q.get(X);if(z?.task===V&&!z.pendingSettings)continue;let H=z&&R$(z.task)&&!R$(V),G=(z?.version??0)+(H?1:0),W=`background:${Z}:${X}:${G}`,K={key:W,chatId:$,elementId:S8.panel(W),element:gQ({...V,id:W}),summary:Y6(V),kind:x8(V),status:V.status,terminal:R$(V)};try{if(!z||H)await this.addRow(K);else{let B=!z.pendingSettings&&GR(z.task,V);if(!await this.updateRow(K,K.terminal,!0,B))continue}Q.set(X,{task:V,version:G})}catch(B){if(this.byTask.get(W)?.rows.get(W)===K)Q.set(X,{task:V,version:G,pendingSettings:!0});Y.push(B)}}if(Y.length)throw AggregateError(Y,Y.map(String).join("; "))})}releaseBackground($){this.background.delete($)}addRow($){return f$($.chatId,async()=>{if(this.byTask.get($.key)){await this.updateRow($,$.terminal,!0);return}let J=$.dedicated?void 0:this.tails.get($.chatId);if(J){if(await this.deps.getChatTailMessageId($.chatId)===J.messageId&&this.deps.getElementCount(J.cardId)<HR){let Y=await this.deps.addElementResult(J.cardId,$.element);if(Y.landed){this.attach(J,$),await this.settings(J);return}if(!oY(Y))throw n8("agent card append",Y)}await this.seal(J)}await this.create($)})}updateRow($,Z=!1,J=!1,Q=!1){return f$($.chatId,async()=>{let Y=this.byTask.get($.key);if(!Y)return!0;if(Y.settled.has($.key)&&!J){if(Z)await this.settings(Y);return!0}if(Y.settled.size===Y.rows.size)Y.settingsJson=void 0;let V=[],X=await this.deps.replaceElementResult(Y.cardId,$.elementId,$.element);if(!X.landed){let z=Y.rows.get($.key);if(Q&&!Z&&!$.terminal&&!Y.pendingSettings&&!oY(X)&&z?.status==="running"&&$.status===z.status&&$.kind===z.kind&&$.summary===z.summary&&$.progressState===z.progressState)return j(`agent: task progress refresh failed task=${$.key}: ${n8("agent task row update",X).message}`),!1;if(!oY(X)||Y.rows.size===1)throw n8("agent task row update",X);let H=Y;await this.seal(H,!0);let G=this.tails.get($.chatId);if(G)await this.seal(G);Y=await this.create($),H.rows.delete($.key),H.settled.delete($.key);try{let W;if(!await this.deps.deleteElementChecked(H.cardId,$.elementId,(K)=>{W=K})){let K=n8("agent moved task row deletion",{landed:!1,failure:W});throw Error(`${K.message}; the previous card may still show its earlier state`)}}catch(W){V.push(String(W))}try{await this.settings(H)}catch(W){V.push(String(W))}}if(Y.rows.set($.key,$),Z)Y.settled.add($.key);else Y.settled.delete($.key);try{await this.settings(Y)}catch(z){V.push(String(z))}if(V.length)throw Error(V.join("; "));return!0})}closeChat($){return f$($,async()=>{let Z=this.tails.get($);if(Z)await this.seal(Z)})}attach($,Z){if($.rows.set(Z.key,Z),this.byTask.set(Z.key,$),Z.terminal)$.settled.add(Z.key);Z.attach?.($.messageId)}async create($){let Z,J=await this.deps.sendCard($.chatId,{schema:"2.0",config:{update_multi:!0,streaming_mode:!$.terminal,summary:{content:$.summary}},body:{elements:[$.element]}},(V)=>{Z=V});if(!J)throw Error(`agent card creation failed: ${w(Z)}`);let Q=await this.deps.convertMessageToCard(J);this.deps.recordCardCreated(Q,1);let Y={cardId:Q,messageId:J,chatId:$.chatId,rows:new Map,settled:new Set,sealed:$.dedicated===!0};if(this.attach(Y,$),!$.dedicated)this.tails.set($.chatId,Y);return Y}async seal($,Z=!1){if($.sealed=!0,this.tails.get($.chatId)===$)this.tails.delete($.chatId);await this.settings($,!Z)}async settings($,Z=!0){this.deps.cancelSummary($.cardId);let J=$.settled.size===$.rows.size,Q={config:{streaming_mode:!J,summary:{content:dY([...$.rows.values()])}}},Y=JSON.stringify(Q);if(Y!==$.settingsJson){let V;if($.pendingSettings=!0,!await this.deps.patchSettingsChecked($.cardId,Q,(X)=>{V=X}))throw n8("agent card settings update",{landed:!1,failure:V});$.settingsJson=Y,$.pendingSettings=!1}if(J&&$.sealed&&Z){await this.deps.dispose($.cardId);for(let V of $.rows.keys())if(this.byTask.get(V)===$)this.byTask.delete(V)}}}function lB($){let{cardMessageId:Z,presentationErrors:J,promptArtifact:Q,...Y}=$;return{key:`run:${$.runId}`,chatId:$.chatId,elementId:m6($.runId),dedicated:$.owner?.kind==="project",element:lY($),summary:p6($),kind:$.owner?.kind==="project"?"project":"delegated",status:$.status,terminal:$.status==="completed"||$.status==="failed"||$.status==="cancelled",progressState:zR("sha256").update(JSON.stringify({...Y,workers:Y.workers.map(({steps:V,usage:X,durationMs:z,outputArtifact:H,...G})=>G)})).digest("hex"),attach:(V)=>{$.cardMessageId=V}}}function oY($){return m2($.failure?.code,$.failure)}function GR($,Z){return $.status==="running"&&Z.status==="running"&&Object.keys({...$,...Z}).every((J)=>J==="steps"||J==="usage"||J==="lastToolName"||$[J]===Z[J])}function n8($,Z){return Error(`${$} MISS: ${w(Z.failure)}`)}var HR=50;var sY=R(()=>{S$();U1();zJ();I()});function dB(){return new a8(tY)}var tY;var rY=R(()=>{sY();U1();Y0();tY={sendCard:o,getChatTailMessageId:nJ,convertMessageToCard:e$,recordCardCreated:h$,getElementCount:U8,addElementResult:$9,replaceElementResult:nW,deleteElementChecked:aW,cancelSummary:e0,patchSettingsChecked:m0,dispose:N$}});function WR(){return JSON.stringify([bZ(),VH(),s0().map(($)=>[$.id,$.enabled,$.spawnRevision,$.usageAccount]),v.list().map(($)=>[$.id,$.name,$.revision])])}function eY(){let $=WR();if(o8?.key===$)return o8.promise;let Z=["codex-sub","claude-sub","glm","dsh-glm","deepseek","deepseek-harness","openrouter","claude-native"],J=(z)=>Z.includes(z)?Z.indexOf(z):Z.length,Q=s0().filter((z)=>z.enabled||z.kind==="codex-subscription"&&v.list().some((H)=>H.id!=="default")).sort((z,H)=>J(z.id)-J(H.id)),Y=new Set,V=[];for(let z of Q){if(z.kind==="codex-subscription"){V.push(d7().then((W)=>W.entries.filter((K)=>!K.duplicateOf).map((K)=>({id:`codex:${K.account.id}`,label:`Codex·${K.account.name}`,usage:$8(K.usage)}))));continue}let H=z.usageAccount?.id??$W(z.id);if(Y.has(H))continue;Y.add(H);let G=z.usageAccount?.label??(H==="glm"?"GLM Coding Plan":H==="deepseek"?"DeepSeek":z.kind==="claude-subscription"?"Claude 订阅":z.display);V.push(Promise.resolve().then(()=>z.readUsage()).catch((W)=>{let K=W instanceof Error?W.message:String(W);return j(`account usage ${H} MISS: ${K}`),{state:"network",windows:[],reason:K}}).then((W)=>[{id:H,label:G,usage:W}]))}let X=Promise.all(V).then((z)=>z.flat()).finally(()=>{if(o8?.promise===X)o8=void 0});return o8={key:$,promise:X},X}var o8;var iB=R(()=>{F0();MQ();H7();X0();q8();z$();I()});function nB($){let Z=[];for(let J of $.matchAll(KR)){let Q=J[1]?.trim();if(Q)Z.push(Q)}return Z}function l6($,Z=process.platform){if(Z!=="win32")return $;let J=BR.exec($);if(!J)return $;return`${J[1].toUpperCase()}:\\`+$.slice(J[0].length).replace(/\//g,"\\")}var KR,BR;var $V=R(()=>{KR=/\[\[send:[ \t]*([^\n]*?)[ \t]*\]\]/g;BR=/^\/([a-zA-Z])\//});function sB($){if(aB.test($))return{marker:"start",body:$.replace(aB,"")};if(oB.test($))return{marker:"end",body:$.replace(oB,"")};return{marker:"none",body:$}}var aB,oB;var tB=R(()=>{aB=/^>{3,}[ \t]?/,oB=/^<{3,}[ \t]?/});async function rB($,Z,J,Q,Y){let{marker:V,body:X}=sB(Z);if(V==="start"){if($.multiMsgBuffer!==null&&$.multiMsgBuffer.length>0)JV($,"reopen");return $.multiMsgBuffer=[],ZV($,X,J,Q,Y),!0}if(V==="end"){if($.multiMsgBuffer===null){if(X.trim()||J.length)return!1;return j(`session "${$.sessionName}": end marker without active multi-msg buffer, ignoring`),!0}ZV($,X,J,Q,Y);let{multiMsgBuffer:z,multiMsgReactions:H}=$;return $.multiMsgBuffer=null,$.multiMsgReactions=new Map,await _R($,z,H),!0}if($.multiMsgBuffer!==null)return ZV($,Z,J,Q,Y),!0;return!1}function ZV($,Z,J,Q,Y){if(Z.trim()||J.length)$.multiMsgBuffer.push({text:Z,files:J,userOpenId:Q,msgId:Y});if(Y)jR($,Y)}function jR($,Z){$.multiMsgReactions.set(Z,""),(async()=>{let J=await K$(Z,"Pin");if(!J)return;if($.multiMsgReactions.has(Z))$.multiMsgReactions.set(Z,J);else g0(Z,J)})()}async function _R($,Z,J){for(let[X,z]of J)if(z)g0(X,z);let Q=Z.filter((X)=>X.text.trim()||X.files.length);if(Q.length===0){j(`session "${$.sessionName}": multi-msg flush with empty buffer, not sent`),await k($.chatId,"⚠️ 多条消息缓冲为空,未发送(只收到标记没有正文)。");return}let Y=Q.map((X)=>{return(X.files.length?X.files.map((H)=>`[file: ${H}]`).join(" ")+`
282
+ `)}}function $R($){return{tag:"column_set",columns:[cY("上一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.max(0,$.page-1)}),cY("刷新",{kind:"agent_identity_page",panel_id:$.panelId,page:$.page}),cY("下一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.min($.totalPages-1,$.page+1)})]}}function cY($,Z){return{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:$},type:"default",behaviors:[{type:"callback",value:Z}]}]}}function ZR($){switch($.status){case"completed":return"✅ 完成";case"failed":return"❌ 失败";case"cancelled":return"\uD83D\uDED1 取消";case"needs_input":return"❓ 等待输入";case"running":return"⏳ 运行中";default:return"⏳ 排队中"}}function iY($){return $==="completed"||$==="failed"||$==="cancelled"}function fB($){let Z=d2($.owner?.kind==="project"?"project":"delegated");switch($.status){case"completed":return`✅ ${Z}完成`;case"failed":return`❌ ${Z}失败`;case"cancelled":return`\uD83D\uDED1 ${Z}已取消`;case"needs_input":return $.owner?.kind==="project"?"❗ 项目任务不支持交互提问":`❓ ${Z}等待主 Agent 回复`;case"queued":return`⏳ ${Z}等待执行`;case"running":return $.workers.length>0&&$.workers.every((J)=>iY(J.status))?`⏳ ${Z}正在收尾`:`⏳ ${Z}正在执行`}}function N1($){return"`"+$.replace(/`/g,"\\`")+"`"}function V1($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hB($,Z){let J=$.replace(/\s+/g," ").trim();return J.length<=Z?J:`${J.slice(0,Z-1)}…`}var kB=8000;var IB=R(()=>{d0();xQ()});function s2($){return JR.has($)?$:null}function c6($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function W9($){return String($?.taskId??$?.id??$?.task_id??"").trim()}function r1($){return String($?.subject??$?.content??"").trim()}function nY($){let Z=$?.status;return Z==="pending"||Z==="in_progress"||Z==="completed"||Z==="deleted"?Z:void 0}function pB($){return`subj:${$}`}function gB($){let Z=$.match(/#\s*(\d+)/);return Z?Z[1]:""}function XR($){let Z=r1($);if(!Z)return null;return{id:W9($)||pB(Z),subject:Z,description:typeof $?.description==="string"?$.description:void 0,activeForm:typeof $?.activeForm==="string"?$.activeForm:void 0,status:nY($)??"pending"}}function u6($,Z,J,Q,Y){if(Z==="TaskList"){let V=c6(Q),X=Array.isArray(V?.tasks)?V.tasks:Array.isArray(V)?V:null;if(X===null)return $;let z=[];for(let H of X){let G=XR(H);if(G)z.push(G)}return z}if(Z==="TaskCreate"){let V=Array.isArray(J?.tasks)?J.tasks:null;if(V){let W=c6(Q),K=Array.isArray(W?.tasks)?W.tasks:Array.isArray(W)?W:null,B=$;return V.forEach((_,P)=>{let L=Y===void 0?_:Y.tasks[P],q=r1(L);if(!q)return;let F=K?.[P],M=F&&W9(F)||gB(Q??"");B=mB(B,M,q,L)}),B}let X=c6(Q),z=X?.task??X,H=W9(z)||gB(Q??""),G=Y===void 0?r1(z)||r1(J):r1(Y);if(!G)return $;return mB($,H,G,Y??J)}if(Z==="TaskUpdate"){let V=W9(J);if(!V)return $;let X=nY(J);if(X==="deleted")return $.filter((H)=>H.id!==V);let z=r1(J);if($.some((H)=>H.id===V))return $.map((H)=>H.id===V?{...H,...X?{status:X}:{},...z?{subject:z}:{},...typeof J?.activeForm==="string"?{activeForm:J.activeForm}:{}}:H);return $}if(Z==="TaskGet"){let V=c6(Q),X=V?.task??V,z=W9(X)||W9(J);if(!z)return $;let H=$.find((K)=>K.id===z),G=r1(X)||H?.subject||r1(J);if(!G)return $;let W={id:z,subject:G,description:typeof X?.description==="string"?X.description:H?.description,activeForm:typeof X?.activeForm==="string"?X.activeForm:H?.activeForm,status:nY(X)??H?.status??"pending"};return H?$.map((K)=>K.id===z?W:K):[...$,W]}return $}function mB($,Z,J,Q){let Y=Z||pB(J),V={...typeof Q?.activeForm==="string"&&Q.activeForm?{activeForm:Q.activeForm}:{},...typeof Q?.description==="string"&&Q.description?{description:Q.description}:{}};if($.some((X)=>X.id===Y))return $.map((X)=>X.id===Y?{...X,id:Y,subject:J,...V}:X);return[...$,{id:Y,subject:J,status:"pending",...V}]}function aY($){let Z=$.filter((V)=>V.status!=="deleted");if(Z.length===0)return"空";let J=new Map;for(let V of Z){let X=YR[V.status];J.set(X,(J.get(X)??0)+1)}let Y=["进行中","待办","完成"].map((V)=>J.has(V)?`${V} ${J.get(V)}`:"").filter(Boolean).join(" · ");return`${Z.length} 项${Y?` · ${Y}`:""}`}function cB($,Z){let J=$.filter((X)=>X.status!=="deleted"),Q=[`**待办**: ${J.length} 项`],Y=(X)=>{let z=parseInt(X,10);return Number.isNaN(z)?Number.MAX_SAFE_INTEGER:z},V=[...J].sort((X,z)=>{let H=Y(X.id)-Y(z.id);return H!==0?H:X.id.localeCompare(z.id)});for(let X of V.slice(0,12)){let z=VR[X.status],H=X.status==="in_progress"&&X.activeForm?X.activeForm:X.subject;Q.push(`- ${z} ${H||"(空)"}`)}if(V.length>12)Q.push(`- 还有 ${V.length-12} 项未显示`);if(Z)Q.push(""),Q.push(Z);return Q.join(`
283
+ `)}function e1($,Z,J,Q){let Y=QR[J.name],V=aY(Z),X=`${J.status} \uD83D\uDD27 ${Y}: ${V}`;return{tag:"collapsible_panel",element_id:C.tool($),header:{title:{tag:"plain_text",content:X}},expanded:!1,elements:[{tag:"markdown",content:cB(Z,Q)}]}}function t2($){return{tag:"collapsible_panel",element_id:C.taskBoardLive,header:{title:{tag:"plain_text",content:`\uD83D\uDCCB 任务总览 · ${aY($)}`}},expanded:!0,elements:[{tag:"markdown",content:cB($)}]}}var JR,QR,YR,VR;var uB=R(()=>{d0();JR=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet"]);QR={TaskCreate:"创建任务",TaskUpdate:"更新任务",TaskList:"任务列表",TaskGet:"查看任务"},YR={pending:"待办",in_progress:"进行中",completed:"完成",deleted:"已删"},VR={pending:"⬜",in_progress:"\uD83D\uDD04",completed:"✅",deleted:"\uD83D\uDDD1️"}});var S$=R(()=>{d0();W6();mK();KB();SB();bB();IB();uB();mQ()});import{createHash as zR}from"node:crypto";class a8{deps;tails=new Map;byTask=new Map;background=new Map;constructor($){this.deps=$}add($){return this.addRow(lB($))}async update($,Z=!1,J=!1){await this.updateRow(lB($),Z,!1,J)}syncBackground($,Z,J){return y$($,async()=>{let Q=this.background.get(Z);if(!Q)this.background.set(Z,Q=new Map);let Y=[];for(let V of J){let X=V.displayId??V.toolUseId??V.id,z=Q.get(X);if(z?.task===V&&!z.pendingSettings)continue;let H=z&&R$(z.task)&&!R$(V),G=(z?.version??0)+(H?1:0),W=`background:${Z}:${X}:${G}`,K={key:W,chatId:$,elementId:S8.panel(W),element:gQ({...V,id:W}),summary:Y6(V),kind:x8(V),status:V.status,terminal:R$(V)};try{if(!z||H)await this.addRow(K);else{let B=!z.pendingSettings&&GR(z.task,V);if(!await this.updateRow(K,K.terminal,!0,B))continue}Q.set(X,{task:V,version:G})}catch(B){if(this.byTask.get(W)?.rows.get(W)===K)Q.set(X,{task:V,version:G,pendingSettings:!0});Y.push(B)}}if(Y.length)throw AggregateError(Y,Y.map(String).join("; "))})}releaseBackground($){this.background.delete($)}addRow($){return y$($.chatId,async()=>{if(this.byTask.get($.key)){await this.updateRow($,$.terminal,!0);return}let J=$.dedicated?void 0:this.tails.get($.chatId);if(J){if(await this.deps.getChatTailMessageId($.chatId)===J.messageId&&this.deps.getElementCount(J.cardId)<HR){let Y=await this.deps.addElementResult(J.cardId,$.element);if(Y.landed){this.attach(J,$),await this.settings(J);return}if(!oY(Y))throw n8("agent card append",Y)}await this.seal(J)}await this.create($)})}updateRow($,Z=!1,J=!1,Q=!1){return y$($.chatId,async()=>{let Y=this.byTask.get($.key);if(!Y)return!0;if(Y.settled.has($.key)&&!J){if(Z)await this.settings(Y);return!0}if(Y.settled.size===Y.rows.size)Y.settingsJson=void 0;let V=[],X=await this.deps.replaceElementResult(Y.cardId,$.elementId,$.element);if(!X.landed){let z=Y.rows.get($.key);if(Q&&!Z&&!$.terminal&&!Y.pendingSettings&&!oY(X)&&z?.status==="running"&&$.status===z.status&&$.kind===z.kind&&$.summary===z.summary&&$.progressState===z.progressState)return j(`agent: task progress refresh failed task=${$.key}: ${n8("agent task row update",X).message}`),!1;if(!oY(X)||Y.rows.size===1)throw n8("agent task row update",X);let H=Y;await this.seal(H,!0);let G=this.tails.get($.chatId);if(G)await this.seal(G);Y=await this.create($),H.rows.delete($.key),H.settled.delete($.key);try{let W;if(!await this.deps.deleteElementChecked(H.cardId,$.elementId,(K)=>{W=K})){let K=n8("agent moved task row deletion",{landed:!1,failure:W});throw Error(`${K.message}; the previous card may still show its earlier state`)}}catch(W){V.push(String(W))}try{await this.settings(H)}catch(W){V.push(String(W))}}if(Y.rows.set($.key,$),Z)Y.settled.add($.key);else Y.settled.delete($.key);try{await this.settings(Y)}catch(z){V.push(String(z))}if(V.length)throw Error(V.join("; "));return!0})}closeChat($){return y$($,async()=>{let Z=this.tails.get($);if(Z)await this.seal(Z)})}attach($,Z){if($.rows.set(Z.key,Z),this.byTask.set(Z.key,$),Z.terminal)$.settled.add(Z.key);Z.attach?.($.messageId)}async create($){let Z,J=await this.deps.sendCard($.chatId,{schema:"2.0",config:{update_multi:!0,streaming_mode:!$.terminal,summary:{content:$.summary}},body:{elements:[$.element]}},(V)=>{Z=V});if(!J)throw Error(`agent card creation failed: ${w(Z)}`);let Q=await this.deps.convertMessageToCard(J);this.deps.recordCardCreated(Q,1);let Y={cardId:Q,messageId:J,chatId:$.chatId,rows:new Map,settled:new Set,sealed:$.dedicated===!0};if(this.attach(Y,$),!$.dedicated)this.tails.set($.chatId,Y);return Y}async seal($,Z=!1){if($.sealed=!0,this.tails.get($.chatId)===$)this.tails.delete($.chatId);await this.settings($,!Z)}async settings($,Z=!0){this.deps.cancelSummary($.cardId);let J=$.settled.size===$.rows.size,Q={config:{streaming_mode:!J,summary:{content:dY([...$.rows.values()])}}},Y=JSON.stringify(Q);if(Y!==$.settingsJson){let V;if($.pendingSettings=!0,!await this.deps.patchSettingsChecked($.cardId,Q,(X)=>{V=X}))throw n8("agent card settings update",{landed:!1,failure:V});$.settingsJson=Y,$.pendingSettings=!1}if(J&&$.sealed&&Z){await this.deps.dispose($.cardId);for(let V of $.rows.keys())if(this.byTask.get(V)===$)this.byTask.delete(V)}}}function lB($){let{cardMessageId:Z,presentationErrors:J,promptArtifact:Q,...Y}=$;return{key:`run:${$.runId}`,chatId:$.chatId,elementId:m6($.runId),dedicated:$.owner?.kind==="project",element:lY($),summary:p6($),kind:$.owner?.kind==="project"?"project":"delegated",status:$.status,terminal:$.status==="completed"||$.status==="failed"||$.status==="cancelled",progressState:zR("sha256").update(JSON.stringify({...Y,workers:Y.workers.map(({steps:V,usage:X,durationMs:z,outputArtifact:H,...G})=>G)})).digest("hex"),attach:(V)=>{$.cardMessageId=V}}}function oY($){return m2($.failure?.code,$.failure)}function GR($,Z){return $.status==="running"&&Z.status==="running"&&Object.keys({...$,...Z}).every((J)=>J==="steps"||J==="usage"||J==="lastToolName"||$[J]===Z[J])}function n8($,Z){return Error(`${$} MISS: ${w(Z.failure)}`)}var HR=50;var sY=R(()=>{S$();U1();zJ();I()});function dB(){return new a8(tY)}var tY;var rY=R(()=>{sY();U1();Y0();tY={sendCard:o,getChatTailMessageId:nJ,convertMessageToCard:e$,recordCardCreated:h$,getElementCount:U8,addElementResult:$9,replaceElementResult:nW,deleteElementChecked:aW,cancelSummary:e0,patchSettingsChecked:m0,dispose:N$}});function WR(){return JSON.stringify([bZ(),VH(),s0().map(($)=>[$.id,$.enabled,$.spawnRevision,$.usageAccount]),v.list().map(($)=>[$.id,$.name,$.revision])])}function eY(){let $=WR();if(o8?.key===$)return o8.promise;let Z=["codex-sub","claude-sub","glm","dsh-glm","deepseek","deepseek-harness","openrouter","claude-native"],J=(z)=>Z.includes(z)?Z.indexOf(z):Z.length,Q=s0().filter((z)=>z.enabled||z.kind==="codex-subscription"&&v.list().some((H)=>H.id!=="default")).sort((z,H)=>J(z.id)-J(H.id)),Y=new Set,V=[];for(let z of Q){if(z.kind==="codex-subscription"){V.push(d7().then((W)=>W.entries.filter((K)=>!K.duplicateOf).map((K)=>({id:`codex:${K.account.id}`,label:`Codex·${K.account.name}`,usage:$8(K.usage)}))));continue}let H=z.usageAccount?.id??$W(z.id);if(Y.has(H))continue;Y.add(H);let G=z.usageAccount?.label??(H==="glm"?"GLM Coding Plan":H==="deepseek"?"DeepSeek":z.kind==="claude-subscription"?"Claude 订阅":z.display);V.push(Promise.resolve().then(()=>z.readUsage()).catch((W)=>{let K=W instanceof Error?W.message:String(W);return j(`account usage ${H} MISS: ${K}`),{state:"network",windows:[],reason:K}}).then((W)=>[{id:H,label:G,usage:W}]))}let X=Promise.all(V).then((z)=>z.flat()).finally(()=>{if(o8?.promise===X)o8=void 0});return o8={key:$,promise:X},X}var o8;var iB=R(()=>{D0();MQ();H7();X0();q8();z$();I()});function nB($){let Z=[];for(let J of $.matchAll(KR)){let Q=J[1]?.trim();if(Q)Z.push(Q)}return Z}function l6($,Z=process.platform){if(Z!=="win32")return $;let J=BR.exec($);if(!J)return $;return`${J[1].toUpperCase()}:\\`+$.slice(J[0].length).replace(/\//g,"\\")}var KR,BR;var $V=R(()=>{KR=/\[\[send:[ \t]*([^\n]*?)[ \t]*\]\]/g;BR=/^\/([a-zA-Z])\//});function sB($){if(aB.test($))return{marker:"start",body:$.replace(aB,"")};if(oB.test($))return{marker:"end",body:$.replace(oB,"")};return{marker:"none",body:$}}var aB,oB;var tB=R(()=>{aB=/^>{3,}[ \t]?/,oB=/^<{3,}[ \t]?/});async function rB($,Z,J,Q,Y){let{marker:V,body:X}=sB(Z);if(V==="start"){if($.multiMsgBuffer!==null&&$.multiMsgBuffer.length>0)JV($,"reopen");return $.multiMsgBuffer=[],ZV($,X,J,Q,Y),!0}if(V==="end"){if($.multiMsgBuffer===null){if(X.trim()||J.length)return!1;return j(`session "${$.sessionName}": end marker without active multi-msg buffer, ignoring`),!0}ZV($,X,J,Q,Y);let{multiMsgBuffer:z,multiMsgReactions:H}=$;return $.multiMsgBuffer=null,$.multiMsgReactions=new Map,await _R($,z,H),!0}if($.multiMsgBuffer!==null)return ZV($,Z,J,Q,Y),!0;return!1}function ZV($,Z,J,Q,Y){if(Z.trim()||J.length)$.multiMsgBuffer.push({text:Z,files:J,userOpenId:Q,msgId:Y});if(Y)jR($,Y)}function jR($,Z){$.multiMsgReactions.set(Z,""),(async()=>{let J=await K$(Z,"Pin");if(!J)return;if($.multiMsgReactions.has(Z))$.multiMsgReactions.set(Z,J);else g0(Z,J)})()}async function _R($,Z,J){for(let[X,z]of J)if(z)g0(X,z);let Q=Z.filter((X)=>X.text.trim()||X.files.length);if(Q.length===0){j(`session "${$.sessionName}": multi-msg flush with empty buffer, not sent`),await k($.chatId,"⚠️ 多条消息缓冲为空,未发送(只收到标记没有正文)。");return}let Y=Q.map((X)=>{return(X.files.length?X.files.map((H)=>`[file: ${H}]`).join(" ")+`
284
284
  `:"")+X.text}).join(`
285
285
 
286
- `),V=Q[Q.length-1];j(`session "${$.sessionName}": multi-msg flush ${Q.length} segment(s) → 1 turn`),await $.onUserMessage(Y,[],V.userOpenId,V.msgId)}function JV($,Z){if($.multiMsgBuffer===null)return;let J=$.multiMsgBuffer.length;j(`session "${$.sessionName}": clear multi-msg buffer (${Z}): ${J} segment(s)`);for(let[Q,Y]of $.multiMsgReactions){if(Y)g0(Q,Y);K$(Q,"CrossMark")}$.multiMsgBuffer=null,$.multiMsgReactions=new Map}var eB=R(()=>{Y0();I();tB()});import{mkdtemp as LR,rm as qR,writeFile as DR}from"node:fs/promises";import{createRequire as FR}from"node:module";import{tmpdir as MR}from"node:os";import{join as $j}from"node:path";function SR($){let Z=Yj.get($);if(Z)return Z;let{liteAdaptor:J}=e2("mathjax-full/js/adaptors/liteAdaptor.js"),{RegisterHTMLHandler:Q}=e2("mathjax-full/js/handlers/html.js"),{mathjax:Y}=e2("mathjax-full/js/mathjax.js"),{TeX:V}=e2("mathjax-full/js/input/tex.js"),{AllPackages:X}=e2("mathjax-full/js/input/tex/AllPackages.js"),{SVG:z}=e2("mathjax-full/js/output/svg.js"),H=J({fontSize:$});Q(H);let G=Y.document("",{InputJax:new V({packages:X}),OutputJax:new z({fontCache:"none"})}),W={adaptor:H,doc:G};return Yj.set($,W),W}function Vj($,Z){let J=Number.parseFloat($??"");if(!Number.isFinite(J)||J<=0)throw Error(`MathJax SVG missing valid ${Z}`);return J}function CR($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xR($,Z=VV,J=!0){try{let Q=Z*UR,{adaptor:Y,doc:V}=SR(Z),X=V.convert($,{display:J,em:Z,ex:Q,containerWidth:80*Z}),z=Y.outerHTML(X);if(/data-mjx-error=|mjx-merror/.test(z)){let t=z.match(/data-mjx-error="([^"]+)"/)?.[1]??"MathJax parse error";throw Error(t)}let H=z.indexOf("<svg"),G=z.lastIndexOf("</svg>");if(H<0||G<0)throw Error("MathJax returned no SVG");let W=z.slice(H,G+6),K=W.match(/^<svg\b[^>]*>/)?.[0];if(!K)throw Error("MathJax returned malformed SVG root");let B=Vj(K.match(/\bwidth="([\d.]+)ex"/)?.[1],"width"),_=Vj(K.match(/\bheight="([\d.]+)ex"/)?.[1],"height"),P=K.match(/\bviewBox="([^"]+)"/)?.[1];if(!P)throw Error("MathJax SVG missing viewBox");let L=P.trim().split(/[\s,]+/).map(Number);if(L.length!==4||L.some((t)=>!Number.isFinite(t))||L[2]<=0||L[3]<=0)throw Error("MathJax SVG has invalid viewBox");let[q,D,M,U]=L,A=/<text\b/.test(W)?TR:0,O=`${q} ${D} ${M+A} ${U}`,N=B*Q,S=A*(N/M),T=Math.max(1,Math.ceil(N+S)),y=Math.max(1,Math.ceil(_*Q)),m=OR-QV*2,b=Math.min(1,m/T),p=Math.max(1,Math.round(T*b)),c=Math.max(1,Math.round(y*b));if(b<1&&c<AR)throw Error(`formula would be unreadable after width cap (${p}x${c})`);let J0=p+QV*2,l=c+Jj*2,f=W.slice(K.length,-6).replace(/currentColor/g,Zj).replace(/font-family="serif"/g,`font-family="${ER}"`);return{svg:[`<svg xmlns="http://www.w3.org/2000/svg" width="${J0}" height="${l}" viewBox="0 0 ${J0} ${l}" style="color:${Zj}">`,`<rect x="0" y="0" width="${J0}" height="${l}" rx="6" fill="${Gj}"/>`,`<svg x="${QV}" y="${Jj}" width="${p}" height="${c}" viewBox="${CR(O)}" preserveAspectRatio="xMidYMid meet">`,f,"</svg>","</svg>"].join(""),width:J0,height:l}}catch(Q){return j(`math-render: TeX→SVG failed for ${$.slice(0,80)}…: ${Q}`),null}}function bR($,Z=VV,J=!0){let Q=xR($,Z,J);if(!Q)return null;try{let{Resvg:Y}=e2("@resvg/resvg-js"),X=new Y(Q.svg,{background:Gj,fitTo:{mode:"original"},shapeRendering:2,textRendering:1,font:{loadSystemFonts:!0,serifFamily:Qj,sansSerifFamily:Qj}}).render().asPng(),z=new DataView(X.buffer,X.byteOffset,X.byteLength),H=z.getUint32(16),G=z.getUint32(20);if(H!==Q.width||G!==Q.height)throw Error(`PNG dimensions ${H}x${G} != SVG ${Q.width}x${Q.height}`);return{png:X,width:H,height:G}}catch(Y){return j(`math-render: SVG→PNG failed for ${$.slice(0,80)}…: ${Y}`),null}}function kR($){if(/^[A-Za-zΑ-ω]$/.test($))return!0;if(/\\[A-Za-z]+|[_^=]|[{}]|[≤≥≠≈∑∫√]/.test($))return!0;return/[A-Za-zΑ-ω]\s*[+\-*/<>]\s*[A-Za-zΑ-ω0-9]/.test($)}function Xj($,Z){let J=[],Q=(W,K,B)=>{let _=W[0],P=K.trim();if(!P)return;J.push({start:Z+W.index,end:Z+W.index+_.length,tex:P,raw:_,display:B})},Y,V=/(?<!\\)\$\$([\s\S]+?)(?<!\\)\$\$|\\\[([\s\S]+?)\\\]/g;while((Y=V.exec($))!==null)Q(Y,Y[1]??Y[2]??"",!0);let X=/\\\(([\s\S]+?)\\\)/g;while((Y=X.exec($))!==null)Q(Y,Y[1]??"",!1);let z=/(?<![\\$])\$(?!\$)([^$\n]+?)(?<![\\$])\$(?!\$)/g;while((Y=z.exec($))!==null){let W=(Y[1]??"").trim();if(kR(W))Q(Y,W,!1)}J.sort((W,K)=>W.start-K.start||K.end-W.end);let H=[],G=-1;for(let W of J){if(W.start<G)continue;H.push(W),G=W.end}return H}function Wj($){let Z=LJ($),J=[],Q=0;for(let Y of Z){if(Q<Y.start)J.push(...Xj($.slice(Q,Y.start),Q));Q=Math.max(Q,Y.end)}if(Q<$.length)J.push(...Xj($.slice(Q),Q));return J}function wR($){let Z=$;if(Z=Z.replace(/\\text\{([^{}]*)\}/g,"$1"),Z=Z.replace(/\\left\s*/g,"").replace(/\\right\s*/g,""),Z=Z.replace(/\\([A-Za-z]+)\b/g,(J,Q)=>{if(zj[Q])return zj[Q];if(Q==="times")return"×";if(Q==="cdot")return"·";if(Q==="div")return"÷";if(Q==="pm")return"±";if(Q==="leq"||Q==="le")return"≤";if(Q==="geq"||Q==="ge")return"≥";if(Q==="neq"||Q==="ne")return"≠";if(Q==="approx")return"≈";if(Q==="sim")return"~";if(Q==="infty")return"∞";if(Q==="partial")return"∂";if(Q==="nabla")return"∇";if(Q==="sqrt")return"√";if(Q==="to")return"→";return J}),/\\/.test(Z))return null;if(Z=Z.replace(/([_^])\{([^{}]+)\}/g,(J,Q,Y)=>Y.length===1?`${Q}${Y}`:`${Q}(${Y})`),Z=Z.replace(/√\{([^{}]+)\}/g,"√($1)"),/[{}]/.test(Z))return null;return Z}function hR($){let Z=Hj.get($);if(Z!==void 0)return Z;return Z=fR++,Hj.set($,Z),Z}function IR($,Z){return`${RR}\x00${hR(Z)}\x00${$}`}function gR($){let Z=2166136261;for(let J=0;J<$.length;J++)Z^=$.charCodeAt(J),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}async function mR($,Z){let J=IR($,Z),Q=r2.get(J);if(Q)return Q;let Y=YV.get(J);if(Y)return Y;let V=(async()=>{let X=bR($,VV,!0);if(!X)return null;let z=null;try{z=await LR($j(MR(),"lodestar-math-"));let H=$j(z,`formula-${gR($)}.png`);await DR(H,X.png);let G=await Z(H,{tex:$,width:X.width,height:X.height});if(!G)return j(`math-render: upload returned no image key for ${$.slice(0,80)}…`),null;let W={key:G,width:X.width,height:X.height};if(r2.has(J))r2.delete(J);r2.set(J,W);while(r2.size>yR){let K=r2.keys().next().value;if(typeof K!=="string")break;r2.delete(K)}return W}catch(H){return j(`math-render: upload failed for ${$.slice(0,80)}…: ${H}`),null}finally{if(z)try{await qR(z,{recursive:!0,force:!0})}catch(H){j(`math-render: temp cleanup failed for ${z}: ${H}`)}}})();YV.set(J,V);try{return await V}finally{YV.delete(J)}}function pR($,Z,J){let Q=$.width<=NR;return{type:"image",tex:Z.tex,index:J,element:{tag:"img",img_key:$.key,alt:{tag:"plain_text",content:Z.tex.replace(/\s+/g," ").slice(0,80)},scale_type:Q?"crop_center":"fit_horizontal",...Q?{size:`${$.width}px ${$.height}px`}:{},preview:!1}}}async function Kj($,Z={}){let J=Wj($);if(!J.length)return{blocks:[{type:"markdown",text:$}],formulaCount:0,renderedImageCount:0};let Q=Z.uploader??vR,Y=await Promise.all(J.map(async(W)=>{if(!W.display){let K=wR(W.tex);if(K!==null)return{unicode:K,uploaded:null}}return{unicode:null,uploaded:await mR(W.tex,Q)}})),V=[],X="",z=0,H=0,G=()=>{if(!X)return;if(X.trim())V.push({type:"markdown",text:X});X=""};for(let W=0;W<J.length;W++){let K=J[W],B=Y[W];if(X+=$.slice(z,K.start),B.unicode!==null){X+=B.unicode,z=K.end;continue}let _=B.uploaded;if(!_){X+=K.raw,z=K.end;continue}G(),V.push(pR(_,K,H++)),z=K.end}if(X+=$.slice(z),G(),!V.length)V.push({type:"markdown",text:$});return{blocks:V,formulaCount:J.length,renderedImageCount:H}}function XV($){return Wj($).length>0}var e2,UR=0.5,VV=22,Zj="#1F2329",Gj="#F7F8FA",QV=12,Jj=8,OR=720,AR=14,NR=278,RR="v4-native-cjk-tail-pad",TR=1100,Qj,ER="Noto Sans CJK SC, Noto Sans CJK JP, Microsoft YaHei, PingFang SC, Arial Unicode MS, sans-serif",Yj,zj,vR=async($)=>{let{uploadImageKey:Z}=await Promise.resolve().then(() => (Y0(),z0));return Z($)},Hj,fR=1,r2,YV,yR=512;var Bj=R(()=>{I();e2=FR(import.meta.url),Qj=process.platform==="win32"?"Microsoft YaHei":process.platform==="darwin"?"PingFang SC":"Noto Sans CJK SC",Yj=new Map;zj={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",Gamma:"Γ",Delta:"Δ",Theta:"Θ",Lambda:"Λ",Pi:"Π",Sigma:"Σ",Phi:"Φ",Psi:"Ψ",Omega:"Ω"};Hj=new WeakMap,r2=new Map,YV=new Map});import{readFileSync as uR}from"node:fs";function K9($){return zV.has($)}function t8($){zV.add($)}function r8($){zV.delete($)}function $2(){try{let $={};for(let[Z,J]of n0)$[Z]=J;r(s8,$)}catch($){throw j(`notify-callbacks: save failed (${s8}): ${$}`),$}}function Lj(){let $=[],Z;try{Z=uR(s8,"utf8")}catch(J){if(J?.code==="ENOENT")return[];throw j(`notify-callbacks: read failed (${s8}): ${J}`),J}try{let J=JSON.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("notify callback store must be an object");let Q=Date.now()-Pj,Y=0,V=0;for(let X of Object.values(J)){if(!X||typeof X!=="object")continue;if(typeof X.notifyId!=="string"||typeof X.callbackUrl!=="string")continue;if(typeof X.createdAt!=="number"||X.createdAt<Q){Y++;continue}if(X.replyState?.status==="sending"&&!X.resolvedAt&&!X.unknownAt)X.unknownAt=Date.now(),X.unknownBy={openId:X.replyState.openId},X.unknownReason="服务在文字回复回传期间中断,无法确认是否送达,禁止自动重试",V++;if(X.dispatchState&&!X.resolvedAt&&!X.unknownAt)X.unknownAt=Date.now(),X.unknownBy={buttonId:X.dispatchState.buttonId,openId:X.dispatchState.openId},X.unknownReason="服务在按钮回调期间中断,无法确认是否送达,禁止自动重试",V++;if(n0.set(X.notifyId,X),(X.replyState?.status==="sending"||X.dispatchState)&&X.unknownAt)$.push(X)}if(j(`notify-callbacks: loaded ${n0.size} registration(s)${Y?`, dropped ${Y} stale`:""}`),V)j(`notify-callbacks: ${V} interrupted callback(s) marked UNKNOWN`);if(Y>0||V>0)$2()}catch(J){throw j(`notify-callbacks: load failed (${s8}): ${J}`),J}return $}function qj($){let Z=Date.now();if(Z-_j>=lR)dR(Z),_j=Z;n0.set($.notifyId,$),$2()}function R1($){return n0.get($)}function Dj($,Z,J){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);if(Q.resolvedAt||Q.unknownAt||Q.dispatchState)throw Error("notify callback is already dispatched or finalized");Q.dispatchState={buttonId:Z,openId:J,startedAt:Date.now()};try{$2()}catch(Y){throw delete Q.dispatchState,Y}}function Fj($){let Z=n0.get($);if(!Z?.dispatchState)throw Error(`notify callback is not dispatching: ${$}`);let J=Z.dispatchState;delete Z.dispatchState;try{return $2(),{state:"retry"}}catch(Q){Z.dispatchState=J;let Y=`callback failure persistence failed: ${Q instanceof Error?Q.message:Q}`;try{d6($,J.buttonId,J.openId,Y)}catch(V){Z.unknownReason=`${Y}; unknown tombstone persistence also failed: ${V instanceof Error?V.message:V}`}return{state:"unknown",detail:Z.unknownReason??Y}}}function HV($){return[...n0.values()].filter((Z)=>Z.chatId===$&&!Z.resolvedAt&&!Z.unknownAt&&(Z.replyState?.status==="waiting"||Z.replyState?.status==="sending"))}function e8($,Z){if(!$)return;return HV($).find((J)=>Z===void 0||J.replyState?.openId===Z)}function Mj($,Z){return!!Z&&[...n0.values()].some((J)=>J.chatId===$&&(J.replyMessageIds?.includes(Z)||J.replyState?.response?.message_id===Z))}function B9($,Z){let J=n0.get($);if(!J)throw Error(`notify registration not found: ${$}`);let{replyState:Q,replyMessageIds:Y}=J;if(J.replyState=Z,Z.response&&!J.replyMessageIds?.includes(Z.response.message_id))J.replyMessageIds=[...J.replyMessageIds??[],Z.response.message_id];try{$2()}catch(V){if(Q)J.replyState=Q;else delete J.replyState;if(Y)J.replyMessageIds=Y;else delete J.replyMessageIds;throw V}}function $3($,Z,J){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);let Y={resolvedAt:Q.resolvedAt,resolvedBy:Q.resolvedBy,unknownAt:Q.unknownAt,unknownBy:Q.unknownBy,unknownReason:Q.unknownReason,dispatchState:Q.dispatchState};Q.resolvedAt=Date.now(),Q.resolvedBy={...Z!==void 0?{buttonId:Z}:{},openId:J},delete Q.unknownAt,delete Q.unknownBy,delete Q.unknownReason,delete Q.dispatchState;try{$2()}catch(V){if(Y.resolvedAt===void 0)delete Q.resolvedAt;else Q.resolvedAt=Y.resolvedAt;if(Y.resolvedBy===void 0)delete Q.resolvedBy;else Q.resolvedBy=Y.resolvedBy;if(Y.unknownAt===void 0)delete Q.unknownAt;else Q.unknownAt=Y.unknownAt;if(Y.unknownBy===void 0)delete Q.unknownBy;else Q.unknownBy=Y.unknownBy;if(Y.unknownReason===void 0)delete Q.unknownReason;else Q.unknownReason=Y.unknownReason;if(Y.dispatchState!==void 0)Q.dispatchState=Y.dispatchState;throw V}}function d6($,Z,J,Q){let Y=n0.get($);if(!Y)throw Error(`notify registration not found: ${$}`);delete Y.resolvedAt,delete Y.resolvedBy,Y.unknownAt=Date.now(),Y.unknownBy={...Z!==void 0?{buttonId:Z}:{},openId:J},Y.unknownReason=Q,$2()}function i6($,Z,J){try{return $3($,Z,J),{state:"complete"}}catch(Q){let V=`resolved tombstone persistence failed: ${Q instanceof Error?Q.message:String(Q)}`;try{d6($,Z,J,V)}catch(X){let z=X instanceof Error?X.message:String(X);V+=`; unknown tombstone persistence also failed: ${z}`;let H=n0.get($);if(H)H.unknownReason=V}return{state:"unknown",detail:V}}}function dR($=Date.now()){let Z=$-Pj,J=0;for(let[Q,Y]of n0)if(typeof Y.createdAt!=="number"||Y.createdAt<Z)n0.delete(Q),J++;if(J>0)$2();return J}async function GV($,Z,J){let Q={notify_id:$.notifyId,message_id:$.messageId,chat_id:$.chatId,project:$.project,..."id"in Z?{button:{id:Z.id,text:Z.text,type:Z.type}}:{response:{type:"text",...Z}},operator:{open_id:J},timestamp:Math.floor(Date.now()/1000)},Y=new AbortController,V=setTimeout(()=>Y.abort(),jj);try{let X=await SX($.callbackUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q),signal:Y.signal});if(X.status>=200&&X.status<300){let H;try{let G=(await X.text()).trim();if(G.startsWith("{")){let W=JSON.parse(G),K=typeof W?.text==="string"?W.text:typeof W?.reply==="string"?W.reply:typeof W?.message==="string"?W.message:"";if(K.trim())H=K.trim().slice(0,500)}else if(G)H=G.slice(0,500)}catch{}return{ok:!0,detail:`${X.status}`,reply:H}}let z="";try{z=(await X.text()).slice(0,120)}catch{}return{ok:!1,detail:`HTTP ${X.status}${z?` ${z}`:""}`}}catch(X){if(X?.name==="AbortError")return{ok:!1,detail:`回调超时 ${jj}ms(本地服务未在窗口内 2xx)`};return{ok:!1,detail:`回调失败: ${String(X?.message??X).slice(0,160)}`}}finally{clearTimeout(V)}}function Uj($){let Z=!!$.resolvedAt,J=!!$.unknownAt,Q=$.resolvedBy?.buttonId??$.unknownBy?.buttonId,Y=Q?$.buttons.find((z)=>z.id===Q):void 0,V=$.replyState?.response,X=Q!==void 0?{button:Y?{id:Y.id,text:Y.text,type:Y.type}:{id:Q}}:V?{response:{type:"text",...V}}:{};return{notify_id:$.notifyId,project:$.project,message_id:$.messageId,resolved:Z,unknown:J,...$.replyState?{reply:{status:Z&&Q===void 0?"resolved":J&&Q===void 0?"unknown":$.replyState.status,prompt_message_id:$.replyState.promptMessageId,operator:{open_id:$.replyState.openId},...$.replyState.cancelReason?{cancel_reason:$.replyState.cancelReason}:{},...$.replyState.error?{error:$.replyState.error}:{}}}:{},...Z?{...X,resolved_at:$.resolvedAt,resolved_by:$.resolvedBy?.openId??null}:{},...J?{...X,unknown_at:$.unknownAt,unknown_by:$.unknownBy?.openId??null,unknown_reason:$.unknownReason}:{}}}var Pj=604800000,jj=2500,n0,_j,lR=86400000,zV,s8;var Z3=R(()=>{u0();I();H0();b0();n0=new Map,_j=Date.now(),zV=new Set;s8=LX});function n6($){return[...$.pendingAsks.entries()].find(([,Z])=>Z.currentIdx!==void 0)}function j9($,Z){let J=$.pendingAsks.get(Z);if(!J||J.currentIdx===void 0)return null;if(e8($.chatId))return"请先完成或取消通知回复,再回答 Agent 的提问";if(n6($)?.[0]!==Z)return"请先回答当前问题,再回答排队中的提问";return null}function WV($,Z){let J=$.pendingAsks.get(Z);if(!J)throw Error(`missing pending ask: ${Z}`);let Q=J.currentIdx===void 0?void 0:e8($.chatId)?"notification":n6($)?.[0]!==Z?"question":void 0;return{currentIdx:J.currentIdx,answered:J.answered,waitingFor:Q}}function KV($,Z){let J=$.pendingAsks.get(Z),Q=$.currentTurn;if(!J||J.currentIdx===void 0||J.announced||j9($,Z)||!Q?.userOpenId||!Q.messageId)return;J.announced=!0;let Y=(J.announcementVersion??0)+1;J.announcementVersion=Y;let V=J.questions[J.currentIdx]?.question.trim()??"",X=V.length>40?V.slice(0,40)+"…":V,z=J.questions.length>1?`❓ 待回答 ${J.questions.length} 题${X?`: ${X}`:""}`:X?`❓ ${X}`:"❓ 等你回答问题";(async()=>{if(e0(Q.cardId),await o7(Q.cardId,{config:{summary:{content:z}}}),$.currentTurn!==Q||$.pendingAsks.get(Z)!==J||J.announcementVersion!==Y||J.currentIdx===void 0||j9($,Z))return;await w2(Q.messageId,[Q.userOpenId])})().catch((H)=>j(`session "${$.sessionName}": question notification failed: ${H}`))}function a6($){let Z=$.currentTurn;if(!Z)return;for(let[J,Q]of $.pendingAsks){let Y=Z.toolByUseId.get(J);if(!Y||Q.currentIdx===void 0)continue;let V=WV($,J);if(V.waitingFor)Q.announced=!1,Q.announcementVersion=(Q.announcementVersion??0)+1;R0(Z.cardId,C.tool(Y.i),H9(Y.i,J,Q.questions,"\uD83E\uDD14",V)),KV($,J)}}function Oj($){return n6($)!==void 0}async function Aj($,Z,J,Q){let Y=n6($);if(!Y){j(`session "${$.sessionName}": no unanswered question; routing text to Agent`),await $.onUserMessage(Z,[],J,Q);return}let[V,X]=Y,z=j9($,V);if(z){let G=`${z}。这条文字未提交,请稍后重新发送。`,W;if(!await k($.chatId,G,(K)=>{W=K}))throw Error(`提问等待提示发送失败: ${G}
287
- ${w(W)}`);return}if(await BV($,V,X.currentIdx,Z,J)&&Q)K$(Q,"CheckMark")}async function Nj($,Z,J,Q,Y){let V=$.pendingAsks.get(Z);if(!V)return j(`session "${$.sessionName}": stray ask answer for ${Z}`),!1;if(J!==V.currentIdx)return j(`session "${$.sessionName}": stale ask click q=${J} current=${V.currentIdx}`),!1;return Rj($,Z,{optionIdx:Q,user:Y})}async function BV($,Z,J,Q,Y){let V=$.pendingAsks.get(Z);if(!V)return j(`session "${$.sessionName}": stray ask custom for ${Z}`),!1;let X=(Q??"").trim();if(!X)return j(`session "${$.sessionName}": empty custom answer, ignoring`),!1;if(J!==V.currentIdx)return j(`session "${$.sessionName}": stale ask custom q=${J} current=${V.currentIdx}`),!1;return Rj($,Z,{customText:X,user:Y})}function Rj($,Z,J){let Q=$.pendingAsks.get(Z);if(!Q||Q.currentIdx===void 0)return!1;let Y=j9($,Z);if(Y)return j(`session "${$.sessionName}": ask ${Z} waiting: ${Y}`),!1;let V=Q.currentIdx,X=Q.questions[V];if(!X)return j(`session "${$.sessionName}": advanceAsk currentIdx=${V} out of range`),!1;let z;if(J.customText!==void 0)z=J.customText;else if(J.optionIdx!==void 0){let B=X.options?.[J.optionIdx];if(!B)return j(`session "${$.sessionName}": advanceAsk option ${J.optionIdx} out of range`),!1;z=B.label}else return j(`session "${$.sessionName}": advanceAsk with neither customText nor optionIdx`),!1;Q.answers[X.question]=z,Q.answered.set(V,{optionIdx:J.optionIdx,customText:J.customText,user:J.user});let H=Q.questions.length,G=void 0;for(let B=V+1;B<H;B++)if(!Q.answered.has(B)){G=B;break}Q.currentIdx=G;let W=$.currentTurn,K=W?.toolByUseId.get(Z);if(W&&K){let B=H9(K.i,Z,Q.questions,G===void 0?"✅":"\uD83E\uDD14",{currentIdx:G,answered:Q.answered});R0(W.cardId,C.tool(K.i),B)}if(G===void 0)if(Q.requestId)jV($,Z);else j(`session "${$.sessionName}": ask ${Z} all answered, waiting for can_use_tool`),a6($);return!0}function jV($,Z){let J=$.pendingAsks.get(Z);if(!J||!J.requestId)return;let Q=$.currentTurn?.toolByUseId.get(Z),Y=Q?.input??{};if($.proc?.sendPermissionResponse(J.requestId,"allow",{updatedInput:{...Y,answers:J.answers}}),$.pendingPermissions.delete(J.requestId),Q)Q.output=JSON.stringify({answers:J.answers}),Q.isError=!1;if($.pendingAsks.delete(Z),a6($),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working"}var o6=R(()=>{U1();S$();Y0();I();Z3()});import{isAbsolute as nR}from"node:path";function p0($){if($?.planLiveInserted)return C.planLive;return $?.taskLiveInserted?C.taskBoardLive:C.footer}function aR($){return $==="ImageGeneration"||$==="imageGeneration"}function oR($,Z,J){if(J||!aR($))return null;let Q=l6(Z.trim());return nR(Q)?Q:null}function sR($){if($==="Read")return"read";if($==="Edit"||$==="MultiEdit"||$==="NotebookEdit")return"edit";return null}function t6($,Z,J){let Q=J.map((Y)=>({...Y,input:Y.displayInput??Y.input,output:Y.displayOutput??Y.output}));return $==="read"?UY(Z,Q):MY(Z,Q)}function Ej($,Z,J,Q,Y){if(!$.currentTurn)return;let V=Y??Q;if($.maybeMidTurnRotate(),$.startWorkingFooter($.currentTurn),$.currentTurn.currentAssistantSegmentId)$.finalizeCurrentAssistantSegment();let X=sR(J);if(X&&$.currentTurn.openBatchI!==null){let W=$.currentTurn.openBatchI,K=$.currentTurn.toolBatches.get(W);if(K&&K.kind===X){let B=K.items.length;K.items.push({toolUseId:Z,input:Q,displayInput:Y,output:null,isError:!1}),$.currentTurn.toolByUseId.set(Z,{i:W,name:J,input:Q,displayInput:Y,batchSlot:B});let _=t6(X,W,K.items);R0($.currentTurn.cardId,C.tool(W),_),s6($.currentTurn,J,V);return}}if(!X)$.currentTurn.openBatchI=null;let z=s2(J);if(z){let W=$.currentTurn;if(z==="TaskCreate"&&!W.taskBoardResetThisTurn)$.taskBoard=[],W.taskBoardResetThisTurn=!0;if(!W.taskLiveInserted)W.taskLiveInserted=!0,v0(W.cardId,t2($.taskBoard),{type:"insert_before",targetElementId:C.footer});else D0(W.cardId,C.taskBoardLive,t2($.taskBoard),{notifyCardFailure:!1});let K=z==="TaskCreate";if(K)W.taskUpdateI=null;else W.taskCreateI=null;let B=(K?W.taskCreateI:W.taskUpdateI)===null;if(B)if(K)W.taskCreateI=W.toolCount++;else W.taskUpdateI=W.toolCount++;let _=K?W.taskCreateI:W.taskUpdateI;W.toolByUseId.set(Z,{i:_,name:J,input:Q,displayInput:Y});let P=e1(_,$.taskBoard,{name:z,status:"⏳"});B?v0(W.cardId,P,{type:"insert_before",targetElementId:p0(W)}):R0(W.cardId,C.tool(_),P),s6(W,J,V);return}$.currentTurn.taskCreateI=null,$.currentTurn.taskUpdateI=null;let H=$.currentTurn.toolCount++;if(X){$.currentTurn.openBatchI=H;let W=[{toolUseId:Z,input:Q,displayInput:Y,output:null,isError:!1}];$.currentTurn.toolBatches.set(H,{kind:X,items:W}),$.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Q,displayInput:Y,batchSlot:0});let K=t6(X,H,W);v0($.currentTurn.cardId,K,{type:"insert_before",targetElementId:p0($.currentTurn)},void 0,"capacity"),s6($.currentTurn,J,V);return}if($.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Q,displayInput:Y}),J==="AskUserQuestion"){let W=Array.isArray(V?.questions)?V.questions:[],K=W.length>0?0:void 0,B=new Map;$.pendingAsks.set(Z,{questions:W,i:H,answers:{},answered:B,currentIdx:K});let _=H9(H,Z,W,"\uD83E\uDD14",WV($,Z));v0($.currentTurn.cardId,_,{type:"insert_before",targetElementId:p0($.currentTurn)}),KV($,Z);return}let G=Y1(H,J,V,null,"⏳");v0($.currentTurn.cardId,G,{type:"insert_before",targetElementId:p0($.currentTurn)},void 0,"capacity"),s6($.currentTurn,J,V)}function s6($,Z,J){if(!$)return;let Q=n1(Z,J),Y=Q.length>80?Q.slice(0,80)+"…":Q,V=n2(Z),X=Y?`\uD83D\uDD27 ${V}: ${Y}`:`\uD83D\uDD27 ${V}`;Z9($.cardId,X)}function Tj($){return typeof $==="string"?$:Array.isArray($)?$.map((Z)=>Z?.text??JSON.stringify(Z)).join(`
288
- `):JSON.stringify($)}function Sj($,Z,J,Q,Y,V,X){if(!$.currentTurn)return;let z=$.currentTurn.toolByUseId.get(Z);if(!z)return;if(Y&&typeof Y==="object")z.input={...z.input,...Object.fromEntries(Object.entries(Y).filter(([,B])=>B!==void 0))};if(X!==void 0)z.displayInput={...z.displayInput??z.input,...X};let H=Tj(J);if(V!==void 0)z.displayOutput=Tj(V);if(z.output=H,z.isError=Q,$.currentTurn.cardRotationFailed)$.maybeMidTurnRotate();let G=oR(z.name,H,Q);if(G){tR($,$.currentTurn,z,G),$4($);return}if(z.name==="AskUserQuestion"){$4($);return}if(z.batchSlot!=null){let B=$.currentTurn.toolBatches.get(z.i);if(B){let _=B.items[z.batchSlot];if(_)_.output=H,_.displayOutput=z.displayOutput,_.displayInput=z.displayInput,_.isError=Q;let P=t6(B.kind,z.i,B.items);R0($.currentTurn.cardId,C.tool(z.i),P)}$4($);return}let W=s2(z.name);if(W){rR($,z,W,H,Q);return}let K=Y1(z.i,z.name,z.displayInput??z.input,z.displayOutput??H,Q?"❌":"✅",z.resolvedNote);R0($.currentTurn.cardId,C.tool(z.i),K),$4($)}function tR($,Z,J,Q){if(Z.outboundSeenPaths.has(Q))return;Z.outboundSeenPaths.add(Q);let Y=Z.cardId,V=C.tool(J.i),X=Z.imageDeliveryInflight??=new Map,z=X.get(Y)??new Set;X.set(Y,z);let H=[],G=(async()=>{let W=null;try{W=await aJ(Q,(L)=>{H.push(`图片上传:${w(L)}`)})}catch(L){H.push(`图片上传:${w(L)}`),j(`generated image upload failed: ${L}`)}if(W){let L=!1;try{L=await D0(Y,V,Y1(J.i,J.name,J.displayInput??J.input,J.displayOutput??J.output??null,"✅",J.resolvedNote,W),{notifyCardFailure:!1,onFailure:(q)=>{H.push(`图片嵌入:${w(q)}`)}})}catch(q){H.push(`图片嵌入:${w(q)}`),j(`generated image embed failed: ${q}`)}if(L){J.imageKey=W,Z.outboundSentPaths.add(Q);return}j(`generated image could not be embedded in card ${Y}; sending it as a separate message`)}let K,B=W?await C7($.chatId,W,(L)=>{K=L})!==null:await j8($.chatId,Q);if(B)Z.outboundSentPaths.add(Q);else j(`generated image delivery failed: ${Q}`);if(!B&&W)H.push(`图片发送:${w(K)}`);J.resolvedNote=[B?"图片已单独发送。":"图片发送失败。",...H].join(`
289
- `);let _,P=!1;try{P=await D0(Y,V,Y1(J.i,J.name,J.displayInput??J.input,J.displayOutput??J.output??null,B?"✅":"❌",J.resolvedNote),{notifyCardFailure:!1,onFailure:(L)=>{_=L}})}catch(L){_=L}if(!P)j(`generated image status write failed card=${Y} path=${Q}: ${w(_)}
286
+ `),V=Q[Q.length-1];j(`session "${$.sessionName}": multi-msg flush ${Q.length} segment(s) → 1 turn`),await $.onUserMessage(Y,[],V.userOpenId,V.msgId)}function JV($,Z){if($.multiMsgBuffer===null)return;let J=$.multiMsgBuffer.length;j(`session "${$.sessionName}": clear multi-msg buffer (${Z}): ${J} segment(s)`);for(let[Q,Y]of $.multiMsgReactions){if(Y)g0(Q,Y);K$(Q,"CrossMark")}$.multiMsgBuffer=null,$.multiMsgReactions=new Map}var eB=R(()=>{Y0();I();tB()});import{mkdtemp as LR,rm as qR,writeFile as FR}from"node:fs/promises";import{createRequire as DR}from"node:module";import{tmpdir as MR}from"node:os";import{join as $j}from"node:path";function SR($){let Z=Yj.get($);if(Z)return Z;let{liteAdaptor:J}=e2("mathjax-full/js/adaptors/liteAdaptor.js"),{RegisterHTMLHandler:Q}=e2("mathjax-full/js/handlers/html.js"),{mathjax:Y}=e2("mathjax-full/js/mathjax.js"),{TeX:V}=e2("mathjax-full/js/input/tex.js"),{AllPackages:X}=e2("mathjax-full/js/input/tex/AllPackages.js"),{SVG:z}=e2("mathjax-full/js/output/svg.js"),H=J({fontSize:$});Q(H);let G=Y.document("",{InputJax:new V({packages:X}),OutputJax:new z({fontCache:"none"})}),W={adaptor:H,doc:G};return Yj.set($,W),W}function Vj($,Z){let J=Number.parseFloat($??"");if(!Number.isFinite(J)||J<=0)throw Error(`MathJax SVG missing valid ${Z}`);return J}function CR($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xR($,Z=VV,J=!0){try{let Q=Z*UR,{adaptor:Y,doc:V}=SR(Z),X=V.convert($,{display:J,em:Z,ex:Q,containerWidth:80*Z}),z=Y.outerHTML(X);if(/data-mjx-error=|mjx-merror/.test(z)){let t=z.match(/data-mjx-error="([^"]+)"/)?.[1]??"MathJax parse error";throw Error(t)}let H=z.indexOf("<svg"),G=z.lastIndexOf("</svg>");if(H<0||G<0)throw Error("MathJax returned no SVG");let W=z.slice(H,G+6),K=W.match(/^<svg\b[^>]*>/)?.[0];if(!K)throw Error("MathJax returned malformed SVG root");let B=Vj(K.match(/\bwidth="([\d.]+)ex"/)?.[1],"width"),_=Vj(K.match(/\bheight="([\d.]+)ex"/)?.[1],"height"),P=K.match(/\bviewBox="([^"]+)"/)?.[1];if(!P)throw Error("MathJax SVG missing viewBox");let L=P.trim().split(/[\s,]+/).map(Number);if(L.length!==4||L.some((t)=>!Number.isFinite(t))||L[2]<=0||L[3]<=0)throw Error("MathJax SVG has invalid viewBox");let[q,F,M,U]=L,A=/<text\b/.test(W)?TR:0,O=`${q} ${F} ${M+A} ${U}`,N=B*Q,S=A*(N/M),T=Math.max(1,Math.ceil(N+S)),f=Math.max(1,Math.ceil(_*Q)),m=OR-QV*2,b=Math.min(1,m/T),p=Math.max(1,Math.round(T*b)),c=Math.max(1,Math.round(f*b));if(b<1&&c<AR)throw Error(`formula would be unreadable after width cap (${p}x${c})`);let J0=p+QV*2,l=c+Jj*2,y=W.slice(K.length,-6).replace(/currentColor/g,Zj).replace(/font-family="serif"/g,`font-family="${ER}"`);return{svg:[`<svg xmlns="http://www.w3.org/2000/svg" width="${J0}" height="${l}" viewBox="0 0 ${J0} ${l}" style="color:${Zj}">`,`<rect x="0" y="0" width="${J0}" height="${l}" rx="6" fill="${Gj}"/>`,`<svg x="${QV}" y="${Jj}" width="${p}" height="${c}" viewBox="${CR(O)}" preserveAspectRatio="xMidYMid meet">`,y,"</svg>","</svg>"].join(""),width:J0,height:l}}catch(Q){return j(`math-render: TeX→SVG failed for ${$.slice(0,80)}…: ${Q}`),null}}function bR($,Z=VV,J=!0){let Q=xR($,Z,J);if(!Q)return null;try{let{Resvg:Y}=e2("@resvg/resvg-js"),X=new Y(Q.svg,{background:Gj,fitTo:{mode:"original"},shapeRendering:2,textRendering:1,font:{loadSystemFonts:!0,serifFamily:Qj,sansSerifFamily:Qj}}).render().asPng(),z=new DataView(X.buffer,X.byteOffset,X.byteLength),H=z.getUint32(16),G=z.getUint32(20);if(H!==Q.width||G!==Q.height)throw Error(`PNG dimensions ${H}x${G} != SVG ${Q.width}x${Q.height}`);return{png:X,width:H,height:G}}catch(Y){return j(`math-render: SVG→PNG failed for ${$.slice(0,80)}…: ${Y}`),null}}function kR($){if(/^[A-Za-zΑ-ω]$/.test($))return!0;if(/\\[A-Za-z]+|[_^=]|[{}]|[≤≥≠≈∑∫√]/.test($))return!0;return/[A-Za-zΑ-ω]\s*[+\-*/<>]\s*[A-Za-zΑ-ω0-9]/.test($)}function Xj($,Z){let J=[],Q=(W,K,B)=>{let _=W[0],P=K.trim();if(!P)return;J.push({start:Z+W.index,end:Z+W.index+_.length,tex:P,raw:_,display:B})},Y,V=/(?<!\\)\$\$([\s\S]+?)(?<!\\)\$\$|\\\[([\s\S]+?)\\\]/g;while((Y=V.exec($))!==null)Q(Y,Y[1]??Y[2]??"",!0);let X=/\\\(([\s\S]+?)\\\)/g;while((Y=X.exec($))!==null)Q(Y,Y[1]??"",!1);let z=/(?<![\\$])\$(?!\$)([^$\n]+?)(?<![\\$])\$(?!\$)/g;while((Y=z.exec($))!==null){let W=(Y[1]??"").trim();if(kR(W))Q(Y,W,!1)}J.sort((W,K)=>W.start-K.start||K.end-W.end);let H=[],G=-1;for(let W of J){if(W.start<G)continue;H.push(W),G=W.end}return H}function Wj($){let Z=LJ($),J=[],Q=0;for(let Y of Z){if(Q<Y.start)J.push(...Xj($.slice(Q,Y.start),Q));Q=Math.max(Q,Y.end)}if(Q<$.length)J.push(...Xj($.slice(Q),Q));return J}function wR($){let Z=$;if(Z=Z.replace(/\\text\{([^{}]*)\}/g,"$1"),Z=Z.replace(/\\left\s*/g,"").replace(/\\right\s*/g,""),Z=Z.replace(/\\([A-Za-z]+)\b/g,(J,Q)=>{if(zj[Q])return zj[Q];if(Q==="times")return"×";if(Q==="cdot")return"·";if(Q==="div")return"÷";if(Q==="pm")return"±";if(Q==="leq"||Q==="le")return"≤";if(Q==="geq"||Q==="ge")return"≥";if(Q==="neq"||Q==="ne")return"≠";if(Q==="approx")return"≈";if(Q==="sim")return"~";if(Q==="infty")return"∞";if(Q==="partial")return"∂";if(Q==="nabla")return"∇";if(Q==="sqrt")return"√";if(Q==="to")return"→";return J}),/\\/.test(Z))return null;if(Z=Z.replace(/([_^])\{([^{}]+)\}/g,(J,Q,Y)=>Y.length===1?`${Q}${Y}`:`${Q}(${Y})`),Z=Z.replace(/√\{([^{}]+)\}/g,"√($1)"),/[{}]/.test(Z))return null;return Z}function hR($){let Z=Hj.get($);if(Z!==void 0)return Z;return Z=yR++,Hj.set($,Z),Z}function IR($,Z){return`${RR}\x00${hR(Z)}\x00${$}`}function gR($){let Z=2166136261;for(let J=0;J<$.length;J++)Z^=$.charCodeAt(J),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}async function mR($,Z){let J=IR($,Z),Q=r2.get(J);if(Q)return Q;let Y=YV.get(J);if(Y)return Y;let V=(async()=>{let X=bR($,VV,!0);if(!X)return null;let z=null;try{z=await LR($j(MR(),"lodestar-math-"));let H=$j(z,`formula-${gR($)}.png`);await FR(H,X.png);let G=await Z(H,{tex:$,width:X.width,height:X.height});if(!G)return j(`math-render: upload returned no image key for ${$.slice(0,80)}…`),null;let W={key:G,width:X.width,height:X.height};if(r2.has(J))r2.delete(J);r2.set(J,W);while(r2.size>fR){let K=r2.keys().next().value;if(typeof K!=="string")break;r2.delete(K)}return W}catch(H){return j(`math-render: upload failed for ${$.slice(0,80)}…: ${H}`),null}finally{if(z)try{await qR(z,{recursive:!0,force:!0})}catch(H){j(`math-render: temp cleanup failed for ${z}: ${H}`)}}})();YV.set(J,V);try{return await V}finally{YV.delete(J)}}function pR($,Z,J){let Q=$.width<=NR;return{type:"image",tex:Z.tex,index:J,element:{tag:"img",img_key:$.key,alt:{tag:"plain_text",content:Z.tex.replace(/\s+/g," ").slice(0,80)},scale_type:Q?"crop_center":"fit_horizontal",...Q?{size:`${$.width}px ${$.height}px`}:{},preview:!1}}}async function Kj($,Z={}){let J=Wj($);if(!J.length)return{blocks:[{type:"markdown",text:$}],formulaCount:0,renderedImageCount:0};let Q=Z.uploader??vR,Y=await Promise.all(J.map(async(W)=>{if(!W.display){let K=wR(W.tex);if(K!==null)return{unicode:K,uploaded:null}}return{unicode:null,uploaded:await mR(W.tex,Q)}})),V=[],X="",z=0,H=0,G=()=>{if(!X)return;if(X.trim())V.push({type:"markdown",text:X});X=""};for(let W=0;W<J.length;W++){let K=J[W],B=Y[W];if(X+=$.slice(z,K.start),B.unicode!==null){X+=B.unicode,z=K.end;continue}let _=B.uploaded;if(!_){X+=K.raw,z=K.end;continue}G(),V.push(pR(_,K,H++)),z=K.end}if(X+=$.slice(z),G(),!V.length)V.push({type:"markdown",text:$});return{blocks:V,formulaCount:J.length,renderedImageCount:H}}function XV($){return Wj($).length>0}var e2,UR=0.5,VV=22,Zj="#1F2329",Gj="#F7F8FA",QV=12,Jj=8,OR=720,AR=14,NR=278,RR="v4-native-cjk-tail-pad",TR=1100,Qj,ER="Noto Sans CJK SC, Noto Sans CJK JP, Microsoft YaHei, PingFang SC, Arial Unicode MS, sans-serif",Yj,zj,vR=async($)=>{let{uploadImageKey:Z}=await Promise.resolve().then(() => (Y0(),z0));return Z($)},Hj,yR=1,r2,YV,fR=512;var Bj=R(()=>{I();e2=DR(import.meta.url),Qj=process.platform==="win32"?"Microsoft YaHei":process.platform==="darwin"?"PingFang SC":"Noto Sans CJK SC",Yj=new Map;zj={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",Gamma:"Γ",Delta:"Δ",Theta:"Θ",Lambda:"Λ",Pi:"Π",Sigma:"Σ",Phi:"Φ",Psi:"Ψ",Omega:"Ω"};Hj=new WeakMap,r2=new Map,YV=new Map});import{readFileSync as uR}from"node:fs";function K9($){return zV.has($)}function t8($){zV.add($)}function r8($){zV.delete($)}function $2(){try{let $={};for(let[Z,J]of n0)$[Z]=J;r(s8,$)}catch($){throw j(`notify-callbacks: save failed (${s8}): ${$}`),$}}function Lj(){let $=[],Z;try{Z=uR(s8,"utf8")}catch(J){if(J?.code==="ENOENT")return[];throw j(`notify-callbacks: read failed (${s8}): ${J}`),J}try{let J=JSON.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("notify callback store must be an object");let Q=Date.now()-Pj,Y=0,V=0;for(let X of Object.values(J)){if(!X||typeof X!=="object")continue;if(typeof X.notifyId!=="string"||typeof X.callbackUrl!=="string")continue;if(typeof X.createdAt!=="number"||X.createdAt<Q){Y++;continue}if(X.replyState?.status==="sending"&&!X.resolvedAt&&!X.unknownAt)X.unknownAt=Date.now(),X.unknownBy={openId:X.replyState.openId},X.unknownReason="服务在文字回复回传期间中断,无法确认是否送达,禁止自动重试",V++;if(X.dispatchState&&!X.resolvedAt&&!X.unknownAt)X.unknownAt=Date.now(),X.unknownBy={buttonId:X.dispatchState.buttonId,openId:X.dispatchState.openId},X.unknownReason="服务在按钮回调期间中断,无法确认是否送达,禁止自动重试",V++;if(n0.set(X.notifyId,X),(X.replyState?.status==="sending"||X.dispatchState)&&X.unknownAt)$.push(X)}if(j(`notify-callbacks: loaded ${n0.size} registration(s)${Y?`, dropped ${Y} stale`:""}`),V)j(`notify-callbacks: ${V} interrupted callback(s) marked UNKNOWN`);if(Y>0||V>0)$2()}catch(J){throw j(`notify-callbacks: load failed (${s8}): ${J}`),J}return $}function qj($){let Z=Date.now();if(Z-_j>=lR)dR(Z),_j=Z;n0.set($.notifyId,$),$2()}function R1($){return n0.get($)}function Fj($,Z,J){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);if(Q.resolvedAt||Q.unknownAt||Q.dispatchState)throw Error("notify callback is already dispatched or finalized");Q.dispatchState={buttonId:Z,openId:J,startedAt:Date.now()};try{$2()}catch(Y){throw delete Q.dispatchState,Y}}function Dj($){let Z=n0.get($);if(!Z?.dispatchState)throw Error(`notify callback is not dispatching: ${$}`);let J=Z.dispatchState;delete Z.dispatchState;try{return $2(),{state:"retry"}}catch(Q){Z.dispatchState=J;let Y=`callback failure persistence failed: ${Q instanceof Error?Q.message:Q}`;try{d6($,J.buttonId,J.openId,Y)}catch(V){Z.unknownReason=`${Y}; unknown tombstone persistence also failed: ${V instanceof Error?V.message:V}`}return{state:"unknown",detail:Z.unknownReason??Y}}}function HV($){return[...n0.values()].filter((Z)=>Z.chatId===$&&!Z.resolvedAt&&!Z.unknownAt&&(Z.replyState?.status==="waiting"||Z.replyState?.status==="sending"))}function e8($,Z){if(!$)return;return HV($).find((J)=>Z===void 0||J.replyState?.openId===Z)}function Mj($,Z){return!!Z&&[...n0.values()].some((J)=>J.chatId===$&&(J.replyMessageIds?.includes(Z)||J.replyState?.response?.message_id===Z))}function B9($,Z){let J=n0.get($);if(!J)throw Error(`notify registration not found: ${$}`);let{replyState:Q,replyMessageIds:Y}=J;if(J.replyState=Z,Z.response&&!J.replyMessageIds?.includes(Z.response.message_id))J.replyMessageIds=[...J.replyMessageIds??[],Z.response.message_id];try{$2()}catch(V){if(Q)J.replyState=Q;else delete J.replyState;if(Y)J.replyMessageIds=Y;else delete J.replyMessageIds;throw V}}function $3($,Z,J){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);let Y={resolvedAt:Q.resolvedAt,resolvedBy:Q.resolvedBy,unknownAt:Q.unknownAt,unknownBy:Q.unknownBy,unknownReason:Q.unknownReason,dispatchState:Q.dispatchState};Q.resolvedAt=Date.now(),Q.resolvedBy={...Z!==void 0?{buttonId:Z}:{},openId:J},delete Q.unknownAt,delete Q.unknownBy,delete Q.unknownReason,delete Q.dispatchState;try{$2()}catch(V){if(Y.resolvedAt===void 0)delete Q.resolvedAt;else Q.resolvedAt=Y.resolvedAt;if(Y.resolvedBy===void 0)delete Q.resolvedBy;else Q.resolvedBy=Y.resolvedBy;if(Y.unknownAt===void 0)delete Q.unknownAt;else Q.unknownAt=Y.unknownAt;if(Y.unknownBy===void 0)delete Q.unknownBy;else Q.unknownBy=Y.unknownBy;if(Y.unknownReason===void 0)delete Q.unknownReason;else Q.unknownReason=Y.unknownReason;if(Y.dispatchState!==void 0)Q.dispatchState=Y.dispatchState;throw V}}function d6($,Z,J,Q){let Y=n0.get($);if(!Y)throw Error(`notify registration not found: ${$}`);delete Y.resolvedAt,delete Y.resolvedBy,Y.unknownAt=Date.now(),Y.unknownBy={...Z!==void 0?{buttonId:Z}:{},openId:J},Y.unknownReason=Q,$2()}function i6($,Z,J){try{return $3($,Z,J),{state:"complete"}}catch(Q){let V=`resolved tombstone persistence failed: ${Q instanceof Error?Q.message:String(Q)}`;try{d6($,Z,J,V)}catch(X){let z=X instanceof Error?X.message:String(X);V+=`; unknown tombstone persistence also failed: ${z}`;let H=n0.get($);if(H)H.unknownReason=V}return{state:"unknown",detail:V}}}function dR($=Date.now()){let Z=$-Pj,J=0;for(let[Q,Y]of n0)if(typeof Y.createdAt!=="number"||Y.createdAt<Z)n0.delete(Q),J++;if(J>0)$2();return J}async function GV($,Z,J){let Q={notify_id:$.notifyId,message_id:$.messageId,chat_id:$.chatId,project:$.project,..."id"in Z?{button:{id:Z.id,text:Z.text,type:Z.type}}:{response:{type:"text",...Z}},operator:{open_id:J},timestamp:Math.floor(Date.now()/1000)},Y=new AbortController,V=setTimeout(()=>Y.abort(),jj);try{let X=await SX($.callbackUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q),signal:Y.signal});if(X.status>=200&&X.status<300){let H;try{let G=(await X.text()).trim();if(G.startsWith("{")){let W=JSON.parse(G),K=typeof W?.text==="string"?W.text:typeof W?.reply==="string"?W.reply:typeof W?.message==="string"?W.message:"";if(K.trim())H=K.trim().slice(0,500)}else if(G)H=G.slice(0,500)}catch{}return{ok:!0,detail:`${X.status}`,reply:H}}let z="";try{z=(await X.text()).slice(0,120)}catch{}return{ok:!1,detail:`HTTP ${X.status}${z?` ${z}`:""}`}}catch(X){if(X?.name==="AbortError")return{ok:!1,detail:`回调超时 ${jj}ms(本地服务未在窗口内 2xx)`};return{ok:!1,detail:`回调失败: ${String(X?.message??X).slice(0,160)}`}}finally{clearTimeout(V)}}function Uj($){let Z=!!$.resolvedAt,J=!!$.unknownAt,Q=$.resolvedBy?.buttonId??$.unknownBy?.buttonId,Y=Q?$.buttons.find((z)=>z.id===Q):void 0,V=$.replyState?.response,X=Q!==void 0?{button:Y?{id:Y.id,text:Y.text,type:Y.type}:{id:Q}}:V?{response:{type:"text",...V}}:{};return{notify_id:$.notifyId,project:$.project,message_id:$.messageId,resolved:Z,unknown:J,...$.replyState?{reply:{status:Z&&Q===void 0?"resolved":J&&Q===void 0?"unknown":$.replyState.status,prompt_message_id:$.replyState.promptMessageId,operator:{open_id:$.replyState.openId},...$.replyState.cancelReason?{cancel_reason:$.replyState.cancelReason}:{},...$.replyState.error?{error:$.replyState.error}:{}}}:{},...Z?{...X,resolved_at:$.resolvedAt,resolved_by:$.resolvedBy?.openId??null}:{},...J?{...X,unknown_at:$.unknownAt,unknown_by:$.unknownBy?.openId??null,unknown_reason:$.unknownReason}:{}}}var Pj=604800000,jj=2500,n0,_j,lR=86400000,zV,s8;var Z3=R(()=>{u0();I();H0();b0();n0=new Map,_j=Date.now(),zV=new Set;s8=LX});function n6($){return[...$.pendingAsks.entries()].find(([,Z])=>Z.currentIdx!==void 0)}function j9($,Z){let J=$.pendingAsks.get(Z);if(!J||J.currentIdx===void 0)return null;if(e8($.chatId))return"请先完成或取消通知回复,再回答 Agent 的提问";if(n6($)?.[0]!==Z)return"请先回答当前问题,再回答排队中的提问";return null}function WV($,Z){let J=$.pendingAsks.get(Z);if(!J)throw Error(`missing pending ask: ${Z}`);let Q=J.currentIdx===void 0?void 0:e8($.chatId)?"notification":n6($)?.[0]!==Z?"question":void 0;return{currentIdx:J.currentIdx,answered:J.answered,waitingFor:Q}}function KV($,Z){let J=$.pendingAsks.get(Z),Q=$.currentTurn;if(!J||J.currentIdx===void 0||J.announced||j9($,Z)||!Q?.userOpenId||!Q.messageId)return;J.announced=!0;let Y=(J.announcementVersion??0)+1;J.announcementVersion=Y;let V=J.questions[J.currentIdx]?.question.trim()??"",X=V.length>40?V.slice(0,40)+"…":V,z=J.questions.length>1?`❓ 待回答 ${J.questions.length} 题${X?`: ${X}`:""}`:X?`❓ ${X}`:"❓ 等你回答问题";(async()=>{if(e0(Q.cardId),await o7(Q.cardId,{config:{summary:{content:z}}}),$.currentTurn!==Q||$.pendingAsks.get(Z)!==J||J.announcementVersion!==Y||J.currentIdx===void 0||j9($,Z))return;await w2(Q.messageId,[Q.userOpenId])})().catch((H)=>j(`session "${$.sessionName}": question notification failed: ${H}`))}function a6($){let Z=$.currentTurn;if(!Z)return;for(let[J,Q]of $.pendingAsks){let Y=Z.toolByUseId.get(J);if(!Y||Q.currentIdx===void 0)continue;let V=WV($,J);if(V.waitingFor)Q.announced=!1,Q.announcementVersion=(Q.announcementVersion??0)+1;R0(Z.cardId,C.tool(Y.i),H9(Y.i,J,Q.questions,"\uD83E\uDD14",V)),KV($,J)}}function Oj($){return n6($)!==void 0}async function Aj($,Z,J,Q){let Y=n6($);if(!Y){j(`session "${$.sessionName}": no unanswered question; routing text to Agent`),await $.onUserMessage(Z,[],J,Q);return}let[V,X]=Y,z=j9($,V);if(z){let G=`${z}。这条文字未提交,请稍后重新发送。`,W;if(!await k($.chatId,G,(K)=>{W=K}))throw Error(`提问等待提示发送失败: ${G}
287
+ ${w(W)}`);return}if(await BV($,V,X.currentIdx,Z,J)&&Q)K$(Q,"CheckMark")}async function Nj($,Z,J,Q,Y){let V=$.pendingAsks.get(Z);if(!V)return j(`session "${$.sessionName}": stray ask answer for ${Z}`),!1;if(J!==V.currentIdx)return j(`session "${$.sessionName}": stale ask click q=${J} current=${V.currentIdx}`),!1;return Rj($,Z,{optionIdx:Q,user:Y})}async function BV($,Z,J,Q,Y){let V=$.pendingAsks.get(Z);if(!V)return j(`session "${$.sessionName}": stray ask custom for ${Z}`),!1;let X=(Q??"").trim();if(!X)return j(`session "${$.sessionName}": empty custom answer, ignoring`),!1;if(J!==V.currentIdx)return j(`session "${$.sessionName}": stale ask custom q=${J} current=${V.currentIdx}`),!1;return Rj($,Z,{customText:X,user:Y})}function Rj($,Z,J){let Q=$.pendingAsks.get(Z);if(!Q||Q.currentIdx===void 0)return!1;let Y=j9($,Z);if(Y)return j(`session "${$.sessionName}": ask ${Z} waiting: ${Y}`),!1;let V=Q.currentIdx,X=Q.questions[V];if(!X)return j(`session "${$.sessionName}": advanceAsk currentIdx=${V} out of range`),!1;let z;if(J.customText!==void 0)z=J.customText;else if(J.optionIdx!==void 0){let B=X.options?.[J.optionIdx];if(!B)return j(`session "${$.sessionName}": advanceAsk option ${J.optionIdx} out of range`),!1;z=B.label}else return j(`session "${$.sessionName}": advanceAsk with neither customText nor optionIdx`),!1;Q.answers[X.question]=z,Q.answered.set(V,{optionIdx:J.optionIdx,customText:J.customText,user:J.user});let H=Q.questions.length,G=void 0;for(let B=V+1;B<H;B++)if(!Q.answered.has(B)){G=B;break}Q.currentIdx=G;let W=$.currentTurn,K=W?.toolByUseId.get(Z);if(W&&K){let B=H9(K.i,Z,Q.questions,G===void 0?"✅":"\uD83E\uDD14",{currentIdx:G,answered:Q.answered});R0(W.cardId,C.tool(K.i),B)}if(G===void 0)if(Q.requestId)jV($,Z);else j(`session "${$.sessionName}": ask ${Z} all answered, waiting for can_use_tool`),a6($);return!0}function jV($,Z){let J=$.pendingAsks.get(Z);if(!J||!J.requestId)return;let Q=$.currentTurn?.toolByUseId.get(Z),Y=Q?.input??{};if($.proc?.sendPermissionResponse(J.requestId,"allow",{updatedInput:{...Y,answers:J.answers}}),$.pendingPermissions.delete(J.requestId),Q)Q.output=JSON.stringify({answers:J.answers}),Q.isError=!1;if($.pendingAsks.delete(Z),a6($),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working"}var o6=R(()=>{U1();S$();Y0();I();Z3()});import{isAbsolute as nR}from"node:path";function p0($){if($?.planLiveInserted)return C.planLive;return $?.taskLiveInserted?C.taskBoardLive:C.footer}function aR($){return $==="ImageGeneration"||$==="imageGeneration"}function oR($,Z,J){if(J||!aR($))return null;let Q=l6(Z.trim());return nR(Q)?Q:null}function sR($){if($==="Read")return"read";if($==="Edit"||$==="MultiEdit"||$==="NotebookEdit")return"edit";return null}function t6($,Z,J){let Q=J.map((Y)=>({...Y,input:Y.displayInput??Y.input,output:Y.displayOutput??Y.output}));return $==="read"?UY(Z,Q):MY(Z,Q)}function Ej($,Z,J,Q,Y){if(!$.currentTurn)return;let V=Y??Q;if($.maybeMidTurnRotate(),$.startWorkingFooter($.currentTurn),$.currentTurn.currentAssistantSegmentId)$.finalizeCurrentAssistantSegment();let X=sR(J);if(X&&$.currentTurn.openBatchI!==null){let W=$.currentTurn.openBatchI,K=$.currentTurn.toolBatches.get(W);if(K&&K.kind===X){let B=K.items.length;K.items.push({toolUseId:Z,input:Q,displayInput:Y,output:null,isError:!1}),$.currentTurn.toolByUseId.set(Z,{i:W,name:J,input:Q,displayInput:Y,batchSlot:B});let _=t6(X,W,K.items);R0($.currentTurn.cardId,C.tool(W),_),s6($.currentTurn,J,V);return}}if(!X)$.currentTurn.openBatchI=null;let z=s2(J);if(z){let W=$.currentTurn;if(z==="TaskCreate"&&!W.taskBoardResetThisTurn)$.taskBoard=[],W.taskBoardResetThisTurn=!0;if(!W.taskLiveInserted)W.taskLiveInserted=!0,v0(W.cardId,t2($.taskBoard),{type:"insert_before",targetElementId:C.footer});else F0(W.cardId,C.taskBoardLive,t2($.taskBoard),{notifyCardFailure:!1});let K=z==="TaskCreate";if(K)W.taskUpdateI=null;else W.taskCreateI=null;let B=(K?W.taskCreateI:W.taskUpdateI)===null;if(B)if(K)W.taskCreateI=W.toolCount++;else W.taskUpdateI=W.toolCount++;let _=K?W.taskCreateI:W.taskUpdateI;W.toolByUseId.set(Z,{i:_,name:J,input:Q,displayInput:Y});let P=e1(_,$.taskBoard,{name:z,status:"⏳"});B?v0(W.cardId,P,{type:"insert_before",targetElementId:p0(W)}):R0(W.cardId,C.tool(_),P),s6(W,J,V);return}$.currentTurn.taskCreateI=null,$.currentTurn.taskUpdateI=null;let H=$.currentTurn.toolCount++;if(X){$.currentTurn.openBatchI=H;let W=[{toolUseId:Z,input:Q,displayInput:Y,output:null,isError:!1}];$.currentTurn.toolBatches.set(H,{kind:X,items:W}),$.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Q,displayInput:Y,batchSlot:0});let K=t6(X,H,W);v0($.currentTurn.cardId,K,{type:"insert_before",targetElementId:p0($.currentTurn)},void 0,"capacity"),s6($.currentTurn,J,V);return}if($.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Q,displayInput:Y}),J==="AskUserQuestion"){let W=Array.isArray(V?.questions)?V.questions:[],K=W.length>0?0:void 0,B=new Map;$.pendingAsks.set(Z,{questions:W,i:H,answers:{},answered:B,currentIdx:K});let _=H9(H,Z,W,"\uD83E\uDD14",WV($,Z));v0($.currentTurn.cardId,_,{type:"insert_before",targetElementId:p0($.currentTurn)}),KV($,Z);return}let G=Y1(H,J,V,null,"⏳");v0($.currentTurn.cardId,G,{type:"insert_before",targetElementId:p0($.currentTurn)},void 0,"capacity"),s6($.currentTurn,J,V)}function s6($,Z,J){if(!$)return;let Q=n1(Z,J),Y=Q.length>80?Q.slice(0,80)+"…":Q,V=n2(Z),X=Y?`\uD83D\uDD27 ${V}: ${Y}`:`\uD83D\uDD27 ${V}`;Z9($.cardId,X)}function Tj($){return typeof $==="string"?$:Array.isArray($)?$.map((Z)=>Z?.text??JSON.stringify(Z)).join(`
288
+ `):JSON.stringify($)}function Sj($,Z,J,Q,Y,V,X){if(!$.currentTurn)return;let z=$.currentTurn.toolByUseId.get(Z);if(!z)return;if(Y&&typeof Y==="object")z.input={...z.input,...Object.fromEntries(Object.entries(Y).filter(([,B])=>B!==void 0))};if(X!==void 0)z.displayInput={...z.displayInput??z.input,...X};let H=Tj(J);if(V!==void 0)z.displayOutput=Tj(V);if(z.output=H,z.isError=Q,$.currentTurn.cardRotationFailed)$.maybeMidTurnRotate();let G=oR(z.name,H,Q);if(G){tR($,$.currentTurn,z,G),$4($);return}if(z.name==="AskUserQuestion"){$4($);return}if(z.batchSlot!=null){let B=$.currentTurn.toolBatches.get(z.i);if(B){let _=B.items[z.batchSlot];if(_)_.output=H,_.displayOutput=z.displayOutput,_.displayInput=z.displayInput,_.isError=Q;let P=t6(B.kind,z.i,B.items);R0($.currentTurn.cardId,C.tool(z.i),P)}$4($);return}let W=s2(z.name);if(W){rR($,z,W,H,Q);return}let K=Y1(z.i,z.name,z.displayInput??z.input,z.displayOutput??H,Q?"❌":"✅",z.resolvedNote);R0($.currentTurn.cardId,C.tool(z.i),K),$4($)}function tR($,Z,J,Q){if(Z.outboundSeenPaths.has(Q))return;Z.outboundSeenPaths.add(Q);let Y=Z.cardId,V=C.tool(J.i),X=Z.imageDeliveryInflight??=new Map,z=X.get(Y)??new Set;X.set(Y,z);let H=[],G=(async()=>{let W=null;try{W=await aJ(Q,(L)=>{H.push(`图片上传:${w(L)}`)})}catch(L){H.push(`图片上传:${w(L)}`),j(`generated image upload failed: ${L}`)}if(W){let L=!1;try{L=await F0(Y,V,Y1(J.i,J.name,J.displayInput??J.input,J.displayOutput??J.output??null,"✅",J.resolvedNote,W),{notifyCardFailure:!1,onFailure:(q)=>{H.push(`图片嵌入:${w(q)}`)}})}catch(q){H.push(`图片嵌入:${w(q)}`),j(`generated image embed failed: ${q}`)}if(L){J.imageKey=W,Z.outboundSentPaths.add(Q);return}j(`generated image could not be embedded in card ${Y}; sending it as a separate message`)}let K,B=W?await C7($.chatId,W,(L)=>{K=L})!==null:await j8($.chatId,Q);if(B)Z.outboundSentPaths.add(Q);else j(`generated image delivery failed: ${Q}`);if(!B&&W)H.push(`图片发送:${w(K)}`);J.resolvedNote=[B?"图片已单独发送。":"图片发送失败。",...H].join(`
289
+ `);let _,P=!1;try{P=await F0(Y,V,Y1(J.i,J.name,J.displayInput??J.input,J.displayOutput??J.output??null,B?"✅":"❌",J.resolvedNote),{notifyCardFailure:!1,onFailure:(L)=>{_=L}})}catch(L){_=L}if(!P)j(`generated image status write failed card=${Y} path=${Q}: ${w(_)}
290
290
  ${J.resolvedNote}`);if(!B&&W)await k($.chatId,`❌ 生成图片发送失败:${H.join(`
291
291
  `)}`)})().catch(async(W)=>{j(`generated image delivery failed: ${W}`),await k($.chatId,`❌ 生成图片发送失败:${[...new Set([...H,w(W)])].join(`
292
- `)}`)});z.add(G),G.finally(()=>{if(z.delete(G),!z.size)X.delete(Y)}).catch((W)=>j(`generated image failure notice failed: ${W}`))}async function _V($,Z){let J=Z?[...$.imageDeliveryInflight?.get(Z)??[]]:[...$.imageDeliveryInflight?.values()??[]].flatMap((Q)=>[...Q]);await Promise.allSettled(J)}function rR($,Z,J,Q,Y){if(!$.currentTurn)return;if(!Y)$.taskBoard=J==="TaskCreate"?u6($.taskBoard,J,Z.input,Q,Z.displayInput):u6($.taskBoard,J,Z.displayInput??Z.input,Z.displayOutput??Q);let V=e1(Z.i,$.taskBoard,{name:J,status:Y?"❌":"✅"},Z.resolvedNote);if(R0($.currentTurn.cardId,C.tool(Z.i),V),$.currentTurn.taskLiveInserted)D0($.currentTurn.cardId,C.taskBoardLive,t2($.taskBoard),{notifyCardFailure:!1});$4($)}function $4($){let Z=$.currentTurn;if(!Z||$.hasPendingAgentTool())return;for(let J of Z.toolByUseId.values())if(J.output==null)return;$.startThinkingFooter(Z)}function PV($,Z,J,Q,Y,V=$.currentTurn){let X=V;if(!X)return;for(let[z,H]of Q){if(X.toolByUseId.has(z))continue;let G=H.batchSlot??null,W=H.input,K=H.displayInput,B=H.displayOutput,_,P;if(G!=null){let A=Y.get(H.i)?.items[G];if(!A)continue;W=A.input,K=A.displayInput,B=A.displayOutput,_=A.output,P=A.isError}else _=H.output??null,P=H.isError??!1;let L=_!=null,q=e4(Z,C.tool(H.i));if(L&&!q)continue;if(G!=null){let A=Y.get(H.i)?.kind;if(!A)continue;let O=X.toolCount++,N={toolUseId:z,input:W,displayInput:K,output:_,displayOutput:B,isError:P};X.toolBatches.set(O,{kind:A,items:[N]}),X.toolByUseId.set(z,{...H,i:O,batchSlot:0}),v0(J,t6(A,O,[N]),{type:"insert_before",targetElementId:p0(X)});continue}let D=s2(H.name);if(D){let A=D==="TaskCreate";if(A)X.taskUpdateI=null;else X.taskCreateI=null;let O=(A?X.taskCreateI:X.taskUpdateI)===null;if(O)if(A)X.taskCreateI=X.toolCount++;else X.taskUpdateI=X.toolCount++;let N=A?X.taskCreateI:X.taskUpdateI;X.toolByUseId.set(z,{...H,i:N});let S=!L?"⏳":P?"❌":"✅",T=e1(N,$.taskBoard,{name:D,status:S},H.resolvedNote);O?v0(J,T,{type:"insert_before",targetElementId:p0(X)}):R0(J,C.tool(N),T);continue}let M=X.toolCount++;X.toolByUseId.set(z,{...H,i:M});let U=!L?"⏳":P?"❌":"✅";v0(J,Y1(M,H.name,K??W,B??_,U,H.resolvedNote,H.imageKey),{type:"insert_before",targetElementId:p0(X)})}}var Cj=R(()=>{$V();U1();S$();Y0();I();o6()});async function xj($,Z,J,Q){let Y=$.pendingPermissions.get(Z);if(!Y)return j(`session "${$.sessionName}": stray permission ${Z}`),{ok:!1,message:"此权限请求已失效或已处理"};let V=$.proc;if(!V)return j(`session "${$.sessionName}": permission ${Z} has no active process`),{ok:!1,message:"后端进程已退出,权限决定未送达"};let X=J==="deny"?"deny":"allow";try{V.sendPermissionResponse(Z,X,J==="allow_always"?{updatedPermissions:Y.permissionSuggestions}:void 0)}catch(G){return j(`session "${$.sessionName}": permission response ${Z} failed: ${G}`),{ok:!1,message:`权限决定发送失败: ${G instanceof Error?G.message:G}`}}$.pendingPermissions.delete(Z);let z=$.currentTurn,H=z?.toolByUseId.get(Y.toolUseId);if(z&&H){let G=s2(H.name);if(J==="deny"){let W=`\uD83D\uDEAB 已拒绝 by ${Q||"匿名"}`,K=G?e1(H.i,$.taskBoard,{name:G,status:"❌"},W):Y1(H.i,H.name,H.displayInput??H.input,W,"❌");R0(z.cardId,C.tool(H.i),K)}else{let W=J==="allow_always"?"始终允许":"已允许";H.resolvedNote=`✅ **${W}** by ${Q||"匿名"}`;let K=G?e1(H.i,$.taskBoard,{name:G,status:"⏳"},H.resolvedNote):Y1(H.i,H.name,H.displayInput??H.input,null,"⏳",H.resolvedNote);R0(z.cardId,C.tool(H.i),K)}}if(j(`session "${$.sessionName}": permission decision request=${Z} tool_use_id=${Y.toolUseId} decision=${J}`),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working";return{ok:!0,message:J==="deny"?"已拒绝":J==="allow_always"?"已始终允许":"已允许"}}function bj($,Z){let J=$.currentTurn;if(!J){j(`session "${$.sessionName}": can_use_tool with no current turn — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no active turn"});return}let Q=Z.tool_use_id;if(!Q){j(`session "${$.sessionName}": can_use_tool without tool_use_id — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no tool_use_id"});return}let Y=J.toolByUseId.get(Q);if(!Y){j(`session "${$.sessionName}": can_use_tool for unknown tool_use_id=${Q} — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"unknown tool_use_id"});return}if(Y.name==="AskUserQuestion"){let X=$.pendingAsks.get(Q);if(!X){j(`session "${$.sessionName}": AskUserQuestion ${Q} missing pendingAsk — deny`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no pending ask"});return}if(X.requestId=Z.request_id,$.pendingPermissions.set(Z.request_id,{toolUseId:Q}),X.currentIdx===void 0)jV($,Q);return}$.status="awaiting_permission",$.pendingPermissions.set(Z.request_id,{toolUseId:Q,permissionSuggestions:Z.permission_suggestions}),j(`session "${$.sessionName}": can_use_tool request=${Z.request_id} tool_use_id=${Q} tool=${Y.name}`);let V=OY(Y.i,Y.name,Y.displayInput??Y.input,Z.request_id);if(R0(J.cardId,C.tool(Y.i),V),J.userOpenId&&J.messageId){let X=n1(Y.name,Y.displayInput??Y.input),z=n2(Y.name),H=X&&X.length>30?X.slice(0,30)+"…":X,G=H?`\uD83D\uDD10 等审批: ${z} · ${H}`:`\uD83D\uDD10 等审批: ${z}`;(async()=>{e0(J.cardId),await o7(J.cardId,{config:{summary:{content:G}}}),await w2(J.messageId,[J.userOpenId])})()}}var kj=R(()=>{U1();S$();Y0();I();o6()});function JT($){let Z=!1,J=()=>{},Q=()=>{},Y=$.sessionId,V=()=>{$.off("context_compacted",H),$.off("exit",G),$.off("error",W)},X=(B)=>{if(Z)return;Z=!0,V(),J(B)},z=(B)=>{if(Z)return;Z=!0,V(),Q(B)},H=(B)=>{if(B.phase==="start")return;if(B.threadId&&Y&&B.threadId!==Y)return;X(B)},G=()=>z(Error(`${$.provider} process exited before context compaction completed`)),W=(B)=>z(B instanceof Error?B:Error(String(B))),K=new Promise((B,_)=>{J=B,Q=_});return $.on("context_compacted",H),$.once("exit",G),$.once("error",W),{promise:K,cancel(){if(Z)return;Z=!0,V()}}}function QT($,Z){let J=[],Q=new Set,Y=(z,H)=>{let G=H.threadId??Z;if(G&&z.threadId&&z.threadId!==G)return!1;if(H.turnId)return z.turnId===H.turnId;return!0},V=(z)=>{for(let H=J.length-1;H>=0;H--){let G=J[H];if(G&&Y(G,z))return G}return null},X=(z)=>{if(Z&&z.threadId&&z.threadId!==Z)return;let H={usage:z.usage,contextWindow:z.contextWindow,threadId:z.threadId,turnId:z.turnId};J.push(H);for(let G of[...Q])if(Y(H,G.notice))G.finish(H)};return $.on("token_usage",X),{waitFor(z,H){let G=V(z);if(G)return Promise.resolve(G);return new Promise((W)=>{let K=null,B={notice:z,finish:(_)=>{if(K)clearTimeout(K);Q.delete(B),W(_)}};K=setTimeout(()=>B.finish(null),H),Q.add(B)})},cancel(){$.off("token_usage",X);for(let z of[...Q])z.finish(null)}}}function YT($){if(!$)return" · \uD83E\uDDE0 MISS";let Z=K6($.usage);if(Z==null)return" · \uD83E\uDDE0 MISS";let J=B6($.contextWindow);return` · \uD83E\uDDE0 ${vK(Z,J)} (${j6(Z,J)})`}async function wj($){$.clearStaleIdleQueueState("compact");let Z=!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0&&!$.openingTurn;if(!$.isRunning()||!$.proc){$.status="stopped",$.opts.onLifecycleChange?.();let G=await $.openStatusCard("compact","⚪ session 当前未运行","grey");if(G)await $.closeStatusCard(G,"⚪ 后端未运行,compact 无效");else await k($.chatId,`⚪ session "${$.sessionName}" 当前未运行,compact 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return}if(!Z){let G=await $.openStatusCard("compact","⚠️ 当前 turn 正在执行","grey");if(G)await $.closeStatusCard(G,"⚠️ 先 stop 当前 turn,再 compact");else await k($.chatId,"⚠️ 当前 turn 正在执行,先 `stop` 后再 `compact`。");return}if($.manualContextCompactionPending){let G=await $.openStatusCard("compact","⏳ 上下文压缩已在进行中","grey");if(G)await $.closeStatusCard(G,"⏳ 上下文压缩已在进行中");else await k($.chatId,"⏳ 上下文压缩已在进行中。");return}let J=$.proc,Q=J.sessionId?h0(J.sessionId):"",Y=$.withModel(Q?`\uD83E\uDDE0 压缩上下文 thread=${Q}`:"\uD83E\uDDE0 压缩上下文…"),V=await $.openStatusCard("compact",Y,"orange"),X=async(G)=>{if(V)await $.closeStatusCard(V,G);else await k($.chatId,G)},z=JT(J),H=QT(J,J.sessionId);$.manualContextCompactionPending=!0;try{$.setStatusCard(V,$.withModel("\uD83E\uDDE0 发起上下文压缩")),await J.compactThread(),$.setStatusCard(V,$.withModel("⏳ 等待压缩完成事件"));let G=await z.promise,W=await H.waitFor(G,ZT),K=G.threadId?` thread=${h0(G.threadId)}`:"";await X($.withModel(`✅ 上下文已压缩${K}${YT(W)}`))}catch(G){if(z.cancel(),G instanceof A2)await X($.withModel(`ⓘ ${G.message}`));else await X(`❌ 上下文压缩失败: ${E(G)}`)}finally{H.cancel(),$.manualContextCompactionPending=!1}}var ZT=1500;var vj=R(()=>{P0();Y0()});import{randomUUID as XT}from"node:crypto";function fj($,Z){return{ok:!1,message:Z,card:v6($.sessionName,!1,Z)}}async function qV($,Z,J){if(Z.cancelled||$.modelSettingsChange!==Z||$.proc!==Z.proc||!Z.proc.isAlive())return fj($,`本次模型切换未保存:${Z.cancelled??"原进程已退出或更换"}${J.ok?"":`;${E(J.error)}`}`);Z.confirmedModel=J.ok||J.error instanceof b4&&J.error.confirmedModel!==null?Z.model:null,Z.confirmedEffort=J.ok?Z.effort:null;let Q=J.ok?null:E(J.error);if(J.ok)try{if($.modelSelectionNeedsProcessStop(Z.provider,Z.sourceId??$.selectedTokenSourceId,Z.model,Z.effort))throw Error("等待期间进程账号配置已变化,请 stop 后重新选择");await $.applyModelSelectionUnlocked(Z.provider,Z.model,Z.effort,Z.sourceId)}catch(Y){Q=`模型和思考档位已应用,但保存选择失败:${E(Y)}`}if(Q!==null)return Z.phase="failed",Z.error=`${Q}。本次完整设置未保存,后续输入暂停;请重新发送 md 完成选择,或 restart 恢复已保存的设置。`,j(`session "${$.sessionName}": model settings incomplete: ${Z.error}`),fj($,Z.error);return $.modelSettingsChange=null,$.modelPanels.delete(Z.panelId),$.resumeInputAfterModelSettingsChange(),{ok:!0,message:`已选择 ${t0(Z.provider)} · ${Z.model} / ${Z.effort}`,card:u8({sessionName:$.sessionName,provider:Z.provider,model:Z.model,effort:Z.effort,scope:MV($,Z.provider)})}}async function zT($,Z,J,Q,Y,V,X){let z,H=new Promise((P)=>{z=P}),G={proc:Z,provider:Z.provider,model:J,effort:Y,sourceId:X,panelId:V,phase:"pending",confirmedModel:null,confirmedEffort:null,cancel(P){G.cancelled=P,z({ok:!1,error:Error(P)})}};$.modelSettingsChange=G;let W=Promise.resolve().then(()=>Z.setModelSettings(Q,Y)).then(()=>({ok:!0}),(P)=>({ok:!1,error:P})),K=Promise.race([W,H]),B=Symbol("model-settings-pending"),_;try{let P=await Promise.race([K,new Promise((q)=>{_=setTimeout(()=>q(B),20000)})]);if(P!==B)return await qV($,G,P);let L=`正在等待 ${t0(Z.provider)} 确认 ${J} / ${Y},尚不能判断切换结果。确认后会更新本卡;仍可回答 Agent 提问或用 stop 打断任务,取消本次切换请发 kill 或 restart。`;return{ok:!1,pending:!0,message:L,card:v6($.sessionName,!0,L),completion:K.then((q)=>$.finishModelSettingsChange(G,q))}}finally{clearTimeout(_)}}function HT($){let Z=$.currentTokenSource();return s0().map((J)=>$.tokenSource(J.id)).filter((J)=>J.enabled||J.kind!=="claude-native").map((J)=>({provider:J.agent,sourceId:J.id,display:J.display,enabled:J.enabled,modelCount:J.models.length,catalogStatus:J.modelCatalogState?.status,catalogError:J.modelCatalogState?.error,selected:Z?.id===J.id}))}function DV($,Z,J=Z.models){let Q=$.currentModelLabel(),Y=$.currentEffortLabel(),V=$.currentTokenSource()?.id===Z.id;return J.map((X)=>{let z=V&&Q===X.model;return{provider:Z.agent,sourceId:Z.id,model:X.model,displayName:X.display,description:X.unavailableReason??(X.efforts.length?"":"effort MISS:上游未声明该后端支持的推理档位"),unavailableReason:X.unavailableReason,origin:X.origin,enabled:!0,isDefault:!1,selected:z,efforts:X.efforts.map((H)=>({effort:H,description:H==="default"?"模型未提供 effort 档位,使用模型原生行为。":"",isDefault:H===X.defaultEffort,selected:z&&Y===H}))}})}async function yj($){let Z=XT(),J=HT($);$.modelPanels.set(Z,{models:[]});let Q,Y=await o($.chatId,EY({sessionName:$.sessionName,panelId:Z,currentDisplay:$.currentTokenSource()?.display??$.currentModelLabel(),providers:J}),(V)=>{Q=V});if(!Y)$.modelPanels.delete(Z),await h($.chatId,`❌ 模型面板发送失败:${w(Q)}`);else{let V=$.modelPanels.get(Z);if(V)V.messageId=Y}}async function FV($,Z,J=""){let Q=Z.trim(),Y=$.tokenSource(Q);if(!Y)return{ok:!1,message:`未知账号: ${Q}`};if(!Y.enabled)return{ok:!1,message:Y.modelCatalogState?.error??`${Y.display} 未配置,请先点「启用」`};let V=J.trim();if(!$.modelPanels.has(V))return{ok:!1,message:"模型面板已失效,请重新发送 model"};if(Y.modelCatalogState?.status==="failed")return{ok:!1,message:`模型目录 MISS:${Y.modelCatalogState.error??"刷新失败"}`};if(Y.modelCatalogState?.status==="idle"||Y.modelCatalogState?.status==="loading")return{ok:!1,message:"模型目录缓存尚未就绪,后台刷新中"};let X=DV($,Y),z=$.modelPanels.get(V)?.messageId;return $.modelPanels.set(V,{models:[],catalog:X,sourceId:Q,messageId:z,mode:"select",editable:!!Y.modelSelection,sourceRevision:Y.spawnRevision}),r6($,V,Q,0)}async function r6($,Z,J,Q){let Y=$.modelPanels.get(Z);if(!Y?.catalog||Y.sourceId!==J)return{ok:!1,message:"模型面板已失效,请重新发送 model"};let V=Math.max(1,Math.ceil(Y.catalog.length/LV));if(!Number.isInteger(Q)||Q<0||Q>=V)return{ok:!1,message:"模型页码无效"};return Y.models=Y.catalog.slice(Q*LV,(Q+1)*LV),Y.page=Q,Y.totalPages=V,{ok:!0,message:"",card:SY({sessionName:$.sessionName,panelId:Z,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),models:Y.models,sourceId:J,editable:Y.editable,allowCustom:!0,mode:Y.mode,...V>1?{pagination:{sourceId:J,page:Q,totalPages:V}}:{}})}}async function hj($,Z,J){let Q=$.modelPanels.get(Z),Y=$.tokenSource(J);if(!Q||Q.sourceId!==J||!Y?.enabled||!Y.modelSelection)return{ok:!1,message:"模型管理面板已失效,请重新发送 md"};if(Y.modelCatalogState?.status!=="ready")return{ok:!1,message:Y.modelCatalogState?.error??"目录未就绪"};let V=Y.modelSelection.availableModels.filter((X)=>X.origin!=="custom"&&!Y.modelSelection.modelIds.includes(X.model)&&(Y.modelSelection.mode==="catalog"||!X.unavailableReason&&X.efforts.length>0));return $.modelPanels.set(Z,{models:[],catalog:DV($,Y,V),sourceId:J,messageId:Q.messageId,mode:"add",editable:!0,sourceRevision:Y.spawnRevision}),r6($,Z,J,0)}async function Ij($,Z,J,Q,Y){let V=$.modelPanels.get(Z),X=$.tokenSource(J);if(!V?.editable||V.sourceId!==J||!X?.modelSelection||V.sourceRevision!==X.spawnRevision||V.mode!==(Y==="add"?"add":"select")||!V.models.some((z)=>z.model===Q))return{ok:!1,message:"模型管理选项已失效,请重新发送 md"};if(Y==="delete"){let z=[...g$.all].filter((H)=>H.currentTokenSource()?.id===J&&H.currentModelLabel()===Q.replace(/\[1m\]$/,""));if(z.length)return{ok:!1,message:`补录模型仍被会话 ${z.map((H)=>H.sessionName).join("、")} 选用,请先切换再删除`}}try{if(Y==="delete")await HK(J,Q,$.codexAccountId());else await XK(J,Q,Y,$.codexAccountId());for(let H of g$.all)for(let[G,W]of H.modelPanels)if(W.sourceId===J&&(H!==$||G!==Z))H.modelPanels.delete(G);return{...await FV($,J,Z),message:Y==="add"?"模型已显示":Y==="delete"?"补录模型已删除":"模型已隐藏"}}catch(z){return{ok:!1,message:`模型列表更新失败:${E(z)}`}}}async function gj($,Z,J,Q=""){let Y=$.tokenSource(Z.trim());if(!Y)return{ok:!1,message:`未知账号: ${Z}`};if(!Y.enabled)return{ok:!1,message:`${Y.display} 未配置`};let V=J.trim();if(!V)return{ok:!1,message:"补录面板缺少 panel_id,请重新发送 model"};return $.modelCustomPrompt={sourceId:Y.id,panelId:V,cardMessageId:Q},{ok:!0,message:"等待模型名",card:xY($.sessionName,Y.display,V)}}async function mj($,Z,J){let Q=$.modelCustomPrompt;if(!Q)return!1;$.modelCustomPrompt=null;let Y=Z.trim(),V=$.tokenSource(Q.sourceId),X=[],z=async(_)=>{if(!Q.cardMessageId)return!1;let P="",L=!1,q=!1;try{P=await e$(Q.cardMessageId),h$(P,1);let D;if(L=await D0(P,C.modelPanel,_,{notifyCardFailure:!1,onFailure:(U)=>{D=U}}),!L)throw Error(`model panel replace rejected: ${w(D)}`);let M;if(q=await m0(P,{config:{streaming_mode:!1}},(U)=>{M=U}),!q)throw Error(`model panel streaming-off rejected: ${w(M)}`)}catch(D){j(`model-custom: card update MISS (${D?.message??D})`),X.push(E(D))}finally{if(P){if(!q)try{let D;if(q=await m0(P,{config:{streaming_mode:!1}},(M)=>{D=M}),!q)X.push(`model panel streaming-off rejected: ${w(D)}`)}catch(D){j(`model-custom: streaming-off retry MISS (${D?.message??D})`),X.push(w(D))}if(L&&q)try{await N$(P)}catch(D){j(`model-custom: card dispose MISS (${D?.message??D})`)}else j(`model-custom: retain card state after checked MISS mutation=${L} streamingOff=${q} card=${P.slice(0,12)}`)}}return L&&q},H=async(_,P)=>{if(await z(_))return!0;let q=[...new Set(X)].join(`
293
- `),D=`⚠️ 模型补录结果未能写回原卡。${P}${q?`
292
+ `)}`)});z.add(G),G.finally(()=>{if(z.delete(G),!z.size)X.delete(Y)}).catch((W)=>j(`generated image failure notice failed: ${W}`))}async function _V($,Z){let J=Z?[...$.imageDeliveryInflight?.get(Z)??[]]:[...$.imageDeliveryInflight?.values()??[]].flatMap((Q)=>[...Q]);await Promise.allSettled(J)}function rR($,Z,J,Q,Y){if(!$.currentTurn)return;if(!Y)$.taskBoard=J==="TaskCreate"?u6($.taskBoard,J,Z.input,Q,Z.displayInput):u6($.taskBoard,J,Z.displayInput??Z.input,Z.displayOutput??Q);let V=e1(Z.i,$.taskBoard,{name:J,status:Y?"❌":"✅"},Z.resolvedNote);if(R0($.currentTurn.cardId,C.tool(Z.i),V),$.currentTurn.taskLiveInserted)F0($.currentTurn.cardId,C.taskBoardLive,t2($.taskBoard),{notifyCardFailure:!1});$4($)}function $4($){let Z=$.currentTurn;if(!Z||$.hasPendingAgentTool())return;for(let J of Z.toolByUseId.values())if(J.output==null)return;$.startThinkingFooter(Z)}function PV($,Z,J,Q,Y,V=$.currentTurn){let X=V;if(!X)return;for(let[z,H]of Q){if(X.toolByUseId.has(z))continue;let G=H.batchSlot??null,W=H.input,K=H.displayInput,B=H.displayOutput,_,P;if(G!=null){let A=Y.get(H.i)?.items[G];if(!A)continue;W=A.input,K=A.displayInput,B=A.displayOutput,_=A.output,P=A.isError}else _=H.output??null,P=H.isError??!1;let L=_!=null,q=e4(Z,C.tool(H.i));if(L&&!q)continue;if(G!=null){let A=Y.get(H.i)?.kind;if(!A)continue;let O=X.toolCount++,N={toolUseId:z,input:W,displayInput:K,output:_,displayOutput:B,isError:P};X.toolBatches.set(O,{kind:A,items:[N]}),X.toolByUseId.set(z,{...H,i:O,batchSlot:0}),v0(J,t6(A,O,[N]),{type:"insert_before",targetElementId:p0(X)});continue}let F=s2(H.name);if(F){let A=F==="TaskCreate";if(A)X.taskUpdateI=null;else X.taskCreateI=null;let O=(A?X.taskCreateI:X.taskUpdateI)===null;if(O)if(A)X.taskCreateI=X.toolCount++;else X.taskUpdateI=X.toolCount++;let N=A?X.taskCreateI:X.taskUpdateI;X.toolByUseId.set(z,{...H,i:N});let S=!L?"⏳":P?"❌":"✅",T=e1(N,$.taskBoard,{name:F,status:S},H.resolvedNote);O?v0(J,T,{type:"insert_before",targetElementId:p0(X)}):R0(J,C.tool(N),T);continue}let M=X.toolCount++;X.toolByUseId.set(z,{...H,i:M});let U=!L?"⏳":P?"❌":"✅";v0(J,Y1(M,H.name,K??W,B??_,U,H.resolvedNote,H.imageKey),{type:"insert_before",targetElementId:p0(X)})}}var Cj=R(()=>{$V();U1();S$();Y0();I();o6()});async function xj($,Z,J,Q){let Y=$.pendingPermissions.get(Z);if(!Y)return j(`session "${$.sessionName}": stray permission ${Z}`),{ok:!1,message:"此权限请求已失效或已处理"};let V=$.proc;if(!V)return j(`session "${$.sessionName}": permission ${Z} has no active process`),{ok:!1,message:"后端进程已退出,权限决定未送达"};let X=J==="deny"?"deny":"allow";try{V.sendPermissionResponse(Z,X,J==="allow_always"?{updatedPermissions:Y.permissionSuggestions}:void 0)}catch(G){return j(`session "${$.sessionName}": permission response ${Z} failed: ${G}`),{ok:!1,message:`权限决定发送失败: ${G instanceof Error?G.message:G}`}}$.pendingPermissions.delete(Z);let z=$.currentTurn,H=z?.toolByUseId.get(Y.toolUseId);if(z&&H){let G=s2(H.name);if(J==="deny"){let W=`\uD83D\uDEAB 已拒绝 by ${Q||"匿名"}`,K=G?e1(H.i,$.taskBoard,{name:G,status:"❌"},W):Y1(H.i,H.name,H.displayInput??H.input,W,"❌");R0(z.cardId,C.tool(H.i),K)}else{let W=J==="allow_always"?"始终允许":"已允许";H.resolvedNote=`✅ **${W}** by ${Q||"匿名"}`;let K=G?e1(H.i,$.taskBoard,{name:G,status:"⏳"},H.resolvedNote):Y1(H.i,H.name,H.displayInput??H.input,null,"⏳",H.resolvedNote);R0(z.cardId,C.tool(H.i),K)}}if(j(`session "${$.sessionName}": permission decision request=${Z} tool_use_id=${Y.toolUseId} decision=${J}`),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working";return{ok:!0,message:J==="deny"?"已拒绝":J==="allow_always"?"已始终允许":"已允许"}}function bj($,Z){let J=$.currentTurn;if(!J){j(`session "${$.sessionName}": can_use_tool with no current turn — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no active turn"});return}let Q=Z.tool_use_id;if(!Q){j(`session "${$.sessionName}": can_use_tool without tool_use_id — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no tool_use_id"});return}let Y=J.toolByUseId.get(Q);if(!Y){j(`session "${$.sessionName}": can_use_tool for unknown tool_use_id=${Q} — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"unknown tool_use_id"});return}if(Y.name==="AskUserQuestion"){let X=$.pendingAsks.get(Q);if(!X){j(`session "${$.sessionName}": AskUserQuestion ${Q} missing pendingAsk — deny`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no pending ask"});return}if(X.requestId=Z.request_id,$.pendingPermissions.set(Z.request_id,{toolUseId:Q}),X.currentIdx===void 0)jV($,Q);return}$.status="awaiting_permission",$.pendingPermissions.set(Z.request_id,{toolUseId:Q,permissionSuggestions:Z.permission_suggestions}),j(`session "${$.sessionName}": can_use_tool request=${Z.request_id} tool_use_id=${Q} tool=${Y.name}`);let V=OY(Y.i,Y.name,Y.displayInput??Y.input,Z.request_id);if(R0(J.cardId,C.tool(Y.i),V),J.userOpenId&&J.messageId){let X=n1(Y.name,Y.displayInput??Y.input),z=n2(Y.name),H=X&&X.length>30?X.slice(0,30)+"…":X,G=H?`\uD83D\uDD10 等审批: ${z} · ${H}`:`\uD83D\uDD10 等审批: ${z}`;(async()=>{e0(J.cardId),await o7(J.cardId,{config:{summary:{content:G}}}),await w2(J.messageId,[J.userOpenId])})()}}var kj=R(()=>{U1();S$();Y0();I();o6()});function JT($){let Z=!1,J=()=>{},Q=()=>{},Y=$.sessionId,V=()=>{$.off("context_compacted",H),$.off("exit",G),$.off("error",W)},X=(B)=>{if(Z)return;Z=!0,V(),J(B)},z=(B)=>{if(Z)return;Z=!0,V(),Q(B)},H=(B)=>{if(B.phase==="start")return;if(B.threadId&&Y&&B.threadId!==Y)return;X(B)},G=()=>z(Error(`${$.provider} process exited before context compaction completed`)),W=(B)=>z(B instanceof Error?B:Error(String(B))),K=new Promise((B,_)=>{J=B,Q=_});return $.on("context_compacted",H),$.once("exit",G),$.once("error",W),{promise:K,cancel(){if(Z)return;Z=!0,V()}}}function QT($,Z){let J=[],Q=new Set,Y=(z,H)=>{let G=H.threadId??Z;if(G&&z.threadId&&z.threadId!==G)return!1;if(H.turnId)return z.turnId===H.turnId;return!0},V=(z)=>{for(let H=J.length-1;H>=0;H--){let G=J[H];if(G&&Y(G,z))return G}return null},X=(z)=>{if(Z&&z.threadId&&z.threadId!==Z)return;let H={usage:z.usage,contextWindow:z.contextWindow,threadId:z.threadId,turnId:z.turnId};J.push(H);for(let G of[...Q])if(Y(H,G.notice))G.finish(H)};return $.on("token_usage",X),{waitFor(z,H){let G=V(z);if(G)return Promise.resolve(G);return new Promise((W)=>{let K=null,B={notice:z,finish:(_)=>{if(K)clearTimeout(K);Q.delete(B),W(_)}};K=setTimeout(()=>B.finish(null),H),Q.add(B)})},cancel(){$.off("token_usage",X);for(let z of[...Q])z.finish(null)}}}function YT($){if(!$)return" · \uD83E\uDDE0 MISS";let Z=K6($.usage);if(Z==null)return" · \uD83E\uDDE0 MISS";let J=B6($.contextWindow);return` · \uD83E\uDDE0 ${vK(Z,J)} (${j6(Z,J)})`}async function wj($){$.clearStaleIdleQueueState("compact");let Z=!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0&&!$.openingTurn;if(!$.isRunning()||!$.proc){$.status="stopped",$.opts.onLifecycleChange?.();let G=await $.openStatusCard("compact","⚪ session 当前未运行","grey");if(G)await $.closeStatusCard(G,"⚪ 后端未运行,compact 无效");else await k($.chatId,`⚪ session "${$.sessionName}" 当前未运行,compact 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return}if(!Z){let G=await $.openStatusCard("compact","⚠️ 当前 turn 正在执行","grey");if(G)await $.closeStatusCard(G,"⚠️ 先 stop 当前 turn,再 compact");else await k($.chatId,"⚠️ 当前 turn 正在执行,先 `stop` 后再 `compact`。");return}if($.manualContextCompactionPending){let G=await $.openStatusCard("compact","⏳ 上下文压缩已在进行中","grey");if(G)await $.closeStatusCard(G,"⏳ 上下文压缩已在进行中");else await k($.chatId,"⏳ 上下文压缩已在进行中。");return}let J=$.proc,Q=J.sessionId?h0(J.sessionId):"",Y=$.withModel(Q?`\uD83E\uDDE0 压缩上下文 thread=${Q}`:"\uD83E\uDDE0 压缩上下文…"),V=await $.openStatusCard("compact",Y,"orange"),X=async(G)=>{if(V)await $.closeStatusCard(V,G);else await k($.chatId,G)},z=JT(J),H=QT(J,J.sessionId);$.manualContextCompactionPending=!0;try{$.setStatusCard(V,$.withModel("\uD83E\uDDE0 发起上下文压缩")),await J.compactThread(),$.setStatusCard(V,$.withModel("⏳ 等待压缩完成事件"));let G=await z.promise,W=await H.waitFor(G,ZT),K=G.threadId?` thread=${h0(G.threadId)}`:"";await X($.withModel(`✅ 上下文已压缩${K}${YT(W)}`))}catch(G){if(z.cancel(),G instanceof A2)await X($.withModel(`ⓘ ${G.message}`));else await X(`❌ 上下文压缩失败: ${E(G)}`)}finally{H.cancel(),$.manualContextCompactionPending=!1}}var ZT=1500;var vj=R(()=>{P0();Y0()});import{randomUUID as XT}from"node:crypto";function yj($,Z){return{ok:!1,message:Z,card:v6($.sessionName,!1,Z)}}async function qV($,Z,J){if(Z.cancelled||$.modelSettingsChange!==Z||$.proc!==Z.proc||!Z.proc.isAlive())return yj($,`本次模型切换未保存:${Z.cancelled??"原进程已退出或更换"}${J.ok?"":`;${E(J.error)}`}`);Z.confirmedModel=J.ok||J.error instanceof b4&&J.error.confirmedModel!==null?Z.model:null,Z.confirmedEffort=J.ok?Z.effort:null;let Q=J.ok?null:E(J.error);if(J.ok)try{if($.modelSelectionNeedsProcessStop(Z.provider,Z.sourceId??$.selectedTokenSourceId,Z.model,Z.effort))throw Error("等待期间进程账号配置已变化,请 stop 后重新选择");await $.applyModelSelectionUnlocked(Z.provider,Z.model,Z.effort,Z.sourceId)}catch(Y){Q=`模型和思考档位已应用,但保存选择失败:${E(Y)}`}if(Q!==null)return Z.phase="failed",Z.error=`${Q}。本次完整设置未保存,后续输入暂停;请重新发送 md 完成选择,或 restart 恢复已保存的设置。`,j(`session "${$.sessionName}": model settings incomplete: ${Z.error}`),yj($,Z.error);return $.modelSettingsChange=null,$.modelPanels.delete(Z.panelId),$.resumeInputAfterModelSettingsChange(),{ok:!0,message:`已选择 ${t0(Z.provider)} · ${Z.model} / ${Z.effort}`,card:u8({sessionName:$.sessionName,provider:Z.provider,model:Z.model,effort:Z.effort,scope:MV($,Z.provider)})}}async function zT($,Z,J,Q,Y,V,X){let z,H=new Promise((P)=>{z=P}),G={proc:Z,provider:Z.provider,model:J,effort:Y,sourceId:X,panelId:V,phase:"pending",confirmedModel:null,confirmedEffort:null,cancel(P){G.cancelled=P,z({ok:!1,error:Error(P)})}};$.modelSettingsChange=G;let W=Promise.resolve().then(()=>Z.setModelSettings(Q,Y)).then(()=>({ok:!0}),(P)=>({ok:!1,error:P})),K=Promise.race([W,H]),B=Symbol("model-settings-pending"),_;try{let P=await Promise.race([K,new Promise((q)=>{_=setTimeout(()=>q(B),20000)})]);if(P!==B)return await qV($,G,P);let L=`正在等待 ${t0(Z.provider)} 确认 ${J} / ${Y},尚不能判断切换结果。确认后会更新本卡;仍可回答 Agent 提问或用 stop 打断任务,取消本次切换请发 kill 或 restart。`;return{ok:!1,pending:!0,message:L,card:v6($.sessionName,!0,L),completion:K.then((q)=>$.finishModelSettingsChange(G,q))}}finally{clearTimeout(_)}}function HT($){let Z=$.currentTokenSource();return s0().map((J)=>$.tokenSource(J.id)).filter((J)=>J.enabled||J.kind!=="claude-native").map((J)=>({provider:J.agent,sourceId:J.id,display:J.display,enabled:J.enabled,modelCount:J.models.length,catalogStatus:J.modelCatalogState?.status,catalogError:J.modelCatalogState?.error,selected:Z?.id===J.id}))}function FV($,Z,J=Z.models){let Q=$.currentModelLabel(),Y=$.currentEffortLabel(),V=$.currentTokenSource()?.id===Z.id;return J.map((X)=>{let z=V&&Q===X.model;return{provider:Z.agent,sourceId:Z.id,model:X.model,displayName:X.display,description:X.unavailableReason??(X.efforts.length?"":"effort MISS:上游未声明该后端支持的推理档位"),unavailableReason:X.unavailableReason,origin:X.origin,enabled:!0,isDefault:!1,selected:z,efforts:X.efforts.map((H)=>({effort:H,description:H==="default"?"模型未提供 effort 档位,使用模型原生行为。":"",isDefault:H===X.defaultEffort,selected:z&&Y===H}))}})}async function fj($){let Z=XT(),J=HT($);$.modelPanels.set(Z,{models:[]});let Q,Y=await o($.chatId,EY({sessionName:$.sessionName,panelId:Z,currentDisplay:$.currentTokenSource()?.display??$.currentModelLabel(),providers:J}),(V)=>{Q=V});if(!Y)$.modelPanels.delete(Z),await h($.chatId,`❌ 模型面板发送失败:${w(Q)}`);else{let V=$.modelPanels.get(Z);if(V)V.messageId=Y}}async function DV($,Z,J=""){let Q=Z.trim(),Y=$.tokenSource(Q);if(!Y)return{ok:!1,message:`未知账号: ${Q}`};if(!Y.enabled)return{ok:!1,message:Y.modelCatalogState?.error??`${Y.display} 未配置,请先点「启用」`};let V=J.trim();if(!$.modelPanels.has(V))return{ok:!1,message:"模型面板已失效,请重新发送 model"};if(Y.modelCatalogState?.status==="failed")return{ok:!1,message:`模型目录 MISS:${Y.modelCatalogState.error??"刷新失败"}`};if(Y.modelCatalogState?.status==="idle"||Y.modelCatalogState?.status==="loading")return{ok:!1,message:"模型目录缓存尚未就绪,后台刷新中"};let X=FV($,Y),z=$.modelPanels.get(V)?.messageId;return $.modelPanels.set(V,{models:[],catalog:X,sourceId:Q,messageId:z,mode:"select",editable:!!Y.modelSelection,sourceRevision:Y.spawnRevision}),r6($,V,Q,0)}async function r6($,Z,J,Q){let Y=$.modelPanels.get(Z);if(!Y?.catalog||Y.sourceId!==J)return{ok:!1,message:"模型面板已失效,请重新发送 model"};let V=Math.max(1,Math.ceil(Y.catalog.length/LV));if(!Number.isInteger(Q)||Q<0||Q>=V)return{ok:!1,message:"模型页码无效"};return Y.models=Y.catalog.slice(Q*LV,(Q+1)*LV),Y.page=Q,Y.totalPages=V,{ok:!0,message:"",card:SY({sessionName:$.sessionName,panelId:Z,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),models:Y.models,sourceId:J,editable:Y.editable,allowCustom:!0,mode:Y.mode,...V>1?{pagination:{sourceId:J,page:Q,totalPages:V}}:{}})}}async function hj($,Z,J){let Q=$.modelPanels.get(Z),Y=$.tokenSource(J);if(!Q||Q.sourceId!==J||!Y?.enabled||!Y.modelSelection)return{ok:!1,message:"模型管理面板已失效,请重新发送 md"};if(Y.modelCatalogState?.status!=="ready")return{ok:!1,message:Y.modelCatalogState?.error??"目录未就绪"};let V=Y.modelSelection.availableModels.filter((X)=>X.origin!=="custom"&&!Y.modelSelection.modelIds.includes(X.model)&&(Y.modelSelection.mode==="catalog"||!X.unavailableReason&&X.efforts.length>0));return $.modelPanels.set(Z,{models:[],catalog:FV($,Y,V),sourceId:J,messageId:Q.messageId,mode:"add",editable:!0,sourceRevision:Y.spawnRevision}),r6($,Z,J,0)}async function Ij($,Z,J,Q,Y){let V=$.modelPanels.get(Z),X=$.tokenSource(J);if(!V?.editable||V.sourceId!==J||!X?.modelSelection||V.sourceRevision!==X.spawnRevision||V.mode!==(Y==="add"?"add":"select")||!V.models.some((z)=>z.model===Q))return{ok:!1,message:"模型管理选项已失效,请重新发送 md"};if(Y==="delete"){let z=[...g$.all].filter((H)=>H.currentTokenSource()?.id===J&&H.currentModelLabel()===Q.replace(/\[1m\]$/,""));if(z.length)return{ok:!1,message:`补录模型仍被会话 ${z.map((H)=>H.sessionName).join("、")} 选用,请先切换再删除`}}try{if(Y==="delete")await HK(J,Q,$.codexAccountId());else await XK(J,Q,Y,$.codexAccountId());for(let H of g$.all)for(let[G,W]of H.modelPanels)if(W.sourceId===J&&(H!==$||G!==Z))H.modelPanels.delete(G);return{...await DV($,J,Z),message:Y==="add"?"模型已显示":Y==="delete"?"补录模型已删除":"模型已隐藏"}}catch(z){return{ok:!1,message:`模型列表更新失败:${E(z)}`}}}async function gj($,Z,J,Q=""){let Y=$.tokenSource(Z.trim());if(!Y)return{ok:!1,message:`未知账号: ${Z}`};if(!Y.enabled)return{ok:!1,message:`${Y.display} 未配置`};let V=J.trim();if(!V)return{ok:!1,message:"补录面板缺少 panel_id,请重新发送 model"};return $.modelCustomPrompt={sourceId:Y.id,panelId:V,cardMessageId:Q},{ok:!0,message:"等待模型名",card:xY($.sessionName,Y.display,V)}}async function mj($,Z,J){let Q=$.modelCustomPrompt;if(!Q)return!1;$.modelCustomPrompt=null;let Y=Z.trim(),V=$.tokenSource(Q.sourceId),X=[],z=async(_)=>{if(!Q.cardMessageId)return!1;let P="",L=!1,q=!1;try{P=await e$(Q.cardMessageId),h$(P,1);let F;if(L=await F0(P,C.modelPanel,_,{notifyCardFailure:!1,onFailure:(U)=>{F=U}}),!L)throw Error(`model panel replace rejected: ${w(F)}`);let M;if(q=await m0(P,{config:{streaming_mode:!1}},(U)=>{M=U}),!q)throw Error(`model panel streaming-off rejected: ${w(M)}`)}catch(F){j(`model-custom: card update MISS (${F?.message??F})`),X.push(E(F))}finally{if(P){if(!q)try{let F;if(q=await m0(P,{config:{streaming_mode:!1}},(M)=>{F=M}),!q)X.push(`model panel streaming-off rejected: ${w(F)}`)}catch(F){j(`model-custom: streaming-off retry MISS (${F?.message??F})`),X.push(w(F))}if(L&&q)try{await N$(P)}catch(F){j(`model-custom: card dispose MISS (${F?.message??F})`)}else j(`model-custom: retain card state after checked MISS mutation=${L} streamingOff=${q} card=${P.slice(0,12)}`)}}return L&&q},H=async(_,P)=>{if(await z(_))return!0;let q=[...new Set(X)].join(`
293
+ `),F=`⚠️ 模型补录结果未能写回原卡。${P}${q?`
294
294
  ${q}`:""}
295
- 请重新发送 model 打开面板。`;if(!await h($.chatId,D))j(`model-custom: visible fallback send MISS (${P})`);return!1},G=(_)=>H(d8(!1,Y,_),`❌ ${Y?`模型 ${Y}`:"模型名"} 未加入:${_}。`);if(!V||!V.enabled)return await G("账号不可用"),!0;if(!Y)return await G("模型名为空"),!0;if(V.models.some((_)=>_.model.toLowerCase()===Y.toLowerCase()))return await H(d8(!1,Y,"已在列表中"),`ℹ️ 模型 ${Y} 已在列表中,未重复加入。`),!0;try{await zK(V.id,Y,$.codexAccountId())}catch(_){return j(`model-custom: config/refresh MISS (${E(_)})`),await G(`配置写入或模型刷新失败:${E(_)}`),!0}j(`model-custom: ${V.id} 补录 ${Y} by ${J}(记录已持久化)`);for(let _ of g$.all)for(let[P,L]of _.modelPanels)if(L.sourceId===V.id&&(_!==$||P!==Q.panelId))_.modelPanels.delete(P);let W=$.tokenSource(V.id);if(!W||W.modelCatalogState?.status!=="ready")return await G(W?.modelCatalogState?.error??"刷新后的账号目录不可用"),!0;let K=DV($,W),B=K.find((_)=>_.model===Y);if(!B)return await G("补录已保存,但刷新后的模型列表未返回该项"),!0;if($.modelPanels.set(Q.panelId,{models:K,messageId:Q.cardMessageId}),B.unavailableReason||!B.efforts.length)return await H(d8(!0,Y,`**MISS**:${B.unavailableReason??"后端未确认 effort"}。记录已保存,可在模型面板删除。`),`模型 ${Y} 已补录,能力尚未确认。`),!0;if(B.efforts.length===1){let _=await $.onModelEffortSelect(B.model,B.efforts[0].effort,Q.panelId,J,B.provider),P=(L)=>H(L.pending?l8(!0,L.message):L.ok?h6({sessionName:$.sessionName,provider:B.provider,model:B.model,effort:B.efforts[0].effort,scope:MV($,B.provider??"codex")}):l8(!1,L.message),L.message);if(await P(_),_.completion)_.completion.then(P).catch(async(L)=>{let q=`模型补录后的切换结果呈现失败:${E(L)}`;j(`model-custom: ${q}`),await h($.chatId,`❌ ${q}`)});return!0}return await H(y6({sessionName:$.sessionName,panelId:Q.panelId,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:B}),`✅ 模型 ${Y} 已补录成功。`),!0}async function pj($,Z=""){let J=Z.trim(),Q=$.modelCustomPrompt;if(!J||!Q||Q.panelId!==J)return{ok:!1,message:"此补录面板已失效",card:f6($.sessionName,"stale")};return $.modelCustomPrompt=null,{ok:!0,message:"已取消",card:f6($.sessionName)}}function GT($,Z){return a$(Z?.provider)?Z.provider:x4($)}function MV($,Z){if(Z==="codex"&&$.proc?.isAlive()&&$.proc.provider===Z)return"Codex 需重启进程生效(发 restart)。";if($.currentTurn)return"当前 turn 不变,后续新 turn 使用。";if($.proc?.isAlive()&&$.proc.provider===Z)return Z==="codex"?"Codex 需重启进程生效(发 restart)。":"下一轮开始使用。";return`下次启动 ${t0(Z)} 时使用。`}async function cj($,Z,J="",Q="",Y=null){let V=Z.trim();if(!V)return await k($.chatId,`❌ ${"模型为空"}`),{ok:!1,message:"模型为空"};let X=GT(V,Y),z=$.modelPanels.get(J.trim())?.models.find((H)=>H.model===V&&(H.provider??"codex")===X);if(!z)return{ok:!1,message:"模型不在当前选项中,请重新发送 model"};if($.modelPanels.get(J.trim())?.mode==="add")return{ok:!1,message:"请先将模型添加到可选列表"};if(z.unavailableReason)return{ok:!1,message:z.unavailableReason};if(z.enabled===!1)return{ok:!1,message:`${z.displayName} 未配置,请先点「启用」`};if(z.efforts.length===0)return{ok:!1,message:"模型未返回 effort"};if(z.efforts.length===1)return UV($,V,z.efforts[0].effort,J,Q,X);return{ok:!0,message:"",card:CY({sessionName:$.sessionName,panelId:J.trim(),currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:z})}}async function UV($,Z,J,Q="",Y="",V=""){if($.modelSettingsChangesClosed)return{ok:!1,message:"daemon 正在停止,本次模型选择未执行"};if($.modelSettingsChange?.proc===$.proc&&$.modelSettingsChange?.phase==="pending")return{ok:!1,message:"上一项模型设置仍在等待后端确认,本次选择未执行;请等待结果,取消切换请发 kill 或 restart。"};let X=Z.trim(),z=J.trim();if(!X)return{ok:!1,message:"模型为空"};let H=Q.trim(),G=$.modelPanels.get(H),W=a$(V)?V:G?.models.find((O)=>O.model===X)?.provider??x4(X);if(W==="dsh"){if(!S0(z))return{ok:!1,message:"DSH reasoning effort 无效"}}else if(W==="claude"){if(!w0(z))return{ok:!1,message:"Claude reasoning effort 无效"}}else if(!U$(z))return{ok:!1,message:"Codex reasoning effort 无效"};let K=z,B=G?.models.find((O)=>O.model===X&&(O.provider??"codex")===W);if(!B||!B.efforts.some((O)=>O.effort===K))return{ok:!1,message:`${t0(W)} · ${X}/${K} 不在选项中`};let _=$.tokenSource(B.sourceId);if(_?.modelCatalogState){if(!_.enabled||_.modelCatalogState.status!=="ready")return{ok:!1,message:`模型目录 MISS:${_.modelCatalogState.error??_.modelCatalogState.status}`};if(!_.models.some((O)=>O.model===X&&O.efforts.includes(K)))return{ok:!1,message:"模型或 effort 已不在账号目录中,请重新发送 model"}}let P=!!B.sourceId&&$.currentTokenSource()?.id!==B.sourceId,L=!$.processSourceMatches(_,X)||!!_?.modelEnvironmentRevision&&_.modelEnvironmentRevision($.currentModelLabel()??"")!==_.modelEnvironmentRevision(X),q=$.modelSelectionNeedsProcessStop(W,B.sourceId??$.selectedTokenSourceId,X,K);if($.currentProvider()===W&&!P&&$.currentModelLabel()===X&&$.currentEffortLabel()===K&&!$.modelSettingsChange&&!q&&!L)return $.modelPanels.delete(H),{ok:!0,message:`当前已是 ${t0(W)} · ${X} / ${K}`,card:u8({sessionName:$.sessionName,provider:W,model:X,effort:K,scope:"当前已是此设置,无需变更。"})};if($.proc?.isAlive()&&$.proc.provider!==W&&($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0))return{ok:!1,message:`当前 ${$.backendLabel($.proc.provider)} turn 正在执行或排队;请等结束或 stop 后再切换到 ${t0(W)}`};let U=$.currentModelLabel()!==X||P,A=!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0);if((L||q)&&$.proc?.isAlive()&&A)return{ok:!1,message:"新模型需要更新进程配置,请等当前任务结束后再选择"};if(W==="claude"&&$.proc?.isAlive()&&$.proc.provider==="claude"&&U&&A)return{ok:!1,message:"当前 Claude turn 正在执行或排队;Claude 模型 profile 通过 env 生效,请等结束或 stop 后再切换"};try{if($.proc?.isAlive()&&$.proc.provider===W&&!P&&!L&&!q){let N=B.sourceId?$.tokenSource(B.sourceId)?.resolveSpawnModel(X)??X:X;if(W==="codex")await $.proc.setModelSettings(N,K);else return await zT($,$.proc,X,N,K,H,B.sourceId)}await $.applyModelSelectionUnlocked(W,X,K,B.sourceId);let O=MV($,W);return $.modelPanels.delete(H),{ok:!0,message:`已选择 ${t0(W)} · ${X} / ${K}`,card:u8({sessionName:$.sessionName,provider:W,model:X,effort:K,scope:O})}}catch(O){let N=`模型切换失败: ${E(O)}`;return j(`session "${$.sessionName}": set model settings failed: ${E(O)}`),{ok:!1,message:N}}}var LV=20;var uj=R(()=>{P0();OV();X0();EQ();j1();P0();S$();U1();Y0();I()});import{createHash as KT}from"node:crypto";function BT($,Z){return`agent:${Buffer.from(`${$}\x00${Z}`,"utf8").toString("base64url")}`}function J3($="default"){return nj(ij($))}function dj($="default"){return jT(ij($))}function ij($){return s0().map((Z)=>Z.forAccount?.($)??Z)}async function jT($){let Z=nj($),Q=(await Promise.all($.filter((V)=>V.kind==="claude-subscription").map(async(V)=>{let X=Z.sourceFailures.find((H)=>H.tokenSourceId===V.id);if(X)return X;let z=await _T(V);return z===null?null:{tokenSourceId:V.id,display:V.display,status:"failed",reason:z}}))).filter((V)=>V!==null),Y=new Set(Q.map((V)=>V.tokenSourceId));return aj(Z.identities.filter((V)=>!Y.has(V.tokenSourceId)),[...Z.sourceFailures.filter((V)=>!Y.has(V.tokenSourceId)),...Q])}function _T($){return PT($)}async function PT($){let Z;try{let J=await $.readUsage();if(J.state==="ok")return null;Z=J.reason??`订阅可用性查询失败:${J.state}`}catch(J){Z=J instanceof Error?J.message:String(J)}return j(`agent identities ${$.id} MISS: ${Z}`),Z}function nj($){let Z=[],J=[];for(let Q of $)LT(Q,Z,J);return aj(Z,J)}function aj($,Z){return{catalogGeneration:KT("sha256").update(JSON.stringify({identities:$,sourceFailures:Z})).digest("hex").slice(0,16),identities:$,sourceFailures:Z}}function LT($,Z,J){let Q=$.modelCatalogState?.status??(!$.enabled?"disabled":$.models.length>0?"ready":"idle");if(!$.enabled)J.push({tokenSourceId:$.id,display:$.display,status:"disabled",reason:"账号未启用"});else if(Q==="loading"||Q==="idle")J.push({tokenSourceId:$.id,display:$.display,status:"loading",reason:"模型目录正在刷新"});else if(Q==="failed")J.push({tokenSourceId:$.id,display:$.display,status:"failed",reason:$.modelCatalogState?.error??"模型目录刷新失败"});else if($.models.length===0)J.push({tokenSourceId:$.id,display:$.display,status:"models_miss",reason:"模型目录为空"});for(let Y of $.models)Z.push(qT($,Y,Q))}function qT($,Z,J){let Q="ready",Y;if(!$.enabled)Q="source_disabled",Y="所属 Token Source 未启用";else if(J==="loading"||J==="idle")Q="catalog_loading",Y="模型目录正在刷新";else if(J==="failed")Q="catalog_failed",Y=$.modelCatalogState?.error??"模型目录刷新失败";else if(Z.unavailableReason||!Z.efforts.length)Q="model_unavailable",Y=Z.unavailableReason??"effort MISS:上游未声明该后端支持的推理档位";return{id:BT($.id,Z.model),displayName:`${$.display} · ${Z.display}`,tokenSourceId:$.id,tokenSourceDisplay:$.display,provider:$.agent,model:Z.model,modelDisplay:Z.display,defaultEffort:Z.defaultEffort,supportedEfforts:[...Z.efforts],sourceDefault:lj($.defaultModel)===lj(Z.model),status:Q,...Y?{reason:Y}:{},spawnRevision:$.spawnRevision}}function lj($){return $.replace(/\[1m\]$/i,"").toLowerCase()}var e6=R(()=>{I();X0()});import{randomUUID as DT}from"node:crypto";async function oj($,Z){if(!Z.trim()){await h($.chatId,"❌ 无法确认操作者身份,未打开 agents 面板");return}rj();let J=`agents_${DT()}`;Q3.set(J,{ownerOpenId:Z,codexAccountId:$.codexAccountId(),page:0,createdAt:Date.now()});let Q;if(!await o($.chatId,tj(J),(V)=>{Q=V}))await h($.chatId,`❌ agents 面板发送失败
296
- ${w(Q)}`)}function sj($,Z,J){let Q=UT($,J),Y=Number(Z);if(!Number.isInteger(Y))return OT("无效页码");let V=MT(Q.codexAccountId);return Q.page=Math.max(0,Math.min(V-1,Y)),Q.createdAt=Date.now(),{ok:!0,message:"已更新",card:tj($)}}function tj($){let Z=Q3.get($);if(!Z)throw Error("Agent 身份面板已过期");let J=J3(Z.codexAccountId),Q=Math.max(1,Math.ceil(J.identities.length/$5));Z.page=Math.min(Z.page,Q-1);let Y=Z.page*$5;return uY({panelId:$,page:Z.page,totalPages:Q,catalog:J.identities.slice(Y,Y+$5),failures:J.sourceFailures})}function MT($){return Math.max(1,Math.ceil(J3($).identities.length/$5))}function UT($,Z){rj();let J=Q3.get($);if(!J)throw Error("Agent 身份面板已过期,请重新发送 agents");if(!J.ownerOpenId||!Z||J.ownerOpenId!==Z)throw Error("只有打开该面板的用户可操作");return J}function OT($){return{ok:!1,message:$,card:t1({title:"agents",message:$,ok:!1})}}function rj(){let $=Date.now()-FT;for(let[Z,J]of Q3)if(J.createdAt<$)Q3.delete(Z)}var $5=8,FT=1800000,Q3;var ej=R(()=>{S$();Y0();e6();Q3=new Map});var RV={};H1(RV,{withTasklistLifecycleLock:()=>Y5,tasklistNameForProject:()=>Q5,reconcileTasklistDeletions:()=>TT,isTasklistAlreadyDeletedError:()=>$_,getTasklistBinding:()=>E1,enableTasklist:()=>AV,deleteTasklistRemoteIdempotently:()=>Z_,deleteTasklist:()=>NV});import{existsSync as NT,readFileSync as RT}from"node:fs";function Q5($){return`${$}[lodestar]`}function E1($){let Z=T1.get($);return Z?_9(Z):null}async function Y5($,Z){let J=Z5.get($)??Promise.resolve(),Q,Y=new Promise((X)=>{Q=X}),V=J.catch(()=>{}).then(()=>Y);Z5.set($,V),await J.catch(()=>{});try{return await Z()}finally{if(Q(),Z5.get($)===V)Z5.delete($)}}function $_($){if($&&typeof $==="object"&&$.code===1470404)return!0;let Z=$ instanceof Error?$.message:String($);return/\bcode=1470404\b/.test(Z)}async function Z_($,Z=UJ){try{return await Z($),"deleted"}catch(J){if($_(J))return"already_deleted";throw J}}async function AV($,Z){return await Y5($,async()=>{let J=E1($);if(J?.deleting)throw Error(`tasklist deletion is pending for ${$}`);if(J)return J;let Q=Q5($);if(Q.length>100)throw Error(`tasklist name is too long (${Q.length}/100): ${Q}`);let Y=await FJ(Z),V=await MJ(Q,Y),X={guid:V.guid,name:V.name,url:V.url,projectName:$,ownerOpenId:Y,createdAt:V.createdAt};return J5($,X),_9(X)})}async function NV($,Z){return await Y5($,async()=>{let J=E1($);if(!J)throw Error("tasklist is not enabled");if(J.guid!==Z)throw Error(`tasklist binding changed: current=${J.guid} requested=${Z}`);if(!J.deleting)J.deleting={requestedAt:new Date().toISOString(),attempts:0},J5($,J);return await J_($,Z)})}async function J_($,Z){let J=E1($);if(!J||J.guid!==Z)throw Error(`tasklist binding changed during deletion: ${$}`);J.deleting??={requestedAt:new Date().toISOString(),attempts:0},J.deleting.attempts++,J.deleting.lastAttemptAt=new Date().toISOString(),J.deleting.lastError=void 0,J5($,J);try{if(await Z_(Z)==="already_deleted")j(`tasklist: ${$} remote list ${Z} already deleted; finishing tombstone`);let Y=new Map(T1);return Y.delete($),Q_(Y),T1.delete($),_9(J)}catch(Q){let Y=E1($);if(Y?.guid===Z&&Y.deleting)Y.deleting.lastError=Q instanceof Error?Q.message:String(Q),J5($,Y);throw Q}}async function TT(){let $=[...T1.entries()].filter(([,J])=>!!J.deleting).map(([J,Q])=>({projectName:J,guid:Q.guid})),Z=[];for(let J of $)try{await Y5(J.projectName,()=>J_(J.projectName,J.guid)),j(`tasklist: reconciled pending deletion for ${J.projectName}`)}catch(Q){Z.push(`${J.projectName}: ${Q instanceof Error?Q.message:String(Q)}`)}if(Z.length)throw Error(`tasklist deletion reconcile failed: ${Z.join("; ")}`)}function ET(){if(!NT(K3))return;try{let $=JSON.parse(RT(K3,"utf8"));if(!$||typeof $!=="object")return;for(let[Z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let Q=J;if(typeof Q.guid!=="string"||!Q.guid||typeof Q.name!=="string"||!Q.name)continue;let Y={guid:Q.guid,name:Q.name,url:typeof Q.url==="string"?Q.url:"",projectName:Z,ownerOpenId:typeof Q.ownerOpenId==="string"?Q.ownerOpenId:"",createdAt:typeof Q.createdAt==="string"?Q.createdAt:void 0,deleting:ST(Q.deleting)};T1.set(Z,Y)}j(`tasklist: loaded ${T1.size} project bindings`)}catch($){j(`tasklist: load map failed: ${$}`)}}function ST($){if(!$||typeof $!=="object")return;let Z=$;if(typeof Z.requestedAt!=="string"||!Z.requestedAt)return;return{requestedAt:Z.requestedAt,lastAttemptAt:typeof Z.lastAttemptAt==="string"?Z.lastAttemptAt:void 0,attempts:typeof Z.attempts==="number"&&Number.isFinite(Z.attempts)&&Z.attempts>=0?Math.floor(Z.attempts):0,lastError:typeof Z.lastError==="string"?Z.lastError:void 0}}function J5($,Z){let J=new Map(T1);J.set($,_9(Z)),Q_(J),T1.set($,_9(Z))}function Q_($=T1){let Z={};for(let[J,Q]of $)Z[J]=_9(Q);r(K3,Z)}function _9($){return JSON.parse(JSON.stringify($))}var T1,Z5;var TV=R(()=>{H0();Y0();I();b0();T1=new Map,Z5=new Map;ET()});function Z2($,Z,J=!1){let Q=$.worktreeProjectName();return pY({projectName:Q,tasklistName:Q5(Q),binding:E1(Q),notice:Z,confirmDelete:J})}async function Y_($){let Z;if(!await o($.chatId,Z2($),(Q)=>{Z=Q}))await h($.chatId,`❌ task 面板发送失败
297
- ${w(Z)}`)}async function V_($){let Z=$.worktreeProjectName();try{let J=E1(Z),Q=await AV(Z,$.chatId),Y=J?"已启用":`已启用 ${Q.name}`;return{ok:!0,message:Y,card:Z2($,{type:"success",content:`✅ ${Y}`})}}catch(J){let Q=`启用失败: ${E(J)}`;return j(`session "${$.sessionName}": tasklist enable failed: ${E(J)}`),{ok:!1,message:Q,card:Z2($,{type:"error",content:`❌ ${Q}`})}}}function X_($,Z){let J=$.worktreeProjectName(),Q=E1(J),Y=Z.trim();if(!Q)return{ok:!1,message:"未启用",card:Z2($,{type:"error",content:"❌ 未启用"})};if(Q.guid!==Y)return{ok:!1,message:"清单绑定已变化",card:Z2($,{type:"error",content:"❌ 清单绑定已变化,请重新打开 task 面板"})};return{ok:!0,message:"请再次确认删除",card:Z2($,{type:"error",content:"⚠️ 删除会删除所有清单内任务"},!0)}}async function z_($,Z){let J=$.worktreeProjectName(),Q=Z.trim();try{let V=`已删除 ${(await NV(J,Q)).name}`;return{ok:!0,message:V,card:Z2($,{type:"success",content:`✅ ${V}`})}}catch(Y){let V=`删除失败: ${E(Y)}`;return j(`session "${$.sessionName}": tasklist delete failed: ${E(Y)}`),{ok:!1,message:V,card:Z2($,{type:"error",content:`❌ ${V}`})}}}var H_=R(()=>{S$();Y0();I();TV()});import{open as xT}from"node:fs/promises";import{basename as bT}from"node:path";function EV($){if(typeof $!=="string"||!$.trim())throw Error("云空间链接 MISS");let Z=new URL($);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("云空间链接无效");return Z.href}function S1($,Z){if(typeof $!=="string"||!$.trim())throw Error(`${Z} MISS`);return $}class G_{deps;queue=Promise.resolve();lastStartedAt=0;constructor($={fetch:V0,getToken:s$,retry:G2,wait:(Z)=>new Promise((J)=>setTimeout(J,Z)),intervalMs:250}){this.deps=$}request($,Z,J="GET",Q,Y){let V=this.queue.then(()=>this.deps.retry($,async()=>{Y?.throwIfAborted();let X=await this.deps.getToken(),z=Q?.(),H=z instanceof FormData,G=this.deps.intervalMs-(Date.now()-this.lastStartedAt);if(G>0)await this.deps.wait(G);Y?.throwIfAborted(),this.lastStartedAt=Date.now();let W=AbortSignal.timeout(vT),K=new AbortController,B=()=>K.abort(W.reason),_=()=>K.abort(Y.reason);W.addEventListener("abort",B,{once:!0}),Y?.addEventListener("abort",_,{once:!0});let P=K.signal;try{let L=await this.deps.fetch(`https://open.feishu.cn/open-apis${Z}`,{method:J,headers:{Authorization:`Bearer ${X}`,...!H&&z!==void 0?{"Content-Type":"application/json"}:{}},...z!==void 0?{body:H?z:JSON.stringify(z)}:{},signal:P});return(await F$(L,$)).data}catch(L){if(P.aborted&&P.reason?.name==="TimeoutError")throw P.reason;throw L}finally{W.removeEventListener("abort",B),Y?.removeEventListener("abort",_)}}));return this.queue=V.then(()=>{},()=>{}),V}async createFolder($,Z){let J=await this.request("创建交付文件夹","/drive/v1/files/create_folder","POST",()=>({name:$,folder_token:""}),Z);return{token:S1(J?.token,"交付文件夹"),url:EV(J?.url)}}async getChatName($,Z){let J=await this.request("读取群名称",`/im/v1/chats/${encodeURIComponent($)}`,"GET",void 0,Z);return S1(J?.name,"群名称")}async getFolder($,Z){let J=await this.request("读取群文件夹",`/drive/explorer/v2/folder/${encodeURIComponent($.token)}/meta`,"GET",void 0,Z),Q=S1(J?.token,"群文件夹");if(Q!==$.token)throw Error("群文件夹返回了不同的标识");return{token:Q,url:EV($.url),name:S1(J?.name,"群文件夹名称")}}async renameFolder($,Z,J){try{await this.request("同步群文件夹名称",`/drive/v1/files/${encodeURIComponent($.token)}?type=folder`,"PATCH",()=>({new_title:Z}),J)}catch(Y){if(Y instanceof l0&&Y.code===99991672)Y.message=`同步群文件夹名称需要应用身份权限 drive:file:upload;${Y.message}`;throw Y}let Q=await this.getFolder($,J);if(Q.name!==Z)throw Error("群文件夹名称更新未生效");return Q}async grantFolderAccess($,Z,J,Q){S1(Z,"交付群"),S1(J,"交付发起人");let Y=`/drive/v1/permissions/${encodeURIComponent($.token)}/members?type=folder`;for(let X of[{member_type:"openid",member_id:J,perm:"full_access",type:"user"},{member_type:"openchat",member_id:Z,perm:"view",type:"chat"}])await this.request("设置交付文件夹权限",Y,"POST",()=>X,Q);let V=await this.request("核对交付文件夹权限",Y,"GET",void 0,Q);if(!Array.isArray(V?.items))throw Error("交付文件夹权限列表 MISS");for(let[X,z,H]of[["openid",J,"full_access"],["openchat",Z,"view"]])if(V.items.find((W)=>W.member_type===X&&W.member_id===z)?.perm!==H)throw Error(`交付文件夹权限未生效:${X} / ${H}`)}async closeFileLinkSharing($,Z){S1($,"交付文件");let J=`/drive/v2/permissions/${encodeURIComponent($)}/public?type=file`;if(await this.request("关闭交付文件链接分享",J,"PATCH",()=>({link_share_entity:"closed"}),Z),(await this.request("核对交付文件链接分享",J,"GET",void 0,Z))?.permission_public?.link_share_entity!=="closed")throw Error("交付文件链接分享未关闭,不能发布交付链接")}async uploadFile($,Z,J,Q){Q?.throwIfAborted();let Y=await xT($,"r");try{let V=await Y.stat();if(!V.isFile())throw Error("交付路径不是普通文件");if(!Number.isSafeInteger(V.size)||V.size<=0)throw Error("不能上传空文件或无效大小的文件");let X=bT($),z={file_name:X,parent_type:"explorer",parent_node:Z.token,size:V.size},H;if(V.size<=kT){let L=await Y.readFile(),q=await Y.stat();if(L.length!==V.size||q.mtimeMs!==V.mtimeMs||q.ctimeMs!==V.ctimeMs)throw Error("交付文件在读取时发生变化");H=await this.request("上传交付文件","/drive/v1/files/upload_all","POST",()=>{let D=new FormData;for(let[M,U]of Object.entries(z))D.append(M,String(U));return D.append("file",new Blob([Uint8Array.from(L)]),X),D},Q)}else{let L=await this.request("准备上传交付文件","/drive/v1/files/upload_prepare","POST",()=>z,Q),q=S1(L?.upload_id,"分片上传事务"),D=L?.block_size,M=L?.block_num;if(!Number.isSafeInteger(D)||D<=0||D>wT||!Number.isSafeInteger(M)||M!==Math.ceil(V.size/D))throw Error("云空间返回的分片策略无效");for(let A=0;A<M;A++){Q?.throwIfAborted();let O=Math.min(D,V.size-A*D),N=Buffer.alloc(O),S=0;while(S<O){let T=await Y.read(N,S,O-S,A*D+S);if(!T.bytesRead)throw Error("交付文件在分片读取时发生变化");S+=T.bytesRead}await this.request("上传交付文件分片","/drive/v1/files/upload_part","POST",()=>{let T=new FormData;return T.append("upload_id",q),T.append("seq",String(A)),T.append("size",String(O)),T.append("file",new Blob([Uint8Array.from(N)]),X),T},Q)}let U=await Y.stat();if(U.size!==V.size||U.mtimeMs!==V.mtimeMs||U.ctimeMs!==V.ctimeMs)throw Error("交付文件在上传期间被修改,未完成上传");H=await this.request("完成交付文件上传","/drive/v1/files/upload_finish","POST",()=>({upload_id:q,block_num:M}),Q)}let G=S1(H?.file_token,"已上传文件"),W={token:G,url:"",name:X,bytes:V.size},K=[];try{J(W)}catch(L){K.push(L)}try{await this.closeFileLinkSharing(G)}catch(L){K.push(L)}if(K.length===1)throw K[0];if(K.length>1)throw AggregateError(K,K.map((L)=>L instanceof Error?L.message:String(L)).join(";"));Q?.throwIfAborted();let B=await this.request("读取交付文件链接","/drive/v1/metas/batch_query","POST",()=>({request_docs:[{doc_token:G,doc_type:"file"}],with_url:!0}),Q),_=B?.metas?.find((L)=>L.doc_token===G&&L.doc_type==="file");if(B?.failed_list?.length||!_)throw Error("已上传文件的元数据 MISS");let P={...W,url:EV(_.url)};return J(P),P}finally{await Y.close()}}}var kT=20971520,wT=20971520,vT=60000,Z4;var W_=R(()=>{u0();Y0();j4();Z4=new G_});import{randomUUID as K_}from"node:crypto";import{basename as fT}from"node:path";class SV{deps;snapshot;queue=Promise.resolve();folderPromise;finishPromise;persistenceError;abort=new AbortController;constructor($,Z){this.deps=Z;if(!$.chatId.trim()||!$.managerOpenId.trim())throw Error("无法确认交付群或本次交付发起人");this.snapshot={...$,version:1,id:K_(),folderAccessReady:!1,files:[]}}add($){if(this.finishPromise)throw Error("本次文件交付已结束");if(this.abort.signal.throwIfAborted(),this.snapshot.files.some((J)=>J.path===$))return;let Z={id:K_(),path:$,name:fT($),status:"pending"};this.snapshot.files.push(Z);try{this.save()}catch(J){throw Z.status="failed",Z.error=J instanceof Error?J.message:String(J),J}this.queue=this.queue.then(async()=>{try{if(this.abort.signal.throwIfAborted(),this.persistenceError)throw Error(this.persistenceError);let J=await this.getFolder(),Q=await this.deps.uploadFile($,J,(Y)=>{Z.file={...Y},Z.bytes=Y.bytes,this.save()},this.abort.signal);Z.file=Q,Z.bytes=Q.bytes,Z.status="ready",this.save()}catch(J){Z.status="failed",Z.error=`${Z.file?"文件已上传,后续处理失败:":""}${J instanceof Error?J.message:String(J)}`;try{this.save()}catch(Q){this.snapshot.error=Q instanceof Error?Q.message:String(Q)}if(!this.abort.signal.aborted)try{await this.deps.reportError(`❌ 文件交付失败:${Z.name}
295
+ 请重新发送 model 打开面板。`;if(!await h($.chatId,F))j(`model-custom: visible fallback send MISS (${P})`);return!1},G=(_)=>H(d8(!1,Y,_),`❌ ${Y?`模型 ${Y}`:"模型名"} 未加入:${_}。`);if(!V||!V.enabled)return await G("账号不可用"),!0;if(!Y)return await G("模型名为空"),!0;if(V.models.some((_)=>_.model.toLowerCase()===Y.toLowerCase()))return await H(d8(!1,Y,"已在列表中"),`ℹ️ 模型 ${Y} 已在列表中,未重复加入。`),!0;try{await zK(V.id,Y,$.codexAccountId())}catch(_){return j(`model-custom: config/refresh MISS (${E(_)})`),await G(`配置写入或模型刷新失败:${E(_)}`),!0}j(`model-custom: ${V.id} 补录 ${Y} by ${J}(记录已持久化)`);for(let _ of g$.all)for(let[P,L]of _.modelPanels)if(L.sourceId===V.id&&(_!==$||P!==Q.panelId))_.modelPanels.delete(P);let W=$.tokenSource(V.id);if(!W||W.modelCatalogState?.status!=="ready")return await G(W?.modelCatalogState?.error??"刷新后的账号目录不可用"),!0;let K=FV($,W),B=K.find((_)=>_.model===Y);if(!B)return await G("补录已保存,但刷新后的模型列表未返回该项"),!0;if($.modelPanels.set(Q.panelId,{models:K,messageId:Q.cardMessageId}),B.unavailableReason||!B.efforts.length)return await H(d8(!0,Y,`**MISS**:${B.unavailableReason??"后端未确认 effort"}。记录已保存,可在模型面板删除。`),`模型 ${Y} 已补录,能力尚未确认。`),!0;if(B.efforts.length===1){let _=await $.onModelEffortSelect(B.model,B.efforts[0].effort,Q.panelId,J,B.provider),P=(L)=>H(L.pending?l8(!0,L.message):L.ok?h6({sessionName:$.sessionName,provider:B.provider,model:B.model,effort:B.efforts[0].effort,scope:MV($,B.provider??"codex")}):l8(!1,L.message),L.message);if(await P(_),_.completion)_.completion.then(P).catch(async(L)=>{let q=`模型补录后的切换结果呈现失败:${E(L)}`;j(`model-custom: ${q}`),await h($.chatId,`❌ ${q}`)});return!0}return await H(f6({sessionName:$.sessionName,panelId:Q.panelId,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:B}),`✅ 模型 ${Y} 已补录成功。`),!0}async function pj($,Z=""){let J=Z.trim(),Q=$.modelCustomPrompt;if(!J||!Q||Q.panelId!==J)return{ok:!1,message:"此补录面板已失效",card:y6($.sessionName,"stale")};return $.modelCustomPrompt=null,{ok:!0,message:"已取消",card:y6($.sessionName)}}function GT($,Z){return a$(Z?.provider)?Z.provider:x4($)}function MV($,Z){if(Z==="codex"&&$.proc?.isAlive()&&$.proc.provider===Z)return"Codex 需重启进程生效(发 restart)。";if($.currentTurn)return"当前 turn 不变,后续新 turn 使用。";if($.proc?.isAlive()&&$.proc.provider===Z)return Z==="codex"?"Codex 需重启进程生效(发 restart)。":"下一轮开始使用。";return`下次启动 ${t0(Z)} 时使用。`}async function cj($,Z,J="",Q="",Y=null){let V=Z.trim();if(!V)return await k($.chatId,`❌ ${"模型为空"}`),{ok:!1,message:"模型为空"};let X=GT(V,Y),z=$.modelPanels.get(J.trim())?.models.find((H)=>H.model===V&&(H.provider??"codex")===X);if(!z)return{ok:!1,message:"模型不在当前选项中,请重新发送 model"};if($.modelPanels.get(J.trim())?.mode==="add")return{ok:!1,message:"请先将模型添加到可选列表"};if(z.unavailableReason)return{ok:!1,message:z.unavailableReason};if(z.enabled===!1)return{ok:!1,message:`${z.displayName} 未配置,请先点「启用」`};if(z.efforts.length===0)return{ok:!1,message:"模型未返回 effort"};if(z.efforts.length===1)return UV($,V,z.efforts[0].effort,J,Q,X);return{ok:!0,message:"",card:CY({sessionName:$.sessionName,panelId:J.trim(),currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:z})}}async function UV($,Z,J,Q="",Y="",V=""){if($.modelSettingsChangesClosed)return{ok:!1,message:"daemon 正在停止,本次模型选择未执行"};if($.modelSettingsChange?.proc===$.proc&&$.modelSettingsChange?.phase==="pending")return{ok:!1,message:"上一项模型设置仍在等待后端确认,本次选择未执行;请等待结果,取消切换请发 kill 或 restart。"};let X=Z.trim(),z=J.trim();if(!X)return{ok:!1,message:"模型为空"};let H=Q.trim(),G=$.modelPanels.get(H),W=a$(V)?V:G?.models.find((O)=>O.model===X)?.provider??x4(X);if(W==="dsh"){if(!S0(z))return{ok:!1,message:"DSH reasoning effort 无效"}}else if(W==="claude"){if(!w0(z))return{ok:!1,message:"Claude reasoning effort 无效"}}else if(!U$(z))return{ok:!1,message:"Codex reasoning effort 无效"};let K=z,B=G?.models.find((O)=>O.model===X&&(O.provider??"codex")===W);if(!B||!B.efforts.some((O)=>O.effort===K))return{ok:!1,message:`${t0(W)} · ${X}/${K} 不在选项中`};let _=$.tokenSource(B.sourceId);if(_?.modelCatalogState){if(!_.enabled||_.modelCatalogState.status!=="ready")return{ok:!1,message:`模型目录 MISS:${_.modelCatalogState.error??_.modelCatalogState.status}`};if(!_.models.some((O)=>O.model===X&&O.efforts.includes(K)))return{ok:!1,message:"模型或 effort 已不在账号目录中,请重新发送 model"}}let P=!!B.sourceId&&$.currentTokenSource()?.id!==B.sourceId,L=!$.processSourceMatches(_,X)||!!_?.modelEnvironmentRevision&&_.modelEnvironmentRevision($.currentModelLabel()??"")!==_.modelEnvironmentRevision(X),q=$.modelSelectionNeedsProcessStop(W,B.sourceId??$.selectedTokenSourceId,X,K);if($.currentProvider()===W&&!P&&$.currentModelLabel()===X&&$.currentEffortLabel()===K&&!$.modelSettingsChange&&!q&&!L)return $.modelPanels.delete(H),{ok:!0,message:`当前已是 ${t0(W)} · ${X} / ${K}`,card:u8({sessionName:$.sessionName,provider:W,model:X,effort:K,scope:"当前已是此设置,无需变更。"})};if($.proc?.isAlive()&&$.proc.provider!==W&&($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0))return{ok:!1,message:`当前 ${$.backendLabel($.proc.provider)} turn 正在执行或排队;请等结束或 stop 后再切换到 ${t0(W)}`};let U=$.currentModelLabel()!==X||P,A=!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0);if((L||q)&&$.proc?.isAlive()&&A)return{ok:!1,message:"新模型需要更新进程配置,请等当前任务结束后再选择"};if(W==="claude"&&$.proc?.isAlive()&&$.proc.provider==="claude"&&U&&A)return{ok:!1,message:"当前 Claude turn 正在执行或排队;Claude 模型 profile 通过 env 生效,请等结束或 stop 后再切换"};try{if($.proc?.isAlive()&&$.proc.provider===W&&!P&&!L&&!q){let N=B.sourceId?$.tokenSource(B.sourceId)?.resolveSpawnModel(X)??X:X;if(W==="codex")await $.proc.setModelSettings(N,K);else return await zT($,$.proc,X,N,K,H,B.sourceId)}await $.applyModelSelectionUnlocked(W,X,K,B.sourceId);let O=MV($,W);return $.modelPanels.delete(H),{ok:!0,message:`已选择 ${t0(W)} · ${X} / ${K}`,card:u8({sessionName:$.sessionName,provider:W,model:X,effort:K,scope:O})}}catch(O){let N=`模型切换失败: ${E(O)}`;return j(`session "${$.sessionName}": set model settings failed: ${E(O)}`),{ok:!1,message:N}}}var LV=20;var uj=R(()=>{P0();OV();X0();EQ();j1();P0();S$();U1();Y0();I()});import{createHash as KT}from"node:crypto";function BT($,Z){return`agent:${Buffer.from(`${$}\x00${Z}`,"utf8").toString("base64url")}`}function J3($="default"){return nj(ij($))}function dj($="default"){return jT(ij($))}function ij($){return s0().map((Z)=>Z.forAccount?.($)??Z)}async function jT($){let Z=nj($),Q=(await Promise.all($.filter((V)=>V.kind==="claude-subscription").map(async(V)=>{let X=Z.sourceFailures.find((H)=>H.tokenSourceId===V.id);if(X)return X;let z=await _T(V);return z===null?null:{tokenSourceId:V.id,display:V.display,status:"failed",reason:z}}))).filter((V)=>V!==null),Y=new Set(Q.map((V)=>V.tokenSourceId));return aj(Z.identities.filter((V)=>!Y.has(V.tokenSourceId)),[...Z.sourceFailures.filter((V)=>!Y.has(V.tokenSourceId)),...Q])}function _T($){return PT($)}async function PT($){let Z;try{let J=await $.readUsage();if(J.state==="ok")return null;Z=J.reason??`订阅可用性查询失败:${J.state}`}catch(J){Z=J instanceof Error?J.message:String(J)}return j(`agent identities ${$.id} MISS: ${Z}`),Z}function nj($){let Z=[],J=[];for(let Q of $)LT(Q,Z,J);return aj(Z,J)}function aj($,Z){return{catalogGeneration:KT("sha256").update(JSON.stringify({identities:$,sourceFailures:Z})).digest("hex").slice(0,16),identities:$,sourceFailures:Z}}function LT($,Z,J){let Q=$.modelCatalogState?.status??(!$.enabled?"disabled":$.models.length>0?"ready":"idle");if(!$.enabled)J.push({tokenSourceId:$.id,display:$.display,status:"disabled",reason:"账号未启用"});else if(Q==="loading"||Q==="idle")J.push({tokenSourceId:$.id,display:$.display,status:"loading",reason:"模型目录正在刷新"});else if(Q==="failed")J.push({tokenSourceId:$.id,display:$.display,status:"failed",reason:$.modelCatalogState?.error??"模型目录刷新失败"});else if($.models.length===0)J.push({tokenSourceId:$.id,display:$.display,status:"models_miss",reason:"模型目录为空"});for(let Y of $.models)Z.push(qT($,Y,Q))}function qT($,Z,J){let Q="ready",Y;if(!$.enabled)Q="source_disabled",Y="所属 Token Source 未启用";else if(J==="loading"||J==="idle")Q="catalog_loading",Y="模型目录正在刷新";else if(J==="failed")Q="catalog_failed",Y=$.modelCatalogState?.error??"模型目录刷新失败";else if(Z.unavailableReason||!Z.efforts.length)Q="model_unavailable",Y=Z.unavailableReason??"effort MISS:上游未声明该后端支持的推理档位";return{id:BT($.id,Z.model),displayName:`${$.display} · ${Z.display}`,tokenSourceId:$.id,tokenSourceDisplay:$.display,provider:$.agent,model:Z.model,modelDisplay:Z.display,defaultEffort:Z.defaultEffort,supportedEfforts:[...Z.efforts],sourceDefault:lj($.defaultModel)===lj(Z.model),status:Q,...Y?{reason:Y}:{},spawnRevision:$.spawnRevision}}function lj($){return $.replace(/\[1m\]$/i,"").toLowerCase()}var e6=R(()=>{I();X0()});import{randomUUID as FT}from"node:crypto";async function oj($,Z){if(!Z.trim()){await h($.chatId,"❌ 无法确认操作者身份,未打开 agents 面板");return}rj();let J=`agents_${FT()}`;Q3.set(J,{ownerOpenId:Z,codexAccountId:$.codexAccountId(),page:0,createdAt:Date.now()});let Q;if(!await o($.chatId,tj(J),(V)=>{Q=V}))await h($.chatId,`❌ agents 面板发送失败
296
+ ${w(Q)}`)}function sj($,Z,J){let Q=UT($,J),Y=Number(Z);if(!Number.isInteger(Y))return OT("无效页码");let V=MT(Q.codexAccountId);return Q.page=Math.max(0,Math.min(V-1,Y)),Q.createdAt=Date.now(),{ok:!0,message:"已更新",card:tj($)}}function tj($){let Z=Q3.get($);if(!Z)throw Error("Agent 身份面板已过期");let J=J3(Z.codexAccountId),Q=Math.max(1,Math.ceil(J.identities.length/$5));Z.page=Math.min(Z.page,Q-1);let Y=Z.page*$5;return uY({panelId:$,page:Z.page,totalPages:Q,catalog:J.identities.slice(Y,Y+$5),failures:J.sourceFailures})}function MT($){return Math.max(1,Math.ceil(J3($).identities.length/$5))}function UT($,Z){rj();let J=Q3.get($);if(!J)throw Error("Agent 身份面板已过期,请重新发送 agents");if(!J.ownerOpenId||!Z||J.ownerOpenId!==Z)throw Error("只有打开该面板的用户可操作");return J}function OT($){return{ok:!1,message:$,card:t1({title:"agents",message:$,ok:!1})}}function rj(){let $=Date.now()-DT;for(let[Z,J]of Q3)if(J.createdAt<$)Q3.delete(Z)}var $5=8,DT=1800000,Q3;var ej=R(()=>{S$();Y0();e6();Q3=new Map});var RV={};H1(RV,{withTasklistLifecycleLock:()=>Y5,tasklistNameForProject:()=>Q5,reconcileTasklistDeletions:()=>TT,isTasklistAlreadyDeletedError:()=>$_,getTasklistBinding:()=>E1,enableTasklist:()=>AV,deleteTasklistRemoteIdempotently:()=>Z_,deleteTasklist:()=>NV});import{existsSync as NT,readFileSync as RT}from"node:fs";function Q5($){return`${$}[lodestar]`}function E1($){let Z=T1.get($);return Z?_9(Z):null}async function Y5($,Z){let J=Z5.get($)??Promise.resolve(),Q,Y=new Promise((X)=>{Q=X}),V=J.catch(()=>{}).then(()=>Y);Z5.set($,V),await J.catch(()=>{});try{return await Z()}finally{if(Q(),Z5.get($)===V)Z5.delete($)}}function $_($){if($&&typeof $==="object"&&$.code===1470404)return!0;let Z=$ instanceof Error?$.message:String($);return/\bcode=1470404\b/.test(Z)}async function Z_($,Z=UJ){try{return await Z($),"deleted"}catch(J){if($_(J))return"already_deleted";throw J}}async function AV($,Z){return await Y5($,async()=>{let J=E1($);if(J?.deleting)throw Error(`tasklist deletion is pending for ${$}`);if(J)return J;let Q=Q5($);if(Q.length>100)throw Error(`tasklist name is too long (${Q.length}/100): ${Q}`);let Y=await DJ(Z),V=await MJ(Q,Y),X={guid:V.guid,name:V.name,url:V.url,projectName:$,ownerOpenId:Y,createdAt:V.createdAt};return J5($,X),_9(X)})}async function NV($,Z){return await Y5($,async()=>{let J=E1($);if(!J)throw Error("tasklist is not enabled");if(J.guid!==Z)throw Error(`tasklist binding changed: current=${J.guid} requested=${Z}`);if(!J.deleting)J.deleting={requestedAt:new Date().toISOString(),attempts:0},J5($,J);return await J_($,Z)})}async function J_($,Z){let J=E1($);if(!J||J.guid!==Z)throw Error(`tasklist binding changed during deletion: ${$}`);J.deleting??={requestedAt:new Date().toISOString(),attempts:0},J.deleting.attempts++,J.deleting.lastAttemptAt=new Date().toISOString(),J.deleting.lastError=void 0,J5($,J);try{if(await Z_(Z)==="already_deleted")j(`tasklist: ${$} remote list ${Z} already deleted; finishing tombstone`);let Y=new Map(T1);return Y.delete($),Q_(Y),T1.delete($),_9(J)}catch(Q){let Y=E1($);if(Y?.guid===Z&&Y.deleting)Y.deleting.lastError=Q instanceof Error?Q.message:String(Q),J5($,Y);throw Q}}async function TT(){let $=[...T1.entries()].filter(([,J])=>!!J.deleting).map(([J,Q])=>({projectName:J,guid:Q.guid})),Z=[];for(let J of $)try{await Y5(J.projectName,()=>J_(J.projectName,J.guid)),j(`tasklist: reconciled pending deletion for ${J.projectName}`)}catch(Q){Z.push(`${J.projectName}: ${Q instanceof Error?Q.message:String(Q)}`)}if(Z.length)throw Error(`tasklist deletion reconcile failed: ${Z.join("; ")}`)}function ET(){if(!NT(K3))return;try{let $=JSON.parse(RT(K3,"utf8"));if(!$||typeof $!=="object")return;for(let[Z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let Q=J;if(typeof Q.guid!=="string"||!Q.guid||typeof Q.name!=="string"||!Q.name)continue;let Y={guid:Q.guid,name:Q.name,url:typeof Q.url==="string"?Q.url:"",projectName:Z,ownerOpenId:typeof Q.ownerOpenId==="string"?Q.ownerOpenId:"",createdAt:typeof Q.createdAt==="string"?Q.createdAt:void 0,deleting:ST(Q.deleting)};T1.set(Z,Y)}j(`tasklist: loaded ${T1.size} project bindings`)}catch($){j(`tasklist: load map failed: ${$}`)}}function ST($){if(!$||typeof $!=="object")return;let Z=$;if(typeof Z.requestedAt!=="string"||!Z.requestedAt)return;return{requestedAt:Z.requestedAt,lastAttemptAt:typeof Z.lastAttemptAt==="string"?Z.lastAttemptAt:void 0,attempts:typeof Z.attempts==="number"&&Number.isFinite(Z.attempts)&&Z.attempts>=0?Math.floor(Z.attempts):0,lastError:typeof Z.lastError==="string"?Z.lastError:void 0}}function J5($,Z){let J=new Map(T1);J.set($,_9(Z)),Q_(J),T1.set($,_9(Z))}function Q_($=T1){let Z={};for(let[J,Q]of $)Z[J]=_9(Q);r(K3,Z)}function _9($){return JSON.parse(JSON.stringify($))}var T1,Z5;var TV=R(()=>{H0();Y0();I();b0();T1=new Map,Z5=new Map;ET()});function Z2($,Z,J=!1){let Q=$.worktreeProjectName();return pY({projectName:Q,tasklistName:Q5(Q),binding:E1(Q),notice:Z,confirmDelete:J})}async function Y_($){let Z;if(!await o($.chatId,Z2($),(Q)=>{Z=Q}))await h($.chatId,`❌ task 面板发送失败
297
+ ${w(Z)}`)}async function V_($){let Z=$.worktreeProjectName();try{let J=E1(Z),Q=await AV(Z,$.chatId),Y=J?"已启用":`已启用 ${Q.name}`;return{ok:!0,message:Y,card:Z2($,{type:"success",content:`✅ ${Y}`})}}catch(J){let Q=`启用失败: ${E(J)}`;return j(`session "${$.sessionName}": tasklist enable failed: ${E(J)}`),{ok:!1,message:Q,card:Z2($,{type:"error",content:`❌ ${Q}`})}}}function X_($,Z){let J=$.worktreeProjectName(),Q=E1(J),Y=Z.trim();if(!Q)return{ok:!1,message:"未启用",card:Z2($,{type:"error",content:"❌ 未启用"})};if(Q.guid!==Y)return{ok:!1,message:"清单绑定已变化",card:Z2($,{type:"error",content:"❌ 清单绑定已变化,请重新打开 task 面板"})};return{ok:!0,message:"请再次确认删除",card:Z2($,{type:"error",content:"⚠️ 删除会删除所有清单内任务"},!0)}}async function z_($,Z){let J=$.worktreeProjectName(),Q=Z.trim();try{let V=`已删除 ${(await NV(J,Q)).name}`;return{ok:!0,message:V,card:Z2($,{type:"success",content:`✅ ${V}`})}}catch(Y){let V=`删除失败: ${E(Y)}`;return j(`session "${$.sessionName}": tasklist delete failed: ${E(Y)}`),{ok:!1,message:V,card:Z2($,{type:"error",content:`❌ ${V}`})}}}var H_=R(()=>{S$();Y0();I();TV()});import{open as xT}from"node:fs/promises";import{basename as bT}from"node:path";function EV($){if(typeof $!=="string"||!$.trim())throw Error("云空间链接 MISS");let Z=new URL($);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("云空间链接无效");return Z.href}function S1($,Z){if(typeof $!=="string"||!$.trim())throw Error(`${Z} MISS`);return $}class G_{deps;queue=Promise.resolve();lastStartedAt=0;constructor($={fetch:V0,getToken:s$,retry:G2,wait:(Z)=>new Promise((J)=>setTimeout(J,Z)),intervalMs:250}){this.deps=$}request($,Z,J="GET",Q,Y){let V=this.queue.then(()=>this.deps.retry($,async()=>{Y?.throwIfAborted();let X=await this.deps.getToken(),z=Q?.(),H=z instanceof FormData,G=this.deps.intervalMs-(Date.now()-this.lastStartedAt);if(G>0)await this.deps.wait(G);Y?.throwIfAborted(),this.lastStartedAt=Date.now();let W=AbortSignal.timeout(vT),K=new AbortController,B=()=>K.abort(W.reason),_=()=>K.abort(Y.reason);W.addEventListener("abort",B,{once:!0}),Y?.addEventListener("abort",_,{once:!0});let P=K.signal;try{let L=await this.deps.fetch(`https://open.feishu.cn/open-apis${Z}`,{method:J,headers:{Authorization:`Bearer ${X}`,...!H&&z!==void 0?{"Content-Type":"application/json"}:{}},...z!==void 0?{body:H?z:JSON.stringify(z)}:{},signal:P});return(await D$(L,$)).data}catch(L){if(P.aborted&&P.reason?.name==="TimeoutError")throw P.reason;throw L}finally{W.removeEventListener("abort",B),Y?.removeEventListener("abort",_)}}));return this.queue=V.then(()=>{},()=>{}),V}async createFolder($,Z){let J=await this.request("创建交付文件夹","/drive/v1/files/create_folder","POST",()=>({name:$,folder_token:""}),Z);return{token:S1(J?.token,"交付文件夹"),url:EV(J?.url)}}async getChatName($,Z){let J=await this.request("读取群名称",`/im/v1/chats/${encodeURIComponent($)}`,"GET",void 0,Z);return S1(J?.name,"群名称")}async getFolder($,Z){let J=await this.request("读取群文件夹",`/drive/explorer/v2/folder/${encodeURIComponent($.token)}/meta`,"GET",void 0,Z),Q=S1(J?.token,"群文件夹");if(Q!==$.token)throw Error("群文件夹返回了不同的标识");return{token:Q,url:EV($.url),name:S1(J?.name,"群文件夹名称")}}async renameFolder($,Z,J){try{await this.request("同步群文件夹名称",`/drive/v1/files/${encodeURIComponent($.token)}?type=folder`,"PATCH",()=>({new_title:Z}),J)}catch(Y){if(Y instanceof l0&&Y.code===99991672)Y.message=`同步群文件夹名称需要应用身份权限 drive:file:upload;${Y.message}`;throw Y}let Q=await this.getFolder($,J);if(Q.name!==Z)throw Error("群文件夹名称更新未生效");return Q}async grantFolderAccess($,Z,J,Q){S1(Z,"交付群"),S1(J,"交付发起人");let Y=`/drive/v1/permissions/${encodeURIComponent($.token)}/members?type=folder`;for(let X of[{member_type:"openid",member_id:J,perm:"full_access",type:"user"},{member_type:"openchat",member_id:Z,perm:"view",type:"chat"}])await this.request("设置交付文件夹权限",Y,"POST",()=>X,Q);let V=await this.request("核对交付文件夹权限",Y,"GET",void 0,Q);if(!Array.isArray(V?.items))throw Error("交付文件夹权限列表 MISS");for(let[X,z,H]of[["openid",J,"full_access"],["openchat",Z,"view"]])if(V.items.find((W)=>W.member_type===X&&W.member_id===z)?.perm!==H)throw Error(`交付文件夹权限未生效:${X} / ${H}`)}async closeFileLinkSharing($,Z){S1($,"交付文件");let J=`/drive/v2/permissions/${encodeURIComponent($)}/public?type=file`;if(await this.request("关闭交付文件链接分享",J,"PATCH",()=>({link_share_entity:"closed"}),Z),(await this.request("核对交付文件链接分享",J,"GET",void 0,Z))?.permission_public?.link_share_entity!=="closed")throw Error("交付文件链接分享未关闭,不能发布交付链接")}async uploadFile($,Z,J,Q){Q?.throwIfAborted();let Y=await xT($,"r");try{let V=await Y.stat();if(!V.isFile())throw Error("交付路径不是普通文件");if(!Number.isSafeInteger(V.size)||V.size<=0)throw Error("不能上传空文件或无效大小的文件");let X=bT($),z={file_name:X,parent_type:"explorer",parent_node:Z.token,size:V.size},H;if(V.size<=kT){let L=await Y.readFile(),q=await Y.stat();if(L.length!==V.size||q.mtimeMs!==V.mtimeMs||q.ctimeMs!==V.ctimeMs)throw Error("交付文件在读取时发生变化");H=await this.request("上传交付文件","/drive/v1/files/upload_all","POST",()=>{let F=new FormData;for(let[M,U]of Object.entries(z))F.append(M,String(U));return F.append("file",new Blob([Uint8Array.from(L)]),X),F},Q)}else{let L=await this.request("准备上传交付文件","/drive/v1/files/upload_prepare","POST",()=>z,Q),q=S1(L?.upload_id,"分片上传事务"),F=L?.block_size,M=L?.block_num;if(!Number.isSafeInteger(F)||F<=0||F>wT||!Number.isSafeInteger(M)||M!==Math.ceil(V.size/F))throw Error("云空间返回的分片策略无效");for(let A=0;A<M;A++){Q?.throwIfAborted();let O=Math.min(F,V.size-A*F),N=Buffer.alloc(O),S=0;while(S<O){let T=await Y.read(N,S,O-S,A*F+S);if(!T.bytesRead)throw Error("交付文件在分片读取时发生变化");S+=T.bytesRead}await this.request("上传交付文件分片","/drive/v1/files/upload_part","POST",()=>{let T=new FormData;return T.append("upload_id",q),T.append("seq",String(A)),T.append("size",String(O)),T.append("file",new Blob([Uint8Array.from(N)]),X),T},Q)}let U=await Y.stat();if(U.size!==V.size||U.mtimeMs!==V.mtimeMs||U.ctimeMs!==V.ctimeMs)throw Error("交付文件在上传期间被修改,未完成上传");H=await this.request("完成交付文件上传","/drive/v1/files/upload_finish","POST",()=>({upload_id:q,block_num:M}),Q)}let G=S1(H?.file_token,"已上传文件"),W={token:G,url:"",name:X,bytes:V.size},K=[];try{J(W)}catch(L){K.push(L)}try{await this.closeFileLinkSharing(G)}catch(L){K.push(L)}if(K.length===1)throw K[0];if(K.length>1)throw AggregateError(K,K.map((L)=>L instanceof Error?L.message:String(L)).join(";"));Q?.throwIfAborted();let B=await this.request("读取交付文件链接","/drive/v1/metas/batch_query","POST",()=>({request_docs:[{doc_token:G,doc_type:"file"}],with_url:!0}),Q),_=B?.metas?.find((L)=>L.doc_token===G&&L.doc_type==="file");if(B?.failed_list?.length||!_)throw Error("已上传文件的元数据 MISS");let P={...W,url:EV(_.url)};return J(P),P}finally{await Y.close()}}}var kT=20971520,wT=20971520,vT=60000,Z4;var W_=R(()=>{u0();Y0();j4();Z4=new G_});import{randomUUID as K_}from"node:crypto";import{basename as yT}from"node:path";class SV{deps;snapshot;queue=Promise.resolve();folderPromise;finishPromise;persistenceError;abort=new AbortController;constructor($,Z){this.deps=Z;if(!$.chatId.trim()||!$.managerOpenId.trim())throw Error("无法确认交付群或本次交付发起人");this.snapshot={...$,version:1,id:K_(),folderAccessReady:!1,files:[]}}add($){if(this.finishPromise)throw Error("本次文件交付已结束");if(this.abort.signal.throwIfAborted(),this.snapshot.files.some((J)=>J.path===$))return;let Z={id:K_(),path:$,name:yT($),status:"pending"};this.snapshot.files.push(Z);try{this.save()}catch(J){throw Z.status="failed",Z.error=J instanceof Error?J.message:String(J),J}this.queue=this.queue.then(async()=>{try{if(this.abort.signal.throwIfAborted(),this.persistenceError)throw Error(this.persistenceError);let J=await this.getFolder(),Q=await this.deps.uploadFile($,J,(Y)=>{Z.file={...Y},Z.bytes=Y.bytes,this.save()},this.abort.signal);Z.file=Q,Z.bytes=Q.bytes,Z.status="ready",this.save()}catch(J){Z.status="failed",Z.error=`${Z.file?"文件已上传,后续处理失败:":""}${J instanceof Error?J.message:String(J)}`;try{this.save()}catch(Q){this.snapshot.error=Q instanceof Error?Q.message:String(Q)}if(!this.abort.signal.aborted)try{await this.deps.reportError(`❌ 文件交付失败:${Z.name}
298
298
  ${Z.error}`)}catch(Q){this.snapshot.error=`错误提示发送失败:${String(Q)}`}}})}finish(){return this.finishPromise??=this.publish(),this.finishPromise}cancel($){if(this.abort.signal.aborted||!this.snapshot.files.some((Z)=>Z.status==="pending"))return!1;return this.snapshot.error=`未完成的文件上传已取消:${$}`,this.abort.abort(new DOMException($,"AbortError")),!0}save(){try{this.deps.persist(this.snapshot)}catch($){throw this.persistenceError=`保存文件交付记录失败:${$ instanceof Error?$.message:String($)}`,Error(this.persistenceError)}}getFolder(){return this.folderPromise??=(async()=>{let $=await this.deps.resolveFolder(this.snapshot,this.abort.signal);return this.snapshot.folder=$,this.snapshot.folderAccessReady=!0,this.save(),$})(),this.folderPromise}async publish(){if(await this.queue,!this.snapshot.files.length)return[];this.snapshot.completedAt=Date.now();try{this.save()}catch(Z){this.snapshot.error=Z instanceof Error?Z.message:String(Z)}let $;try{let Z;if($=await this.deps.sendCard(this.snapshot,(J)=>{Z=J}),!$)throw Error(`飞书未返回交付卡消息 ID:${w(Z)}`)}catch(Z){let J=`交付卡发送失败:${Z instanceof Error?Z.message:String(Z)}`;this.snapshot.error=J;try{this.save()}catch(Q){this.snapshot.error+=`;${String(Q)}`}return await this.deps.reportError(`❌ ${this.snapshot.error}${this.snapshot.folderAccessReady?`
299
- 已上传文件所在文件夹:${this.snapshot.folder.url}`:""}`),[]}this.snapshot.messageId=$;try{this.save()}catch(Z){await this.deps.reportError(`❌ 交付卡已发送,但${String(Z)}`)}return this.snapshot.files.filter((Z)=>Z.status==="ready").map((Z)=>Z.path)}}var B_=()=>{};class CV{deps;state;locks=new Map;constructor($){this.deps=$}get($,Z){let J=H$(Z),Q=this.load(),Y=Q.workspaces[J]?.enabled;if(Y===void 0){let X=new Set(this.legacyChats($,J).map((z)=>Q.groups[z].legacyEnabled));if(X.size>1)throw Error("同一工作目录的旧群文件交付设置冲突,请发送 files on 或 files off 统一设置");if(X.size)Y=X.values().next().value,this.commitMode($,J,Y)}let V=this.load().groups[$]?.folder;return{enabled:Y??!1,...V?{folder:structuredClone(V)}:{}}}mode($,Z){return this.get($,Z).enabled?"drive":"chat"}enable($,Z,J){let Q=H$(Z);return this.exclusive(`workspace:${Q}`,()=>this.exclusive(`chat:${$}`,async()=>{return await this.prepare($,J,!0),this.commitMode($,Q,!0),this.get($,Z)}))}disable($,Z){let J=H$(Z);return this.exclusive(`workspace:${J}`,async()=>{return this.commitMode($,J,!1),this.get($,Z)})}resolveFolder($,Z){return this.exclusive(`chat:${$.chatId}`,()=>this.prepare($.chatId,$.managerOpenId,!0,Z))}bindExisting($,Z,J,Q){return this.exclusive(`chat:${$}`,async()=>{let Y=this.load().groups[$];if(Y?.folder&&Y.folder.token!==Q.token)throw Error("本群已经绑定其他文件夹");let V=await this.deps.getFolder(Q);return this.commitFolder($,V),await this.prepare($,J,!1),this.get($,Z)})}async prepare($,Z,J,Q){if(Q?.throwIfAborted(),!$.trim()||!Z.trim())throw Error("无法确认交付群或管理权限接收人");let Y=await this.deps.getChatName($,Q);if(!Y.trim())throw Error("群名称 MISS");let V=this.load().groups[$]?.folder;if(!V){if(!J)throw Error("本群尚未绑定云空间文件夹");V={...await this.deps.createFolder(Y,Q),name:Y},this.commitFolder($,V)}let X=await this.deps.getFolder(V,Q);if(X.token!==V.token)throw Error("云空间返回的文件夹与本群绑定不一致");if(V=X.name===Y?X:await this.deps.renameFolder(X,Y,Q),V.name!==Y)throw Error("文件夹名称尚未与群名同步");return this.commitFolder($,V),await this.deps.grantFolderAccess(V,$,Z,Q),V}exclusive($,Z){let Q=(this.locks.get($)??Promise.resolve()).then(Z),Y=Q.then(()=>{},()=>{});return this.locks.set($,Y),Y.then(()=>{if(this.locks.get($)===Y)this.locks.delete($)}),Q}load(){if(this.state)return this.state;let $=this.deps.read();if($===void 0)return this.state={version:2,workspaces:{},groups:{}};let Z=JSON.parse($);if(![1,2].includes(Z?.version)||!Y3(Z.groups)||Z.version===2&&!Y3(Z.workspaces))throw Error("文件交付设置格式无效");let J={version:2,workspaces:{},groups:{}};for(let[Y,V]of Object.entries(Z.workspaces??{})){if(!Y3(V)||typeof V.enabled!=="boolean"||H$(Y)!==Y)throw Error("工作目录文件交付开关无效");J.workspaces[Y]={enabled:V.enabled}}for(let[Y,V]of Object.entries(Z.groups)){if(!Y||!Y3(V))throw Error("群文件夹绑定无效");let X=Z.version===1?V.enabled:V.legacyEnabled;if((Z.version===1||X!==void 0)&&typeof X!=="boolean")throw Error("群文件交付开关无效");if(X&&!V.folder)throw Error("已启用的旧群缺少文件夹绑定");if(V.folder!==void 0)yT(V.folder);J.groups[Y]={...V.folder?{folder:structuredClone(V.folder)}:{},...X===void 0?{}:{legacyEnabled:X}}}let Q=new Map;for(let[Y,V]of Object.entries(J.groups)){if(!V.folder)continue;let X=Q.get(V.folder.token);if(X!==void 0)throw Error(`云空间文件夹重复绑定到多个群:${X} / ${Y}`);Q.set(V.folder.token,Y)}return this.state=J}legacyChats($,Z){return Object.entries(this.load().groups).filter(([J,Q])=>{if(Q.legacyEnabled===void 0)return!1;if(J===$)return!0;let Y=this.deps.workDirForChat(J);return Y!==void 0&&H$(Y)===Z}).map(([J])=>J)}commitMode($,Z,J){let Q=structuredClone(this.load());Q.workspaces[Z]={enabled:J};for(let Y of this.legacyChats($,Z))delete Q.groups[Y].legacyEnabled;this.commit(Q)}commitFolder($,Z){for(let[Q,Y]of Object.entries(this.load().groups))if(Q!==$&&Y.folder?.token===Z.token)throw Error("云空间文件夹已绑定其他群,不能共用交付目录");let J=structuredClone(this.load());J.groups[$]={...J.groups[$],folder:Z},this.commit(J)}commit($){this.deps.write($),this.state=$}}function Y3($){return!!$&&typeof $==="object"&&!Array.isArray($)}function yT($){if(!Y3($)||typeof $.token!=="string"||!$.token.trim()||typeof $.name!=="string"||!$.name.trim()||typeof $.url!=="string")throw Error("群文件夹绑定无效");let Z=new URL($.url);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("群文件夹链接无效")}var j_=R(()=>{m4()});import{join as hT}from"node:path";import{readFileSync as IT}from"node:fs";function __($){return new SV($,{resolveFolder:(Z,J)=>P9.resolveFolder(Z,J),uploadFile:(Z,J,Q,Y)=>Z4.uploadFile(Z,J,Q,Y),sendCard:(Z,J)=>o($.chatId,eQ(Z),J),persist:(Z)=>r(hT(qX,`${Z.id}.json`),Z),reportError:async(Z)=>{if(j(`file delivery ${$.projectName}: ${Z}`),!await k($.chatId,Z))throw Error(Z)}})}var P9;var P_=R(()=>{Y0();W_();B_();W6();H0();b0();I();j_();m4();P9=new CV({read:()=>{try{return IT(I5,"utf8")}catch($){if($?.code==="ENOENT")return;throw $}},write:($)=>r(I5,$),workDirForChat:($)=>{let Z=[...U0].filter(([,Y])=>Y===$).map(([Y])=>Y),J=O0.get($);if(!Z.length&&J)Z.push(J);let Q=new Set(Z.map((Y)=>H$(c4(Y))));if(Q.size>1)throw Error(`旧文件交付群绑定了多个工作目录: ${$}`);return Q.values().next().value},getChatName:($,Z)=>Z4.getChatName($,Z),createFolder:($,Z)=>Z4.createFolder($,Z),getFolder:($,Z)=>Z4.getFolder($,Z),renameFolder:($,Z,J)=>Z4.renameFolder($,Z,J),grantFolderAccess:($,Z,J,Q)=>Z4.grantFolderAccess($,Z,J,Q)})});async function L_($,Z,J,Q,Y,V){let X,z="",H="";try{switch(Q.trim().toLowerCase()){case"":case"status":X=Y.get($);break;case"on":X=await Y.enable($,J),z="已开启此工作目录的云空间交付;同目录各群从下一轮任务生效。";break;case"off":X=await Y.disable($),z="此工作目录已恢复直接发送聊天附件;同目录各群从下一轮任务生效,云空间中的历史文件保留。";break;default:throw Error("用法:files、files on、files off")}}catch(K){H=K instanceof Error?K.message:String(K);try{X=Y.get($)}catch{X=void 0}}let G=$Y({groupName:Z,workDir:V,settings:X,notice:z,error:H}),W;if(!await Y.sendCard(G,(K)=>{W=K}))await Y.reportError(`❌ 文件交付设置卡发送失败:${w(W)}${H?`
299
+ 已上传文件所在文件夹:${this.snapshot.folder.url}`:""}`),[]}this.snapshot.messageId=$;try{this.save()}catch(Z){await this.deps.reportError(`❌ 交付卡已发送,但${String(Z)}`)}return this.snapshot.files.filter((Z)=>Z.status==="ready").map((Z)=>Z.path)}}var B_=()=>{};class CV{deps;state;locks=new Map;constructor($){this.deps=$}get($,Z){let J=H$(Z),Q=this.load(),Y=Q.workspaces[J]?.enabled;if(Y===void 0){let X=new Set(this.legacyChats($,J).map((z)=>Q.groups[z].legacyEnabled));if(X.size>1)throw Error("同一工作目录的旧群文件交付设置冲突,请发送 files on 或 files off 统一设置");if(X.size)Y=X.values().next().value,this.commitMode($,J,Y)}let V=this.load().groups[$]?.folder;return{enabled:Y??!1,...V?{folder:structuredClone(V)}:{}}}mode($,Z){return this.get($,Z).enabled?"drive":"chat"}enable($,Z,J){let Q=H$(Z);return this.exclusive(`workspace:${Q}`,()=>this.exclusive(`chat:${$}`,async()=>{return await this.prepare($,J,!0),this.commitMode($,Q,!0),this.get($,Z)}))}disable($,Z){let J=H$(Z);return this.exclusive(`workspace:${J}`,async()=>{return this.commitMode($,J,!1),this.get($,Z)})}resolveFolder($,Z){return this.exclusive(`chat:${$.chatId}`,()=>this.prepare($.chatId,$.managerOpenId,!0,Z))}bindExisting($,Z,J,Q){return this.exclusive(`chat:${$}`,async()=>{let Y=this.load().groups[$];if(Y?.folder&&Y.folder.token!==Q.token)throw Error("本群已经绑定其他文件夹");let V=await this.deps.getFolder(Q);return this.commitFolder($,V),await this.prepare($,J,!1),this.get($,Z)})}async prepare($,Z,J,Q){if(Q?.throwIfAborted(),!$.trim()||!Z.trim())throw Error("无法确认交付群或管理权限接收人");let Y=await this.deps.getChatName($,Q);if(!Y.trim())throw Error("群名称 MISS");let V=this.load().groups[$]?.folder;if(!V){if(!J)throw Error("本群尚未绑定云空间文件夹");V={...await this.deps.createFolder(Y,Q),name:Y},this.commitFolder($,V)}let X=await this.deps.getFolder(V,Q);if(X.token!==V.token)throw Error("云空间返回的文件夹与本群绑定不一致");if(V=X.name===Y?X:await this.deps.renameFolder(X,Y,Q),V.name!==Y)throw Error("文件夹名称尚未与群名同步");return this.commitFolder($,V),await this.deps.grantFolderAccess(V,$,Z,Q),V}exclusive($,Z){let Q=(this.locks.get($)??Promise.resolve()).then(Z),Y=Q.then(()=>{},()=>{});return this.locks.set($,Y),Y.then(()=>{if(this.locks.get($)===Y)this.locks.delete($)}),Q}load(){if(this.state)return this.state;let $=this.deps.read();if($===void 0)return this.state={version:2,workspaces:{},groups:{}};let Z=JSON.parse($);if(![1,2].includes(Z?.version)||!Y3(Z.groups)||Z.version===2&&!Y3(Z.workspaces))throw Error("文件交付设置格式无效");let J={version:2,workspaces:{},groups:{}};for(let[Y,V]of Object.entries(Z.workspaces??{})){if(!Y3(V)||typeof V.enabled!=="boolean"||H$(Y)!==Y)throw Error("工作目录文件交付开关无效");J.workspaces[Y]={enabled:V.enabled}}for(let[Y,V]of Object.entries(Z.groups)){if(!Y||!Y3(V))throw Error("群文件夹绑定无效");let X=Z.version===1?V.enabled:V.legacyEnabled;if((Z.version===1||X!==void 0)&&typeof X!=="boolean")throw Error("群文件交付开关无效");if(X&&!V.folder)throw Error("已启用的旧群缺少文件夹绑定");if(V.folder!==void 0)fT(V.folder);J.groups[Y]={...V.folder?{folder:structuredClone(V.folder)}:{},...X===void 0?{}:{legacyEnabled:X}}}let Q=new Map;for(let[Y,V]of Object.entries(J.groups)){if(!V.folder)continue;let X=Q.get(V.folder.token);if(X!==void 0)throw Error(`云空间文件夹重复绑定到多个群:${X} / ${Y}`);Q.set(V.folder.token,Y)}return this.state=J}legacyChats($,Z){return Object.entries(this.load().groups).filter(([J,Q])=>{if(Q.legacyEnabled===void 0)return!1;if(J===$)return!0;let Y=this.deps.workDirForChat(J);return Y!==void 0&&H$(Y)===Z}).map(([J])=>J)}commitMode($,Z,J){let Q=structuredClone(this.load());Q.workspaces[Z]={enabled:J};for(let Y of this.legacyChats($,Z))delete Q.groups[Y].legacyEnabled;this.commit(Q)}commitFolder($,Z){for(let[Q,Y]of Object.entries(this.load().groups))if(Q!==$&&Y.folder?.token===Z.token)throw Error("云空间文件夹已绑定其他群,不能共用交付目录");let J=structuredClone(this.load());J.groups[$]={...J.groups[$],folder:Z},this.commit(J)}commit($){this.deps.write($),this.state=$}}function Y3($){return!!$&&typeof $==="object"&&!Array.isArray($)}function fT($){if(!Y3($)||typeof $.token!=="string"||!$.token.trim()||typeof $.name!=="string"||!$.name.trim()||typeof $.url!=="string")throw Error("群文件夹绑定无效");let Z=new URL($.url);if(Z.protocol!=="https:"||Z.username||Z.password)throw Error("群文件夹链接无效")}var j_=R(()=>{m4()});import{join as hT}from"node:path";import{readFileSync as IT}from"node:fs";function __($){return new SV($,{resolveFolder:(Z,J)=>P9.resolveFolder(Z,J),uploadFile:(Z,J,Q,Y)=>Z4.uploadFile(Z,J,Q,Y),sendCard:(Z,J)=>o($.chatId,eQ(Z),J),persist:(Z)=>r(hT(qX,`${Z.id}.json`),Z),reportError:async(Z)=>{if(j(`file delivery ${$.projectName}: ${Z}`),!await k($.chatId,Z))throw Error(Z)}})}var P9;var P_=R(()=>{Y0();W_();B_();W6();H0();b0();I();j_();m4();P9=new CV({read:()=>{try{return IT(I5,"utf8")}catch($){if($?.code==="ENOENT")return;throw $}},write:($)=>r(I5,$),workDirForChat:($)=>{let Z=[...U0].filter(([,Y])=>Y===$).map(([Y])=>Y),J=O0.get($);if(!Z.length&&J)Z.push(J);let Q=new Set(Z.map((Y)=>H$(c4(Y))));if(Q.size>1)throw Error(`旧文件交付群绑定了多个工作目录: ${$}`);return Q.values().next().value},getChatName:($,Z)=>Z4.getChatName($,Z),createFolder:($,Z)=>Z4.createFolder($,Z),getFolder:($,Z)=>Z4.getFolder($,Z),renameFolder:($,Z,J)=>Z4.renameFolder($,Z,J),grantFolderAccess:($,Z,J,Q)=>Z4.grantFolderAccess($,Z,J,Q)})});async function L_($,Z,J,Q,Y,V){let X,z="",H="";try{switch(Q.trim().toLowerCase()){case"":case"status":X=Y.get($);break;case"on":X=await Y.enable($,J),z="已开启此工作目录的云空间交付;同目录各群从下一轮任务生效。";break;case"off":X=await Y.disable($),z="此工作目录已恢复直接发送聊天附件;同目录各群从下一轮任务生效,云空间中的历史文件保留。";break;default:throw Error("用法:files、files on、files off")}}catch(K){H=K instanceof Error?K.message:String(K);try{X=Y.get($)}catch{X=void 0}}let G=$Y({groupName:Z,workDir:V,settings:X,notice:z,error:H}),W;if(!await Y.sendCard(G,(K)=>{W=K}))await Y.reportError(`❌ 文件交付设置卡发送失败:${w(W)}${H?`
300
300
  设置失败:${H}`:""}`)}var q_=R(()=>{W6()});function V5($,Z="zh"){if(Z==="en")return["- After generating and checking a local file, submit it for delivery by placing `[[send: /abs/path]]` on its own line in the reply body. Replace the path with the absolute path of an existing file. Use this only when the user requests a file or you are delivering a final artifact.",...$==="chat"?["- This group delivers files as chat attachments. Check file sizes before submission: each file must be no larger than 30 MB (30 * 1024 * 1024 bytes). Losslessly compress or split larger files first, preserving all requested content."]:[]].join(`
301
301
  `);return[`- ${"生成并检查本地文件后,在回复正文中独占一行输出 `[[send: /abs/path]]` 提交交付,路径必须替换成实际存在的绝对路径。只在用户要文件或交付最终产物时使用。"}`,...$==="chat"?["- 本群通过聊天附件交付,交付前检查文件大小,单文件不超过 30 MB(30 × 1024 × 1024 字节);超限先无损压缩或分卷,保持用户要求的内容。"]:[]].join(`
302
- `)}function D_($,Z,J="zh"){if(J==="en"){let Y={codex:"- When clarification is needed, ask the user with the request_user_input tool; do not present multiple-choice questions as plain text.",claude:"- When clarification is needed, ask the user with Claude Code's built-in AskUserQuestion tool.",dsh:"- When clarification is needed, ask the user with the ask_user_question tool; do not present multiple-choice questions as plain text."};return["- Text beginning with `[file: /abs/path]` identifies an attached file at that path. Read it when relevant.",V5(Z,J),'- Lodestar generates file delivery instructions from the working directory settings. When the host later injects a "File delivery instructions update", replace all previous file delivery instructions with that update.',"- Lodestar handles uploads, permissions, and cards for local task artifacts. The agent must not call these Feishu APIs directly, read credentials or look up tokens for delivery, or depend on the Feishu CLI. Delegated agents return only file paths and descriptions; the main agent submits delivery.","- A delivery marker only submits a file; it does not prove that the upload succeeded. Treat the actual attachment, delivery card, or error issued by Lodestar as the outcome. Do not invent cloud storage links or send the same file again with other tools.","- `files`, `files on`, and `files off` are management commands that the user enters in the group, not shell commands. Do not switch delivery methods or rewrite the working directory configuration on your own.",Y[$],"- After generating an image with the image generation tool, do not add explanatory text or `[[send: ...]]`. Lodestar automatically displays the image and prompt, in a collapsible panel when supported, or as a separate image when embedding is unavailable. For images generated with scripts or file editing, use `[[send: /abs/path]]` as described above.","- Every Bash / shell command must start with the shell comment `# desc: <brief description>` on its first line, followed by the actual command. This comment only provides a summary for Lodestar cards; do not rely on it to change command behavior."].join(`
302
+ `)}function F_($,Z,J="zh"){if(J==="en"){let Y={codex:"- When clarification is needed, ask the user with the request_user_input tool; do not present multiple-choice questions as plain text.",claude:"- When clarification is needed, ask the user with Claude Code's built-in AskUserQuestion tool.",dsh:"- When clarification is needed, ask the user with the ask_user_question tool; do not present multiple-choice questions as plain text."};return["- Text beginning with `[file: /abs/path]` identifies an attached file at that path. Read it when relevant.",V5(Z,J),'- Lodestar generates file delivery instructions from the working directory settings. When the host later injects a "File delivery instructions update", replace all previous file delivery instructions with that update.',"- Lodestar handles uploads, permissions, and cards for local task artifacts. The agent must not call these Feishu APIs directly, read credentials or look up tokens for delivery, or depend on the Feishu CLI. Delegated agents return only file paths and descriptions; the main agent submits delivery.","- A delivery marker only submits a file; it does not prove that the upload succeeded. Treat the actual attachment, delivery card, or error issued by Lodestar as the outcome. Do not invent cloud storage links or send the same file again with other tools.","- `files`, `files on`, and `files off` are management commands that the user enters in the group, not shell commands. Do not switch delivery methods or rewrite the working directory configuration on your own.",Y[$],"- After generating an image with the image generation tool, do not add explanatory text or `[[send: ...]]`. Lodestar automatically displays the image and prompt, in a collapsible panel when supported, or as a separate image when embedding is unavailable. For images generated with scripts or file editing, use `[[send: /abs/path]]` as described above.","- Every Bash / shell command must start with the shell comment `# desc: <brief description>` on its first line, followed by the actual command. This comment only provides a summary for Lodestar cards; do not rely on it to change command behavior."].join(`
303
303
  `)}let Q={codex:"- 当你有问题需要澄清时,使用 request_user_input 工具向用户提问;不要把多选题写成文本。",claude:"- 当你有问题需要澄清时,使用 Claude Code 自带的 AskUserQuestion 工具向用户提问。",dsh:"- 当你有问题需要澄清时,使用 ask_user_question 工具向用户提问;不要把多选题写成文本。"};return["- 以 `[file: /abs/path]` 开头的文本表示该路径上挂着一个文件,相关时去读它。",V5(Z),"- 文件交付约定由 Lodestar 按工作目录设置生成;后续收到宿主注入的“文件交付约定更新”时,用其完整替换此前的文件交付约定。",`- ${"交付本地任务产物时,上传、权限和卡片均由 Lodestar 处理。Agent 不直接调用这些飞书接口,不为交付读取凭据或查找 token,也不依赖飞书 CLI。被委派的 Agent 只返回文件路径和说明,由主 Agent 提交交付。"}`,`- ${"交付标记只表示提交,不能据此声称上传成功。以 Lodestar 实际发出的附件、交付卡或错误提示为准,不编造云空间链接,不用其他工具重复发送。"}`,`- ${"`files`、`files on`、`files off` 是用户在群里输入的管理命令,不是 Shell 命令;不要擅自切换交付方式或改写工作目录配置。"}`,Q[$],...gT].join(`
304
- `)}function F_($,Z="zh"){if(Z==="en")return`[Lodestar File delivery instructions update]
304
+ `)}function D_($,Z="zh"){if(Z==="en")return`[Lodestar File delivery instructions update]
305
305
  Starting with this turn, the following instructions fully replace the previous file delivery instructions:
306
306
  ${V5($,Z)}`;return`[Lodestar 文件交付约定更新]
307
307
  以下约定从本轮起完整替换此前的文件交付约定:
308
- ${V5($)}`}var gT;var xV=R(()=>{gT=["- 使用图片生成工具生成图片后,不要再补充说明文字或 `[[send: ...]]`;Lodestar 会自动展示图片和提示词,支持时放进折叠面板,无法嵌入时单独发送。若你用脚本或文件编辑生成图片,按上一条用 `[[send: /abs/path]]` 发出。","- 每次调用 Bash / shell 命令时,第一行都必须写 shell 注释 `# desc: <一句中文说明>`,再写真正命令。这个注释只给 Lodestar 卡片做摘要,不要依赖它改变命令行为。"]});function J4($){return _7(D1($.sessionName)??$.sessionName)}function L9($){return c4(J4($))}function U_($){return c4($.sessionName)}function O_($,Z,J=$.currentProvider()){let Q=$.selectedModel??($.selectedTokenSourceId?M0($.selectedTokenSourceId)?.defaultModel:void 0),Y=J==="claude"&&i1($.selectedTokenSourceId,Q),V=D_(J,Z,Y?"en":"zh"),X=V3($);return X?`${V}
308
+ ${V5($)}`}var gT;var xV=R(()=>{gT=["- 使用图片生成工具生成图片后,不要再补充说明文字或 `[[send: ...]]`;Lodestar 会自动展示图片和提示词,支持时放进折叠面板,无法嵌入时单独发送。若你用脚本或文件编辑生成图片,按上一条用 `[[send: /abs/path]]` 发出。","- 每次调用 Bash / shell 命令时,第一行都必须写 shell 注释 `# desc: <一句中文说明>`,再写真正命令。这个注释只给 Lodestar 卡片做摘要,不要依赖它改变命令行为。"]});function J4($){return _7(F1($.sessionName)??$.sessionName)}function L9($){return c4(J4($))}function U_($){return c4($.sessionName)}function O_($,Z,J=$.currentProvider()){let Q=$.selectedModel??($.selectedTokenSourceId?M0($.selectedTokenSourceId)?.defaultModel:void 0),Y=J==="claude"&&i1($.selectedTokenSourceId,Q),V=F_(J,Z,Y?"en":"zh"),X=V3($);return X?`${V}
309
309
  ${X}`:V}function A_($,Z){return V3($)??""}function bV($){return V3($)?"已载入wt特殊约定":null}function N_($,Z){let J=bV($);return J?`${Z}
310
310
  ${J}`:Z}function V3($){let Z=J4($),J=WG($.workDir,L9($),Z);if(!J)return null;return[`你要把下面这份额外的工作树约定视为和AGENTS.md一样重要。来源文件:${J.path}`,"",`# Additional AGENTS.md instructions for ${$.workDir}`,"","<INSTRUCTIONS>",J.content,"</INSTRUCTIONS>"].join(`
311
311
  `)}async function R_($,Z,J){if(!Z){await kV($);return}let Q=x2(Z);if(!Q){await k($.chatId,"❌ 名称无效。用英文/数字/._-,最长 63。");return}if(!J){await k($.chatId,"❌ 找不到发起人,不能拉群。");return}let Y=J4($),V=L9($);try{await j7(V,async()=>{let X;try{X=BG(V,Y,Q)}catch(z){await k($.chatId,`❌ wt 失败: ${E(z)}`);return}try{let z=await cJ(X.chatName,J),H=z.created?"已创建":z.joined?"已加入":"已在群内",G;if(!await o($.chatId,i8({slug:Q,branch:X.branch,status:H}),(_)=>{G=_}))await h($.chatId,`❌ wt 卡片失败: ${Q}
@@ -313,55 +313,55 @@ ${w(G)}`);let K;if(!await o(z.chatId,i8({slug:Q,branch:X.branch,status:"就绪",
313
313
  ${w(K)}`)}catch(z){await k($.chatId,`❌ wt 已建,拉群失败: ${E(z)}`)}})}catch(X){await k($.chatId,`❌ wt 失败: ${E(X)}`)}}async function T_($,Z){let J=J4($),Q=L9($);return await j7(Q,async()=>{return await mT(J,Q,Z)})}async function mT($,Z,J){let Q=KG(Z,$),Y=Q.filter((z)=>z.state==="merged"&&!z.mounted).length,V=Q.filter((z)=>z.state!=="merged"||z.mounted),X=await R7();return kY({projectName:$,projectDir:Z,hiddenMergedUnmountedCount:Y,notice:J,entries:V.map((z)=>{let H=X.get(z.chatName)??[],G=U0.get(z.chatName),W=G&&H.includes(G)?G:H.length===1?H[0]:null;return{slug:z.slug,chatName:z.chatName,branch:z.branch,state:z.state,path:z.worktreePath??z.expectedPath,mounted:z.mounted,dirtyCount:z.dirtyCount,statusLine:z.statusLine,error:z.error,chatId:W,duplicateChatCount:H.length}})})}async function kV($){try{let Z=await T_($),J;if(!await o($.chatId,Z,(Y)=>{J=Y}))await h($.chatId,`❌ wt 列表失败
314
314
  ${w(J)}`)}catch(Z){await k($.chatId,`❌ wt 列表失败: ${E(Z)}`)}}async function M_($,Z,J,Q){try{return{ok:Z,message:J,card:await T_($,{type:Q,content:J})}}catch(Y){let V=`列表刷新失败: ${E(Y)}`;return j(`session "${$.sessionName}": wt action panel refresh failed: ${E(Y)}`),{ok:!1,message:`${J}
315
315
  ${V}`,card:i8({slug:"wt",branch:"work/*",status:J,body:V,template:"red"})}}}async function E_($,Z){let J=x2(Z);if(!J)return M_($,!1,"❌ 名称无效","error");let Q=J4($),Y=L9($),V;try{V=await j7(Y,async()=>{let X=I4(Q,J);if($.hasRunningPeerSession(X))return{ok:!1,message:`❌ 解散 ${J} 失败: Codex 正在运行,请先在 ${X} 群里 stop 或 kill。`,type:"error"};HJ(Y,Q,J);let z=await lJ(X),H=jG(Y,Q,J);return{ok:!0,message:[`✅ ${J} 已解散`,H.removedWorktree?"dir removed":"dir missing",z.disbanded?"group removed":"group missing",H.branch].join(`
316
- `),type:"success"}})}catch(X){V={ok:!1,message:`❌ 解散 ${J} 失败: ${E(X)}`,type:"error"}}return M_($,V.ok,V.message,V.type)}var S_=R(()=>{X0();xV();b8();S$();Y0();I();jJ()});import{closeSync as cT,openSync as uT,readSync as lT,readdirSync as dT,statSync as iT}from"node:fs";import{randomUUID as vV}from"node:crypto";import{join as nT}from"node:path";function z5($){return D1($.sessionName)??$.sessionName}function x_($){let Z=yJ($,wV);return wV.add(Z),Z}function b_($){wV.delete($)}function q9($){let Z=C_.get($);if(!Z)Z=new Map,C_.set($,Z);let J=Date.now();for(let[Q,Y]of Z){let V=Y.status==="consumed"?sT:oT,X=Y.consumedAt??Y.createdAt;if(J-X>V)Z.delete(Q)}return Z}function rT($,Z){return $.provider===Z.provider&&($.codexAccountId??"default")===(Z.codexAccountId??"default")&&!!$.codexAccountAutomatic===!!Z.codexAccountAutomatic&&$.tokenSourceId===Z.tokenSourceId&&$.model===Z.model&&$.effort===Z.effort}function k_($,Z,J,Q){let Y={id:vV(),mode:Z,requesterOpenId:J,provider:$.selectedProvider,sourceSessionId:$.lastSessionId,workDir:$.workDir,baseName:z5($),routing:$.conversationRouting(),createdAt:Date.now(),status:"open",choices:Q};return q9($).set(Y.id,Y),Y}function fV($,Z,J,Q,Y){let V=q9($).get(J);if(!V||V.mode!==Z)return{error:"这张选择卡已过期,请重新发送命令"};if(!Y||V.requesterOpenId!==Y)return{error:"只有打开这张选择卡的用户可以执行;请自行发送命令重新打开"};if(V.status!=="open")return{error:"这张选择卡已执行或正在处理,请勿重复点击"};if(V.provider!==$.selectedProvider||V.workDir!==$.workDir||V.sourceSessionId!==$.lastSessionId||!rT(V.routing,$.conversationRouting()))return{error:"这张卡对应的 provider、目录或源会话已经变化,请重新发送命令"};let X=V.choices.get(Q);if(!X)return{error:"无效的选择项,这张卡可能已过期"};return V.status="processing",{panel:V,choice:X}}function X5($){$.status="consumed",$.consumedAt=Date.now()}function eT($){return{kind:"fork",source:$.source,through:$}}function $E($){return l4($.sessionName).filter((Z)=>Z.checkpoint.provider===$.selectedProvider&&Z.checkpoint.source.cwd===$.workDir)}function ZE($){let Z=d4($.sessionName);if(Z===null||Z.kind==="fresh")return Z;try{return E0(Z,$.selectedProvider,$.workDir),Z}catch{return null}}function JE($){let Z=Y7($),J;try{J=dT(Z)}catch(Y){if(Y?.code==="ENOENT")return[];throw Error(`读取 Claude 会话目录失败: ${Y?.message??Y}`)}let Q=[];for(let Y of J){if(!Y.endsWith(".jsonl"))continue;let V=Y.slice(0,-6);if(N4("claude",V))continue;let X=nT(Z,Y),z;try{z=iT(X).mtimeMs}catch(H){throw Error(`读取 Claude 会话元数据失败 (${Y}): ${H?.message??H}`)}Q.push({provider:"claude",sessionId:V,cwd:$,preview:YE(X),ts:z})}return Q.sort((Y,V)=>V.ts-Y.ts)}function QE($){let Z=$.slice().sort((Y,V)=>V.ts-Y.ts),J=Date.now()-aT,Q=Z.filter((Y)=>Y.ts>=J).length;return Z.slice(0,Math.min(tT,Math.max(10,Q)))}function YE($){let Z="",J=null;try{J=uT($,"r");let Y=Buffer.alloc(65536),V=lT(J,Y,0,65536,0);Z=Y.subarray(0,V).toString("utf8")}catch(Y){throw Error(`读取 Claude 会话摘要失败 (${$}): ${Y?.message??Y}`)}finally{if(J!==null)cT(J)}let Q="";for(let Y of Z.split(`
316
+ `),type:"success"}})}catch(X){V={ok:!1,message:`❌ 解散 ${J} 失败: ${E(X)}`,type:"error"}}return M_($,V.ok,V.message,V.type)}var S_=R(()=>{X0();xV();b8();S$();Y0();I();jJ()});import{closeSync as cT,openSync as uT,readSync as lT,readdirSync as dT,statSync as iT}from"node:fs";import{randomUUID as vV}from"node:crypto";import{join as nT}from"node:path";function z5($){return F1($.sessionName)??$.sessionName}function x_($){let Z=fJ($,wV);return wV.add(Z),Z}function b_($){wV.delete($)}function q9($){let Z=C_.get($);if(!Z)Z=new Map,C_.set($,Z);let J=Date.now();for(let[Q,Y]of Z){let V=Y.status==="consumed"?sT:oT,X=Y.consumedAt??Y.createdAt;if(J-X>V)Z.delete(Q)}return Z}function rT($,Z){return $.provider===Z.provider&&($.codexAccountId??"default")===(Z.codexAccountId??"default")&&!!$.codexAccountAutomatic===!!Z.codexAccountAutomatic&&$.tokenSourceId===Z.tokenSourceId&&$.model===Z.model&&$.effort===Z.effort}function k_($,Z,J,Q){let Y={id:vV(),mode:Z,requesterOpenId:J,provider:$.selectedProvider,sourceSessionId:$.lastSessionId,workDir:$.workDir,baseName:z5($),routing:$.conversationRouting(),createdAt:Date.now(),status:"open",choices:Q};return q9($).set(Y.id,Y),Y}function yV($,Z,J,Q,Y){let V=q9($).get(J);if(!V||V.mode!==Z)return{error:"这张选择卡已过期,请重新发送命令"};if(!Y||V.requesterOpenId!==Y)return{error:"只有打开这张选择卡的用户可以执行;请自行发送命令重新打开"};if(V.status!=="open")return{error:"这张选择卡已执行或正在处理,请勿重复点击"};if(V.provider!==$.selectedProvider||V.workDir!==$.workDir||V.sourceSessionId!==$.lastSessionId||!rT(V.routing,$.conversationRouting()))return{error:"这张卡对应的 provider、目录或源会话已经变化,请重新发送命令"};let X=V.choices.get(Q);if(!X)return{error:"无效的选择项,这张卡可能已过期"};return V.status="processing",{panel:V,choice:X}}function X5($){$.status="consumed",$.consumedAt=Date.now()}function eT($){return{kind:"fork",source:$.source,through:$}}function $E($){return l4($.sessionName).filter((Z)=>Z.checkpoint.provider===$.selectedProvider&&Z.checkpoint.source.cwd===$.workDir)}function ZE($){let Z=d4($.sessionName);if(Z===null||Z.kind==="fresh")return Z;try{return E0(Z,$.selectedProvider,$.workDir),Z}catch{return null}}function JE($){let Z=Y7($),J;try{J=dT(Z)}catch(Y){if(Y?.code==="ENOENT")return[];throw Error(`读取 Claude 会话目录失败: ${Y?.message??Y}`)}let Q=[];for(let Y of J){if(!Y.endsWith(".jsonl"))continue;let V=Y.slice(0,-6);if(N4("claude",V))continue;let X=nT(Z,Y),z;try{z=iT(X).mtimeMs}catch(H){throw Error(`读取 Claude 会话元数据失败 (${Y}): ${H?.message??H}`)}Q.push({provider:"claude",sessionId:V,cwd:$,preview:YE(X),ts:z})}return Q.sort((Y,V)=>V.ts-Y.ts)}function QE($){let Z=$.slice().sort((Y,V)=>V.ts-Y.ts),J=Date.now()-aT,Q=Z.filter((Y)=>Y.ts>=J).length;return Z.slice(0,Math.min(tT,Math.max(10,Q)))}function YE($){let Z="",J=null;try{J=uT($,"r");let Y=Buffer.alloc(65536),V=lT(J,Y,0,65536,0);Z=Y.subarray(0,V).toString("utf8")}catch(Y){throw Error(`读取 Claude 会话摘要失败 (${$}): ${Y?.message??Y}`)}finally{if(J!==null)cT(J)}let Q="";for(let Y of Z.split(`
317
317
  `)){let V=Y.trim();if(!V)continue;let X;try{X=JSON.parse(V)}catch{continue}if(X.type==="queue-operation"&&X.operation==="enqueue"&&typeof X.content==="string"){let z=X.content.trim();if(z)return z.slice(0,80)}if(!Q&&X.type==="user"&&X.message){let z=VE(X.message);if(z)Q=z}}return Q.slice(0,80)}function VE($){let Z=$?.content;if(typeof Z==="string")return Z;if(!Array.isArray(Z))return"";for(let J of Z)if(J?.type==="text"&&typeof J.text==="string")return J.text;return""}async function w_($,Z,J){if(!J){await k($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let Q=$E($),Y=ZE($),V=new Map,X=[];for(let K=0;K<Q.length;K++){let B=Q[K];if(K===0&&Y===null)continue;let _=vV(),P=K===0?Y:eT(Q[K-1].checkpoint);V.set(_,{kind:Z,launch:P,branchBase:Y,seedAnchors:Q.slice(0,K),writes:Q.slice(K).flatMap((L)=>L.writes)}),X.push({choiceId:_,preview:B.preview,ts:B.ts})}X.reverse();let z=k_($,Z,J,V),H=vY({projectName:z5($),panelId:z.id,mode:Z,entries:X}),G,W;try{G=await o($.chatId,H,(K)=>{W=K})}catch(K){throw q9($).delete(z.id),K}if(!G)q9($).delete(z.id),await h($.chatId,`❌ ${Z==="fork"?"fk":"bk"} 列表发送失败
318
- ${w(W)}`)}function v_($,Z){return w_($,"fork",Z)}function f_($,Z){return w_($,"back",Z)}async function y_($,Z){if(!Z){await k($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let J;try{J=$.selectedProvider==="codex"?await $.listCodexConversations():$.selectedProvider==="dsh"?await $.listDshConversations():JE($.workDir)}catch(G){await h($.chatId,`❌ 历史会话读取失败: ${G instanceof Error?G.message:G}`);return}let Q=new Map,Y=QE(J).map((G)=>{let W=vV();return Q.set(W,{kind:"resume",launch:{kind:"fork",source:{provider:G.provider,sessionId:G.sessionId,cwd:G.cwd}},sourcePreview:G.preview,sourceTs:G.ts,sourceStatus:G.status}),{choiceId:W,preview:G.preview,ts:G.ts}}),V=k_($,"resume",Z,Q),X=fY({projectName:z5($),panelId:V.id,entries:Y}),z,H;try{z=await o($.chatId,X,(G)=>{H=G})}catch(G){throw q9($).delete(V.id),G}if(!z)q9($).delete(V.id),await h($.chatId,`❌ rs 历史列表发送失败
319
- ${w(H)}`)}async function h_($,Z){if(!Z){await k($.chatId,"❌ 找不到发起人,无法建临时群。");return}if(!$.opts.onCreateTempSession){await k($.chatId,"❌ 临时群能力未就绪(daemon 未注入回调)。");return}let J=x_(z5($));await k($.chatId,`\uD83D\uDE80 正在创建 ${J} · ${$.backendLabel()} 新会话。它与当前群共享工作目录;当前会话不受影响。`);let Q;try{Q=await $.opts.onCreateTempSession({chatName:J,userOpenId:Z,workDir:$.workDir,routing:$.conversationRouting(),launch:{kind:"fresh"},branchBase:{kind:"fresh"},seedAnchors:[]})}finally{b_(J)}if(!Q.ok){await k($.chatId,`❌ 建临时会话失败: ${Q.error??"未知"}`);return}await k($.chatId,`✅ 已创建 ${J}。临时群不会自动删除;在该群发送 bye 可停止并解散。`)}async function I_($){if(!D1($.sessionName)){await k($.chatId,"❌ bye 只能在带 *MMDD-HHMM 后缀的临时会话群里使用。");return}if(!$.opts.onDisbandTempSession){await k($.chatId,"❌ 解散能力未就绪(daemon 未注入回调)。");return}await k($.chatId,`\uD83D\uDC4B 正在停止会话并解散 ${$.sessionName}…`);let Z=await $.opts.onDisbandTempSession($.sessionName,$.chatId);if(!Z.ok)await k($.chatId,`❌ 解散失败: ${Z.error??"未知"}`)}async function g_($,Z,J,Q){let Y=fV($,"fork",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;try{if(X.kind!=="fork")return{ok:!1,message:"选择项类型不匹配"};if(!$.opts.onCreateTempSession)return{ok:!1,message:"临时群能力未就绪"};let z=x_(V.baseName);j(`session-temp: fork ${$.sessionName} → ${z} (${X.launch.kind})`),await k($.chatId,`\uD83D\uDD31 正在分叉到 ${z}…`);let H;try{H=await $.opts.onCreateTempSession({chatName:z,userOpenId:Q,workDir:V.workDir,routing:V.routing,launch:X.launch,branchBase:X.branchBase,seedAnchors:X.seedAnchors})}finally{b_(z)}if(!H.ok)return{ok:!1,message:`分叉失败: ${H.error??"未知"}`};return{ok:!0,message:`已分叉到 ${z};原会话和磁盘文件未回滚`}}catch(z){return{ok:!1,message:`分叉失败: ${z instanceof Error?z.message:z}`}}finally{X5(V)}}async function m_($,Z,J,Q){let Y=fV($,"back",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;try{if(X.kind!=="back")return{ok:!1,message:"选择项类型不匹配"};let z="";try{let W;if(!await o($.chatId,yY({projectName:V.baseName,entries:X.writes}),(B)=>{W=B}))z=`;文件变更记录卡发送失败: ${w(W)}`}catch(W){z=`;文件变更记录卡发送失败: ${w(W)}`}if(j(`session-temp: back ${$.sessionName} (${X.launch.kind}, writes=${X.writes.length})`),!await $.rollbackTo(X.launch,{anchors:X.seedAnchors,base:X.branchBase}))return{ok:!1,message:`回退失败;原会话绑定未改,请检查日志后重试${z}`};if(V.routing.provider==="claude")return{ok:!0,message:`本群已准备 Claude 新分支;发送下一条消息时生成并接入,旧会话未删除,磁盘文件未回滚${z}`};return{ok:!0,message:`本群已改接新会话${$.lastSessionId?` ${h0($.lastSessionId)}`:""};旧会话未删除,磁盘文件未回滚${z}`}}catch(z){return{ok:!1,message:`回退失败: ${z instanceof Error?z.message:z}`}}finally{X5(V)}}async function p_($,Z,J,Q){let Y=fV($,"resume",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;if(X.kind!=="resume")throw X5(V),Error("resume panel contained a non-resume choice");let z=X.launch.source.sessionId,H=$.lastSessionId,G=(K,B)=>({projectName:V.baseName,provider:X.launch.source.provider,selectedPreview:X.sourcePreview,selectedTs:X.sourceTs,sourceSessionId:z,...X.sourceStatus?{sourceStatus:X.sourceStatus}:{},previousSessionId:H,newSessionId:K,bindingState:B}),W=(K,B,_,P=null)=>({ok:K,message:B,resumePresentation:G(P,_)});try{if($.isRunning())return W(!1,"当前群已经启动了新进程;为避免误杀,请先停止后重新发送 rs","unchanged");if(X.sourceStatus==="active")return W(!1,"所选 Codex 会话仍在运行;请先在原位置停止后再创建完整分支","unchanged");if(j(`session-temp: history fork ${$.sessionName} ← ${X.launch.source.provider} ${z}`),!await $.rollbackTo(X.launch,{anchors:[],base:X.launch,pendingLaunch:X.launch.source.provider==="claude"?{launch:X.launch,previousSessionId:H}:null}))return W(!1,"历史分支创建失败;原会话绑定未改,请检查日志后重试","unchanged");if(X.launch.source.provider==="claude")return W(!0,"Claude 独立分支已准备;首条消息时生成并接入新会话","prepared");let B=$.lastSessionId;if(!B)return W(!1,"历史分支已启动,但后端没有返回新会话 id","unknown");if(B===z||H&&B===H)return W(!1,"后端没有返回独立的新会话 id;为避免误判,本次不标记为恢复成功","unknown",B);return W(!0,"已创建并接入独立分支;源会话未修改","changed",B)}catch(K){return W(!1,`历史分支创建失败: ${K instanceof Error?K.message:K}`,"unknown")}finally{X5(V)}}var aT=86400000,oT=1800000,sT=3600000,tT=40,C_,wV;var c_=R(()=>{Y0();S$();I();v4();y9();K2();C_=new WeakMap,wV=new Set});import{existsSync as u_}from"node:fs";import{randomBytes as yV,randomUUID as zE,timingSafeEqual as HE}from"node:crypto";import{isAbsolute as GE}from"node:path";function IV($,Z=new Set){if($ instanceof P2)return $;if(!$||typeof $!=="object"&&typeof $!=="function"||Z.has($))return null;if(Z.add($),$ instanceof AggregateError)for(let J of $.errors){let Q=IV(J,Z);if(Q)return Q}if($ instanceof Error&&$.cause!==void 0)return IV($.cause,Z);return null}function WE($){return $.itemId||$.turnId||"__latest__"}function l_($){let Z=[];if($.itemId)Z.push(`item:${$.itemId}`);if($.turnId)Z.push(`turn:${$.threadId??$.sessionId??"-"}:${$.turnId}`);return Z}function KE($){let Z=null;for(let J of $.contextCompactionPending.keys())Z=J;return Z}function BE($,Z){if(!$)return Z;return{...$,...Z,phase:"end"}}function W5(){return g.runtime?.live_elapsed??"bucket"}function n_($,Z){return`${$} (${V9(Date.now()-Z,W5()).label})`}function D9($){return $.length?$.map((Z)=>`${Z.operation}: ${w(Z)}`).join(`
320
- `):w(void 0)}function qE($,Z){let J=Z?.apiMessage??Z?.message??"MISS";for(let Q of[Z?.cardId,Z?.elementId,Z?.targetElementId])if(Q)J=J.split(Q).join("<id>");return J=J.replace(/^cardkit\s+\S+\s+\S+\s+HTTP\s+\d+:\s*/i,"").replace(/\s+log_id=\S+/gi,"").replace(/\s+/g," ").trim(),`${$??"MISS"}:${Z?.httpStatus??"MISS"}:${J}`}var d_="Thinking...",jE="Writing...",_E="Working...",hV=1e4,H5=720000,PE=50,LE=256,G5=1e4,i_=250,g$;var OV=R(()=>{y9();F8();P0();j1();mQ();P0();k0();b8();tQ();rY();X0();F0();Q9();v4();U1();S$();Y0();I();H0();NY();z$();J9();iB();zQ();$V();eB();Bj();Cj();o6();kj();CQ();vj();uj();ej();H_();P_();q_();xV();S_();c_();K2();g$=class g${sessionName;chatId;opts;static all=new Set;proc=null;lifecycleTail=Promise.resolve();lifecycleSequence=0;procEpoch=0;stoppingProc=null;blockedProc=null;blockedProcReason=null;agentCapability=null;procSourceRevisions=new WeakMap;procFileDeliveryModes=new WeakMap;procPendingFileDeliveryModes=new WeakMap;procFileDeliveryNeedsUpdate=new WeakSet;currentTurn=null;contextCompactionReceipts=new Map;contextCompactionOwnerIds=new WeakMap;contextCompactionOwnerSequence=0;lastManualContextCompactionCompletedAt=0;lastManualContextCompactionWasAnonymous=!1;backgroundTasks=[];pendingBgTasks=[];agentCards;backgroundOwner=yV(16).toString("hex");backgroundRefreshTimer=null;backgroundSync=null;backgroundWriteError=null;lastMainTaskToolUseId=null;nativeAgentTools=new Map;bgResumePending=!1;orphanAssistantSegments=[];orphanAssistantCurrent="";bgResumeCardless=!1;pendingPermissions=new Map;pendingAsks=new Map;currentGoal=null;status="stopped";pendingUserMessageCount=0;pendingMidTurnMsgs=[];steeringSend=null;steeringGeneration=0;submittedSteering=new Map;steeringBoundary=null;pendingTurnInputs=[];multiMsgBuffer=null;multiMsgReactions=new Map;lastUserOpenId="";pendingReactionIds=new Map;currentBatchReactionIds=new Map;initCount=0;openingTurn=!1;openingTurnOwner=null;turnOpenSequence=0;turnCloseInflight=new Set;fileDeliveries=new Set;turnCounter=0;userInterrupted=!1;lastSessionId=null;lastSessionRef=null;selectedProvider="claude";selectedModel=null;selectedEffort=null;selectedTokenSourceId=null;modelPanels=new Map;modelSettingsChange=null;modelSettingsChangesClosed=!1;modelCustomPrompt=null;startedAt=0;cumStats={tokens:0,costUsd:0,turns:0};lastTurnDelta=null;currentTurnUsageBaseline=null;currentTurnUsageBaselineKnown=!1;lastTurnUsage=null;usageTotalsSeedUnknown=!1;resumePersistenceError=null;daemonRestoreRequired=!1;manualContextCompactionPending=!1;taskBoard=[];constructor($,Z,J={}){this.sessionName=$;this.chatId=Z;this.opts=J;this.agentCards=J.agentCards??dB(),g$.all.add(this);let Q=IJ($);this.selectedProvider=Q?.provider??"claude",this.selectedModel=Q?.model??null,this.selectedEffort=Q?.effort??null,this.selectedTokenSourceId=this.deriveTokenSourceId(Q);let Y=M0(this.selectedTokenSourceId);if(Y){if(this.selectedProvider=Y.agent,Y.id==="glm"&&this.selectedModel==="claude:glm")this.selectedModel=Y.defaultModel,this.selectedEffort="max"}if(this.selectedModel)j(`session "${$}": restored selected provider=${this.selectedProvider} model=${this.selectedModel} effort=${this.selectedEffort??"unset"}`);if(this.lastSessionRef=c1($,this.selectedProvider),this.lastSessionId=this.lastSessionRef?.sessionId??null,this.lastSessionId)j(`session "${$}": restored ${this.selectedProvider} lastSessionId=${this.lastSessionId}`);let V=i4($);if(V)if(this.selectedProvider!=="claude")W$($,[],null,null),j(`session "${$}": cleared pending Claude fork after provider changed`);else{E0(V.launch,"claude",this.workDir);let X=this.lastSessionId===V.previousSessionId,z=this.lastSessionRef,H=!X&&z?.provider==="claude"&&z.cwd===this.workDir&&z.sessionId!==V.launch.source.sessionId&&z.sessionId!==V.previousSessionId;if(!X&&!H)throw Error(`pending Claude fork has inconsistent resume binding for session "${$}"`);this.pendingConversationMaterialization=V,j(`session "${$}": restored ${H?"materialized":"pending"} Claude fork source=${V.launch.source.sessionId}`)}}peerSnapshot(){return{name:this.sessionName,status:this.status,uptimeMs:this.startedAt?Date.now()-this.startedAt:void 0,...this.proc?.isAlive()&&this.proc.provider==="codex"&&!this.currentTokenSource()?.codexApiProvider&&this.proc.codexAccountSelectionMode?.()!==null&&!(this.proc.turnRetry?.reason==="quota"&&this.proc.turnRetry.phase==="waiting")?{codexAccountName:v.get(M$(this.proc)).name}:{}}}get workDir(){return U_(this)}isRunning(){return!!this.proc&&this.proc.isAlive()}shouldRevive(){return this.daemonRestoreRequired||this.isRunning()&&this.stoppingProc!==this.proc&&this.blockedProc!==this.proc}deriveTokenSourceId($){let Z=$?.tokenSourceId;if(typeof Z==="string"&&Z.trim())return Z.trim();let J=$?.provider??this.selectedProvider;return wZ(J)[0]?.id??null}currentTokenSource(){return this.tokenSource(this.selectedTokenSourceId)}codexStartAccountOverride;codexAccountId(){return this.proc?.isAlive()&&this.proc.provider==="codex"?M$(this.proc):this.codexStartAccountOverride??v.selected(this.sessionName)}tokenSource($){let Z=M0($);return Z?.forAccount?j0($,this.codexAccountId()):Z}currentProvider(){return this.selectedProvider}conversationRouting(){let $=!!this.currentTokenSource()?.codexApiProvider;return{provider:this.selectedProvider,tokenSourceId:this.selectedTokenSourceId,model:this.selectedModel,effort:this.selectedEffort,...$||this.codexAccountId()===d?{}:{codexAccountId:this.codexAccountId()},...!$&&v.preferred(this.sessionName)===null?{codexAccountAutomatic:!0}:{}}}applyConversationRouting($){if(this.isRunning()||this.currentTurn||this.openingTurn)throw Error("cannot change conversation routing while the session is running");let Z=M0($.tokenSourceId);if($.codexAccountId&&!Z?.codexApiProvider)v.get($.codexAccountId);if(Z&&Z.agent!==$.provider)throw Error(`token source "${Z.id}" belongs to ${Z.agent}, not ${$.provider}`);if(this.selectedProvider!==$.provider)W$(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;if(this.selectedProvider=$.provider,this.selectedTokenSourceId=$.tokenSourceId,this.selectedModel=$.model,this.selectedEffort=$.effort,this.lastSessionRef=c1(this.sessionName,$.provider),this.lastSessionId=this.lastSessionRef?.sessionId??null,l1(this.sessionName,$.provider,$.model,$.effort,$.tokenSourceId),!Z?.codexApiProvider){let J=$.codexAccountId??d;if($.codexAccountAutomatic)v.selectAuto(this.sessionName);else if(v.selected(this.sessionName)!==J)v.select(this.sessionName,J)}}dshEffortForSpawn(){if(S0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource(),Z=$&&n$($,this.selectedModel??$.defaultModel);if(!Z||!S0(Z.defaultEffort))throw Error("DSH model reasoning effort is unavailable");return Z.defaultEffort}async listDshConversations(){if(this.selectedProvider!=="dsh")throw Error("DSH history requested under a different provider");let $=this.currentTokenSource();if(!$?.enabled||$.agent!=="dsh")throw Error("DSH token source is unavailable");return(await r4({cwd:this.workDir,env:$.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"session/list",{cwd:this.workDir})).filter((J)=>!N4("dsh",J.sessionId))}async listCodexConversations(){if(this.selectedProvider!=="codex")throw Error("Codex history requested for a non-Codex session");let $=this.currentTokenSource();if(!$?.codexApiProvider&&!_8(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");if(this.selectedTokenSourceId&&(!$||!$.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Z=$?.enabled?$:void 0,J=Z?(z)=>Z.spawnEnv(z):void 0,Q=new E4({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Z?.id??null,transformEnv:J,...Z?.codexApiProvider?{apiProvider:Z.codexApiProvider}:{}}),Y=null,V=null;try{Y=await Q.listConversations()}catch(z){V=z}let X=null;try{await Q.kill(2000)}catch(z){X=z}if(V&&X)throw AggregateError([V,X],`Codex history query and cleanup failed: ${E(V)}; ${E(X)}`);if(V)throw V;if(X)throw X;return Y??[]}async resolveLegacyResumeRef($){if($.cwd!==null)return $;if($.provider!==this.selectedProvider)throw Error(`legacy resume provider mismatch: ${$.provider} != ${this.selectedProvider}`);let Z;if($.provider==="dsh")throw Error("DSH resume reference requires its original cwd");else if($.provider==="claude"){let J=V7(this.workDir,$.sessionId);if(!u_(J))throw Error(`旧 Claude 会话不属于当前 cwd,或 transcript 不存在: ${h0($.sessionId)}`);Z={...$,cwd:this.workDir}}else{let J=this.currentTokenSource();if(!J?.codexApiProvider&&!_8(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");if(this.selectedTokenSourceId&&(!J||!J.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Q=J?.enabled?J:void 0,Y=new E4({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Q?.id??null,transformEnv:Q?(z)=>Q.spawnEnv(z):void 0,...Q?.codexApiProvider?{apiProvider:Q.codexApiProvider}:{}}),V=null;try{Z=await Y.readConversationRef($.sessionId)}catch(z){V=z,Z=$}let X=null;try{await Y.kill(2000)}catch(z){X=z}if(V&&X)throw AggregateError([V,X],`Codex legacy resume lookup and cleanup failed: read=${E(V)}; cleanup=${E(X)}`);if(V)throw V;if(X)throw X}return E0({kind:"resume",source:Z},this.selectedProvider,this.workDir),W8(this.sessionName,Z),Z}hasRunningPeerSession($){return[...g$.all].some((Z)=>Z.sessionName===$&&Z.isRunning())}modelForSpawn(){if(this.selectedProvider==="codex")return;return this.selectedModel??void 0}effortForSpawn(){if(this.selectedProvider==="codex"){let $=this.currentTokenSource();if(!$||!$.enabled&&$.id!=="codex-sub")return;return U$(this.selectedEffort)?this.selectedEffort:g9}return g9}claudeEffortForSpawn(){if(this.selectedProvider==="claude"&&w0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude"){let Z=n$($,this.selectedModel??$.defaultModel);if(!w0(Z?.defaultEffort))throw Error("Claude 默认 effort MISS,请通过 model 面板明确选择");return Z.defaultEffort}return h1}currentModelLabel(){if(this.modelSettingsChange?.proc===this.proc&&this.modelSettingsChange.phase==="failed")return this.modelSettingsChange.confirmedModel;return(this.selectedModel??this.currentTokenSource()?.defaultModel??this.proc?.lastModel??null)?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null}currentEffortLabel(){if(this.modelSettingsChange?.proc===this.proc&&this.modelSettingsChange.phase==="failed")return this.modelSettingsChange.confirmedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude")return this.selectedEffort??n$($,this.selectedModel??$.defaultModel)?.defaultEffort??null;return this.selectedEffort??(this.selectedProvider==="dsh"?this.dshEffortForSpawn():void 0)??this.proc?.lastEffort??(this.selectedProvider==="claude"?h1:g9)}runtimeModelSelection(){let $=this.proc?.isAlive()?this.proc:null,Z=$?.provider??this.selectedProvider;if($&&this.modelSettingsChange?.proc===$&&this.modelSettingsChange.phase==="failed")return{provider:Z,model:this.modelSettingsChange.confirmedModel,effort:this.modelSettingsChange.confirmedEffort};let J=!$||$.provider===this.selectedProvider,Q=($?.lastModel??(J?this.currentModelLabel():null))?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null,Y=$?.lastEffort??(J?this.currentEffortLabel():Z==="claude"?h1:g9);return{provider:Z,model:Q,effort:Y}}withModel($,Z){let J=this.modelLine(Z);return $.includes(J)?$:`${$} · ${J}`}async replaceFooterContent($,Z){let J;return{landed:await D0($,C.footer,this.footerElement(Z),{notifyCardFailure:!1,onFailure:(Y)=>{J=Y}}),failure:J}}footerElement($){return{tag:"markdown",element_id:C.footer,content:$.trim()||" "}}modelLine($=this.currentTurn??this.runtimeModelSelection()){return JY($.provider,$.model,$.effort)}backendLabel($=this.selectedProvider){return t0($)}pendingConversationLaunch=null;codexQuotaWaitLaunch=null;pendingConversationMaterialization=null;lastTurnUserPreview="";pendingCodexTurnAnchors=[];pendingMaterializationLaunch(){let $=this.pendingConversationMaterialization;if(!$)return null;if(E0($.launch,"claude",this.workDir),this.selectedProvider!=="claude")throw Error("pending Claude fork cannot launch under a non-Claude provider");if(this.lastSessionId===$.previousSessionId)return $.launch;let Z=this.lastSessionRef;if(Z?.provider==="claude"&&Z.cwd===this.workDir&&Z.sessionId!==$.launch.source.sessionId&&Z.sessionId!==$.previousSessionId)return{kind:"resume",source:Z};throw Error("pending Claude fork has no safe launch target")}spawnAgent($,Z){this.agentCapability=yV(32).toString("base64url");let J={LODESTAR_AGENT_URL:z9(g.notify.bind,g.notify.port),LODESTAR_AGENT_CAPABILITY:this.agentCapability,LODESTAR_AGENT_SESSION:this.sessionName,LODESTAR_AGENT_ROLE:"main"},Q=Z??this.pendingConversationLaunch??this.pendingMaterializationLaunch()??($?{kind:"resume",source:$}:{kind:"fresh"});E0(Q,this.selectedProvider,this.workDir);let Y=this.currentTokenSource(),V=this.selectedProvider==="codex"&&this.selectedTokenSourceId==="codex-sub";if(this.selectedTokenSourceId&&(!Y||!Y.enabled&&!V))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或在 model 面板选择其他账号`);let X=Y?.enabled||V?Y:void 0,z=this.currentTurn?.fileDeliveryMode??this.getFileDeliveryMode(),H=k8({provider:this.selectedProvider,workDir:this.workDir,tokenSourceId:X?.id??null,...this.selectedProvider==="codex"?{codexAccountId:v.selected(this.sessionName)}:{},...V?{codexAccountPreference:this.codexStartAccountOverride??v.preferred(this.sessionName)}:{},model:X?this.selectedModel??X.defaultModel:this.modelForSpawn(),effort:this.selectedProvider==="dsh"?this.dshEffortForSpawn():this.selectedProvider==="claude"?this.claudeEffortForSpawn():this.effortForSpawn(),launch:Q,developerInstructions:this.spawnDeveloperInstructions(z),profile:z8(this.workDir),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:G4},hostEnv:J});return this.procSourceRevisions.set(H.process,H.sourceRevision),this.procFileDeliveryModes.set(H.process,z),H.process}async applyModelSelection($,Z,J,Q){await this.runLifecycle("apply-model-selection",()=>this.applyModelSelectionUnlocked($,Z,J,Q))}async applyModelSelectionUnlocked($,Z,J,Q){let Y=this.selectedProvider,V=Q??this.selectedTokenSourceId,X=M0(V),z=X?Z||null:$==="codex"?null:Z,H=X?J??n$(X,Z||X.defaultModel)?.defaultEffort??null:$==="codex"?null:J;await this.stopIdleMismatchedProcessUnlocked($,V,z,H);let G=Y!==$?{anchors:l4(this.sessionName).slice(),base:d4(this.sessionName),pending:i4(this.sessionName)}:null;if(G)W$(this.sessionName,[],null,null);try{l1(this.sessionName,$,z,H,V)}catch(W){if(G)try{W$(this.sessionName,G.anchors,G.base,G.pending)}catch(K){throw AggregateError([W,K],`model selection write failed: ${E(W)}; conversation state restore failed: ${E(K)}`)}throw W}if(G)this.pendingConversationMaterialization=null;if($!=="codex"||V!=="codex-sub")this.codexQuotaWaitLaunch=null;this.selectedProvider=$,this.selectedTokenSourceId=V,this.selectedModel=z,this.selectedEffort=H,this.lastSessionRef=c1(this.sessionName,$),this.lastSessionId=this.lastSessionRef?.sessionId??null}async stopIdleMismatchedProcess(){await this.runLifecycle("stop-idle-mismatched",()=>this.stopIdleMismatchedProcessUnlocked())}processSourceMatches($,Z){if(this.proc?.quotaWaitPromise&&!this.proc.sessionId&&this.proc.turnRetry?.reason==="quota")return!0;if(this.proc?.sourceRevision)return this.proc.sourceRevision()===C4($,Z);return!this.proc||!this.procSourceRevisions.has(this.proc)||this.procSourceRevisions.get(this.proc)===C4($,Z)}modelSelectionNeedsProcessStop($=this.selectedProvider,Z=this.selectedTokenSourceId,J=this.selectedModel,Q=this.selectedEffort){let Y=this.proc;return!!Y?.isAlive()&&(this.blockedProc===Y||Y.provider!==$||Y.tokenSourceId!==Z||$==="claude"&&Y.provider==="claude"&&v$(Y)!==i1(Z,J??this.tokenSource(Z)?.defaultModel)||$==="claude"&&Y.provider==="claude"&&Q!==null&&(Y.lastEffort??this.selectedEffort)==="default"!==(Q==="default")||!this.processSourceMatches(this.tokenSource(Z),J))}async stopIdleMismatchedProcessUnlocked($=this.selectedProvider,Z=this.selectedTokenSourceId,J=this.selectedModel,Q=this.selectedEffort){if(!this.proc||!this.modelSelectionNeedsProcessStop($,Z,J,Q))return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return;let Y=this.proc;j(`session "${this.sessionName}": stop idle ${Y.provider} process before switching to ${$}`),this.beginProcStop(Y),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let V=await this.settleProcResumableState(Y),X=null;try{await Y.kill()}catch(G){X=G}V=await this.settleProcResumableState(Y);let z=this.finishProcStop(Y,X);this.opts.onLifecycleChange?.();let H=[...X?[X]:!z?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...V?[Error(V)]:[]];if(H.length===1)throw H[0];if(H.length>1)throw AggregateError(H,`idle process stop failed: ${H.map(E).join("; ")}`)}async stopIdleCurrentProcess($){return await this.runLifecycle("stop-idle-current",()=>this.stopIdleCurrentProcessUnlocked($))}async stopIdleCurrentProcessUnlocked($){if(!this.proc?.isAlive())return!1;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return!1;let Z=this.proc;j(`session "${this.sessionName}": stop idle ${Z.provider} process: ${$}`),this.beginProcStop(Z),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let J=await this.settleProcResumableState(Z),Q=null;try{await Z.kill()}catch(X){Q=X}J=await this.settleProcResumableState(Z);let Y=this.finishProcStop(Z,Q);this.opts.onLifecycleChange?.();let V=[...Q?[Q]:!Y?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...J?[Error(J)]:[]];if(V.length===1)throw V[0];if(V.length>1)throw AggregateError(V,`idle process stop failed: ${V.map(E).join("; ")}`);return!0}startFooterTimer($,Z,J=(Q)=>Q){let Q=Date.now(),Y=Z,V=!1,X=!1,z=!1,H=!1,G=null,W=()=>{if(V)return;if(X){H=!0;return}X=!0,H=!1;let B=Y;this.replaceFooterContent($,J(n_(Y,Q))).then((_)=>{if(X=!1,V)return;if(_.landed){if(H)W();return}if(z=!0,G)clearTimeout(G);if(G=null,H&&Y!==B)W()})},K=()=>{if(V||z)return;let{nextDelayMs:B}=V9(Date.now()-Q,W5());G=setTimeout(()=>{W(),K()},Math.max(1,Math.ceil(B)))};return W(),K(),{setStatus(B){if(B===Y)return;Y=B,W()},stop(){if(V=!0,G)clearTimeout(G)},elapsedSec(){return(Date.now()-Q)/1000}}}async openStatusCard($,Z,J="blue"){let Q=Date.now(),Y=RY({sessionName:this.sessionName,title:$,status:n_(Z,Q),template:J}),V,X=await o(this.chatId,Y,(H)=>{V=H});if(!X)return j(`session "${this.sessionName}": status card send failed title=${$}`),await h(this.chatId,`❌ 创建状态卡片失败: ${$}
318
+ ${w(W)}`)}function v_($,Z){return w_($,"fork",Z)}function y_($,Z){return w_($,"back",Z)}async function f_($,Z){if(!Z){await k($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let J;try{J=$.selectedProvider==="codex"?await $.listCodexConversations():$.selectedProvider==="dsh"?await $.listDshConversations():JE($.workDir)}catch(G){await h($.chatId,`❌ 历史会话读取失败: ${G instanceof Error?G.message:G}`);return}let Q=new Map,Y=QE(J).map((G)=>{let W=vV();return Q.set(W,{kind:"resume",launch:{kind:"fork",source:{provider:G.provider,sessionId:G.sessionId,cwd:G.cwd}},sourcePreview:G.preview,sourceTs:G.ts,sourceStatus:G.status}),{choiceId:W,preview:G.preview,ts:G.ts}}),V=k_($,"resume",Z,Q),X=yY({projectName:z5($),panelId:V.id,entries:Y}),z,H;try{z=await o($.chatId,X,(G)=>{H=G})}catch(G){throw q9($).delete(V.id),G}if(!z)q9($).delete(V.id),await h($.chatId,`❌ rs 历史列表发送失败
319
+ ${w(H)}`)}async function h_($,Z){if(!Z){await k($.chatId,"❌ 找不到发起人,无法建临时群。");return}if(!$.opts.onCreateTempSession){await k($.chatId,"❌ 临时群能力未就绪(daemon 未注入回调)。");return}let J=x_(z5($));await k($.chatId,`\uD83D\uDE80 正在创建 ${J} · ${$.backendLabel()} 新会话。它与当前群共享工作目录;当前会话不受影响。`);let Q;try{Q=await $.opts.onCreateTempSession({chatName:J,userOpenId:Z,workDir:$.workDir,routing:$.conversationRouting(),launch:{kind:"fresh"},branchBase:{kind:"fresh"},seedAnchors:[]})}finally{b_(J)}if(!Q.ok){await k($.chatId,`❌ 建临时会话失败: ${Q.error??"未知"}`);return}await k($.chatId,`✅ 已创建 ${J}。临时群不会自动删除;在该群发送 bye 可停止并解散。`)}async function I_($){if(!F1($.sessionName)){await k($.chatId,"❌ bye 只能在带 *MMDD-HHMM 后缀的临时会话群里使用。");return}if(!$.opts.onDisbandTempSession){await k($.chatId,"❌ 解散能力未就绪(daemon 未注入回调)。");return}await k($.chatId,`\uD83D\uDC4B 正在停止会话并解散 ${$.sessionName}…`);let Z=await $.opts.onDisbandTempSession($.sessionName,$.chatId);if(!Z.ok)await k($.chatId,`❌ 解散失败: ${Z.error??"未知"}`)}async function g_($,Z,J,Q){let Y=yV($,"fork",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;try{if(X.kind!=="fork")return{ok:!1,message:"选择项类型不匹配"};if(!$.opts.onCreateTempSession)return{ok:!1,message:"临时群能力未就绪"};let z=x_(V.baseName);j(`session-temp: fork ${$.sessionName} → ${z} (${X.launch.kind})`),await k($.chatId,`\uD83D\uDD31 正在分叉到 ${z}…`);let H;try{H=await $.opts.onCreateTempSession({chatName:z,userOpenId:Q,workDir:V.workDir,routing:V.routing,launch:X.launch,branchBase:X.branchBase,seedAnchors:X.seedAnchors})}finally{b_(z)}if(!H.ok)return{ok:!1,message:`分叉失败: ${H.error??"未知"}`};return{ok:!0,message:`已分叉到 ${z};原会话和磁盘文件未回滚`}}catch(z){return{ok:!1,message:`分叉失败: ${z instanceof Error?z.message:z}`}}finally{X5(V)}}async function m_($,Z,J,Q){let Y=yV($,"back",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;try{if(X.kind!=="back")return{ok:!1,message:"选择项类型不匹配"};let z="";try{let W;if(!await o($.chatId,fY({projectName:V.baseName,entries:X.writes}),(B)=>{W=B}))z=`;文件变更记录卡发送失败: ${w(W)}`}catch(W){z=`;文件变更记录卡发送失败: ${w(W)}`}if(j(`session-temp: back ${$.sessionName} (${X.launch.kind}, writes=${X.writes.length})`),!await $.rollbackTo(X.launch,{anchors:X.seedAnchors,base:X.branchBase}))return{ok:!1,message:`回退失败;原会话绑定未改,请检查日志后重试${z}`};if(V.routing.provider==="claude")return{ok:!0,message:`本群已准备 Claude 新分支;发送下一条消息时生成并接入,旧会话未删除,磁盘文件未回滚${z}`};return{ok:!0,message:`本群已改接新会话${$.lastSessionId?` ${h0($.lastSessionId)}`:""};旧会话未删除,磁盘文件未回滚${z}`}}catch(z){return{ok:!1,message:`回退失败: ${z instanceof Error?z.message:z}`}}finally{X5(V)}}async function p_($,Z,J,Q){let Y=yV($,"resume",Z,J,Q);if("error"in Y)return{ok:!1,message:Y.error,replaceCard:!1};let{panel:V,choice:X}=Y;if(X.kind!=="resume")throw X5(V),Error("resume panel contained a non-resume choice");let z=X.launch.source.sessionId,H=$.lastSessionId,G=(K,B)=>({projectName:V.baseName,provider:X.launch.source.provider,selectedPreview:X.sourcePreview,selectedTs:X.sourceTs,sourceSessionId:z,...X.sourceStatus?{sourceStatus:X.sourceStatus}:{},previousSessionId:H,newSessionId:K,bindingState:B}),W=(K,B,_,P=null)=>({ok:K,message:B,resumePresentation:G(P,_)});try{if($.isRunning())return W(!1,"当前群已经启动了新进程;为避免误杀,请先停止后重新发送 rs","unchanged");if(X.sourceStatus==="active")return W(!1,"所选 Codex 会话仍在运行;请先在原位置停止后再创建完整分支","unchanged");if(j(`session-temp: history fork ${$.sessionName} ← ${X.launch.source.provider} ${z}`),!await $.rollbackTo(X.launch,{anchors:[],base:X.launch,pendingLaunch:X.launch.source.provider==="claude"?{launch:X.launch,previousSessionId:H}:null}))return W(!1,"历史分支创建失败;原会话绑定未改,请检查日志后重试","unchanged");if(X.launch.source.provider==="claude")return W(!0,"Claude 独立分支已准备;首条消息时生成并接入新会话","prepared");let B=$.lastSessionId;if(!B)return W(!1,"历史分支已启动,但后端没有返回新会话 id","unknown");if(B===z||H&&B===H)return W(!1,"后端没有返回独立的新会话 id;为避免误判,本次不标记为恢复成功","unknown",B);return W(!0,"已创建并接入独立分支;源会话未修改","changed",B)}catch(K){return W(!1,`历史分支创建失败: ${K instanceof Error?K.message:K}`,"unknown")}finally{X5(V)}}var aT=86400000,oT=1800000,sT=3600000,tT=40,C_,wV;var c_=R(()=>{Y0();S$();I();v4();f9();K2();C_=new WeakMap,wV=new Set});import{existsSync as u_}from"node:fs";import{randomBytes as fV,randomUUID as zE,timingSafeEqual as HE}from"node:crypto";import{isAbsolute as GE}from"node:path";function IV($,Z=new Set){if($ instanceof P2)return $;if(!$||typeof $!=="object"&&typeof $!=="function"||Z.has($))return null;if(Z.add($),$ instanceof AggregateError)for(let J of $.errors){let Q=IV(J,Z);if(Q)return Q}if($ instanceof Error&&$.cause!==void 0)return IV($.cause,Z);return null}function WE($){return $.itemId||$.turnId||"__latest__"}function l_($){let Z=[];if($.itemId)Z.push(`item:${$.itemId}`);if($.turnId)Z.push(`turn:${$.threadId??$.sessionId??"-"}:${$.turnId}`);return Z}function KE($){let Z=null;for(let J of $.contextCompactionPending.keys())Z=J;return Z}function BE($,Z){if(!$)return Z;return{...$,...Z,phase:"end"}}function W5(){return g.runtime?.live_elapsed??"bucket"}function n_($,Z){return`${$} (${V9(Date.now()-Z,W5()).label})`}function F9($){return $.length?$.map((Z)=>`${Z.operation}: ${w(Z)}`).join(`
320
+ `):w(void 0)}function qE($,Z){let J=Z?.apiMessage??Z?.message??"MISS";for(let Q of[Z?.cardId,Z?.elementId,Z?.targetElementId])if(Q)J=J.split(Q).join("<id>");return J=J.replace(/^cardkit\s+\S+\s+\S+\s+HTTP\s+\d+:\s*/i,"").replace(/\s+log_id=\S+/gi,"").replace(/\s+/g," ").trim(),`${$??"MISS"}:${Z?.httpStatus??"MISS"}:${J}`}var d_="Thinking...",jE="Writing...",_E="Working...",hV=1e4,H5=720000,PE=50,LE=256,G5=1e4,i_=250,g$;var OV=R(()=>{f9();D8();P0();j1();mQ();P0();k0();b8();tQ();rY();X0();D0();Q9();v4();U1();S$();Y0();I();H0();NY();z$();J9();iB();zQ();$V();eB();Bj();Cj();o6();kj();CQ();vj();uj();ej();H_();P_();q_();xV();S_();c_();K2();g$=class g${sessionName;chatId;opts;static all=new Set;proc=null;lifecycleTail=Promise.resolve();lifecycleSequence=0;procEpoch=0;stoppingProc=null;blockedProc=null;blockedProcReason=null;agentCapability=null;procSourceRevisions=new WeakMap;procFileDeliveryModes=new WeakMap;procPendingFileDeliveryModes=new WeakMap;procFileDeliveryNeedsUpdate=new WeakSet;currentTurn=null;contextCompactionReceipts=new Map;contextCompactionOwnerIds=new WeakMap;contextCompactionOwnerSequence=0;lastManualContextCompactionCompletedAt=0;lastManualContextCompactionWasAnonymous=!1;backgroundTasks=[];pendingBgTasks=[];agentCards;backgroundOwner=fV(16).toString("hex");backgroundRefreshTimer=null;backgroundSync=null;backgroundWriteError=null;lastMainTaskToolUseId=null;nativeAgentTools=new Map;bgResumePending=!1;orphanAssistantSegments=[];orphanAssistantCurrent="";bgResumeCardless=!1;pendingPermissions=new Map;pendingAsks=new Map;currentGoal=null;status="stopped";pendingUserMessageCount=0;pendingMidTurnMsgs=[];steeringSend=null;steeringGeneration=0;submittedSteering=new Map;steeringBoundary=null;pendingTurnInputs=[];multiMsgBuffer=null;multiMsgReactions=new Map;lastUserOpenId="";pendingReactionIds=new Map;currentBatchReactionIds=new Map;initCount=0;openingTurn=!1;openingTurnOwner=null;turnOpenSequence=0;turnCloseInflight=new Set;fileDeliveries=new Set;turnCounter=0;userInterrupted=!1;lastSessionId=null;lastSessionRef=null;selectedProvider="claude";selectedModel=null;selectedEffort=null;selectedTokenSourceId=null;modelPanels=new Map;modelSettingsChange=null;modelSettingsChangesClosed=!1;modelCustomPrompt=null;startedAt=0;cumStats={tokens:0,costUsd:0,turns:0};lastTurnDelta=null;currentTurnUsageBaseline=null;currentTurnUsageBaselineKnown=!1;lastTurnUsage=null;usageTotalsSeedUnknown=!1;resumePersistenceError=null;daemonRestoreRequired=!1;manualContextCompactionPending=!1;taskBoard=[];constructor($,Z,J={}){this.sessionName=$;this.chatId=Z;this.opts=J;this.agentCards=J.agentCards??dB(),g$.all.add(this);let Q=IJ($);this.selectedProvider=Q?.provider??"claude",this.selectedModel=Q?.model??null,this.selectedEffort=Q?.effort??null,this.selectedTokenSourceId=this.deriveTokenSourceId(Q);let Y=M0(this.selectedTokenSourceId);if(Y){if(this.selectedProvider=Y.agent,Y.id==="glm"&&this.selectedModel==="claude:glm")this.selectedModel=Y.defaultModel,this.selectedEffort="max"}if(this.selectedModel)j(`session "${$}": restored selected provider=${this.selectedProvider} model=${this.selectedModel} effort=${this.selectedEffort??"unset"}`);if(this.lastSessionRef=c1($,this.selectedProvider),this.lastSessionId=this.lastSessionRef?.sessionId??null,this.lastSessionId)j(`session "${$}": restored ${this.selectedProvider} lastSessionId=${this.lastSessionId}`);let V=i4($);if(V)if(this.selectedProvider!=="claude")W$($,[],null,null),j(`session "${$}": cleared pending Claude fork after provider changed`);else{E0(V.launch,"claude",this.workDir);let X=this.lastSessionId===V.previousSessionId,z=this.lastSessionRef,H=!X&&z?.provider==="claude"&&z.cwd===this.workDir&&z.sessionId!==V.launch.source.sessionId&&z.sessionId!==V.previousSessionId;if(!X&&!H)throw Error(`pending Claude fork has inconsistent resume binding for session "${$}"`);this.pendingConversationMaterialization=V,j(`session "${$}": restored ${H?"materialized":"pending"} Claude fork source=${V.launch.source.sessionId}`)}}peerSnapshot(){return{name:this.sessionName,status:this.status,uptimeMs:this.startedAt?Date.now()-this.startedAt:void 0,...this.proc?.isAlive()&&this.proc.provider==="codex"&&!this.currentTokenSource()?.codexApiProvider&&this.proc.codexAccountSelectionMode?.()!==null&&!(this.proc.turnRetry?.reason==="quota"&&this.proc.turnRetry.phase==="waiting")?{codexAccountName:v.get(M$(this.proc)).name}:{}}}get workDir(){return U_(this)}isRunning(){return!!this.proc&&this.proc.isAlive()}shouldRevive(){return this.daemonRestoreRequired||this.isRunning()&&this.stoppingProc!==this.proc&&this.blockedProc!==this.proc}deriveTokenSourceId($){let Z=$?.tokenSourceId;if(typeof Z==="string"&&Z.trim())return Z.trim();let J=$?.provider??this.selectedProvider;return wZ(J)[0]?.id??null}currentTokenSource(){return this.tokenSource(this.selectedTokenSourceId)}codexStartAccountOverride;codexAccountId(){return this.proc?.isAlive()&&this.proc.provider==="codex"?M$(this.proc):this.codexStartAccountOverride??v.selected(this.sessionName)}tokenSource($){let Z=M0($);return Z?.forAccount?j0($,this.codexAccountId()):Z}currentProvider(){return this.selectedProvider}conversationRouting(){let $=!!this.currentTokenSource()?.codexApiProvider;return{provider:this.selectedProvider,tokenSourceId:this.selectedTokenSourceId,model:this.selectedModel,effort:this.selectedEffort,...$||this.codexAccountId()===d?{}:{codexAccountId:this.codexAccountId()},...!$&&v.preferred(this.sessionName)===null?{codexAccountAutomatic:!0}:{}}}applyConversationRouting($){if(this.isRunning()||this.currentTurn||this.openingTurn)throw Error("cannot change conversation routing while the session is running");let Z=M0($.tokenSourceId);if($.codexAccountId&&!Z?.codexApiProvider)v.get($.codexAccountId);if(Z&&Z.agent!==$.provider)throw Error(`token source "${Z.id}" belongs to ${Z.agent}, not ${$.provider}`);if(this.selectedProvider!==$.provider)W$(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;if(this.selectedProvider=$.provider,this.selectedTokenSourceId=$.tokenSourceId,this.selectedModel=$.model,this.selectedEffort=$.effort,this.lastSessionRef=c1(this.sessionName,$.provider),this.lastSessionId=this.lastSessionRef?.sessionId??null,l1(this.sessionName,$.provider,$.model,$.effort,$.tokenSourceId),!Z?.codexApiProvider){let J=$.codexAccountId??d;if($.codexAccountAutomatic)v.selectAuto(this.sessionName);else if(v.selected(this.sessionName)!==J)v.select(this.sessionName,J)}}dshEffortForSpawn(){if(S0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource(),Z=$&&n$($,this.selectedModel??$.defaultModel);if(!Z||!S0(Z.defaultEffort))throw Error("DSH model reasoning effort is unavailable");return Z.defaultEffort}async listDshConversations(){if(this.selectedProvider!=="dsh")throw Error("DSH history requested under a different provider");let $=this.currentTokenSource();if(!$?.enabled||$.agent!=="dsh")throw Error("DSH token source is unavailable");return(await r4({cwd:this.workDir,env:$.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"session/list",{cwd:this.workDir})).filter((J)=>!N4("dsh",J.sessionId))}async listCodexConversations(){if(this.selectedProvider!=="codex")throw Error("Codex history requested for a non-Codex session");let $=this.currentTokenSource();if(!$?.codexApiProvider&&!_8(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");if(this.selectedTokenSourceId&&(!$||!$.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Z=$?.enabled?$:void 0,J=Z?(z)=>Z.spawnEnv(z):void 0,Q=new E4({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Z?.id??null,transformEnv:J,...Z?.codexApiProvider?{apiProvider:Z.codexApiProvider}:{}}),Y=null,V=null;try{Y=await Q.listConversations()}catch(z){V=z}let X=null;try{await Q.kill(2000)}catch(z){X=z}if(V&&X)throw AggregateError([V,X],`Codex history query and cleanup failed: ${E(V)}; ${E(X)}`);if(V)throw V;if(X)throw X;return Y??[]}async resolveLegacyResumeRef($){if($.cwd!==null)return $;if($.provider!==this.selectedProvider)throw Error(`legacy resume provider mismatch: ${$.provider} != ${this.selectedProvider}`);let Z;if($.provider==="dsh")throw Error("DSH resume reference requires its original cwd");else if($.provider==="claude"){let J=V7(this.workDir,$.sessionId);if(!u_(J))throw Error(`旧 Claude 会话不属于当前 cwd,或 transcript 不存在: ${h0($.sessionId)}`);Z={...$,cwd:this.workDir}}else{let J=this.currentTokenSource();if(!J?.codexApiProvider&&!_8(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");if(this.selectedTokenSourceId&&(!J||!J.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Q=J?.enabled?J:void 0,Y=new E4({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Q?.id??null,transformEnv:Q?(z)=>Q.spawnEnv(z):void 0,...Q?.codexApiProvider?{apiProvider:Q.codexApiProvider}:{}}),V=null;try{Z=await Y.readConversationRef($.sessionId)}catch(z){V=z,Z=$}let X=null;try{await Y.kill(2000)}catch(z){X=z}if(V&&X)throw AggregateError([V,X],`Codex legacy resume lookup and cleanup failed: read=${E(V)}; cleanup=${E(X)}`);if(V)throw V;if(X)throw X}return E0({kind:"resume",source:Z},this.selectedProvider,this.workDir),W8(this.sessionName,Z),Z}hasRunningPeerSession($){return[...g$.all].some((Z)=>Z.sessionName===$&&Z.isRunning())}modelForSpawn(){if(this.selectedProvider==="codex")return;return this.selectedModel??void 0}effortForSpawn(){if(this.selectedProvider==="codex"){let $=this.currentTokenSource();if(!$||!$.enabled&&$.id!=="codex-sub")return;return U$(this.selectedEffort)?this.selectedEffort:g9}return g9}claudeEffortForSpawn(){if(this.selectedProvider==="claude"&&w0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude"){let Z=n$($,this.selectedModel??$.defaultModel);if(!w0(Z?.defaultEffort))throw Error("Claude 默认 effort MISS,请通过 model 面板明确选择");return Z.defaultEffort}return h1}currentModelLabel(){if(this.modelSettingsChange?.proc===this.proc&&this.modelSettingsChange.phase==="failed")return this.modelSettingsChange.confirmedModel;return(this.selectedModel??this.currentTokenSource()?.defaultModel??this.proc?.lastModel??null)?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null}currentEffortLabel(){if(this.modelSettingsChange?.proc===this.proc&&this.modelSettingsChange.phase==="failed")return this.modelSettingsChange.confirmedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude")return this.selectedEffort??n$($,this.selectedModel??$.defaultModel)?.defaultEffort??null;return this.selectedEffort??(this.selectedProvider==="dsh"?this.dshEffortForSpawn():void 0)??this.proc?.lastEffort??(this.selectedProvider==="claude"?h1:g9)}runtimeModelSelection(){let $=this.proc?.isAlive()?this.proc:null,Z=$?.provider??this.selectedProvider;if($&&this.modelSettingsChange?.proc===$&&this.modelSettingsChange.phase==="failed")return{provider:Z,model:this.modelSettingsChange.confirmedModel,effort:this.modelSettingsChange.confirmedEffort};let J=!$||$.provider===this.selectedProvider,Q=($?.lastModel??(J?this.currentModelLabel():null))?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null,Y=$?.lastEffort??(J?this.currentEffortLabel():Z==="claude"?h1:g9);return{provider:Z,model:Q,effort:Y}}withModel($,Z){let J=this.modelLine(Z);return $.includes(J)?$:`${$} · ${J}`}async replaceFooterContent($,Z){let J;return{landed:await F0($,C.footer,this.footerElement(Z),{notifyCardFailure:!1,onFailure:(Y)=>{J=Y}}),failure:J}}footerElement($){return{tag:"markdown",element_id:C.footer,content:$.trim()||" "}}modelLine($=this.currentTurn??this.runtimeModelSelection()){return JY($.provider,$.model,$.effort)}backendLabel($=this.selectedProvider){return t0($)}pendingConversationLaunch=null;codexQuotaWaitLaunch=null;pendingConversationMaterialization=null;lastTurnUserPreview="";pendingCodexTurnAnchors=[];pendingMaterializationLaunch(){let $=this.pendingConversationMaterialization;if(!$)return null;if(E0($.launch,"claude",this.workDir),this.selectedProvider!=="claude")throw Error("pending Claude fork cannot launch under a non-Claude provider");if(this.lastSessionId===$.previousSessionId)return $.launch;let Z=this.lastSessionRef;if(Z?.provider==="claude"&&Z.cwd===this.workDir&&Z.sessionId!==$.launch.source.sessionId&&Z.sessionId!==$.previousSessionId)return{kind:"resume",source:Z};throw Error("pending Claude fork has no safe launch target")}spawnAgent($,Z){this.agentCapability=fV(32).toString("base64url");let J={LODESTAR_AGENT_URL:z9(g.notify.bind,g.notify.port),LODESTAR_AGENT_CAPABILITY:this.agentCapability,LODESTAR_AGENT_SESSION:this.sessionName,LODESTAR_AGENT_ROLE:"main"},Q=Z??this.pendingConversationLaunch??this.pendingMaterializationLaunch()??($?{kind:"resume",source:$}:{kind:"fresh"});E0(Q,this.selectedProvider,this.workDir);let Y=this.currentTokenSource(),V=this.selectedProvider==="codex"&&this.selectedTokenSourceId==="codex-sub";if(this.selectedTokenSourceId&&(!Y||!Y.enabled&&!V))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或在 model 面板选择其他账号`);let X=Y?.enabled||V?Y:void 0,z=this.currentTurn?.fileDeliveryMode??this.getFileDeliveryMode(),H=k8({provider:this.selectedProvider,workDir:this.workDir,tokenSourceId:X?.id??null,...this.selectedProvider==="codex"?{codexAccountId:v.selected(this.sessionName)}:{},...V?{codexAccountPreference:this.codexStartAccountOverride??v.preferred(this.sessionName)}:{},model:X?this.selectedModel??X.defaultModel:this.modelForSpawn(),effort:this.selectedProvider==="dsh"?this.dshEffortForSpawn():this.selectedProvider==="claude"?this.claudeEffortForSpawn():this.effortForSpawn(),launch:Q,developerInstructions:this.spawnDeveloperInstructions(z),profile:z8(this.workDir),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:G4},hostEnv:J});return this.procSourceRevisions.set(H.process,H.sourceRevision),this.procFileDeliveryModes.set(H.process,z),H.process}async applyModelSelection($,Z,J,Q){await this.runLifecycle("apply-model-selection",()=>this.applyModelSelectionUnlocked($,Z,J,Q))}async applyModelSelectionUnlocked($,Z,J,Q){let Y=this.selectedProvider,V=Q??this.selectedTokenSourceId,X=M0(V),z=X?Z||null:$==="codex"?null:Z,H=X?J??n$(X,Z||X.defaultModel)?.defaultEffort??null:$==="codex"?null:J;await this.stopIdleMismatchedProcessUnlocked($,V,z,H);let G=Y!==$?{anchors:l4(this.sessionName).slice(),base:d4(this.sessionName),pending:i4(this.sessionName)}:null;if(G)W$(this.sessionName,[],null,null);try{l1(this.sessionName,$,z,H,V)}catch(W){if(G)try{W$(this.sessionName,G.anchors,G.base,G.pending)}catch(K){throw AggregateError([W,K],`model selection write failed: ${E(W)}; conversation state restore failed: ${E(K)}`)}throw W}if(G)this.pendingConversationMaterialization=null;if($!=="codex"||V!=="codex-sub")this.codexQuotaWaitLaunch=null;this.selectedProvider=$,this.selectedTokenSourceId=V,this.selectedModel=z,this.selectedEffort=H,this.lastSessionRef=c1(this.sessionName,$),this.lastSessionId=this.lastSessionRef?.sessionId??null}async stopIdleMismatchedProcess(){await this.runLifecycle("stop-idle-mismatched",()=>this.stopIdleMismatchedProcessUnlocked())}processSourceMatches($,Z){if(this.proc?.quotaWaitPromise&&!this.proc.sessionId&&this.proc.turnRetry?.reason==="quota")return!0;if(this.proc?.sourceRevision)return this.proc.sourceRevision()===C4($,Z);return!this.proc||!this.procSourceRevisions.has(this.proc)||this.procSourceRevisions.get(this.proc)===C4($,Z)}modelSelectionNeedsProcessStop($=this.selectedProvider,Z=this.selectedTokenSourceId,J=this.selectedModel,Q=this.selectedEffort){let Y=this.proc;return!!Y?.isAlive()&&(this.blockedProc===Y||Y.provider!==$||Y.tokenSourceId!==Z||$==="claude"&&Y.provider==="claude"&&v$(Y)!==i1(Z,J??this.tokenSource(Z)?.defaultModel)||$==="claude"&&Y.provider==="claude"&&Q!==null&&(Y.lastEffort??this.selectedEffort)==="default"!==(Q==="default")||!this.processSourceMatches(this.tokenSource(Z),J))}async stopIdleMismatchedProcessUnlocked($=this.selectedProvider,Z=this.selectedTokenSourceId,J=this.selectedModel,Q=this.selectedEffort){if(!this.proc||!this.modelSelectionNeedsProcessStop($,Z,J,Q))return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return;let Y=this.proc;j(`session "${this.sessionName}": stop idle ${Y.provider} process before switching to ${$}`),this.beginProcStop(Y),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let V=await this.settleProcResumableState(Y),X=null;try{await Y.kill()}catch(G){X=G}V=await this.settleProcResumableState(Y);let z=this.finishProcStop(Y,X);this.opts.onLifecycleChange?.();let H=[...X?[X]:!z?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...V?[Error(V)]:[]];if(H.length===1)throw H[0];if(H.length>1)throw AggregateError(H,`idle process stop failed: ${H.map(E).join("; ")}`)}async stopIdleCurrentProcess($){return await this.runLifecycle("stop-idle-current",()=>this.stopIdleCurrentProcessUnlocked($))}async stopIdleCurrentProcessUnlocked($){if(!this.proc?.isAlive())return!1;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return!1;let Z=this.proc;j(`session "${this.sessionName}": stop idle ${Z.provider} process: ${$}`),this.beginProcStop(Z),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let J=await this.settleProcResumableState(Z),Q=null;try{await Z.kill()}catch(X){Q=X}J=await this.settleProcResumableState(Z);let Y=this.finishProcStop(Z,Q);this.opts.onLifecycleChange?.();let V=[...Q?[Q]:!Y?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...J?[Error(J)]:[]];if(V.length===1)throw V[0];if(V.length>1)throw AggregateError(V,`idle process stop failed: ${V.map(E).join("; ")}`);return!0}startFooterTimer($,Z,J=(Q)=>Q){let Q=Date.now(),Y=Z,V=!1,X=!1,z=!1,H=!1,G=null,W=()=>{if(V)return;if(X){H=!0;return}X=!0,H=!1;let B=Y;this.replaceFooterContent($,J(n_(Y,Q))).then((_)=>{if(X=!1,V)return;if(_.landed){if(H)W();return}if(z=!0,G)clearTimeout(G);if(G=null,H&&Y!==B)W()})},K=()=>{if(V||z)return;let{nextDelayMs:B}=V9(Date.now()-Q,W5());G=setTimeout(()=>{W(),K()},Math.max(1,Math.ceil(B)))};return W(),K(),{setStatus(B){if(B===Y)return;Y=B,W()},stop(){if(V=!0,G)clearTimeout(G)},elapsedSec(){return(Date.now()-Q)/1000}}}async openStatusCard($,Z,J="blue"){let Q=Date.now(),Y=RY({sessionName:this.sessionName,title:$,status:n_(Z,Q),template:J}),V,X=await o(this.chatId,Y,(H)=>{V=H});if(!X)return j(`session "${this.sessionName}": status card send failed title=${$}`),await h(this.chatId,`❌ 创建状态卡片失败: ${$}
321
321
  ${w(V)}`),null;let z;try{z=await e$(X)}catch(H){return j(`session "${this.sessionName}": status card id_convert failed title=${$}: ${H}`),await h(this.chatId,`❌ 状态卡片初始化失败: ${$}
322
- ${w(H)}`),null}return h$(z,1),{cardId:z,title:$,timer:this.startFooterTimer(z,Z,(H)=>p8($,H))}}setStatusCard($,Z){$?.timer.setStatus(Z)}async closeStatusCard($,Z){if(!$)return;$.timer.stop();let J=$.timer.elapsedSec(),Q=p8($.title,`${Z} (${f0(J)})`);await d1($.cardId);let Y=[],V=(H)=>{Y.push(H)},X=await D0($.cardId,C.footer,this.footerElement(Q),{onFailure:V});e0($.cardId);let z=await m0($.cardId,o2({durationSec:J,suffix:Z}),V);if(X&&z)await N$($.cardId);else{let H=`footer=${X?"ok":"MISS"}, settings=${z?"ok":"MISS"}`;j(`session "${this.sessionName}": status card terminal transaction incomplete card=${$.cardId.slice(0,12)} ${H}`),await h(this.chatId,`⚠️ 状态卡片终态写入失败 (${H}):${Z}
323
- ${D9(Y)}`)}}async runLifecycle($,Z){let J=this.lifecycleTail,Q;this.lifecycleTail=new Promise((V)=>{Q=V}),await J;let Y=++this.lifecycleSequence;j(`session "${this.sessionName}": lifecycle#${Y} ${$} begin`);try{return await Z()}finally{Q(),j(`session "${this.sessionName}": lifecycle#${Y} ${$} end`)}}beginTurnOpen($=this.proc,Z=this.procEpoch,J=!1){if(this.openingTurnOwner)throw Error(`turn card open already owned by token=${this.openingTurnOwner.token}; same-process opens must wait for the current owner`);let Q,Y=new Promise((X)=>{Q=X}),V={token:++this.turnOpenSequence,proc:$,procEpoch:Z,sawResult:!1,terminalForcePush:!1,pendingCompactions:[],backendTurnStarted:J,done:Y,resolveDone:Q};return this.openingTurnOwner=V,this.openingTurn=!0,V}ownsTurnOpen($){return this.openingTurnOwner===$&&this.proc===$.proc&&this.procEpoch===$.procEpoch}releaseTurnOpen($){if(this.openingTurnOwner!==$)return;this.openingTurnOwner=null,this.openingTurn=!1,$.resolveDone(),this.steerPendingInputs()}invalidateTurnOpen(){let $=this.openingTurnOwner;this.openingTurnOwner=null,this.openingTurn=!1,$?.resolveDone()}async waitForTurnOpenSlot($,Z){while(this.openingTurnOwner)if(await this.openingTurnOwner.done,this.proc!==$||this.procEpoch!==Z||!$.isAlive())return!1;return this.proc===$&&this.procEpoch===Z&&$.isAlive()}attachProc($){this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.cancel("原进程已更换"),this.modelSettingsChange=null,this.invalidateTurnOpen(),this.stoppingProc=null,this.blockedProc=null,this.blockedProcReason=null,this.proc=$;let Z=++this.procEpoch;this.wireProc($,Z)}detachProc($){if(this.proc!==$)return!1;if(this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.cancel("原进程已退出"),this.modelSettingsChange=null,this.invalidateTurnOpen(),this.proc=null,this.agentCapability=null,this.stoppingProc===$)this.stoppingProc=null;if(this.blockedProc===$)this.blockedProc=null,this.blockedProcReason=null;return this.procEpoch++,!0}beginProcStop($){if(this.steeringGeneration++,this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.proc===$)this.modelSettingsChange.cancel("原进程正在停止"),this.modelSettingsChange=null;this.stoppingProc=$,this.agentCapability=null}acceptsAgentCapability($){let Z=this.agentCapability;if(!Z||!$||!this.proc?.isAlive())return!1;let J=Buffer.from(Z),Q=Buffer.from($);return J.length===Q.length&&HE(J,Q)}async cancelAgentRuns($="用户取消"){await this.opts.onCancelAgentRuns?.(this.sessionName,this.chatId,$)}finishProcStop($,Z){if(this.stoppingProc===$)this.stoppingProc=null;if(!$.isAlive())return this.discardPendingCodexTurnAnchors($,"confirmed process stop"),this.detachProc($),!0;return this.blockedProc=$,this.blockedProcReason=Z?E(Z):"kill returned while process still reports alive",j(`session "${this.sessionName}": process stop unconfirmed; lifecycle blocked: ${this.blockedProcReason}`),!1}blockedProcessMessage(){let $=this.blockedProc;if(!$)return null;if(!$.isAlive())return this.detachProc($),null;return`旧 ${this.backendLabel($.provider)} 进程尚未确认退出,会话已阻断: ${this.blockedProcReason??"未知原因"}`}async stopOwnedProc($,Z){if(this.proc!==$)return!$.isAlive();this.beginProcStop($);let J=null;try{await $.kill(Z)}catch(Q){J=Q}return this.finishProcStop($,J)}async settleProcResumableState($){let Z=null,J=$.conversationMaterializationBarrier?.();if(J)try{await J}catch(V){Z=`Codex 会话落盘确认失败: ${E(V)}`}let Q=$.conversationMaterializationFailure?.();if(Q&&$.isConversationResumable?.()!==!0)Z=`Codex 会话落盘确认失败: ${E(Q)}`;let Y=this.persistResumableSessionId(!1,$,!1);return[Z,Y].filter(Boolean).join(";")||null}resetFreshConversationState(){this.daemonRestoreRequired=!1,this.codexQuotaWaitLaunch=null,this.turnCounter=0,this.pendingConversationMaterialization=null,W$(this.sessionName,[],{kind:"fresh"},null),this.currentGoal=null,this.cumStats={tokens:0,costUsd:0,turns:0},this.lastTurnDelta=null,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.lastTurnUsage=null,this.usageTotalsSeedUnknown=!1}async start($={}){return await this.runLifecycle("start",()=>this.startUnlocked($))}async startWithCodexAccount($,Z={}){return this.runLifecycle("hi-account",async()=>{if(v.get($),this.selectedProvider!=="codex"||this.currentTokenSource()?.codexApiProvider){if(this.proc?.isAlive())await this.stopUnlocked("切换到 Codex",{...Z,announce:!1});let Y=j0("codex-sub",$)?.defaultModel||null;W$(this.sessionName,[],null,null),l1(this.sessionName,"codex",Y,null,"codex-sub"),this.pendingConversationMaterialization=null,this.selectedProvider="codex",this.selectedTokenSourceId="codex-sub",this.selectedModel=Y,this.selectedEffort=null,this.lastSessionRef=c1(this.sessionName,"codex"),this.lastSessionId=this.lastSessionRef?.sessionId??null}if(this.selectedTokenSourceId!=="codex-sub")l1(this.sessionName,"codex",this.selectedModel,this.selectedEffort,"codex-sub"),this.selectedTokenSourceId="codex-sub";this.codexStartAccountOverride=$;let J=this.pendingConversationLaunch;this.pendingConversationLaunch??=this.codexQuotaWaitLaunch;try{if(this.proc?.isAlive()&&this.proc.provider==="codex"&&M$(this.proc)===$&&this.proc.turnRetry?.reason!=="quota")return Z.onStatus?.(`✅ 正在使用「${v.get($).name}」`),!0;return this.pendingConversationLaunch?.kind!=="fresh"&&!!(this.proc?.isAlive()||this.lastSessionRef||this.pendingConversationLaunch)?await this.restartUnlocked(!0,Z):await this.startUnlocked(Z)}finally{this.pendingConversationLaunch=J,this.codexStartAccountOverride=void 0}})}async startUnlocked($={}){let Z=$.announce??!0,J=$.onStatus,Q=this.blockedProcessMessage();if(Q){if(this.status="stopped",J?.(`❌ ${Q}`),Z)await k(this.chatId,`❌ ${Q}。请重试 stop/restart,或等待旧进程退出。`);return!1}if(this.proc&&!this.proc.isAlive())this.detachProc(this.proc);if(this.isRunning()){if(this.proc?.provider===this.selectedProvider)return J?.(this.withModel(`✅ ${this.backendLabel()} 已运行`)),!0;if(await this.stopIdleMismatchedProcessUnlocked(),this.proc?.isAlive())return J?.(`⚠️ 当前 ${this.backendLabel(this.proc.provider)} turn 尚未结束,模型切换将在后续新 turn 生效`),!0}if(this.selectedProvider==="codex")J?.(this.currentTokenSource()?.codexApiProvider?"\uD83D\uDD0E 检查 Codex API 来源":"\uD83D\uDD0E 检查 Codex 登录");else J?.("\uD83D\uDD0E 检查 Claude Code");if(this.selectedProvider==="codex"&&this.selectedTokenSourceId!=="codex-sub"&&!this.currentTokenSource()?.codexApiProvider&&!_8(this.codexAccountId())){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.("❌ Codex 未登录 ChatGPT 账号"),Z){let W;if(!await o(this.chatId,Q1({phase:"warning",title:"需要登录",hint:"默认:codex-login · 额外:codex-login 备注"}),(B)=>{W=B}))throw Error(`Codex 登录引导卡片发送失败:${w(W)}`)}return!1}if(!u_(this.workDir)){if(J?.(`\uD83C\uDD95 创建项目目录 ~/${this.sessionName}`),Z)await k(this.chatId,`\uD83C\uDD95 目录 ~/${this.sessionName} 不存在,正在创建…`);try{oJ(this.workDir)}catch(W){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.(`❌ 创建项目失败: ${W}`),Z)await k(this.chatId,`❌ 创建项目失败: ${W}`);return!1}}if(!$.freshConversationStateAlreadyReset&&!this.pendingConversationMaterialization)this.resetFreshConversationState();this.status="starting",J?.(this.withModel(`\uD83D\uDE80 启动 ${this.backendLabel()}`));let Y;try{Y=this.spawnAgent()}catch(W){let K=`${this.backendLabel()} 启动失败: ${E(W)}`;if(j(`session "${this.sessionName}": ${K}`),J?.(`❌ ${K}`),Z)await k(this.chatId,`❌ ${K}`);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}this.attachProc(Y);let V=this.backendLabel(),X=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(Y,i_):null;J?.(this.selectedProvider==="claude"?`⏳ 检查 ${V} 启动`:`⏳ 等待 ${V} init`);let z,H=null;try{Y.sendInitialize(),z=Y.initializationPromise?.()}catch(W){z=void 0,H=W}let G=H?{state:"error",error:H}:this.selectedProvider==="claude"?await X:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(z),()=>{j(`session "${this.sessionName}": codex init still pending after ${hV/1000}s`),J?.(this.withModel(`⏳ 仍在等待 ${V} init 确认`))});if(G.state==="error"||G.state==="exit"){let W=G.error?E(G.error):G.state;j(`session "${this.sessionName}": ${this.selectedProvider} init failed: ${W}`);let B=await this.stopOwnedProc(Y,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,_=`❌ ${V} 启动失败: ${W}${B}`;if(J?.(_),Z)await k(this.chatId,_);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(G.state==="timeout"){j(`session "${this.sessionName}": ${this.selectedProvider} init wait timeout (${H5/1000}s)`);let K=await this.stopOwnedProc(Y,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,B=`❌ ${V} 启动超时: ${H5/1000} 秒内初始化事务未完成${K}`;if(J?.(B),Z)await k(this.chatId,B);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(this.proc!==Y||!Y.isAlive()){let W=`${V} 启动期间已退出`;if(j(`session "${this.sessionName}": ${W}`),J?.(`❌ ${W}`),Z)await k(this.chatId,`❌ ${W}`);return this.detachProc(Y),this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(G.state==="waiting_quota"){if(this.pendingConversationLaunch&&this.pendingConversationLaunch.kind!=="fresh")this.codexQuotaWaitLaunch=this.pendingConversationLaunch;if(this.status="starting",this.startedAt=Date.now(),this.opts.onLifecycleChange?.(),J?.("⏳ 账号额度用尽 · 自动等待恢复,可用后继续"),Z)await o(this.chatId,Q1({phase:"checking",title:"等待额度恢复",message:"额度恢复后自动继续",hint:"stop 可取消等待"}));return!0}if(Z){let W=this.modelLine();await k(this.chatId,[this.withWorktreeInstructionNotice(`✅ Lodestar session "${this.sessionName}" 已就绪,发消息开始对话。`),W].filter(Boolean).join(`
324
- `))}return this.status="idle",this.startedAt=Date.now(),this.daemonRestoreRequired=!1,this.opts.onLifecycleChange?.(),J?.(this.withModel(this.withWorktreeInstructionNotice(`✅ ${this.backendLabel()} 已就绪`))),!0}requireCodexInitializationPromise($){if(!$||typeof $.then!=="function")return Promise.reject(Error("Codex process did not expose its initialization transaction"));return Promise.resolve($)}async waitForCodexInitialization($,Z){return await new Promise((J)=>{let Q=!1,Y=(z,H)=>{if(Q)return;Q=!0,clearTimeout(V),clearTimeout(X),J({state:z,error:H})},V=setTimeout(()=>{if(Q)return;try{Z?.()}catch(z){Y("error",z)}},hV),X=setTimeout(()=>{Y("timeout",Error(`codex init timed out after ${H5/1000}s`))},H5);$.then(()=>Y("init"),(z)=>Y("error",z)),this.proc?.quotaWaitPromise?.().then(()=>Y("waiting_quota"),(z)=>Y("error",z))})}async waitForProcEarlyFailure($,Z){return await new Promise((J)=>{let Q=!1,Y=(G,W)=>{if(Q)return;Q=!0,clearTimeout(V),$.off("init",X),$.off("error",z),$.off("exit",H),J({state:G,error:W})},V=setTimeout(()=>Y("ready"),Z),X=()=>Y("init"),z=(G)=>Y("error",G),H=(G)=>Y("exit",G);$.once("init",X),$.once("error",z),$.once("exit",H)})}releaseAllReactions(){for(let[$,Z]of[...this.pendingReactionIds.entries(),...this.currentBatchReactionIds.entries()])if(Z)g0($,Z);this.pendingReactionIds=new Map,this.currentBatchReactionIds=new Map}clearStaleIdleQueueState($){if(this.initCount<1||this.currentTurn||this.openingTurn||this.pendingUserMessageCount===0)return;j(`session "${this.sessionName}": clear stale pending queue before ${$} pendingCount=${this.pendingUserMessageCount} reactions=${this.pendingReactionIds.size}`),this.pendingUserMessageCount=0;for(let[Z,J]of this.pendingReactionIds)if(J)g0(Z,J);this.pendingReactionIds=new Map}async stop($="已终止",Z={}){this.cancelFileDeliveries($),await this.runLifecycle("stop",()=>this.stopUnlocked($,Z))}cancelFileDeliveries($){let Z=!1;for(let J of this.fileDeliveries)Z=J.cancel($)||Z;return Z}async stopUnlocked($="已终止",Z={}){this.cancelFileDeliveries($);let J=Z.announce??!0,Q=Z.onStatus;this.daemonRestoreRequired=!1;let Y=this.proc;if(Y)this.beginProcStop(Y);let V=null;try{await this.cancelAgentRuns($)}catch(D){V=D}if(!Y){if(this.status="stopped",this.opts.onLifecycleChange?.(),V)throw V;if(Q?.("⚪ session 当前未运行"),J)await k(this.chatId,`⚪ session "${this.sessionName}" 当前未运行`);return}let X=this.persistResumableSessionId(!1,Y,!1),z=null;if(Q?.(`\uD83D\uDED1 停止 ${this.backendLabel(Y.provider)}`),j(`session "${this.sessionName}": stop (${$})`),this.invalidateTurnOpen(),this.currentTurn)this.closeTurnCard(`\uD83D\uDED1 ${$}`).catch((D)=>{j(`session "${this.sessionName}": stop current main-card close failed: ${E(D)}`)});let H=this.waitForTurnCloses().catch((D)=>j(`session "${this.sessionName}": stop main-card close failed: ${E(D)}`));this.beginProcStop(Y),this.status="stopped";let G=[];try{this.opts.onLifecycleChange?.()}catch(D){G.push(D),j(`session "${this.sessionName}": stop intent lifecycle write failed: ${E(D)}`)}let W=Y.conversationMaterializationBarrier?.();if(W){try{await W}catch(D){z=`Codex 会话落盘确认失败: ${E(D)}`}X=this.persistResumableSessionId(!1,Y,!1)}this.clearMultiMsgBuffer("stop"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.bgResumePending=!1,this.discardOrphanAssistant(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1;let K=null;try{await Y.kill()}catch(D){K=D}let B=Y.conversationMaterializationFailure?.();if(B&&Y.isConversationResumable?.()!==!0)z=`Codex 会话落盘确认失败: ${E(B)}`;X=this.persistResumableSessionId(!1,Y,!1);let P=(await Promise.allSettled([this.resetBackgroundTasks(),H])).filter((D)=>D.status==="rejected").map((D)=>D.reason);for(let D of P)j(`session "${this.sessionName}": stop terminal cleanup failed: ${E(D)}`);let L=this.finishProcStop(Y,K);try{this.opts.onLifecycleChange?.()}catch(D){G.push(D),j(`session "${this.sessionName}": stop final lifecycle write failed: ${E(D)}`)}let q=[...V?[V]:[],...K?[K]:[],...!L&&!K?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...P,...G,...X?[Error(X)]:[],...z&&Y.isConversationResumable?.()!==!0?[Error(z)]:[]];if(q.length===1)throw q[0];if(q.length>1)throw AggregateError(q,`stop failed: ${q.map(E).join("; ")}`);if(Q?.(`✅ ${$}`),J)await k(this.chatId,`\uD83D\uDD34 ${$} (session: ${this.sessionName})`)}async restart($=!1,Z={}){return await this.runLifecycle("restart",()=>this.restartUnlocked($,Z))}requireDaemonRestore(){this.daemonRestoreRequired=!0}async restoreAfterDaemonRestart(){return await this.runLifecycle("daemon-restore",async()=>{if(this.requireDaemonRestore(),!this.lastSessionRef&&!this.pendingMaterializationLaunch())return this.status="stopped",this.opts.onLifecycleChange?.(),await k(this.chatId,"❌ daemon 重启后没有可用的恢复点。请发送 rs 选择历史会话,或 hi 明确启动新会话。"),!1;return await this.restartUnlocked(!0)})}async continueAfterDaemonRestart(){await this.runLifecycle("daemon-continue",async()=>{let $=this.proc;if(this.daemonRestoreRequired||this.status!=="idle"||this.initCount<1||!$?.isAlive()||!this.lastSessionRef||$.sessionId!==this.lastSessionRef.sessionId||$.provider!==this.lastSessionRef.provider||this.lastSessionId!==$.sessionId||this.modelSelectionNeedsProcessStop()||this.currentTurn||this.openingTurn||this.steeringSend||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)throw Error("原会话尚未恢复为空闲可用状态,未发送自动续接请求");await this.onUserMessageUnlocked("[宿主重启自动续接] daemon 已重启并恢复本会话。按用户已授权的范围继续尚未完成的工作,先核对已有执行结果,不要重复已完成的测试或操作。若工作已完成,直接报告结果。",[],"","",$)})}async restartUnlocked($=!1,Z={},J){let Q=Z.announce??!0,Y=Z.onStatus,V=this.status,X=null;if(!$&&!this.pendingConversationLaunch&&this.pendingConversationMaterialization)X=this.pendingConversationMaterialization,u1(this.sessionName,null),this.pendingConversationMaterialization=null;let z=this.pendingConversationLaunch??($?this.codexQuotaWaitLaunch:null)??this.pendingMaterializationLaunch(),H=this.lastSessionRef;if($&&!z&&H?.cwd===null)try{H=await this.resolveLegacyResumeRef(H),this.lastSessionRef=H,this.lastSessionId=H.sessionId}catch(b){let p=this.invalidateMissingCodexResume(H.sessionId,b,J),c=p?`❌ 旧会话不可恢复: ${E(b)};${p}`:`❌ 旧会话 cwd 校验失败: ${E(b)};请在进程已停时发送 rs 重新选择历史会话`;if(this.status=this.proc?.isAlive()?V:"stopped",Y?.(c),Q)await k(this.chatId,c);return!1}let G=H?.sessionId??null,W=z&&z.kind!=="fresh"?z.source.sessionId:G,K=W?h0(W):"",B=null,_=(b=this.proc)=>{if(!$||z||b?.provider!=="codex"||b.isConversationResumable?.()!==!0)return;B=this.persistResumableSessionId(!1,b,!1),H=this.lastSessionRef,G=H?.sessionId??null,W=G,K=W?h0(W):""},P=null;if(!Y&&Q&&$&&G){let b=this.proc?this.withModel(`\uD83D\uDD01 重启 ${this.backendLabel(this.proc.provider)}`):this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`);if(P=await this.openStatusCard("restart",b),P)Y=(p)=>this.setStatusCard(P,p)}let L=Q&&!P,q=async(b)=>{if(P)await this.closeStatusCard(P,b)},D=Boolean(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0||this.pendingTurnInputs.length>0||kQ(this.backgroundTasks)||this.pendingBgTasks.length>0||this.backgroundSync);this.bgResumePending=!1,this.invalidateTurnOpen(),this.discardOrphanAssistant();for(let b of this.fileDeliveries)b.cancel("会话正在重启");if(this.currentTurn)this.closeTurnCard("\uD83D\uDD01 已中止,正在重启").catch((b)=>{j(`session "${this.sessionName}": restart current main-card close failed: ${E(b)}`)});let M=this.waitForTurnCloses().catch((b)=>j(`session "${this.sessionName}": restart main-card close failed: ${E(b)}`)),U=null,A=null,O=null;if(this.proc){let b=this.proc;Y?.(`\uD83D\uDED1 停止当前 ${this.backendLabel(b.provider)}`),O=b;let p=this.agentCapability;this.beginProcStop(b);try{await this.cancelAgentRuns("会话正在重启")}catch(l){A=l}let c=b.conversationMaterializationBarrier?.();if(c)try{await c}catch(l){B=`Codex 会话落盘确认失败: ${E(l)}`}if(_(b),$&&!z&&B&&!A&&!D&&b.isAlive()){if(this.proc===b&&this.stoppingProc===b)this.stoppingProc=null,this.agentCapability=p;this.status=V;let l=`❌ ${this.backendLabel(b.provider)} 恢复点尚未安全落盘,已保留当前进程: ${B}`;if(j(`session "${this.sessionName}": abort restart before kill: ${B}`),Y?.(l),L)await k(this.chatId,l);return await q(l),!1}try{await b.kill()}catch(l){U=l}let J0=b.conversationMaterializationFailure?.();if(J0&&b.isConversationResumable?.()!==!0)B=`Codex 会话落盘确认失败: ${E(J0)}`;_(b)}else try{await this.cancelAgentRuns("会话正在重启")}catch(b){A=b}this.clearMultiMsgBuffer("restart"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;let S=(await Promise.allSettled([this.resetBackgroundTasks(),M])).filter((b)=>b.status==="rejected").map((b)=>b.reason);for(let b of S)j(`session "${this.sessionName}": restart terminal cleanup failed: ${E(b)}`);let T=O?this.finishProcStop(O,U):!0,y=[...A?[`agents=${E(A)}`]:[],...U?[`kill=${E(U)}`]:[],...!T&&!U?[`kill=${this.blockedProcReason??"process stop unconfirmed"}`]:[],...S.map((b)=>`cleanup=${E(b)}`),...B?[`resume=${B}`]:[]];if(y.length>0&&X)try{u1(this.sessionName,X),this.pendingConversationMaterialization=X}catch(b){y.push(`pendingRestore=${E(b)}`)}if(y.length>0){let b=`❌ 旧 ${this.backendLabel()} 进程停止/清理失败: ${y.join("; ")}`;if(this.status="stopped",this.opts.onLifecycleChange?.(),Y?.(b),L)await k(this.chatId,b);return await q(b),!1}let m=z?.kind==="resume"||z?.kind==="fork";if($&&H||m){this.status="starting",this.usageTotalsSeedUnknown=!0,Y?.(this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`));let b;try{b=this.spawnAgent(H??void 0,z??void 0)}catch(t){let K0=`❌ ${this.backendLabel()} 恢复失败: ${E(t)}`;if(j(`session "${this.sessionName}": ${this.selectedProvider} resume failed before spawn: ${E(t)}`),Y?.(K0),L)await k(this.chatId,K0);return this.status="stopped",this.opts.onLifecycleChange?.(),await q(K0),!1}this.attachProc(b);let p=this.backendLabel(),c=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(b,i_):null;Y?.(this.selectedProvider==="claude"?`⏳ 检查 ${p} 恢复启动`:`⏳ 等待 ${p} init 确认`);let J0,l=null;try{b.sendInitialize(),J0=b.initializationPromise?.()}catch(t){J0=void 0,l=t}let f=l?{state:"error",error:l}:this.selectedProvider==="claude"?await c:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(J0),()=>{j(`session "${this.sessionName}": codex resume init still pending after ${hV/1000}s`),Y?.(this.withModel(`⏳ 仍在等待 ${p} init 确认 thread=${K}`))});if(f.state==="error"||f.state==="exit"||f.state==="timeout"){let t=f.state==="error"?this.invalidateMissingCodexResume(W,f.error,J):null,K0=[f.error?E(f.error):f.state,t].filter(Boolean).join(";");j(`session "${this.sessionName}": ${this.selectedProvider} resume failed: ${K0}`);let x=await this.stopOwnedProc(b,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,u=f.state==="timeout"?`❌ ${p} 恢复超时${x}`:`❌ ${p} 恢复失败: ${K0}${x}`;if(Y?.(u),L)await k(this.chatId,u);return this.status="stopped",this.opts.onLifecycleChange?.(),await q(u),!1}if(this.proc!==b||!b.isAlive()){let t=`❌ ${p} 恢复期间已退出`;if(j(`session "${this.sessionName}": ${this.selectedProvider} resume process exited before ready`),Y?.(t),L)await k(this.chatId,t);return this.detachProc(b),this.status="stopped",this.opts.onLifecycleChange?.(),await q(t),!1}let Q0=this.withModel(this.withWorktreeInstructionNotice(f.state==="waiting_quota"?"⏳ 账号额度用尽 · 等待后自动恢复原会话":this.selectedProvider==="claude"&&f.state==="ready"?`✅ 已准备恢复上一会话 thread=${K}`:`✅ 已恢复上一会话 thread=${K}`));if(f.state==="waiting_quota"){let t=z??(H?{kind:"resume",source:H}:null);if(t&&t.kind!=="fresh")this.codexQuotaWaitLaunch=t}if(Y?.(Q0),L)await k(this.chatId,Q0);if(this.status=f.state==="waiting_quota"?"starting":"idle",this.startedAt=Date.now(),f.state!=="waiting_quota")this.daemonRestoreRequired=!1;this.opts.onLifecycleChange?.();try{await q(Q0)}catch(t){j(`session "${this.sessionName}": restart succeeded but status-card close failed: ${E(t)}`),await h(this.chatId,`⚠️ ${Q0}
325
- 状态卡收尾失败: ${E(t)}`)}return!0}else{if($&&!z){if(Y?.("⚠️ 没有可恢复的上一会话,将以新会话启动"),L)await k(this.chatId,"⚠️ 没有可恢复的上一会话,将以新会话启动")}return this.resetFreshConversationState(),await this.startUnlocked({...Z,freshConversationStateAlreadyReset:!0})}}async startForked($,Z={}){return await this.runLifecycle("start-forked",async()=>{E0($,this.selectedProvider,this.workDir);let J=i4(this.sessionName),Q=this.selectedProvider==="claude"?{launch:$,previousSessionId:this.lastSessionId}:null;if(Q)u1(this.sessionName,Q),this.pendingConversationMaterialization=Q;this.pendingConversationLaunch=$;try{let Y=await this.startUnlocked(Z);if(!Y&&Q)u1(this.sessionName,J),this.pendingConversationMaterialization=J;return Y}catch(Y){if(!Q)throw Y;try{u1(this.sessionName,J),this.pendingConversationMaterialization=J}catch(V){throw AggregateError([Y,V],`fork start and pending-intent restore failed: ${E(Y)}; ${E(V)}`)}throw Y}finally{this.pendingConversationLaunch=null}})}async rollbackTo($,Z,J={}){return await this.runLifecycle("rollback",async()=>{E0($,this.selectedProvider,this.workDir);let Q=Z?{anchors:Z.anchors.slice(),base:Z.base,pendingLaunch:Z.pendingLaunch!==void 0?Z.pendingLaunch:this.selectedProvider==="claude"&&$.kind==="fork"?{launch:$,previousSessionId:this.lastSessionId}:null}:null,Y=this.proc,V=this.lastSessionId,X=this.lastSessionRef,z=l4(this.sessionName).slice(),H=d4(this.sessionName),G=i4(this.sessionName),W={codexQuotaWaitLaunch:this.codexQuotaWaitLaunch,turnCounter:this.turnCounter,currentGoal:this.currentGoal,cumStats:{...this.cumStats},lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,currentTurnUsageBaseline:this.currentTurnUsageBaseline?{...this.currentTurnUsageBaseline}:null,currentTurnUsageBaselineKnown:this.currentTurnUsageBaselineKnown,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,usageTotalsSeedUnknown:this.usageTotalsSeedUnknown},K=!1,B=()=>{if(K)this.lastSessionId=null,this.lastSessionRef=null,u4(this.sessionName,"codex");else if(this.lastSessionId=V,this.lastSessionRef=X,X)W8(this.sessionName,X);else u4(this.sessionName,this.selectedProvider);W$(this.sessionName,z,H,G),this.pendingConversationMaterialization=G,this.codexQuotaWaitLaunch=W.codexQuotaWaitLaunch,this.turnCounter=W.turnCounter,this.currentGoal=W.currentGoal,this.cumStats=W.cumStats,this.lastTurnDelta=W.lastTurnDelta,this.currentTurnUsageBaseline=W.currentTurnUsageBaseline,this.currentTurnUsageBaselineKnown=W.currentTurnUsageBaselineKnown,this.lastTurnUsage=W.lastTurnUsage,this.usageTotalsSeedUnknown=W.usageTotalsSeedUnknown},_=!1;if(Q?.pendingLaunch)W$(this.sessionName,Q.anchors,Q.base,Q.pendingLaunch),this.pendingConversationMaterialization=Q.pendingLaunch,_=!0;this.pendingConversationLaunch=$;let P=(L)=>{K=X?.provider==="codex"&&X.sessionId===L};try{let L;try{L=$.kind==="fresh"?await this.restartUnlocked(!1,J,P):await this.restartUnlocked(!0,J,P)}catch(q){let D=null,M=this.proc&&this.proc!==Y?this.proc:null;if(M)try{await this.stopUnlocked("回滚启动事务失败",{announce:!1})}catch(N){D=N}let U=!M||this.proc!==M&&!M.isAlive();if(!U&&!D)D=Error("replacement process stop was not confirmed");let A=null;if(U)try{B()}catch(N){A=N}let O=[q,...D?[D]:[],...A?[A]:[]];if(O.length===1)throw q;throw AggregateError(O,`rollback launch and cleanup failed: ${O.map(E).join("; ")}`)}if(!L)return B(),!1;if(Q)try{if(!_)W$(this.sessionName,Q.anchors,Q.base,Q.pendingLaunch);this.pendingConversationMaterialization=Q.pendingLaunch}catch(q){let D=null,M=this.proc;try{await this.stopUnlocked("回滚分支状态持久化失败",{announce:!1})}catch(N){D=N}let U=!M||this.proc!==M&&!M.isAlive();if(!U&&!D)D=Error("replacement process stop was not confirmed");let A=null;if(U)try{B()}catch(N){A=N}let O=[q,...D?[D]:[],...A?[A]:[]];if(O.length===1)throw q;throw AggregateError(O,`rollback branch commit failed: ${O.map(E).join("; ")}`)}return L}finally{this.pendingConversationLaunch=null}})}dispose(){g$.all.delete(this)}recordTurnAnchor($){let Z=this.proc;if(!Z?.sessionId||!$)return null;if($.provider!==Z.provider||$.source.sessionId!==Z.sessionId||$.source.cwd!==this.workDir){let Q=`拒绝了与当前会话不匹配的 checkpoint provider=${$.provider} source=${$.source.sessionId}`;return j(`session "${this.sessionName}": ${Q}`),this.lastTurnUserPreview="",Q}let J={checkpoint:$,preview:this.lastTurnUserPreview.slice(0,80),ts:Date.now(),writes:this.collectTurnWrites()};if(this.lastTurnUserPreview="",Z.provider==="codex"&&Z.isConversationResumable?.()!==!0){if(this.pendingCodexTurnAnchors.filter((Y)=>Y.proc===Z).length>=64)return j(`session "${this.sessionName}": ${"Codex rollout 长期未确认,延迟 checkpoint 队列已满"} thread=${Z.sessionId}`),"Codex rollout 长期未确认,延迟 checkpoint 队列已满";return this.pendingCodexTurnAnchors.push({proc:Z,anchor:J}),j(`session "${this.sessionName}": defer Codex turn checkpoint until rollout confirmation thread=${Z.sessionId} checkpoint=${$.id}`),null}return this.appendTurnAnchor(J)}appendTurnAnchor($){try{return fJ(this.sessionName,$),null}catch(Z){let J=`分叉 checkpoint 持久化失败: ${E(Z)}`;return j(`session "${this.sessionName}": ${J}`),J}}flushPendingCodexTurnAnchors($){let Z=null,J=[];for(let Q of this.pendingCodexTurnAnchors){if(Q.proc!==$||Z){J.push(Q);continue}if(Z=this.appendTurnAnchor(Q.anchor),Z)J.push(Q)}return this.pendingCodexTurnAnchors=J,Z}discardPendingCodexTurnAnchors($,Z){if($.provider!=="codex")return;let J=this.pendingCodexTurnAnchors.length;this.pendingCodexTurnAnchors=this.pendingCodexTurnAnchors.filter((Y)=>Y.proc!==$);let Q=J-this.pendingCodexTurnAnchors.length;if(Q>0)j(`session "${this.sessionName}": dropped ${Q} unmaterialized Codex checkpoint(s): ${Z}`)}collectTurnWrites(){let $=this.currentTurn;if(!$)return[];let Z=[];for(let J of $.toolByUseId.values())Z.push(...gY(J.name,J.input));return Z}worktreeProjectName(){return J4(this)}worktreeProjectDir(){return L9(this)}spawnDeveloperInstructions($=this.getFileDeliveryMode()){return O_(this,$,this.currentProvider())}delegatedAgentDeveloperInstructions($){return A_(this,$)}worktreeInstructionLoadedNotice(){return bV(this)}withWorktreeInstructionNotice($){return N_(this,$)}worktreeExtraInstruction(){return V3(this)}runWorktreeCommand($,Z){return R_(this,$,Z)}showWorktrees(){return kV(this)}showTasklistPanel(){return Y_(this)}showAgentIdentityPanel($=""){return oj(this,$)}onAgentIdentityPage($,Z,J){return sj($,Z,J)}onTasklistEnable(){return V_(this)}onTasklistDeletePrompt($){return X_(this,$)}onTasklistDeleteConfirm($){return z_(this,$)}runCompactCommand(){return wj(this)}showModelPanel(){return yj(this)}finishModelSettingsChange($,Z){return this.runLifecycle("model-settings-complete",()=>qV(this,$,Z))}closeModelSettingsChanges(){this.modelSettingsChangesClosed=!0,this.modelSettingsChange?.cancel("daemon 正在停止")}modelSettingsBlockReason(){let $=this.modelSettingsChange;if(!$||$.proc!==this.proc||!$.proc.isAlive())return null;return $.phase==="pending"?"模型设置仍在等待后端确认,请等待结果;取消切换请发 kill 或 restart。":$.error??"模型设置未确认,请重新发送 md 选择模型。"}resumeInputAfterModelSettingsChange(){this.drainMidTurnAndOpen().catch(async($)=>{let Z=`模型设置已完成,但排队输入提交失败:${E($)}`;j(`session "${this.sessionName}": ${Z}`),await h(this.chatId,`❌ ${Z}`)})}onModelSelect($,Z="",J="",Q=null){return this.runLifecycle("model-select",()=>cj(this,$,Z,J,Q))}onModelEffortSelect($,Z,J="",Q="",Y=""){return this.runLifecycle("model-effort-select",()=>UV(this,$,Z,J,Q,Y))}onProviderSelect($,Z=""){return FV(this,$,Z)}onModelPage($,Z,J){return r6(this,$,Z,J)}onModelAddOpen($,Z){return hj(this,$,Z)}onModelListEdit($,Z,J,Q){return this.runLifecycle("model-list-edit",()=>Ij(this,$,Z,J,Q))}onModelPanelCancel($=""){return pj(this,$)}onModelCustomPrompt($,Z,J=""){return gj(this,$,Z,J)}consumeModelCustomMessage($,Z){return mj(this,$,Z)}onWorktreeDisband($){return E_(this,$)}showForkList($=""){return v_(this,$)}showBackList($=""){return f_(this,$)}showResumeList($=""){return y_(this,$)}runBtwCommand($){return h_(this,$)}runByeCommand(){return I_(this)}onForkSelect($,Z,J=""){return g_(this,$,Z,J)}onBackSelect($,Z,J=""){return m_(this,$,Z,J)}onResumeSelect($,Z,J=""){return p_(this,$,Z,J)}runCommand($,Z="",J){return KK(this,$,Z,J)}getFileDeliveryMode(){return P9.mode(this.chatId,this.workDir)}runFileDeliveryCommand($,Z){return L_(this.chatId,this.sessionName,Z,$,{get:(J)=>P9.get(J,this.workDir),enable:(J,Q)=>P9.enable(J,this.workDir,Q),disable:(J)=>P9.disable(J,this.workDir),sendCard:(J,Q)=>o(this.chatId,J,Q),reportError:async(J)=>{if(j(`session "${this.sessionName}": ${J}`),!await k(this.chatId,J))throw Error(J)}},this.workDir)}async buildConsoleOpts($,Z){let J=await FB(),Q=this.runtimeModelSelection();return{sessionName:this.sessionName,status:this.status,provider:Q.provider,model:Q.model??void 0,effort:Q.effort??"MISS",worktreeInstructionNotice:this.worktreeInstructionLoadedNotice(),peers:[...g$.all].filter((Y)=>Y.isRunning()).map((Y)=>({...Y.peerSnapshot(),isCurrent:Y===this})),usage:$,glmUsage:Z,accountUsages:await eY(),sysinfo:J}}async buildConsoleCard($){return w6(await this.buildConsoleOpts($))}async patchConsoleUsage($){let Z=await this.buildConsoleOpts(void 0);try{Z.accountUsages=await eY()}catch(Y){let V=E(Y);j(`console usage MISS: ${V}`),Z.accountUsages=[{id:"error",label:"额度",usage:{state:"network",windows:[],reason:V}}]}let J;if(!await D0($,C.consoleUsage,c8(Z),{notifyCardFailure:!1,onFailure:(Y)=>{J=Y}}))throw Error(`console usage element replace rejected: ${w(J)}`)}async mutateStaticCard($,Z,J){let Q=!0,Y=[];try{await J()}catch(X){Q=!1,Y.push(E(X)),j(`session "${this.sessionName}": ${Z} mutation failed: ${E(X)}`)}let V=!1;try{V=await m0($,{config:{streaming_mode:!1}},(X)=>{Y.push(w(X))})}catch(X){Y.push(w(X)),j(`session "${this.sessionName}": ${Z} streaming-off failed: ${E(X)}`)}if(!Q||!V)return j(`session "${this.sessionName}": ${Z} state retained after checked MISS mutation=${Q} streamingOff=${V} card=${$.slice(0,12)}`),await h(this.chatId,`⚠️ 卡片更新失败 (${Z})。
322
+ ${w(H)}`),null}return h$(z,1),{cardId:z,title:$,timer:this.startFooterTimer(z,Z,(H)=>p8($,H))}}setStatusCard($,Z){$?.timer.setStatus(Z)}async closeStatusCard($,Z){if(!$)return;$.timer.stop();let J=$.timer.elapsedSec(),Q=p8($.title,`${Z} (${y0(J)})`);await d1($.cardId);let Y=[],V=(H)=>{Y.push(H)},X=await F0($.cardId,C.footer,this.footerElement(Q),{onFailure:V});e0($.cardId);let z=await m0($.cardId,o2({durationSec:J,suffix:Z}),V);if(X&&z)await N$($.cardId);else{let H=`footer=${X?"ok":"MISS"}, settings=${z?"ok":"MISS"}`;j(`session "${this.sessionName}": status card terminal transaction incomplete card=${$.cardId.slice(0,12)} ${H}`),await h(this.chatId,`⚠️ 状态卡片终态写入失败 (${H}):${Z}
323
+ ${F9(Y)}`)}}async runLifecycle($,Z){let J=this.lifecycleTail,Q;this.lifecycleTail=new Promise((V)=>{Q=V}),await J;let Y=++this.lifecycleSequence;j(`session "${this.sessionName}": lifecycle#${Y} ${$} begin`);try{return await Z()}finally{Q(),j(`session "${this.sessionName}": lifecycle#${Y} ${$} end`)}}beginTurnOpen($=this.proc,Z=this.procEpoch,J=!1){if(this.openingTurnOwner)throw Error(`turn card open already owned by token=${this.openingTurnOwner.token}; same-process opens must wait for the current owner`);let Q,Y=new Promise((X)=>{Q=X}),V={token:++this.turnOpenSequence,proc:$,procEpoch:Z,sawResult:!1,terminalForcePush:!1,pendingCompactions:[],backendTurnStarted:J,done:Y,resolveDone:Q};return this.openingTurnOwner=V,this.openingTurn=!0,V}ownsTurnOpen($){return this.openingTurnOwner===$&&this.proc===$.proc&&this.procEpoch===$.procEpoch}releaseTurnOpen($){if(this.openingTurnOwner!==$)return;this.openingTurnOwner=null,this.openingTurn=!1,$.resolveDone(),this.steerPendingInputs()}invalidateTurnOpen(){let $=this.openingTurnOwner;this.openingTurnOwner=null,this.openingTurn=!1,$?.resolveDone()}async waitForTurnOpenSlot($,Z){while(this.openingTurnOwner)if(await this.openingTurnOwner.done,this.proc!==$||this.procEpoch!==Z||!$.isAlive())return!1;return this.proc===$&&this.procEpoch===Z&&$.isAlive()}attachProc($){this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.cancel("原进程已更换"),this.modelSettingsChange=null,this.invalidateTurnOpen(),this.stoppingProc=null,this.blockedProc=null,this.blockedProcReason=null,this.proc=$;let Z=++this.procEpoch;this.wireProc($,Z)}detachProc($){if(this.proc!==$)return!1;if(this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.cancel("原进程已退出"),this.modelSettingsChange=null,this.invalidateTurnOpen(),this.proc=null,this.agentCapability=null,this.stoppingProc===$)this.stoppingProc=null;if(this.blockedProc===$)this.blockedProc=null,this.blockedProcReason=null;return this.procEpoch++,!0}beginProcStop($){if(this.steeringGeneration++,this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,this.modelSettingsChange?.proc===$)this.modelSettingsChange.cancel("原进程正在停止"),this.modelSettingsChange=null;this.stoppingProc=$,this.agentCapability=null}acceptsAgentCapability($){let Z=this.agentCapability;if(!Z||!$||!this.proc?.isAlive())return!1;let J=Buffer.from(Z),Q=Buffer.from($);return J.length===Q.length&&HE(J,Q)}async cancelAgentRuns($="用户取消"){await this.opts.onCancelAgentRuns?.(this.sessionName,this.chatId,$)}finishProcStop($,Z){if(this.stoppingProc===$)this.stoppingProc=null;if(!$.isAlive())return this.discardPendingCodexTurnAnchors($,"confirmed process stop"),this.detachProc($),!0;return this.blockedProc=$,this.blockedProcReason=Z?E(Z):"kill returned while process still reports alive",j(`session "${this.sessionName}": process stop unconfirmed; lifecycle blocked: ${this.blockedProcReason}`),!1}blockedProcessMessage(){let $=this.blockedProc;if(!$)return null;if(!$.isAlive())return this.detachProc($),null;return`旧 ${this.backendLabel($.provider)} 进程尚未确认退出,会话已阻断: ${this.blockedProcReason??"未知原因"}`}async stopOwnedProc($,Z){if(this.proc!==$)return!$.isAlive();this.beginProcStop($);let J=null;try{await $.kill(Z)}catch(Q){J=Q}return this.finishProcStop($,J)}async settleProcResumableState($){let Z=null,J=$.conversationMaterializationBarrier?.();if(J)try{await J}catch(V){Z=`Codex 会话落盘确认失败: ${E(V)}`}let Q=$.conversationMaterializationFailure?.();if(Q&&$.isConversationResumable?.()!==!0)Z=`Codex 会话落盘确认失败: ${E(Q)}`;let Y=this.persistResumableSessionId(!1,$,!1);return[Z,Y].filter(Boolean).join(";")||null}resetFreshConversationState(){this.daemonRestoreRequired=!1,this.codexQuotaWaitLaunch=null,this.turnCounter=0,this.pendingConversationMaterialization=null,W$(this.sessionName,[],{kind:"fresh"},null),this.currentGoal=null,this.cumStats={tokens:0,costUsd:0,turns:0},this.lastTurnDelta=null,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.lastTurnUsage=null,this.usageTotalsSeedUnknown=!1}async start($={}){return await this.runLifecycle("start",()=>this.startUnlocked($))}async startWithCodexAccount($,Z={}){return this.runLifecycle("hi-account",async()=>{if(v.get($),this.selectedProvider!=="codex"||this.currentTokenSource()?.codexApiProvider){if(this.proc?.isAlive())await this.stopUnlocked("切换到 Codex",{...Z,announce:!1});let Y=j0("codex-sub",$)?.defaultModel||null;W$(this.sessionName,[],null,null),l1(this.sessionName,"codex",Y,null,"codex-sub"),this.pendingConversationMaterialization=null,this.selectedProvider="codex",this.selectedTokenSourceId="codex-sub",this.selectedModel=Y,this.selectedEffort=null,this.lastSessionRef=c1(this.sessionName,"codex"),this.lastSessionId=this.lastSessionRef?.sessionId??null}if(this.selectedTokenSourceId!=="codex-sub")l1(this.sessionName,"codex",this.selectedModel,this.selectedEffort,"codex-sub"),this.selectedTokenSourceId="codex-sub";this.codexStartAccountOverride=$;let J=this.pendingConversationLaunch;this.pendingConversationLaunch??=this.codexQuotaWaitLaunch;try{if(this.proc?.isAlive()&&this.proc.provider==="codex"&&M$(this.proc)===$&&this.proc.turnRetry?.reason!=="quota")return Z.onStatus?.(`✅ 正在使用「${v.get($).name}」`),!0;return this.pendingConversationLaunch?.kind!=="fresh"&&!!(this.proc?.isAlive()||this.lastSessionRef||this.pendingConversationLaunch)?await this.restartUnlocked(!0,Z):await this.startUnlocked(Z)}finally{this.pendingConversationLaunch=J,this.codexStartAccountOverride=void 0}})}async startUnlocked($={}){let Z=$.announce??!0,J=$.onStatus,Q=this.blockedProcessMessage();if(Q){if(this.status="stopped",J?.(`❌ ${Q}`),Z)await k(this.chatId,`❌ ${Q}。请重试 stop/restart,或等待旧进程退出。`);return!1}if(this.proc&&!this.proc.isAlive())this.detachProc(this.proc);if(this.isRunning()){if(this.proc?.provider===this.selectedProvider)return J?.(this.withModel(`✅ ${this.backendLabel()} 已运行`)),!0;if(await this.stopIdleMismatchedProcessUnlocked(),this.proc?.isAlive())return J?.(`⚠️ 当前 ${this.backendLabel(this.proc.provider)} turn 尚未结束,模型切换将在后续新 turn 生效`),!0}if(this.selectedProvider==="codex")J?.(this.currentTokenSource()?.codexApiProvider?"\uD83D\uDD0E 检查 Codex API 来源":"\uD83D\uDD0E 检查 Codex 登录");else J?.("\uD83D\uDD0E 检查 Claude Code");if(this.selectedProvider==="codex"&&this.selectedTokenSourceId!=="codex-sub"&&!this.currentTokenSource()?.codexApiProvider&&!_8(this.codexAccountId())){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.("❌ Codex 未登录 ChatGPT 账号"),Z){let W;if(!await o(this.chatId,Q1({phase:"warning",title:"需要登录",hint:"默认:codex-login · 额外:codex-login 备注"}),(B)=>{W=B}))throw Error(`Codex 登录引导卡片发送失败:${w(W)}`)}return!1}if(!u_(this.workDir)){if(J?.(`\uD83C\uDD95 创建项目目录 ~/${this.sessionName}`),Z)await k(this.chatId,`\uD83C\uDD95 目录 ~/${this.sessionName} 不存在,正在创建…`);try{oJ(this.workDir)}catch(W){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.(`❌ 创建项目失败: ${W}`),Z)await k(this.chatId,`❌ 创建项目失败: ${W}`);return!1}}if(!$.freshConversationStateAlreadyReset&&!this.pendingConversationMaterialization)this.resetFreshConversationState();this.status="starting",J?.(this.withModel(`\uD83D\uDE80 启动 ${this.backendLabel()}`));let Y;try{Y=this.spawnAgent()}catch(W){let K=`${this.backendLabel()} 启动失败: ${E(W)}`;if(j(`session "${this.sessionName}": ${K}`),J?.(`❌ ${K}`),Z)await k(this.chatId,`❌ ${K}`);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}this.attachProc(Y);let V=this.backendLabel(),X=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(Y,i_):null;J?.(this.selectedProvider==="claude"?`⏳ 检查 ${V} 启动`:`⏳ 等待 ${V} init`);let z,H=null;try{Y.sendInitialize(),z=Y.initializationPromise?.()}catch(W){z=void 0,H=W}let G=H?{state:"error",error:H}:this.selectedProvider==="claude"?await X:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(z),()=>{j(`session "${this.sessionName}": codex init still pending after ${hV/1000}s`),J?.(this.withModel(`⏳ 仍在等待 ${V} init 确认`))});if(G.state==="error"||G.state==="exit"){let W=G.error?E(G.error):G.state;j(`session "${this.sessionName}": ${this.selectedProvider} init failed: ${W}`);let B=await this.stopOwnedProc(Y,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,_=`❌ ${V} 启动失败: ${W}${B}`;if(J?.(_),Z)await k(this.chatId,_);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(G.state==="timeout"){j(`session "${this.sessionName}": ${this.selectedProvider} init wait timeout (${H5/1000}s)`);let K=await this.stopOwnedProc(Y,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,B=`❌ ${V} 启动超时: ${H5/1000} 秒内初始化事务未完成${K}`;if(J?.(B),Z)await k(this.chatId,B);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(this.proc!==Y||!Y.isAlive()){let W=`${V} 启动期间已退出`;if(j(`session "${this.sessionName}": ${W}`),J?.(`❌ ${W}`),Z)await k(this.chatId,`❌ ${W}`);return this.detachProc(Y),this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(G.state==="waiting_quota"){if(this.pendingConversationLaunch&&this.pendingConversationLaunch.kind!=="fresh")this.codexQuotaWaitLaunch=this.pendingConversationLaunch;if(this.status="starting",this.startedAt=Date.now(),this.opts.onLifecycleChange?.(),J?.("⏳ 账号额度用尽 · 自动等待恢复,可用后继续"),Z)await o(this.chatId,Q1({phase:"checking",title:"等待额度恢复",message:"额度恢复后自动继续",hint:"stop 可取消等待"}));return!0}if(Z){let W=this.modelLine();await k(this.chatId,[this.withWorktreeInstructionNotice(`✅ Lodestar session "${this.sessionName}" 已就绪,发消息开始对话。`),W].filter(Boolean).join(`
324
+ `))}return this.status="idle",this.startedAt=Date.now(),this.daemonRestoreRequired=!1,this.opts.onLifecycleChange?.(),J?.(this.withModel(this.withWorktreeInstructionNotice(`✅ ${this.backendLabel()} 已就绪`))),!0}requireCodexInitializationPromise($){if(!$||typeof $.then!=="function")return Promise.reject(Error("Codex process did not expose its initialization transaction"));return Promise.resolve($)}async waitForCodexInitialization($,Z){return await new Promise((J)=>{let Q=!1,Y=(z,H)=>{if(Q)return;Q=!0,clearTimeout(V),clearTimeout(X),J({state:z,error:H})},V=setTimeout(()=>{if(Q)return;try{Z?.()}catch(z){Y("error",z)}},hV),X=setTimeout(()=>{Y("timeout",Error(`codex init timed out after ${H5/1000}s`))},H5);$.then(()=>Y("init"),(z)=>Y("error",z)),this.proc?.quotaWaitPromise?.().then(()=>Y("waiting_quota"),(z)=>Y("error",z))})}async waitForProcEarlyFailure($,Z){return await new Promise((J)=>{let Q=!1,Y=(G,W)=>{if(Q)return;Q=!0,clearTimeout(V),$.off("init",X),$.off("error",z),$.off("exit",H),J({state:G,error:W})},V=setTimeout(()=>Y("ready"),Z),X=()=>Y("init"),z=(G)=>Y("error",G),H=(G)=>Y("exit",G);$.once("init",X),$.once("error",z),$.once("exit",H)})}releaseAllReactions(){for(let[$,Z]of[...this.pendingReactionIds.entries(),...this.currentBatchReactionIds.entries()])if(Z)g0($,Z);this.pendingReactionIds=new Map,this.currentBatchReactionIds=new Map}clearStaleIdleQueueState($){if(this.initCount<1||this.currentTurn||this.openingTurn||this.pendingUserMessageCount===0)return;j(`session "${this.sessionName}": clear stale pending queue before ${$} pendingCount=${this.pendingUserMessageCount} reactions=${this.pendingReactionIds.size}`),this.pendingUserMessageCount=0;for(let[Z,J]of this.pendingReactionIds)if(J)g0(Z,J);this.pendingReactionIds=new Map}async stop($="已终止",Z={}){this.cancelFileDeliveries($),await this.runLifecycle("stop",()=>this.stopUnlocked($,Z))}cancelFileDeliveries($){let Z=!1;for(let J of this.fileDeliveries)Z=J.cancel($)||Z;return Z}async stopUnlocked($="已终止",Z={}){this.cancelFileDeliveries($);let J=Z.announce??!0,Q=Z.onStatus;this.daemonRestoreRequired=!1;let Y=this.proc;if(Y)this.beginProcStop(Y);let V=null;try{await this.cancelAgentRuns($)}catch(F){V=F}if(!Y){if(this.status="stopped",this.opts.onLifecycleChange?.(),V)throw V;if(Q?.("⚪ session 当前未运行"),J)await k(this.chatId,`⚪ session "${this.sessionName}" 当前未运行`);return}let X=this.persistResumableSessionId(!1,Y,!1),z=null;if(Q?.(`\uD83D\uDED1 停止 ${this.backendLabel(Y.provider)}`),j(`session "${this.sessionName}": stop (${$})`),this.invalidateTurnOpen(),this.currentTurn)this.closeTurnCard(`\uD83D\uDED1 ${$}`).catch((F)=>{j(`session "${this.sessionName}": stop current main-card close failed: ${E(F)}`)});let H=this.waitForTurnCloses().catch((F)=>j(`session "${this.sessionName}": stop main-card close failed: ${E(F)}`));this.beginProcStop(Y),this.status="stopped";let G=[];try{this.opts.onLifecycleChange?.()}catch(F){G.push(F),j(`session "${this.sessionName}": stop intent lifecycle write failed: ${E(F)}`)}let W=Y.conversationMaterializationBarrier?.();if(W){try{await W}catch(F){z=`Codex 会话落盘确认失败: ${E(F)}`}X=this.persistResumableSessionId(!1,Y,!1)}this.clearMultiMsgBuffer("stop"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.bgResumePending=!1,this.discardOrphanAssistant(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1;let K=null;try{await Y.kill()}catch(F){K=F}let B=Y.conversationMaterializationFailure?.();if(B&&Y.isConversationResumable?.()!==!0)z=`Codex 会话落盘确认失败: ${E(B)}`;X=this.persistResumableSessionId(!1,Y,!1);let P=(await Promise.allSettled([this.resetBackgroundTasks(),H])).filter((F)=>F.status==="rejected").map((F)=>F.reason);for(let F of P)j(`session "${this.sessionName}": stop terminal cleanup failed: ${E(F)}`);let L=this.finishProcStop(Y,K);try{this.opts.onLifecycleChange?.()}catch(F){G.push(F),j(`session "${this.sessionName}": stop final lifecycle write failed: ${E(F)}`)}let q=[...V?[V]:[],...K?[K]:[],...!L&&!K?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...P,...G,...X?[Error(X)]:[],...z&&Y.isConversationResumable?.()!==!0?[Error(z)]:[]];if(q.length===1)throw q[0];if(q.length>1)throw AggregateError(q,`stop failed: ${q.map(E).join("; ")}`);if(Q?.(`✅ ${$}`),J)await k(this.chatId,`\uD83D\uDD34 ${$} (session: ${this.sessionName})`)}async restart($=!1,Z={}){return await this.runLifecycle("restart",()=>this.restartUnlocked($,Z))}requireDaemonRestore(){this.daemonRestoreRequired=!0}async restoreAfterDaemonRestart(){return await this.runLifecycle("daemon-restore",async()=>{if(this.requireDaemonRestore(),!this.lastSessionRef&&!this.pendingMaterializationLaunch())return this.status="stopped",this.opts.onLifecycleChange?.(),await k(this.chatId,"❌ daemon 重启后没有可用的恢复点。请发送 rs 选择历史会话,或 hi 明确启动新会话。"),!1;return await this.restartUnlocked(!0)})}async continueAfterDaemonRestart(){await this.runLifecycle("daemon-continue",async()=>{let $=this.proc;if(this.daemonRestoreRequired||this.status!=="idle"||this.initCount<1||!$?.isAlive()||!this.lastSessionRef||$.sessionId!==this.lastSessionRef.sessionId||$.provider!==this.lastSessionRef.provider||this.lastSessionId!==$.sessionId||this.modelSelectionNeedsProcessStop()||this.currentTurn||this.openingTurn||this.steeringSend||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)throw Error("原会话尚未恢复为空闲可用状态,未发送自动续接请求");await this.onUserMessageUnlocked("[宿主重启自动续接] daemon 已重启并恢复本会话。按用户已授权的范围继续尚未完成的工作,先核对已有执行结果,不要重复已完成的测试或操作。若工作已完成,直接报告结果。",[],"","",$)})}async restartUnlocked($=!1,Z={},J){let Q=Z.announce??!0,Y=Z.onStatus,V=this.status,X=null;if(!$&&!this.pendingConversationLaunch&&this.pendingConversationMaterialization)X=this.pendingConversationMaterialization,u1(this.sessionName,null),this.pendingConversationMaterialization=null;let z=this.pendingConversationLaunch??($?this.codexQuotaWaitLaunch:null)??this.pendingMaterializationLaunch(),H=this.lastSessionRef;if($&&!z&&H?.cwd===null)try{H=await this.resolveLegacyResumeRef(H),this.lastSessionRef=H,this.lastSessionId=H.sessionId}catch(b){let p=this.invalidateMissingCodexResume(H.sessionId,b,J),c=p?`❌ 旧会话不可恢复: ${E(b)};${p}`:`❌ 旧会话 cwd 校验失败: ${E(b)};请在进程已停时发送 rs 重新选择历史会话`;if(this.status=this.proc?.isAlive()?V:"stopped",Y?.(c),Q)await k(this.chatId,c);return!1}let G=H?.sessionId??null,W=z&&z.kind!=="fresh"?z.source.sessionId:G,K=W?h0(W):"",B=null,_=(b=this.proc)=>{if(!$||z||b?.provider!=="codex"||b.isConversationResumable?.()!==!0)return;B=this.persistResumableSessionId(!1,b,!1),H=this.lastSessionRef,G=H?.sessionId??null,W=G,K=W?h0(W):""},P=null;if(!Y&&Q&&$&&G){let b=this.proc?this.withModel(`\uD83D\uDD01 重启 ${this.backendLabel(this.proc.provider)}`):this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`);if(P=await this.openStatusCard("restart",b),P)Y=(p)=>this.setStatusCard(P,p)}let L=Q&&!P,q=async(b)=>{if(P)await this.closeStatusCard(P,b)},F=Boolean(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0||this.pendingTurnInputs.length>0||kQ(this.backgroundTasks)||this.pendingBgTasks.length>0||this.backgroundSync);this.bgResumePending=!1,this.invalidateTurnOpen(),this.discardOrphanAssistant();for(let b of this.fileDeliveries)b.cancel("会话正在重启");if(this.currentTurn)this.closeTurnCard("\uD83D\uDD01 已中止,正在重启").catch((b)=>{j(`session "${this.sessionName}": restart current main-card close failed: ${E(b)}`)});let M=this.waitForTurnCloses().catch((b)=>j(`session "${this.sessionName}": restart main-card close failed: ${E(b)}`)),U=null,A=null,O=null;if(this.proc){let b=this.proc;Y?.(`\uD83D\uDED1 停止当前 ${this.backendLabel(b.provider)}`),O=b;let p=this.agentCapability;this.beginProcStop(b);try{await this.cancelAgentRuns("会话正在重启")}catch(l){A=l}let c=b.conversationMaterializationBarrier?.();if(c)try{await c}catch(l){B=`Codex 会话落盘确认失败: ${E(l)}`}if(_(b),$&&!z&&B&&!A&&!F&&b.isAlive()){if(this.proc===b&&this.stoppingProc===b)this.stoppingProc=null,this.agentCapability=p;this.status=V;let l=`❌ ${this.backendLabel(b.provider)} 恢复点尚未安全落盘,已保留当前进程: ${B}`;if(j(`session "${this.sessionName}": abort restart before kill: ${B}`),Y?.(l),L)await k(this.chatId,l);return await q(l),!1}try{await b.kill()}catch(l){U=l}let J0=b.conversationMaterializationFailure?.();if(J0&&b.isConversationResumable?.()!==!0)B=`Codex 会话落盘确认失败: ${E(J0)}`;_(b)}else try{await this.cancelAgentRuns("会话正在重启")}catch(b){A=b}this.clearMultiMsgBuffer("restart"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;let S=(await Promise.allSettled([this.resetBackgroundTasks(),M])).filter((b)=>b.status==="rejected").map((b)=>b.reason);for(let b of S)j(`session "${this.sessionName}": restart terminal cleanup failed: ${E(b)}`);let T=O?this.finishProcStop(O,U):!0,f=[...A?[`agents=${E(A)}`]:[],...U?[`kill=${E(U)}`]:[],...!T&&!U?[`kill=${this.blockedProcReason??"process stop unconfirmed"}`]:[],...S.map((b)=>`cleanup=${E(b)}`),...B?[`resume=${B}`]:[]];if(f.length>0&&X)try{u1(this.sessionName,X),this.pendingConversationMaterialization=X}catch(b){f.push(`pendingRestore=${E(b)}`)}if(f.length>0){let b=`❌ 旧 ${this.backendLabel()} 进程停止/清理失败: ${f.join("; ")}`;if(this.status="stopped",this.opts.onLifecycleChange?.(),Y?.(b),L)await k(this.chatId,b);return await q(b),!1}let m=z?.kind==="resume"||z?.kind==="fork";if($&&H||m){this.status="starting",this.usageTotalsSeedUnknown=!0,Y?.(this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${K}`));let b;try{b=this.spawnAgent(H??void 0,z??void 0)}catch(t){let K0=`❌ ${this.backendLabel()} 恢复失败: ${E(t)}`;if(j(`session "${this.sessionName}": ${this.selectedProvider} resume failed before spawn: ${E(t)}`),Y?.(K0),L)await k(this.chatId,K0);return this.status="stopped",this.opts.onLifecycleChange?.(),await q(K0),!1}this.attachProc(b);let p=this.backendLabel(),c=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(b,i_):null;Y?.(this.selectedProvider==="claude"?`⏳ 检查 ${p} 恢复启动`:`⏳ 等待 ${p} init 确认`);let J0,l=null;try{b.sendInitialize(),J0=b.initializationPromise?.()}catch(t){J0=void 0,l=t}let y=l?{state:"error",error:l}:this.selectedProvider==="claude"?await c:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(J0),()=>{j(`session "${this.sessionName}": codex resume init still pending after ${hV/1000}s`),Y?.(this.withModel(`⏳ 仍在等待 ${p} init 确认 thread=${K}`))});if(y.state==="error"||y.state==="exit"||y.state==="timeout"){let t=y.state==="error"?this.invalidateMissingCodexResume(W,y.error,J):null,K0=[y.error?E(y.error):y.state,t].filter(Boolean).join(";");j(`session "${this.sessionName}": ${this.selectedProvider} resume failed: ${K0}`);let x=await this.stopOwnedProc(b,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,u=y.state==="timeout"?`❌ ${p} 恢复超时${x}`:`❌ ${p} 恢复失败: ${K0}${x}`;if(Y?.(u),L)await k(this.chatId,u);return this.status="stopped",this.opts.onLifecycleChange?.(),await q(u),!1}if(this.proc!==b||!b.isAlive()){let t=`❌ ${p} 恢复期间已退出`;if(j(`session "${this.sessionName}": ${this.selectedProvider} resume process exited before ready`),Y?.(t),L)await k(this.chatId,t);return this.detachProc(b),this.status="stopped",this.opts.onLifecycleChange?.(),await q(t),!1}let Q0=this.withModel(this.withWorktreeInstructionNotice(y.state==="waiting_quota"?"⏳ 账号额度用尽 · 等待后自动恢复原会话":this.selectedProvider==="claude"&&y.state==="ready"?`✅ 已准备恢复上一会话 thread=${K}`:`✅ 已恢复上一会话 thread=${K}`));if(y.state==="waiting_quota"){let t=z??(H?{kind:"resume",source:H}:null);if(t&&t.kind!=="fresh")this.codexQuotaWaitLaunch=t}if(Y?.(Q0),L)await k(this.chatId,Q0);if(this.status=y.state==="waiting_quota"?"starting":"idle",this.startedAt=Date.now(),y.state!=="waiting_quota")this.daemonRestoreRequired=!1;this.opts.onLifecycleChange?.();try{await q(Q0)}catch(t){j(`session "${this.sessionName}": restart succeeded but status-card close failed: ${E(t)}`),await h(this.chatId,`⚠️ ${Q0}
325
+ 状态卡收尾失败: ${E(t)}`)}return!0}else{if($&&!z){if(Y?.("⚠️ 没有可恢复的上一会话,将以新会话启动"),L)await k(this.chatId,"⚠️ 没有可恢复的上一会话,将以新会话启动")}return this.resetFreshConversationState(),await this.startUnlocked({...Z,freshConversationStateAlreadyReset:!0})}}async startForked($,Z={}){return await this.runLifecycle("start-forked",async()=>{E0($,this.selectedProvider,this.workDir);let J=i4(this.sessionName),Q=this.selectedProvider==="claude"?{launch:$,previousSessionId:this.lastSessionId}:null;if(Q)u1(this.sessionName,Q),this.pendingConversationMaterialization=Q;this.pendingConversationLaunch=$;try{let Y=await this.startUnlocked(Z);if(!Y&&Q)u1(this.sessionName,J),this.pendingConversationMaterialization=J;return Y}catch(Y){if(!Q)throw Y;try{u1(this.sessionName,J),this.pendingConversationMaterialization=J}catch(V){throw AggregateError([Y,V],`fork start and pending-intent restore failed: ${E(Y)}; ${E(V)}`)}throw Y}finally{this.pendingConversationLaunch=null}})}async rollbackTo($,Z,J={}){return await this.runLifecycle("rollback",async()=>{E0($,this.selectedProvider,this.workDir);let Q=Z?{anchors:Z.anchors.slice(),base:Z.base,pendingLaunch:Z.pendingLaunch!==void 0?Z.pendingLaunch:this.selectedProvider==="claude"&&$.kind==="fork"?{launch:$,previousSessionId:this.lastSessionId}:null}:null,Y=this.proc,V=this.lastSessionId,X=this.lastSessionRef,z=l4(this.sessionName).slice(),H=d4(this.sessionName),G=i4(this.sessionName),W={codexQuotaWaitLaunch:this.codexQuotaWaitLaunch,turnCounter:this.turnCounter,currentGoal:this.currentGoal,cumStats:{...this.cumStats},lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,currentTurnUsageBaseline:this.currentTurnUsageBaseline?{...this.currentTurnUsageBaseline}:null,currentTurnUsageBaselineKnown:this.currentTurnUsageBaselineKnown,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,usageTotalsSeedUnknown:this.usageTotalsSeedUnknown},K=!1,B=()=>{if(K)this.lastSessionId=null,this.lastSessionRef=null,u4(this.sessionName,"codex");else if(this.lastSessionId=V,this.lastSessionRef=X,X)W8(this.sessionName,X);else u4(this.sessionName,this.selectedProvider);W$(this.sessionName,z,H,G),this.pendingConversationMaterialization=G,this.codexQuotaWaitLaunch=W.codexQuotaWaitLaunch,this.turnCounter=W.turnCounter,this.currentGoal=W.currentGoal,this.cumStats=W.cumStats,this.lastTurnDelta=W.lastTurnDelta,this.currentTurnUsageBaseline=W.currentTurnUsageBaseline,this.currentTurnUsageBaselineKnown=W.currentTurnUsageBaselineKnown,this.lastTurnUsage=W.lastTurnUsage,this.usageTotalsSeedUnknown=W.usageTotalsSeedUnknown},_=!1;if(Q?.pendingLaunch)W$(this.sessionName,Q.anchors,Q.base,Q.pendingLaunch),this.pendingConversationMaterialization=Q.pendingLaunch,_=!0;this.pendingConversationLaunch=$;let P=(L)=>{K=X?.provider==="codex"&&X.sessionId===L};try{let L;try{L=$.kind==="fresh"?await this.restartUnlocked(!1,J,P):await this.restartUnlocked(!0,J,P)}catch(q){let F=null,M=this.proc&&this.proc!==Y?this.proc:null;if(M)try{await this.stopUnlocked("回滚启动事务失败",{announce:!1})}catch(N){F=N}let U=!M||this.proc!==M&&!M.isAlive();if(!U&&!F)F=Error("replacement process stop was not confirmed");let A=null;if(U)try{B()}catch(N){A=N}let O=[q,...F?[F]:[],...A?[A]:[]];if(O.length===1)throw q;throw AggregateError(O,`rollback launch and cleanup failed: ${O.map(E).join("; ")}`)}if(!L)return B(),!1;if(Q)try{if(!_)W$(this.sessionName,Q.anchors,Q.base,Q.pendingLaunch);this.pendingConversationMaterialization=Q.pendingLaunch}catch(q){let F=null,M=this.proc;try{await this.stopUnlocked("回滚分支状态持久化失败",{announce:!1})}catch(N){F=N}let U=!M||this.proc!==M&&!M.isAlive();if(!U&&!F)F=Error("replacement process stop was not confirmed");let A=null;if(U)try{B()}catch(N){A=N}let O=[q,...F?[F]:[],...A?[A]:[]];if(O.length===1)throw q;throw AggregateError(O,`rollback branch commit failed: ${O.map(E).join("; ")}`)}return L}finally{this.pendingConversationLaunch=null}})}dispose(){g$.all.delete(this)}recordTurnAnchor($){let Z=this.proc;if(!Z?.sessionId||!$)return null;if($.provider!==Z.provider||$.source.sessionId!==Z.sessionId||$.source.cwd!==this.workDir){let Q=`拒绝了与当前会话不匹配的 checkpoint provider=${$.provider} source=${$.source.sessionId}`;return j(`session "${this.sessionName}": ${Q}`),this.lastTurnUserPreview="",Q}let J={checkpoint:$,preview:this.lastTurnUserPreview.slice(0,80),ts:Date.now(),writes:this.collectTurnWrites()};if(this.lastTurnUserPreview="",Z.provider==="codex"&&Z.isConversationResumable?.()!==!0){if(this.pendingCodexTurnAnchors.filter((Y)=>Y.proc===Z).length>=64)return j(`session "${this.sessionName}": ${"Codex rollout 长期未确认,延迟 checkpoint 队列已满"} thread=${Z.sessionId}`),"Codex rollout 长期未确认,延迟 checkpoint 队列已满";return this.pendingCodexTurnAnchors.push({proc:Z,anchor:J}),j(`session "${this.sessionName}": defer Codex turn checkpoint until rollout confirmation thread=${Z.sessionId} checkpoint=${$.id}`),null}return this.appendTurnAnchor(J)}appendTurnAnchor($){try{return yJ(this.sessionName,$),null}catch(Z){let J=`分叉 checkpoint 持久化失败: ${E(Z)}`;return j(`session "${this.sessionName}": ${J}`),J}}flushPendingCodexTurnAnchors($){let Z=null,J=[];for(let Q of this.pendingCodexTurnAnchors){if(Q.proc!==$||Z){J.push(Q);continue}if(Z=this.appendTurnAnchor(Q.anchor),Z)J.push(Q)}return this.pendingCodexTurnAnchors=J,Z}discardPendingCodexTurnAnchors($,Z){if($.provider!=="codex")return;let J=this.pendingCodexTurnAnchors.length;this.pendingCodexTurnAnchors=this.pendingCodexTurnAnchors.filter((Y)=>Y.proc!==$);let Q=J-this.pendingCodexTurnAnchors.length;if(Q>0)j(`session "${this.sessionName}": dropped ${Q} unmaterialized Codex checkpoint(s): ${Z}`)}collectTurnWrites(){let $=this.currentTurn;if(!$)return[];let Z=[];for(let J of $.toolByUseId.values())Z.push(...gY(J.name,J.input));return Z}worktreeProjectName(){return J4(this)}worktreeProjectDir(){return L9(this)}spawnDeveloperInstructions($=this.getFileDeliveryMode()){return O_(this,$,this.currentProvider())}delegatedAgentDeveloperInstructions($){return A_(this,$)}worktreeInstructionLoadedNotice(){return bV(this)}withWorktreeInstructionNotice($){return N_(this,$)}worktreeExtraInstruction(){return V3(this)}runWorktreeCommand($,Z){return R_(this,$,Z)}showWorktrees(){return kV(this)}showTasklistPanel(){return Y_(this)}showAgentIdentityPanel($=""){return oj(this,$)}onAgentIdentityPage($,Z,J){return sj($,Z,J)}onTasklistEnable(){return V_(this)}onTasklistDeletePrompt($){return X_(this,$)}onTasklistDeleteConfirm($){return z_(this,$)}runCompactCommand(){return wj(this)}showModelPanel(){return fj(this)}finishModelSettingsChange($,Z){return this.runLifecycle("model-settings-complete",()=>qV(this,$,Z))}closeModelSettingsChanges(){this.modelSettingsChangesClosed=!0,this.modelSettingsChange?.cancel("daemon 正在停止")}modelSettingsBlockReason(){let $=this.modelSettingsChange;if(!$||$.proc!==this.proc||!$.proc.isAlive())return null;return $.phase==="pending"?"模型设置仍在等待后端确认,请等待结果;取消切换请发 kill 或 restart。":$.error??"模型设置未确认,请重新发送 md 选择模型。"}resumeInputAfterModelSettingsChange(){this.drainMidTurnAndOpen().catch(async($)=>{let Z=`模型设置已完成,但排队输入提交失败:${E($)}`;j(`session "${this.sessionName}": ${Z}`),await h(this.chatId,`❌ ${Z}`)})}onModelSelect($,Z="",J="",Q=null){return this.runLifecycle("model-select",()=>cj(this,$,Z,J,Q))}onModelEffortSelect($,Z,J="",Q="",Y=""){return this.runLifecycle("model-effort-select",()=>UV(this,$,Z,J,Q,Y))}onProviderSelect($,Z=""){return DV(this,$,Z)}onModelPage($,Z,J){return r6(this,$,Z,J)}onModelAddOpen($,Z){return hj(this,$,Z)}onModelListEdit($,Z,J,Q){return this.runLifecycle("model-list-edit",()=>Ij(this,$,Z,J,Q))}onModelPanelCancel($=""){return pj(this,$)}onModelCustomPrompt($,Z,J=""){return gj(this,$,Z,J)}consumeModelCustomMessage($,Z){return mj(this,$,Z)}onWorktreeDisband($){return E_(this,$)}showForkList($=""){return v_(this,$)}showBackList($=""){return y_(this,$)}showResumeList($=""){return f_(this,$)}runBtwCommand($){return h_(this,$)}runByeCommand(){return I_(this)}onForkSelect($,Z,J=""){return g_(this,$,Z,J)}onBackSelect($,Z,J=""){return m_(this,$,Z,J)}onResumeSelect($,Z,J=""){return p_(this,$,Z,J)}runCommand($,Z="",J){return KK(this,$,Z,J)}getFileDeliveryMode(){return P9.mode(this.chatId,this.workDir)}runFileDeliveryCommand($,Z){return L_(this.chatId,this.sessionName,Z,$,{get:(J)=>P9.get(J,this.workDir),enable:(J,Q)=>P9.enable(J,this.workDir,Q),disable:(J)=>P9.disable(J,this.workDir),sendCard:(J,Q)=>o(this.chatId,J,Q),reportError:async(J)=>{if(j(`session "${this.sessionName}": ${J}`),!await k(this.chatId,J))throw Error(J)}},this.workDir)}async buildConsoleOpts($,Z){let J=await DB(),Q=this.runtimeModelSelection();return{sessionName:this.sessionName,status:this.status,provider:Q.provider,model:Q.model??void 0,effort:Q.effort??"MISS",worktreeInstructionNotice:this.worktreeInstructionLoadedNotice(),peers:[...g$.all].filter((Y)=>Y.isRunning()).map((Y)=>({...Y.peerSnapshot(),isCurrent:Y===this})),usage:$,glmUsage:Z,accountUsages:await eY(),sysinfo:J}}async buildConsoleCard($){return w6(await this.buildConsoleOpts($))}async patchConsoleUsage($){let Z=await this.buildConsoleOpts(void 0);try{Z.accountUsages=await eY()}catch(Y){let V=E(Y);j(`console usage MISS: ${V}`),Z.accountUsages=[{id:"error",label:"额度",usage:{state:"network",windows:[],reason:V}}]}let J;if(!await F0($,C.consoleUsage,c8(Z),{notifyCardFailure:!1,onFailure:(Y)=>{J=Y}}))throw Error(`console usage element replace rejected: ${w(J)}`)}async mutateStaticCard($,Z,J){let Q=!0,Y=[];try{await J()}catch(X){Q=!1,Y.push(E(X)),j(`session "${this.sessionName}": ${Z} mutation failed: ${E(X)}`)}let V=!1;try{V=await m0($,{config:{streaming_mode:!1}},(X)=>{Y.push(w(X))})}catch(X){Y.push(w(X)),j(`session "${this.sessionName}": ${Z} streaming-off failed: ${E(X)}`)}if(!Q||!V)return j(`session "${this.sessionName}": ${Z} state retained after checked MISS mutation=${Q} streamingOff=${V} card=${$.slice(0,12)}`),await h(this.chatId,`⚠️ 卡片更新失败 (${Z})。
326
326
  ${Y.join(`
327
- `)||w(void 0)}`),!1;try{await N$($)}catch(X){return j(`session "${this.sessionName}": ${Z} dispose failed: ${E(X)}`),!1}return Q}patchConsoleUsageLater($){this.mutateStaticCard($,"console usage",()=>this.patchConsoleUsage($))}async replaceStatusCardWithConsole($,Z){$.timer.stop();let J=$.timer.elapsedSec(),Q=await this.buildConsoleOpts(void 0);await d1($.cardId);let Y=[],V=(K)=>{Y.push(K)},X=await D0($.cardId,C.footer,b6(Q,C.footer),{onFailure:V}),z=await c2($.cardId,x6(Q),{type:"insert_after",targetElementId:C.footer,onFailure:V}),H=await c2($.cardId,k6(Q.sysinfo),{type:"insert_after",targetElementId:C.consoleProjects,onFailure:V}),G=await c2($.cardId,c8(Q),{type:"insert_after",targetElementId:C.consoleHost,onFailure:V});if(!X||!z||!H||!G){await h(this.chatId,`⚠️ 控制台卡片结构写入失败,请重新发送 hi。
328
- ${D9(Y)}`),await this.mutateStaticCard($.cardId,"console structure",async()=>{});return}if(e0($.cardId),!await m0($.cardId,o2({durationSec:J,suffix:Z}),V))await h(this.chatId,`⚠️ 控制台卡片状态写入失败。
329
- ${D9(Y)}`);this.patchConsoleUsageLater($.cardId)}async showConsole(){let $=await this.buildConsoleOpts(void 0);await o(this.chatId,w6($))}interrupt(){if(this.steeringGeneration++,this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,!this.proc)return;if(j(`session "${this.sessionName}": interrupt`),v$(this.proc))this.procPendingFileDeliveryModes.delete(this.proc),this.procFileDeliveryNeedsUpdate.add(this.proc);if(v$(this.proc)&&this.proc.hasPendingNativeTurn?.()===!1)this.userInterrupted=!1;this.proc.sendInterrupt()}disabledSubscriptionMessage($=this.selectedTokenSourceId){let Z=this.tokenSource($);return Z?.kind==="claude-subscription"&&!Z.enabled?Z.modelCatalogState?.error??"Claude Code 订阅未启用,请发送 claude-sub 查看状态":null}async sendClaimedUserText($,Z){let J=this.modelSettingsBlockReason();if(J)throw Error(J);let Q=this.disabledSubscriptionMessage($.tokenSourceId);if(Q){let H=`❌ ${Q}。消息未送给 Agent,请启用后重发或通过 md 切换来源。`;if(this.pendingTurnInputs=[],this.currentTurn)await this.closeTurnCard(H);else await k(this.chatId,H);return this.status="idle",!1}let Y=this.currentTurn,V=Y?Y.fileDeliveryMode??=this.getFileDeliveryMode():this.getFileDeliveryMode(),X=this.procFileDeliveryModes.get($),z=X===V&&!this.procFileDeliveryNeedsUpdate.has($)?"":`${F_(V,v$($)?"en":"zh")}
327
+ `)||w(void 0)}`),!1;try{await N$($)}catch(X){return j(`session "${this.sessionName}": ${Z} dispose failed: ${E(X)}`),!1}return Q}patchConsoleUsageLater($){this.mutateStaticCard($,"console usage",()=>this.patchConsoleUsage($))}async replaceStatusCardWithConsole($,Z){$.timer.stop();let J=$.timer.elapsedSec(),Q=await this.buildConsoleOpts(void 0);await d1($.cardId);let Y=[],V=(K)=>{Y.push(K)},X=await F0($.cardId,C.footer,b6(Q,C.footer),{onFailure:V}),z=await c2($.cardId,x6(Q),{type:"insert_after",targetElementId:C.footer,onFailure:V}),H=await c2($.cardId,k6(Q.sysinfo),{type:"insert_after",targetElementId:C.consoleProjects,onFailure:V}),G=await c2($.cardId,c8(Q),{type:"insert_after",targetElementId:C.consoleHost,onFailure:V});if(!X||!z||!H||!G){await h(this.chatId,`⚠️ 控制台卡片结构写入失败,请重新发送 hi。
328
+ ${F9(Y)}`),await this.mutateStaticCard($.cardId,"console structure",async()=>{});return}if(e0($.cardId),!await m0($.cardId,o2({durationSec:J,suffix:Z}),V))await h(this.chatId,`⚠️ 控制台卡片状态写入失败。
329
+ ${F9(Y)}`);this.patchConsoleUsageLater($.cardId)}async showConsole(){let $=await this.buildConsoleOpts(void 0);await o(this.chatId,w6($))}interrupt(){if(this.steeringGeneration++,this.submittedSteering.clear(),this.steeringBoundary?.start(),this.steeringBoundary=null,!this.proc)return;if(j(`session "${this.sessionName}": interrupt`),v$(this.proc))this.procPendingFileDeliveryModes.delete(this.proc),this.procFileDeliveryNeedsUpdate.add(this.proc);if(v$(this.proc)&&this.proc.hasPendingNativeTurn?.()===!1)this.userInterrupted=!1;this.proc.sendInterrupt()}disabledSubscriptionMessage($=this.selectedTokenSourceId){let Z=this.tokenSource($);return Z?.kind==="claude-subscription"&&!Z.enabled?Z.modelCatalogState?.error??"Claude Code 订阅未启用,请发送 claude-sub 查看状态":null}async sendClaimedUserText($,Z){let J=this.modelSettingsBlockReason();if(J)throw Error(J);let Q=this.disabledSubscriptionMessage($.tokenSourceId);if(Q){let H=`❌ ${Q}。消息未送给 Agent,请启用后重发或通过 md 切换来源。`;if(this.pendingTurnInputs=[],this.currentTurn)await this.closeTurnCard(H);else await k(this.chatId,H);return this.status="idle",!1}let Y=this.currentTurn,V=Y?Y.fileDeliveryMode??=this.getFileDeliveryMode():this.getFileDeliveryMode(),X=this.procFileDeliveryModes.get($),z=X===V&&!this.procFileDeliveryNeedsUpdate.has($)?"":`${D_(V,v$($)?"en":"zh")}
330
330
 
331
331
  `;if(v$($))this.procPendingFileDeliveryModes.set($,V);else this.procFileDeliveryModes.set($,V);this.pendingUserMessageCount++;try{if(v$($))$.sendUserText(Z,[],{contextPrefix:z});else $.sendUserText(z+Z,[])}catch(H){if(this.pendingUserMessageCount=Math.max(0,this.pendingUserMessageCount-1),this.procPendingFileDeliveryModes.delete($),X===void 0)this.procFileDeliveryModes.delete($);else this.procFileDeliveryModes.set($,X);throw H}return!0}async startColdUserTurn($,Z,J){if(!this.pendingConversationMaterialization)this.resetFreshConversationState();this.pendingTurnInputs.push($);let Q=this.beginTurnOpen();try{let V=await this.openTurnCard(Q,J,"user_message",{initialFooter:"Waiting...(0s)",startThinking:!1,directStart:!0});if(!V||this.currentTurn!==V)return;let X=this.startFooterTimer(V.cardId,`\uD83D\uDE80 启动 ${this.backendLabel()}`,(W)=>this.withModel(W)),z=`\uD83D\uDE80 启动 ${this.backendLabel()}`,H=await this.startUnlocked({announce:!1,freshConversationStateAlreadyReset:!0,onStatus:(W)=>{z=W,X.setStatus(W)}});if(X.stop(),await d1(V.cardId),!H){this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),await this.closeTurnCard(z.startsWith("❌")?z:"❌ 启动失败",{forcePush:!0});return}let G=this.proc;if(!G?.isAlive()){await this.closeTurnCard(`❌ ${this.backendLabel()} 启动后已退出`,{forcePush:!0});return}if(this.startThinkingFooter(V),!await this.sendClaimedUserText(G,Z))return;this.status="working"}finally{this.releaseTurnOpen(Q)}}async onUserMessage($,Z=[],J="",Q=""){await this.runLifecycle("user-message",()=>this.onUserMessageUnlocked($,Z,J,Q))}async onUserMessageUnlocked($,Z,J,Q,Y){let V=this.modelSettingsBlockReason();if(V){if(await k(this.chatId,`⚠️ ${V} 本条消息未送给 Agent,请确认设置后重发。`),Y)throw Error(V);return}let X=this.disabledSubscriptionMessage();if(X){if(await k(this.chatId,`❌ ${X}。消息未送给 Agent,请启用后重发或通过 md 切换来源。`),Y)throw Error(X);return}let z=this.blockedProcessMessage();if(z){if(await k(this.chatId,`❌ ${z}。请重试 stop/restart,或等待旧进程退出。`),Y)throw Error(z);return}if(this.daemonRestoreRequired){if(await k(this.chatId,"❌ daemon 重启后的会话恢复尚未成功,这条消息未送给 Agent。请发送 rs 选择历史会话,或 hi 明确启动新会话,然后重发消息。"),Y)throw Error("daemon 会话恢复尚未成功");return}if(this.clearStaleIdleQueueState("user_message"),this.proc?.isAlive()&&!this.currentTurn&&!this.openingTurn&&!this.steeringSend&&this.pendingUserMessageCount===0&&this.pendingMidTurnMsgs.length===0)await this.stopIdleMismatchedProcessUnlocked();let H=this.currentTurn!==null||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0;this.lastUserOpenId=J;let W=(Z.length?Z.map((B)=>`[file: ${B}]`).join(" ")+`
332
- `:"")+$,K=(B)=>{this.pendingReactionIds.set(B,""),(async()=>{let _=await K$(B,"OneSecond");if(!_)return;if(this.pendingReactionIds.has(B))this.pendingReactionIds.set(B,_);else if(this.currentBatchReactionIds.has(B))this.currentBatchReactionIds.set(B,_);else g0(B,_)})().catch((_)=>{j(`session "${this.sessionName}": reaction tracking failed: ${E(_)}`)})};if(Y&&(this.proc!==Y||!Y.isAlive()))throw Error("原会话进程已退出,未发送自动续接请求,也未创建新会话");if(!this.isRunning()){if(this.openingTurn||this.currentTurn){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);return}await this.startColdUserTurn($,W,J);return}if(this.currentTurn!==null||this.steeringSend){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);this.steerPendingInputs();return}if(!this.openingTurn&&this.initCount>=1){let B=this.proc,_=this.procEpoch,P=this.beginTurnOpen(B,_);try{this.pendingTurnInputs.push($);let L=await this.openTurnCard(P,J,"user_message");if(!L||this.currentTurn!==L){if(Y)throw Error("自动续接卡片未打开,未发送续接请求");return}if(this.proc!==B||this.procEpoch!==_||!B.isAlive()){if(await this.closeTurnCard(`⚠️ ${this.backendLabel(B.provider)} 已退出`),Y)throw Error("原会话进程已退出,未发送自动续接请求");return}if(!await this.sendClaimedUserText(B,W)){if(Y)throw Error("自动续接请求提交失败,未重试");return}this.status="working"}finally{this.releaseTurnOpen(P)}return}if(this.openingTurn||this.pendingUserMessageCount>0){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);return}if(this.pendingTurnInputs.push($),!await this.sendClaimedUserText(this.proc,W))return;if(H&&Q)K(Q)}hasPendingAsk(){return Oj(this)}refreshPendingAsks(){a6(this)}askBlockReason($){return j9(this,$)}onMultiMessageInbound($,Z,J,Q){return rB(this,$,Z,J,Q)}clearMultiMsgBuffer($){JV(this,$)}onAskMessageAnswer($,Z,J){return Aj(this,$,Z,J)}onAskAnswer($,Z,J,Q){return Nj(this,$,Z,J,Q)}onAskCustomAnswer($,Z,J,Q){return BV(this,$,Z,J,Q)}onPermissionDecision($,Z,J){return xj(this,$,Z,J)}clearResumeBindingForFreshCodex($){if($.isConversationResumable?.())throw Error("fresh Codex thread was unexpectedly marked resumable during init");let Z=c1(this.sessionName,"codex");if(u4(this.sessionName,"codex"),this.selectedProvider==="codex")this.lastSessionRef=null,this.lastSessionId=null;if(Z)j(`session "${this.sessionName}": cleared pre-fresh Codex resume binding thread=${Z.sessionId}`)}invalidateMissingCodexResume($,Z,J){if(!$||this.selectedProvider!=="codex")return null;let Q=IV(Z);if(!Q||!["thread/read","thread/resume","thread/fork"].includes(Q.method)||Q.serverCode!==-32600||Q.serverMessage!==`no rollout found for thread id ${$}`)return null;let Y=c1(this.sessionName,"codex");if(!Y||Y.sessionId!==$)return null;try{u4(this.sessionName,"codex")}catch(X){let z=`已确认恢复点无 rollout,但作废失败: ${E(X)}`;return j(`session "${this.sessionName}": ${z} thread=${$}`),z}if(this.lastSessionRef?.provider==="codex"&&this.lastSessionRef.sessionId===$)this.lastSessionRef=null,this.lastSessionId=null;J?.($);let V=`已作废无 rollout 的恢复点 thread=${h0($)}`;return j(`session "${this.sessionName}": ${V} fullThread=${$}`),V}persistResumableSessionId($=!1,Z=this.proc,J=!0){let Q=Z?.provider==="claude"?this.pendingConversationMaterialization:null,Y=Z?.sessionId;if(!Z)return null;if(Z.provider==="codex"&&Z.isConversationResumable?.()!==!0)return null;if(!Y){if(!Q)return null;let z=Error("Claude pending fork did not provide a materialized session id");if(j(`session "${this.sessionName}": ${z.message}`),$)throw z;return z.message}if(Z.provider==="codex")this.codexQuotaWaitLaunch=null;let V={provider:Z.provider,sessionId:Y,cwd:this.workDir};if(Q&&(Y===Q.launch.source.sessionId||Q.previousSessionId!==null&&Y===Q.previousSessionId)){let z=Error(`Claude fork did not materialize an independent session id (${Y})`);if(j(`session "${this.sessionName}": ${z.message}`),$)throw z;return z.message}try{W8(this.sessionName,V)}catch(z){let H=`会话恢复点持久化失败: ${E(z)}`,G=this.resumePersistenceError!==H;if(this.resumePersistenceError=H,Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Y;if(j(`session "${this.sessionName}": ${H}`),$)throw z;if(G&&J)h(this.chatId,`⚠️ ${H};当前进程可继续,但 daemon 重启前请先解决本机状态目录写入问题。`);return H}if(Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Y;let X=Z.provider==="codex"?this.flushPendingCodexTurnAnchors(Z):null;if(X){let z=this.resumePersistenceError!==X;if(this.resumePersistenceError=X,$)throw Error(X);if(z&&J)h(this.chatId,`⚠️ ${X}`);return X}return this.resumePersistenceError=null,null}consumePendingConversationMaterialization(){let $=this.pendingConversationMaterialization;if(!$)return null;let Z=this.lastSessionRef;if(Z?.provider!=="claude"||Z.cwd!==this.workDir||Z.sessionId===$.launch.source.sessionId||Z.sessionId===$.previousSessionId)return j(`session "${this.sessionName}": ${"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker"}`),"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker";try{return u1(this.sessionName,null),this.pendingConversationMaterialization=null,null}catch(J){let Q=`Claude 待生成分支标记清除失败: ${E(J)}`;return j(`session "${this.sessionName}": ${Q}`),Q}}bgStore(){return{active:this.backgroundTasks,pending:this.pendingBgTasks}}applyBgStore($){this.backgroundTasks=$.active,this.pendingBgTasks=$.pending}onMainThreadAdvance(){if(this.pendingBgTasks.length===0)return;this.applyBgStore(fQ(this.bgStore())),this.onBackgroundTaskChanged()}bgTaskOwns($){return this.backgroundTasks.some((Z)=>Z.toolUseId===$)||this.pendingBgTasks.some((Z)=>Z.toolUseId===$)}hasPendingAgentTool(){return this.nativeAgentTools.size>0}onBackgroundTaskChanged($=!1){if(!this.backgroundTasks.length)return;if($){if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull().catch((Z)=>this.reportBackgroundWriteFailure(Z))}else this.scheduleBackgroundRefresh()}scheduleBackgroundRefresh(){if(this.backgroundRefreshTimer)return;this.backgroundRefreshTimer=setTimeout(()=>{this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull().catch(($)=>this.reportBackgroundWriteFailure($))},1500)}refreshBackgroundCardFull(){let $=this.backgroundOwner,Z=[...this.backgroundTasks],J=this.agentCards.syncBackground(this.chatId,$,Z),Q;return Q=J.then(()=>{this.backgroundWriteError=null}).finally(()=>{if(this.backgroundSync===Q)this.backgroundSync=null}),this.backgroundSync=Q,Q}async reportBackgroundWriteFailure($){let Z=E($);if(j(`session "${this.sessionName}": task panel update failed: ${Z}`),this.backgroundWriteError===Z)return;this.backgroundWriteError=Z,await h(this.chatId,`⚠️ 运行任务面板更新失败:${Z}`)}async resetBackgroundTasks(){if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null;let $=Date.now();if(this.backgroundTasks=this.backgroundTasks.map((Z)=>R$(Z)?Z:{...Z,status:"killed",endTime:Z.endTime??$}),this.pendingBgTasks=[],this.backgroundSync)try{await this.backgroundSync}catch(Z){j(`session "${this.sessionName}": retrying terminal delegation update after: ${E(Z)}`)}if(await this.refreshBackgroundCardFull(),this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null,this.agentCards.releaseBackground(this.backgroundOwner),this.backgroundOwner=yV(16).toString("hex"),this.backgroundTasks=[],this.nativeAgentTools.clear(),this.lastMainTaskToolUseId=null}startScheduledTurnCard($,Z,J,Q){if(this.proc!==$||this.procEpoch!==Z||!$.isAlive())return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.bgResumePending)return;let Y;try{Y=this.beginTurnOpen($,Z,!0)}catch(X){j(`session "${this.sessionName}": scheduled turn-open ownership conflict: ${E(X)}`);return}let V=J.replace(/\s+/g," ").trim();this.lastTurnUserPreview=`⏰ ${V.slice(0,78)}`,j(`session "${this.sessionName}": scheduled wakeup prompt=${Q??"MISS"}`),(async()=>{try{let X=await this.openTurnCard(Y,"","scheduled_wakeup");if(this.proc!==$||this.procEpoch!==Z){if(j(`session "${this.sessionName}": scheduled ${$.provider} turn became stale while opening epoch=${Z}`),X&&this.currentTurn===X)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);return}if(!X||this.currentTurn!==X){if(!this.ownsTurnOpen(Y))return;if(this.bgResumeCardless=!0,Y.sawResult)Y.sawResult=!1,j(`session "${this.sessionName}": scheduled open failed after result — flushing orphan now`),this.flushOrphanAssistantToChat("scheduled open failed, result already arrived");else j(`session "${this.sessionName}": scheduled open failed — orphan text flush will cover the output`)}else if(Y.sawResult)Y.sawResult=!1,j(`session "${this.sessionName}": scheduled result raced card-open — closing freshly-opened card`),await this.closeTurnCard(Y.terminalSuffix,{forcePush:Y.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(Y)}})().catch((X)=>{j(`session "${this.sessionName}": scheduled turn-open handler failed: ${E(X)}`)})}wireProc($,Z){if(Z===void 0)this.invalidateTurnOpen();let J=Z??++this.procEpoch;if(Z===void 0&&this.proc!==$)this.proc=$;let Q=()=>this.proc===$&&this.procEpoch===J;if(v$($))$.setTranslationPresentationPolicy?.((z)=>{if(!Q()||this.stoppingProc===$||this.blockedProc===$)return"hidden";if(z.kind==="assistant_text"&&z.parentToolUseId)return"hidden";if((z.kind==="tool_input"||z.kind==="tool_result")&&z.parentToolUseId&&this.bgTaskOwns(z.parentToolUseId))return"background";if(z.kind==="tool_result"&&z.toolName==="AskUserQuestion")return"hidden";return"main"});let Y=!1,V=!1,X=(z,H)=>{$.on(z,(G)=>{let W=this.steeringGeneration,K={result:{...$.lastResult},totalUsage:$.lastTotalUsage?{...$.lastTotalUsage}:null},B=()=>{if(!Q()){if(!Y)Y=!0,j(`session "${this.sessionName}": ignore stale ${$.provider} event=${String(z)} epoch=${J} currentEpoch=${this.procEpoch}`);return}if(W!==this.steeringGeneration&&z!=="exit"&&z!=="error")return;let _=this.steeringBoundary;if(_&&_.proc===$&&_.epoch===J&&z!=="error"&&!(z==="exit"&&(this.stoppingProc===$||this.blockedProc===$))){if(z==="user_input_consumed"&&_.collecting){H(G,K);return}if(_.events.push(B),(!G||typeof G!=="object"||!("parentToolUseId"in G)||!G.parentToolUseId)&&(z==="input_batch_end"||z==="assistant_text"||z==="assistant_block_stop"||z==="tool_use"||z==="tool_result"||z==="can_use_tool"||z==="hook_callback"||z==="turn_retry"||z==="codex_account_changed"||z==="thinking_progress"||z==="plan_delta"||z==="turn_plan_updated"||z==="context_compacted"||z==="turn_started"||z==="result"||z==="exit"))_.start();return}if(z!=="exit"&&(this.stoppingProc===$||this.blockedProc===$)){if(!V)V=!0,j(`session "${this.sessionName}": ignore ${$.provider} event=${String(z)} while process stop is pending`);return}H(G,K)};B()})};X("error",(z)=>{j(`session "${this.sessionName}": ${$.provider} process error: ${z}`)}),X("user_input_submitted",()=>{let z=this.procPendingFileDeliveryModes.get($);if(z===void 0)return;this.procFileDeliveryModes.set($,z),this.procPendingFileDeliveryModes.delete($),this.procFileDeliveryNeedsUpdate.delete($)}),X("init",()=>{if($.provider==="codex"&&$.quotaWaitPromise){if(this.daemonRestoreRequired=!1,this.status==="starting")this.status=this.currentTurn?"working":"idle";this.opts.onLifecycleChange?.()}if($.provider==="codex"&&$.launchKind==="fresh")this.clearResumeBindingForFreshCodex($);else this.persistResumableSessionId(!0);if(this.initCount++,j(`session "${this.sessionName}": SDK init#${this.initCount} pendingCount=${this.pendingUserMessageCount} midBuffer=${this.pendingMidTurnMsgs.length} currentTurn=${this.currentTurn?"yes":"no"} openingTurn=${this.openingTurn}`),this.currentTurn||this.openingTurn){if(this.pendingUserMessageCount>0)j(`session "${this.sessionName}": SDK init claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;this.steerPendingInputs();return}let z=this.pendingUserMessageCount>0,H=!z&&this.bgResumePending;if(!z&&!H)return;let G=this.lastUserOpenId,W;try{W=this.beginTurnOpen($,J,!0)}catch(_){j(`session "${this.sessionName}": init turn-open ownership conflict: ${E(_)}`);return}if(this.bgResumePending=!1,z)this.pendingUserMessageCount=0,this.currentBatchReactionIds=this.pendingReactionIds,this.pendingReactionIds=new Map;let K=z?[...this.currentBatchReactionIds.keys()]:[],B=()=>{for(let _ of K){let P=this.currentBatchReactionIds.get(_);if(this.currentBatchReactionIds.delete(_),P)g0(_,P)}};(async()=>{try{let _=await this.openTurnCard(W,G,z?"user_message":"bg_task_resume");if(!Q()){if(j(`session "${this.sessionName}": ${$.provider} became stale while opening turn card epoch=${J}`),_&&this.currentTurn===_)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);B();return}if(!_||this.currentTurn!==_){if(!this.ownsTurnOpen(W)){B();return}if(W.sawResult&&W.terminalSuffix)h(this.chatId,W.terminalSuffix);if(z)j(`session "${this.sessionName}": init-path openTurnCard failed — sendInterrupt + release reactions`),this.proc?.sendInterrupt(),B();else if(this.bgResumeCardless=!0,W.sawResult)W.sawResult=!1,j(`session "${this.sessionName}": bg-resume openTurnCard failed, result already arrived — flushing orphan now`),this.flushOrphanAssistantToChat("bg-resume open failed, result already arrived");else j(`session "${this.sessionName}": bg-resume openTurnCard failed — orphan text flush will cover the output`)}else if(W.sawResult)W.sawResult=!1,j(`session "${this.sessionName}": result raced card-open — closing freshly-opened turn card now`),await this.closeTurnCard(W.terminalSuffix,{forcePush:W.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(W)}})().catch((_)=>{j(`session "${this.sessionName}": init turn-open handler failed: ${E(_)}`)})}),X("scheduled_turn_input",({text:z,displayText:H,promptId:G})=>{if($.provider!=="claude"&&$.provider!=="dsh")return;this.startScheduledTurnCard($,J,H??z,G)}),X("conversation_materialized",({session_id:z,source:H})=>{if($.provider!=="codex")return;if($.sessionId!==z){j(`session "${this.sessionName}": ignore mismatched Codex materialization session=${z} current=${$.sessionId??"MISS"} source=${H}`);return}j(`session "${this.sessionName}": Codex resume point materialized thread=${z} source=${H}`),this.persistResumableSessionId()}),X("conversation_materialization_failed",({session_id:z,source:H,error:G})=>{if($.provider!=="codex"||$.sessionId!==z)return;let W=`Codex 会话落盘确认失败,未写恢复点: ${E(G)}`,K=this.resumePersistenceError!==W;if(this.resumePersistenceError=W,j(`session "${this.sessionName}": ${W} thread=${z} source=${H}`),K)h(this.chatId,`⚠️ ${W}`)}),X("turn_retry",()=>{if(this.currentTurn)this.startThinkingFooter(this.currentTurn)}),X("codex_account_changed",({accountId:z,diagnostics:H})=>{if(j(`session "${this.sessionName}": Codex account=${z}`),this.pendingAsks.clear(),this.pendingPermissions.clear(),H.length)j(`session "${this.sessionName}": Codex 未参与选号的账号: ${H.join(";")}`)}),X("turn_started",({retry:z},H)=>{if((this.currentTurn||this.openingTurn)&&this.pendingUserMessageCount>0)j(`session "${this.sessionName}": turn_started claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;if(this.persistResumableSessionId(),this.steerPendingInputs(),z){if(this.currentTurn)this.startThinkingFooter(this.currentTurn);return}let G=H.totalUsage;if(this.usageTotalsSeedUnknown&&!G){this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;return}this.currentTurnUsageBaseline=G?{...G}:null,this.currentTurnUsageBaselineKnown=!0}),X("turn_input_error",({error:z,displayError:H})=>{j(`session "${this.sessionName}": native input processing failed: ${z}`),h(this.chatId,`⚠️ ${this.backendLabel($.provider)} 输入处理错误:${H??z}`)}),X("user_input_consumed",({inputId:z})=>this.onSteeringInputConsumed($,J,z)),X("input_batch_end",()=>{}),X("thinking_progress",()=>{}),X("token_usage",({totalUsage:z})=>{if(this.persistResumableSessionId(),z)this.usageTotalsSeedUnknown=!1}),X("turn_plan_updated",(z)=>{this.handleTurnPlanUpdated(z)}),X("plan_delta",(z)=>{this.handlePlanDelta(z)}),X("context_compacted",(z)=>{this.handleContextCompacted(z)}),X("rate_limits_updated",(z)=>{if($.provider==="codex"&&!M0($.tokenSourceId)?.codexApiProvider)$H(z,M$($))}),X("thread_goal_updated",(z)=>{this.handleThreadGoalUpdated(z)}),X("thread_goal_cleared",()=>{this.handleThreadGoalCleared()}),X("assistant_text",({text:z,displayText:H,parentToolUseId:G})=>{if(G)return;this.appendAssistant(H??z)}),X("assistant_block_stop",({parentToolUseId:z})=>{if(z)return;this.finalizeCurrentAssistantSegment(),this.onMainThreadAdvance()}),X("tool_use",({id:z,name:H,input:G,displayInput:W,parentToolUseId:K})=>{let B=W??G;if(K&&this.bgTaskOwns(K)){this.applyBgStore(yQ({active:this.backgroundTasks,pending:this.pendingBgTasks},K,z,H,B)),this.onBackgroundTaskChanged();return}if(!K&&(H==="Task"||H==="Agent"||$.provider==="dsh"&&(H==="subagent"||H==="subagent_fork"))){let _=this.currentTurn;if(_)this.startWorkingFooter(_),this.finalizeCurrentAssistantSegment(),_.openBatchI=null,_.taskCreateI=null,_.taskUpdateI=null;if(this.onMainThreadAdvance(),this.nativeAgentTools.set(z,{confirmed:!1,input:G,displayInput:W}),$.provider==="claude")this.lastMainTaskToolUseId=z,this.applyBgStore(C8(this.bgStore(),{task_id:z,tool_use_id:z,task_type:"subagent",description:B?.description||B?.name||"子 Agent",prompt:B?.prompt,subagent_type:G?.subagent_type})),this.onBackgroundTaskChanged(!0);return}if(Ej(this,z,H,G,W),!K)this.onMainThreadAdvance()}),X("tool_result",({tool_use_id:z,content:H,displayContent:G,displayInput:W,is_error:K,parentToolUseId:B,input:_})=>{let P=G??H;if(B&&this.bgTaskOwns(B)){this.applyBgStore(IQ({active:this.backgroundTasks,pending:this.pendingBgTasks},B,z,P,K)),this.onBackgroundTaskChanged();return}let L=!B&&this.nativeAgentTools.get(z);if(L){if(this.nativeAgentTools.delete(z),this.lastMainTaskToolUseId===z)this.lastMainTaskToolUseId=null;if(K||$.provider==="claude"&&!L.confirmed&&L.input?.run_in_background!==!0){let q=typeof P==="string"?P:Array.isArray(P)?P.map((M)=>typeof M?.text==="string"?M.text:JSON.stringify(M)).join(`
333
- `):JSON.stringify(P)??"MISS",D=this.backgroundTasks.find((M)=>M.toolUseId===z);if(!D)this.applyBgStore(C8(this.bgStore(),{task_id:z,tool_use_id:z,task_type:"subagent",description:(L.displayInput??L.input)?.description||"子 Agent",prompt:(L.displayInput??L.input)?.prompt})),D=this.backgroundTasks.find((M)=>M.toolUseId===z);this.applyBgStore(Q6(this.bgStore(),{task_id:D.id,status:K?"failed":"completed",summary:q})),this.onBackgroundTaskChanged(!0)}$4(this);return}Sj(this,z,H,K,_,G,W)}),X("can_use_tool",(z)=>{bj(this,z)}),X("hook_callback",(z)=>{this.proc?.sendHookResponse(z.request_id,{})}),X("result",(z,H)=>{if(v$($)&&z?.subtype==="claude_turn_start_failed")this.pendingUserMessageCount=Math.max(0,this.pendingUserMessageCount-1),this.procPendingFileDeliveryModes.delete($);this.releaseUnconsumedSteering($);let G=this.persistResumableSessionId(),W=G?null:this.consumePendingConversationMaterialization(),K=[G,W].filter(Boolean).join(";")||null;if(this.accumulateResultStats(H),this.openingTurnOwner)this.openingTurnOwner.sawResult=!0;if(this.userInterrupted){this.userInterrupted=!1,this.discardOrphanAssistant(),this.bgResumePending=!1;let N=this.proc?.lastResult.subtype??"unknown",S=this.proc?.lastResult.is_error===!0;j(`session "${this.sessionName}": SDK result after user stop subtype=${N} isError=${S} — ignored`),this.status="idle";return}let B=z?.is_error!==!0?this.recordTurnAnchor(z?.checkpoint):null;if(z?.is_error===!0)this.lastTurnUserPreview="";if(!this.currentTurn&&!this.openingTurn)this.flushOrphanAssistantToChat("result with no turn card");let _=this.pendingMidTurnMsgs.length>0,P=H.result.is_error===!0,L=H.result.subtype??"success",q=z?.displayError??z?.error,D=typeof q==="string"&&q.trim()?q.trim():L,M,U=!1,A=this.proc?this.backendLabel(this.proc.provider):this.backendLabel(),O=[K,B].filter(Boolean).join(";")||null;if(O)M=`⚠️ ${O}`,U=!0;else if(_)M=P?`⚠️ ${A} ${D},用户已介入`:"\uD83D\uDCE8 转交新卡";else if(P)M=`⚠️ ${A} ${D}`,U=!0;if(this.openingTurnOwner)this.openingTurnOwner.terminalSuffix=M,this.openingTurnOwner.terminalForcePush=U;if(O&&!this.currentTurn&&!this.openingTurn)h(this.chatId,`⚠️ ${O}`);if(j(`session "${this.sessionName}": SDK result subtype=${L} isError=${P} midBuffer=${this.pendingMidTurnMsgs.length} forcePush=${U}`),this.closeTurnCard(M,{forcePush:U,hasFreshResult:!0}).catch((N)=>{j(`session "${this.sessionName}": result card close failed: ${E(N)}`)}),this.status="idle",_)this.drainMidTurnAndOpen().catch((N)=>{j(`session "${this.sessionName}": mid-turn drain failed: ${E(N)}`)})}),X("bg_task_started",(z)=>{let H=z.tool_use_id??($.provider==="claude"?this.lastMainTaskToolUseId:null)??void 0,G=H?this.nativeAgentTools.get(H):void 0;if(G)G.confirmed=!0;j(`session "${this.sessionName}": bg_task_started task=${z.task_id} type=${z.task_type??"-"} subagent=${z.subagent_type??"-"} toolUseId=${H?.slice(0,8)??"-"} desc=${(z.description??"").slice(0,40)}`),this.applyBgStore(C8(this.bgStore(),{...z,...z.display,tool_use_id:H})),this.onBackgroundTaskChanged(!0)}),X("bg_task_progress",(z)=>{this.applyBgStore(wQ(this.bgStore(),{...z,...z.display})),this.onBackgroundTaskChanged()}),X("bg_task_updated",(z)=>{this.applyBgStore(vQ(this.bgStore(),{...z,patch:{...z.patch,...z.display}})),this.onBackgroundTaskChanged(!!z.patch.status||z.patch.is_backgrounded===!0)}),X("bg_task_settled",(z)=>{if(j(`session "${this.sessionName}": bg_task_settled task=${z.task_id} status=${z.status}`),this.applyBgStore(Q6(this.bgStore(),{...z,...z.display})),this.onBackgroundTaskChanged(!0),$.provider==="claude"&&!this.currentTurn&&!this.openingTurn&&this.initCount>=1)this.bgResumePending=!0}),X("subagent_step",(z)=>{this.applyBgStore(hQ(this.bgStore(),z.thread_id,z.item_id,z.tool,z.phase,z.brief)),this.onBackgroundTaskChanged()}),X("exit",({code:z,signal:H,expected:G})=>{if(j(`session "${this.sessionName}": ${$.provider} exited code=${z} signal=${H} expected=${G}`),this.stoppingProc===$||this.blockedProc===$){if(this.blockedProc===$){let P=$.conversationMaterializationFailure?.(),L=this.persistResumableSessionId(!1,$,!1),q=[P&&$.isConversationResumable?.()!==!0?`Codex 会话落盘确认失败: ${E(P)}`:null,L].filter(Boolean).join(";");if(q)h(this.chatId,`⚠️ 旧进程退出后的恢复状态收尾失败: ${q}`);this.discardPendingCodexTurnAnchors($,"blocked process finally exited")}j(`session "${this.sessionName}": blocked/stopping ${$.provider} exit confirmed`),this.detachProc($),this.status="stopped",this.opts.onLifecycleChange?.();return}this.discardPendingCodexTurnAnchors($,"unexpected process exit"),this.cancelAgentRuns(`${$.provider} process exited`).catch((P)=>{j(`session "${this.sessionName}": cancel Agent runs after process exit failed: ${E(P)}`)});let W=this.backendLabel($.provider),K=`code=${z??"null"}, signal=${H??"null"}`,B=G?`\uD83D\uDED1 ${W} 已退出`:`⚠️ ${W} 异常退出 (${K})`;if(this.currentTurn)this.closeTurnCard(B).catch((P)=>{j(`session "${this.sessionName}": process-exit current main-card close failed: ${E(P)}`)});let _=this.waitForTurnCloses().catch((P)=>{j(`session "${this.sessionName}": process-exit main-card close failed: ${E(P)}`)});this.detachProc($),this.flushOrphanAssistantToChat("process exit"),this.bgResumePending=!1,this.bgResumeCardless=!1,this.clearMultiMsgBuffer("process exit"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.userInterrupted=!1,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped",this.opts.onLifecycleChange?.(),this.runLifecycle("process-exit-cleanup",async()=>{let P=await Promise.allSettled([_,this.resetBackgroundTasks()]);for(let L of P)if(L.status==="rejected")j(`session "${this.sessionName}": process-exit terminal cleanup failed: ${E(L.reason)}`);if(!G)await k(this.chatId,`⚠️ ${W} 异常退出 (${K})。回复任意消息将重新启动。`)}).catch((P)=>{j(`session "${this.sessionName}": process-exit cleanup rejected: ${E(P)}`)})})}accumulateResultStats($){let Z=$?.result??this.proc?.lastResult;if(!Z)return;let J=this.currentTurnUsageBaselineKnown?PZ($?$.totalUsage:this.proc?.lastTotalUsage,this.currentTurnUsageBaseline):this.proc?.provider==="claude"&&Z.usage?{...Z.usage}:null;this.lastTurnUsage=J,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;let Q=LZ(J),Y=this.proc?.provider==="claude"?0:Z.cost_delta_usd??0,V=Z.duration_ms??0;if(Q!=null)this.cumStats.tokens+=Q;this.cumStats.costUsd+=Y,this.cumStats.turns+=Z.num_turns??1,this.lastTurnDelta={tokens:Q,costUsd:Y,durationMs:V}}currentContextTokens($=this.proc){if($?.provider==="claude"||$?.provider==="dsh")return $.lastContextTokens??null;let Z=$?.lastUsage;return K6(Z)}contextLimitForDisplay($=this.proc){return B6($?.lastContextWindow)}steerPendingInputs(){let $=this.proc,Z=this.currentTurn;if(!$?.steerUserText||!Z||this.openingTurn||this.steeringSend||this.pendingMidTurnMsgs.length===0||this.modelSettingsBlockReason())return;let J=this.procEpoch,Q=this.steeringGeneration,Y=this.pendingMidTurnMsgs.splice(0),V=this.pendingReactionIds,X=zE(),z={proc:$,epoch:J,generation:Q,turn:Z,batch:Y,reactions:V,consumed:!1};this.submittedSteering.set(X,z);let H=!1,G=!1,W=()=>this.proc===$&&this.procEpoch===J&&this.steeringGeneration===Q&&$.isAlive(),K=Promise.resolve().then(async()=>{if(!W())return;let B=this.disabledSubscriptionMessage($.tokenSourceId);if(B)throw Error(B);if(G=await $.steerUserText(Y.map((_)=>_.wireText).join(`
332
+ `:"")+$,K=(B)=>{this.pendingReactionIds.set(B,""),(async()=>{let _=await K$(B,"OneSecond");if(!_)return;if(this.pendingReactionIds.has(B))this.pendingReactionIds.set(B,_);else if(this.currentBatchReactionIds.has(B))this.currentBatchReactionIds.set(B,_);else g0(B,_)})().catch((_)=>{j(`session "${this.sessionName}": reaction tracking failed: ${E(_)}`)})};if(Y&&(this.proc!==Y||!Y.isAlive()))throw Error("原会话进程已退出,未发送自动续接请求,也未创建新会话");if(!this.isRunning()){if(this.openingTurn||this.currentTurn){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);return}await this.startColdUserTurn($,W,J);return}if(this.currentTurn!==null||this.steeringSend){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);this.steerPendingInputs();return}if(!this.openingTurn&&this.initCount>=1){let B=this.proc,_=this.procEpoch,P=this.beginTurnOpen(B,_);try{this.pendingTurnInputs.push($);let L=await this.openTurnCard(P,J,"user_message");if(!L||this.currentTurn!==L){if(Y)throw Error("自动续接卡片未打开,未发送续接请求");return}if(this.proc!==B||this.procEpoch!==_||!B.isAlive()){if(await this.closeTurnCard(`⚠️ ${this.backendLabel(B.provider)} 已退出`),Y)throw Error("原会话进程已退出,未发送自动续接请求");return}if(!await this.sendClaimedUserText(B,W)){if(Y)throw Error("自动续接请求提交失败,未重试");return}this.status="working"}finally{this.releaseTurnOpen(P)}return}if(this.openingTurn||this.pendingUserMessageCount>0){if(this.pendingMidTurnMsgs.push({text:$,wireText:W,userOpenId:J,msgId:Q}),Q)K(Q);return}if(this.pendingTurnInputs.push($),!await this.sendClaimedUserText(this.proc,W))return;if(H&&Q)K(Q)}hasPendingAsk(){return Oj(this)}refreshPendingAsks(){a6(this)}askBlockReason($){return j9(this,$)}onMultiMessageInbound($,Z,J,Q){return rB(this,$,Z,J,Q)}clearMultiMsgBuffer($){JV(this,$)}onAskMessageAnswer($,Z,J){return Aj(this,$,Z,J)}onAskAnswer($,Z,J,Q){return Nj(this,$,Z,J,Q)}onAskCustomAnswer($,Z,J,Q){return BV(this,$,Z,J,Q)}onPermissionDecision($,Z,J){return xj(this,$,Z,J)}clearResumeBindingForFreshCodex($){if($.isConversationResumable?.())throw Error("fresh Codex thread was unexpectedly marked resumable during init");let Z=c1(this.sessionName,"codex");if(u4(this.sessionName,"codex"),this.selectedProvider==="codex")this.lastSessionRef=null,this.lastSessionId=null;if(Z)j(`session "${this.sessionName}": cleared pre-fresh Codex resume binding thread=${Z.sessionId}`)}invalidateMissingCodexResume($,Z,J){if(!$||this.selectedProvider!=="codex")return null;let Q=IV(Z);if(!Q||!["thread/read","thread/resume","thread/fork"].includes(Q.method)||Q.serverCode!==-32600||Q.serverMessage!==`no rollout found for thread id ${$}`)return null;let Y=c1(this.sessionName,"codex");if(!Y||Y.sessionId!==$)return null;try{u4(this.sessionName,"codex")}catch(X){let z=`已确认恢复点无 rollout,但作废失败: ${E(X)}`;return j(`session "${this.sessionName}": ${z} thread=${$}`),z}if(this.lastSessionRef?.provider==="codex"&&this.lastSessionRef.sessionId===$)this.lastSessionRef=null,this.lastSessionId=null;J?.($);let V=`已作废无 rollout 的恢复点 thread=${h0($)}`;return j(`session "${this.sessionName}": ${V} fullThread=${$}`),V}persistResumableSessionId($=!1,Z=this.proc,J=!0){let Q=Z?.provider==="claude"?this.pendingConversationMaterialization:null,Y=Z?.sessionId;if(!Z)return null;if(Z.provider==="codex"&&Z.isConversationResumable?.()!==!0)return null;if(!Y){if(!Q)return null;let z=Error("Claude pending fork did not provide a materialized session id");if(j(`session "${this.sessionName}": ${z.message}`),$)throw z;return z.message}if(Z.provider==="codex")this.codexQuotaWaitLaunch=null;let V={provider:Z.provider,sessionId:Y,cwd:this.workDir};if(Q&&(Y===Q.launch.source.sessionId||Q.previousSessionId!==null&&Y===Q.previousSessionId)){let z=Error(`Claude fork did not materialize an independent session id (${Y})`);if(j(`session "${this.sessionName}": ${z.message}`),$)throw z;return z.message}try{W8(this.sessionName,V)}catch(z){let H=`会话恢复点持久化失败: ${E(z)}`,G=this.resumePersistenceError!==H;if(this.resumePersistenceError=H,Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Y;if(j(`session "${this.sessionName}": ${H}`),$)throw z;if(G&&J)h(this.chatId,`⚠️ ${H};当前进程可继续,但 daemon 重启前请先解决本机状态目录写入问题。`);return H}if(Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Y;let X=Z.provider==="codex"?this.flushPendingCodexTurnAnchors(Z):null;if(X){let z=this.resumePersistenceError!==X;if(this.resumePersistenceError=X,$)throw Error(X);if(z&&J)h(this.chatId,`⚠️ ${X}`);return X}return this.resumePersistenceError=null,null}consumePendingConversationMaterialization(){let $=this.pendingConversationMaterialization;if(!$)return null;let Z=this.lastSessionRef;if(Z?.provider!=="claude"||Z.cwd!==this.workDir||Z.sessionId===$.launch.source.sessionId||Z.sessionId===$.previousSessionId)return j(`session "${this.sessionName}": ${"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker"}`),"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker";try{return u1(this.sessionName,null),this.pendingConversationMaterialization=null,null}catch(J){let Q=`Claude 待生成分支标记清除失败: ${E(J)}`;return j(`session "${this.sessionName}": ${Q}`),Q}}bgStore(){return{active:this.backgroundTasks,pending:this.pendingBgTasks}}applyBgStore($){this.backgroundTasks=$.active,this.pendingBgTasks=$.pending}onMainThreadAdvance(){if(this.pendingBgTasks.length===0)return;this.applyBgStore(yQ(this.bgStore())),this.onBackgroundTaskChanged()}bgTaskOwns($){return this.backgroundTasks.some((Z)=>Z.toolUseId===$)||this.pendingBgTasks.some((Z)=>Z.toolUseId===$)}hasPendingAgentTool(){return this.nativeAgentTools.size>0}onBackgroundTaskChanged($=!1){if(!this.backgroundTasks.length)return;if($){if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull().catch((Z)=>this.reportBackgroundWriteFailure(Z))}else this.scheduleBackgroundRefresh()}scheduleBackgroundRefresh(){if(this.backgroundRefreshTimer)return;this.backgroundRefreshTimer=setTimeout(()=>{this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull().catch(($)=>this.reportBackgroundWriteFailure($))},1500)}refreshBackgroundCardFull(){let $=this.backgroundOwner,Z=[...this.backgroundTasks],J=this.agentCards.syncBackground(this.chatId,$,Z),Q;return Q=J.then(()=>{this.backgroundWriteError=null}).finally(()=>{if(this.backgroundSync===Q)this.backgroundSync=null}),this.backgroundSync=Q,Q}async reportBackgroundWriteFailure($){let Z=E($);if(j(`session "${this.sessionName}": task panel update failed: ${Z}`),this.backgroundWriteError===Z)return;this.backgroundWriteError=Z,await h(this.chatId,`⚠️ 运行任务面板更新失败:${Z}`)}async resetBackgroundTasks(){if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null;let $=Date.now();if(this.backgroundTasks=this.backgroundTasks.map((Z)=>R$(Z)?Z:{...Z,status:"killed",endTime:Z.endTime??$}),this.pendingBgTasks=[],this.backgroundSync)try{await this.backgroundSync}catch(Z){j(`session "${this.sessionName}": retrying terminal delegation update after: ${E(Z)}`)}if(await this.refreshBackgroundCardFull(),this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer);this.backgroundRefreshTimer=null,this.agentCards.releaseBackground(this.backgroundOwner),this.backgroundOwner=fV(16).toString("hex"),this.backgroundTasks=[],this.nativeAgentTools.clear(),this.lastMainTaskToolUseId=null}startScheduledTurnCard($,Z,J,Q){if(this.proc!==$||this.procEpoch!==Z||!$.isAlive())return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.bgResumePending)return;let Y;try{Y=this.beginTurnOpen($,Z,!0)}catch(X){j(`session "${this.sessionName}": scheduled turn-open ownership conflict: ${E(X)}`);return}let V=J.replace(/\s+/g," ").trim();this.lastTurnUserPreview=`⏰ ${V.slice(0,78)}`,j(`session "${this.sessionName}": scheduled wakeup prompt=${Q??"MISS"}`),(async()=>{try{let X=await this.openTurnCard(Y,"","scheduled_wakeup");if(this.proc!==$||this.procEpoch!==Z){if(j(`session "${this.sessionName}": scheduled ${$.provider} turn became stale while opening epoch=${Z}`),X&&this.currentTurn===X)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);return}if(!X||this.currentTurn!==X){if(!this.ownsTurnOpen(Y))return;if(this.bgResumeCardless=!0,Y.sawResult)Y.sawResult=!1,j(`session "${this.sessionName}": scheduled open failed after result — flushing orphan now`),this.flushOrphanAssistantToChat("scheduled open failed, result already arrived");else j(`session "${this.sessionName}": scheduled open failed — orphan text flush will cover the output`)}else if(Y.sawResult)Y.sawResult=!1,j(`session "${this.sessionName}": scheduled result raced card-open — closing freshly-opened card`),await this.closeTurnCard(Y.terminalSuffix,{forcePush:Y.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(Y)}})().catch((X)=>{j(`session "${this.sessionName}": scheduled turn-open handler failed: ${E(X)}`)})}wireProc($,Z){if(Z===void 0)this.invalidateTurnOpen();let J=Z??++this.procEpoch;if(Z===void 0&&this.proc!==$)this.proc=$;let Q=()=>this.proc===$&&this.procEpoch===J;if(v$($))$.setTranslationPresentationPolicy?.((z)=>{if(!Q()||this.stoppingProc===$||this.blockedProc===$)return"hidden";if(z.kind==="assistant_text"&&z.parentToolUseId)return"hidden";if((z.kind==="tool_input"||z.kind==="tool_result")&&z.parentToolUseId&&this.bgTaskOwns(z.parentToolUseId))return"background";if(z.kind==="tool_result"&&z.toolName==="AskUserQuestion")return"hidden";return"main"});let Y=!1,V=!1,X=(z,H)=>{$.on(z,(G)=>{let W=this.steeringGeneration,K={result:{...$.lastResult},totalUsage:$.lastTotalUsage?{...$.lastTotalUsage}:null},B=()=>{if(!Q()){if(!Y)Y=!0,j(`session "${this.sessionName}": ignore stale ${$.provider} event=${String(z)} epoch=${J} currentEpoch=${this.procEpoch}`);return}if(W!==this.steeringGeneration&&z!=="exit"&&z!=="error")return;let _=this.steeringBoundary;if(_&&_.proc===$&&_.epoch===J&&z!=="error"&&!(z==="exit"&&(this.stoppingProc===$||this.blockedProc===$))){if(z==="user_input_consumed"&&_.collecting){H(G,K);return}if(_.events.push(B),(!G||typeof G!=="object"||!("parentToolUseId"in G)||!G.parentToolUseId)&&(z==="input_batch_end"||z==="assistant_text"||z==="assistant_block_stop"||z==="tool_use"||z==="tool_result"||z==="can_use_tool"||z==="hook_callback"||z==="turn_retry"||z==="codex_account_changed"||z==="thinking_progress"||z==="plan_delta"||z==="turn_plan_updated"||z==="context_compacted"||z==="turn_started"||z==="result"||z==="exit"))_.start();return}if(z!=="exit"&&(this.stoppingProc===$||this.blockedProc===$)){if(!V)V=!0,j(`session "${this.sessionName}": ignore ${$.provider} event=${String(z)} while process stop is pending`);return}H(G,K)};B()})};X("error",(z)=>{j(`session "${this.sessionName}": ${$.provider} process error: ${z}`)}),X("user_input_submitted",()=>{let z=this.procPendingFileDeliveryModes.get($);if(z===void 0)return;this.procFileDeliveryModes.set($,z),this.procPendingFileDeliveryModes.delete($),this.procFileDeliveryNeedsUpdate.delete($)}),X("init",()=>{if($.provider==="codex"&&$.quotaWaitPromise){if(this.daemonRestoreRequired=!1,this.status==="starting")this.status=this.currentTurn?"working":"idle";this.opts.onLifecycleChange?.()}if($.provider==="codex"&&$.launchKind==="fresh")this.clearResumeBindingForFreshCodex($);else this.persistResumableSessionId(!0);if(this.initCount++,j(`session "${this.sessionName}": SDK init#${this.initCount} pendingCount=${this.pendingUserMessageCount} midBuffer=${this.pendingMidTurnMsgs.length} currentTurn=${this.currentTurn?"yes":"no"} openingTurn=${this.openingTurn}`),this.currentTurn||this.openingTurn){if(this.pendingUserMessageCount>0)j(`session "${this.sessionName}": SDK init claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;this.steerPendingInputs();return}let z=this.pendingUserMessageCount>0,H=!z&&this.bgResumePending;if(!z&&!H)return;let G=this.lastUserOpenId,W;try{W=this.beginTurnOpen($,J,!0)}catch(_){j(`session "${this.sessionName}": init turn-open ownership conflict: ${E(_)}`);return}if(this.bgResumePending=!1,z)this.pendingUserMessageCount=0,this.currentBatchReactionIds=this.pendingReactionIds,this.pendingReactionIds=new Map;let K=z?[...this.currentBatchReactionIds.keys()]:[],B=()=>{for(let _ of K){let P=this.currentBatchReactionIds.get(_);if(this.currentBatchReactionIds.delete(_),P)g0(_,P)}};(async()=>{try{let _=await this.openTurnCard(W,G,z?"user_message":"bg_task_resume");if(!Q()){if(j(`session "${this.sessionName}": ${$.provider} became stale while opening turn card epoch=${J}`),_&&this.currentTurn===_)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);B();return}if(!_||this.currentTurn!==_){if(!this.ownsTurnOpen(W)){B();return}if(W.sawResult&&W.terminalSuffix)h(this.chatId,W.terminalSuffix);if(z)j(`session "${this.sessionName}": init-path openTurnCard failed — sendInterrupt + release reactions`),this.proc?.sendInterrupt(),B();else if(this.bgResumeCardless=!0,W.sawResult)W.sawResult=!1,j(`session "${this.sessionName}": bg-resume openTurnCard failed, result already arrived — flushing orphan now`),this.flushOrphanAssistantToChat("bg-resume open failed, result already arrived");else j(`session "${this.sessionName}": bg-resume openTurnCard failed — orphan text flush will cover the output`)}else if(W.sawResult)W.sawResult=!1,j(`session "${this.sessionName}": result raced card-open — closing freshly-opened turn card now`),await this.closeTurnCard(W.terminalSuffix,{forcePush:W.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(W)}})().catch((_)=>{j(`session "${this.sessionName}": init turn-open handler failed: ${E(_)}`)})}),X("scheduled_turn_input",({text:z,displayText:H,promptId:G})=>{if($.provider!=="claude"&&$.provider!=="dsh")return;this.startScheduledTurnCard($,J,H??z,G)}),X("conversation_materialized",({session_id:z,source:H})=>{if($.provider!=="codex")return;if($.sessionId!==z){j(`session "${this.sessionName}": ignore mismatched Codex materialization session=${z} current=${$.sessionId??"MISS"} source=${H}`);return}j(`session "${this.sessionName}": Codex resume point materialized thread=${z} source=${H}`),this.persistResumableSessionId()}),X("conversation_materialization_failed",({session_id:z,source:H,error:G})=>{if($.provider!=="codex"||$.sessionId!==z)return;let W=`Codex 会话落盘确认失败,未写恢复点: ${E(G)}`,K=this.resumePersistenceError!==W;if(this.resumePersistenceError=W,j(`session "${this.sessionName}": ${W} thread=${z} source=${H}`),K)h(this.chatId,`⚠️ ${W}`)}),X("turn_retry",()=>{if(this.currentTurn)this.startThinkingFooter(this.currentTurn)}),X("codex_account_changed",({accountId:z,diagnostics:H})=>{if(j(`session "${this.sessionName}": Codex account=${z}`),this.pendingAsks.clear(),this.pendingPermissions.clear(),H.length)j(`session "${this.sessionName}": Codex 未参与选号的账号: ${H.join(";")}`)}),X("turn_started",({retry:z},H)=>{if((this.currentTurn||this.openingTurn)&&this.pendingUserMessageCount>0)j(`session "${this.sessionName}": turn_started claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;if(this.persistResumableSessionId(),this.steerPendingInputs(),z){if(this.currentTurn)this.startThinkingFooter(this.currentTurn);return}let G=H.totalUsage;if(this.usageTotalsSeedUnknown&&!G){this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;return}this.currentTurnUsageBaseline=G?{...G}:null,this.currentTurnUsageBaselineKnown=!0}),X("turn_input_error",({error:z,displayError:H})=>{j(`session "${this.sessionName}": native input processing failed: ${z}`),h(this.chatId,`⚠️ ${this.backendLabel($.provider)} 输入处理错误:${H??z}`)}),X("user_input_consumed",({inputId:z})=>this.onSteeringInputConsumed($,J,z)),X("input_batch_end",()=>{}),X("thinking_progress",()=>{}),X("token_usage",({totalUsage:z})=>{if(this.persistResumableSessionId(),z)this.usageTotalsSeedUnknown=!1}),X("turn_plan_updated",(z)=>{this.handleTurnPlanUpdated(z)}),X("plan_delta",(z)=>{this.handlePlanDelta(z)}),X("context_compacted",(z)=>{this.handleContextCompacted(z)}),X("rate_limits_updated",(z)=>{if($.provider==="codex"&&!M0($.tokenSourceId)?.codexApiProvider)$H(z,M$($))}),X("thread_goal_updated",(z)=>{this.handleThreadGoalUpdated(z)}),X("thread_goal_cleared",()=>{this.handleThreadGoalCleared()}),X("assistant_text",({text:z,displayText:H,parentToolUseId:G})=>{if(G)return;this.appendAssistant(H??z)}),X("assistant_block_stop",({parentToolUseId:z})=>{if(z)return;this.finalizeCurrentAssistantSegment(),this.onMainThreadAdvance()}),X("tool_use",({id:z,name:H,input:G,displayInput:W,parentToolUseId:K})=>{let B=W??G;if(K&&this.bgTaskOwns(K)){this.applyBgStore(fQ({active:this.backgroundTasks,pending:this.pendingBgTasks},K,z,H,B)),this.onBackgroundTaskChanged();return}if(!K&&(H==="Task"||H==="Agent"||$.provider==="dsh"&&(H==="subagent"||H==="subagent_fork"))){let _=this.currentTurn;if(_)this.startWorkingFooter(_),this.finalizeCurrentAssistantSegment(),_.openBatchI=null,_.taskCreateI=null,_.taskUpdateI=null;if(this.onMainThreadAdvance(),this.nativeAgentTools.set(z,{confirmed:!1,input:G,displayInput:W}),$.provider==="claude")this.lastMainTaskToolUseId=z,this.applyBgStore(C8(this.bgStore(),{task_id:z,tool_use_id:z,task_type:"subagent",description:B?.description||B?.name||"子 Agent",prompt:B?.prompt,subagent_type:G?.subagent_type})),this.onBackgroundTaskChanged(!0);return}if(Ej(this,z,H,G,W),!K)this.onMainThreadAdvance()}),X("tool_result",({tool_use_id:z,content:H,displayContent:G,displayInput:W,is_error:K,parentToolUseId:B,input:_})=>{let P=G??H;if(B&&this.bgTaskOwns(B)){this.applyBgStore(IQ({active:this.backgroundTasks,pending:this.pendingBgTasks},B,z,P,K)),this.onBackgroundTaskChanged();return}let L=!B&&this.nativeAgentTools.get(z);if(L){if(this.nativeAgentTools.delete(z),this.lastMainTaskToolUseId===z)this.lastMainTaskToolUseId=null;if(K||$.provider==="claude"&&!L.confirmed&&L.input?.run_in_background!==!0){let q=typeof P==="string"?P:Array.isArray(P)?P.map((M)=>typeof M?.text==="string"?M.text:JSON.stringify(M)).join(`
333
+ `):JSON.stringify(P)??"MISS",F=this.backgroundTasks.find((M)=>M.toolUseId===z);if(!F)this.applyBgStore(C8(this.bgStore(),{task_id:z,tool_use_id:z,task_type:"subagent",description:(L.displayInput??L.input)?.description||"子 Agent",prompt:(L.displayInput??L.input)?.prompt})),F=this.backgroundTasks.find((M)=>M.toolUseId===z);this.applyBgStore(Q6(this.bgStore(),{task_id:F.id,status:K?"failed":"completed",summary:q})),this.onBackgroundTaskChanged(!0)}$4(this);return}Sj(this,z,H,K,_,G,W)}),X("can_use_tool",(z)=>{bj(this,z)}),X("hook_callback",(z)=>{this.proc?.sendHookResponse(z.request_id,{})}),X("result",(z,H)=>{if(v$($)&&z?.subtype==="claude_turn_start_failed")this.pendingUserMessageCount=Math.max(0,this.pendingUserMessageCount-1),this.procPendingFileDeliveryModes.delete($);this.releaseUnconsumedSteering($);let G=this.persistResumableSessionId(),W=G?null:this.consumePendingConversationMaterialization(),K=[G,W].filter(Boolean).join(";")||null;if(this.accumulateResultStats(H),this.openingTurnOwner)this.openingTurnOwner.sawResult=!0;if(this.userInterrupted){this.userInterrupted=!1,this.discardOrphanAssistant(),this.bgResumePending=!1;let N=this.proc?.lastResult.subtype??"unknown",S=this.proc?.lastResult.is_error===!0;j(`session "${this.sessionName}": SDK result after user stop subtype=${N} isError=${S} — ignored`),this.status="idle";return}let B=z?.is_error!==!0?this.recordTurnAnchor(z?.checkpoint):null;if(z?.is_error===!0)this.lastTurnUserPreview="";if(!this.currentTurn&&!this.openingTurn)this.flushOrphanAssistantToChat("result with no turn card");let _=this.pendingMidTurnMsgs.length>0,P=H.result.is_error===!0,L=H.result.subtype??"success",q=z?.displayError??z?.error,F=typeof q==="string"&&q.trim()?q.trim():L,M,U=!1,A=this.proc?this.backendLabel(this.proc.provider):this.backendLabel(),O=[K,B].filter(Boolean).join(";")||null;if(O)M=`⚠️ ${O}`,U=!0;else if(_)M=P?`⚠️ ${A} ${F},用户已介入`:"\uD83D\uDCE8 转交新卡";else if(P)M=`⚠️ ${A} ${F}`,U=!0;if(this.openingTurnOwner)this.openingTurnOwner.terminalSuffix=M,this.openingTurnOwner.terminalForcePush=U;if(O&&!this.currentTurn&&!this.openingTurn)h(this.chatId,`⚠️ ${O}`);if(j(`session "${this.sessionName}": SDK result subtype=${L} isError=${P} midBuffer=${this.pendingMidTurnMsgs.length} forcePush=${U}`),this.closeTurnCard(M,{forcePush:U,hasFreshResult:!0}).catch((N)=>{j(`session "${this.sessionName}": result card close failed: ${E(N)}`)}),this.status="idle",_)this.drainMidTurnAndOpen().catch((N)=>{j(`session "${this.sessionName}": mid-turn drain failed: ${E(N)}`)})}),X("bg_task_started",(z)=>{let H=z.tool_use_id??($.provider==="claude"?this.lastMainTaskToolUseId:null)??void 0,G=H?this.nativeAgentTools.get(H):void 0;if(G)G.confirmed=!0;j(`session "${this.sessionName}": bg_task_started task=${z.task_id} type=${z.task_type??"-"} subagent=${z.subagent_type??"-"} toolUseId=${H?.slice(0,8)??"-"} desc=${(z.description??"").slice(0,40)}`),this.applyBgStore(C8(this.bgStore(),{...z,...z.display,tool_use_id:H})),this.onBackgroundTaskChanged(!0)}),X("bg_task_progress",(z)=>{this.applyBgStore(wQ(this.bgStore(),{...z,...z.display})),this.onBackgroundTaskChanged()}),X("bg_task_updated",(z)=>{this.applyBgStore(vQ(this.bgStore(),{...z,patch:{...z.patch,...z.display}})),this.onBackgroundTaskChanged(!!z.patch.status||z.patch.is_backgrounded===!0)}),X("bg_task_settled",(z)=>{if(j(`session "${this.sessionName}": bg_task_settled task=${z.task_id} status=${z.status}`),this.applyBgStore(Q6(this.bgStore(),{...z,...z.display})),this.onBackgroundTaskChanged(!0),$.provider==="claude"&&!this.currentTurn&&!this.openingTurn&&this.initCount>=1)this.bgResumePending=!0}),X("subagent_step",(z)=>{this.applyBgStore(hQ(this.bgStore(),z.thread_id,z.item_id,z.tool,z.phase,z.brief)),this.onBackgroundTaskChanged()}),X("exit",({code:z,signal:H,expected:G})=>{if(j(`session "${this.sessionName}": ${$.provider} exited code=${z} signal=${H} expected=${G}`),this.stoppingProc===$||this.blockedProc===$){if(this.blockedProc===$){let P=$.conversationMaterializationFailure?.(),L=this.persistResumableSessionId(!1,$,!1),q=[P&&$.isConversationResumable?.()!==!0?`Codex 会话落盘确认失败: ${E(P)}`:null,L].filter(Boolean).join(";");if(q)h(this.chatId,`⚠️ 旧进程退出后的恢复状态收尾失败: ${q}`);this.discardPendingCodexTurnAnchors($,"blocked process finally exited")}j(`session "${this.sessionName}": blocked/stopping ${$.provider} exit confirmed`),this.detachProc($),this.status="stopped",this.opts.onLifecycleChange?.();return}this.discardPendingCodexTurnAnchors($,"unexpected process exit"),this.cancelAgentRuns(`${$.provider} process exited`).catch((P)=>{j(`session "${this.sessionName}": cancel Agent runs after process exit failed: ${E(P)}`)});let W=this.backendLabel($.provider),K=`code=${z??"null"}, signal=${H??"null"}`,B=G?`\uD83D\uDED1 ${W} 已退出`:`⚠️ ${W} 异常退出 (${K})`;if(this.currentTurn)this.closeTurnCard(B).catch((P)=>{j(`session "${this.sessionName}": process-exit current main-card close failed: ${E(P)}`)});let _=this.waitForTurnCloses().catch((P)=>{j(`session "${this.sessionName}": process-exit main-card close failed: ${E(P)}`)});this.detachProc($),this.flushOrphanAssistantToChat("process exit"),this.bgResumePending=!1,this.bgResumeCardless=!1,this.clearMultiMsgBuffer("process exit"),this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),this.initCount=0,this.invalidateTurnOpen(),this.pendingAsks.clear(),this.pendingPermissions.clear(),this.userInterrupted=!1,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped",this.opts.onLifecycleChange?.(),this.runLifecycle("process-exit-cleanup",async()=>{let P=await Promise.allSettled([_,this.resetBackgroundTasks()]);for(let L of P)if(L.status==="rejected")j(`session "${this.sessionName}": process-exit terminal cleanup failed: ${E(L.reason)}`);if(!G)await k(this.chatId,`⚠️ ${W} 异常退出 (${K})。回复任意消息将重新启动。`)}).catch((P)=>{j(`session "${this.sessionName}": process-exit cleanup rejected: ${E(P)}`)})})}accumulateResultStats($){let Z=$?.result??this.proc?.lastResult;if(!Z)return;let J=this.currentTurnUsageBaselineKnown?PZ($?$.totalUsage:this.proc?.lastTotalUsage,this.currentTurnUsageBaseline):this.proc?.provider==="claude"&&Z.usage?{...Z.usage}:null;this.lastTurnUsage=J,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;let Q=LZ(J),Y=this.proc?.provider==="claude"?0:Z.cost_delta_usd??0,V=Z.duration_ms??0;if(Q!=null)this.cumStats.tokens+=Q;this.cumStats.costUsd+=Y,this.cumStats.turns+=Z.num_turns??1,this.lastTurnDelta={tokens:Q,costUsd:Y,durationMs:V}}currentContextTokens($=this.proc){if($?.provider==="claude"||$?.provider==="dsh")return $.lastContextTokens??null;let Z=$?.lastUsage;return K6(Z)}contextLimitForDisplay($=this.proc){return B6($?.lastContextWindow)}steerPendingInputs(){let $=this.proc,Z=this.currentTurn;if(!$?.steerUserText||!Z||this.openingTurn||this.steeringSend||this.pendingMidTurnMsgs.length===0||this.modelSettingsBlockReason())return;let J=this.procEpoch,Q=this.steeringGeneration,Y=this.pendingMidTurnMsgs.splice(0),V=this.pendingReactionIds,X=zE(),z={proc:$,epoch:J,generation:Q,turn:Z,batch:Y,reactions:V,consumed:!1};this.submittedSteering.set(X,z);let H=!1,G=!1,W=()=>this.proc===$&&this.procEpoch===J&&this.steeringGeneration===Q&&$.isAlive(),K=Promise.resolve().then(async()=>{if(!W())return;let B=this.disabledSubscriptionMessage($.tokenSourceId);if(B)throw Error(B);if(G=await $.steerUserText(Y.map((_)=>_.wireText).join(`
334
334
 
335
335
  `),[],X),!W())return;if(!G){this.pendingMidTurnMsgs.unshift(...Y),this.submittedSteering.delete(X),H=!0;return}}).catch(async(B)=>{j(`session "${this.sessionName}": steering input failed: ${E(B)}`),await h(this.chatId,`❌ 追加消息${z.consumed?"已确认进入执行流,但提交回执异常":"提交未获确认,未自动重发"}:${E(B)}`)}).finally(()=>{if(Z.steeringInflight?.delete(K),this.steeringSend===K)this.steeringSend=null;if(!W())this.submittedSteering.delete(X);if(!H&&!z.consumed&&!this.submittedSteering.has(X))this.releaseSteeringReactions(z);if(!W())return;if(!this.currentTurn&&!this.openingTurn&&this.pendingMidTurnMsgs.length)this.drainMidTurnAndOpen().catch((B)=>j(`session "${this.sessionName}": input drain failed: ${E(B)}`));else if(G)this.steerPendingInputs()});this.steeringSend=K,(Z.steeringInflight??=new Set).add(K)}releaseSteeringReactions($){for(let Z of $.batch){let J=$.reactions.get(Z.msgId);if($.reactions.delete(Z.msgId),J)g0(Z.msgId,J)}}releaseUnconsumedSteering($){let Z=0;for(let[J,Q]of this.submittedSteering){if(Q.proc!==$)continue;this.submittedSteering.delete(J),this.releaseSteeringReactions(Q),Z+=Q.batch.length}if(Z){let J=`本轮已结束,但 ${Z} 条追加消息缺少原生处理位置确认,未据此换卡或自动重发。`;j(`session "${this.sessionName}": ${J}`),h(this.chatId,`⚠️ ${J}`)}}onSteeringInputConsumed($,Z,J){let Q=this.submittedSteering.get(J);if(!Q||Q.proc!==$||Q.epoch!==Z)return;this.submittedSteering.delete(J),Q.consumed=!0;let{turn:Y,generation:V}=Q;if(this.currentTurn!==Y||V!==this.steeringGeneration){this.releaseSteeringReactions(Q);return}j(`session "${this.sessionName}": steering consumed input=${J} messages=${Q.batch.length}`);let X=this.steeringBoundary;if(X?.collecting&&X.turn===Y&&X.proc===$&&X.epoch===Z){X.inputs.push(...Q.batch.map((B)=>B.text)),X.inputIds.push(J),X.reactionOwners.push(Q);return}let z,H=new Promise((B)=>{z=B}),G={turn:Y,proc:$,epoch:Z,generation:V,events:[],inputs:Q.batch.map((B)=>B.text),inputIds:[J],collecting:!0,reactionOwners:[Q],start:()=>{G.collecting=!1,z()}};this.steeringBoundary=G;let W=()=>this.steeringBoundary===G&&this.proc===$&&this.procEpoch===Z&&this.steeringGeneration===V&&this.currentTurn===Y;if(!Y.rotating)this.finalizeCurrentAssistantSegment();let K=Promise.resolve().then(async()=>{if(await H,Y.rotating)await Y.rotating;if(!W())return;this.finalizeCurrentAssistantSegment(),j(`session "${this.sessionName}": steering input batch inputs=${G.inputs.length} receipts=${G.inputIds.length} — rotate at native boundary`),this.startMidTurnRotate(Y,{userInputs:G.inputs,onCardSent:()=>{if(!W())return;for(let B of G.reactionOwners)this.releaseSteeringReactions(B)}}),await Y.rotating}).catch(async(B)=>{j(`session "${this.sessionName}": input-boundary card handoff failed: ${E(B)}`),await h(this.chatId,`⚠️ 追加消息已进入执行流,但换卡失败:${E(B)}`)}).finally(()=>{if(Y.steeringInflight?.delete(K),this.steeringBoundary!==G)return;this.steeringBoundary=null;for(let B of G.events)B()});(Y.steeringInflight??=new Set).add(K)}async drainMidTurnAndOpen(){if(this.steeringSend)await this.steeringSend;if(this.pendingMidTurnMsgs.length===0)return;if(this.modelSettingsBlockReason())return;let $=this.proc,Z=this.procEpoch;if(!$?.isAlive())return;if(!await this.waitForTurnOpenSlot($,Z))return;if(this.currentTurn||this.openingTurn||this.pendingMidTurnMsgs.length===0||this.modelSettingsBlockReason())return;let J;try{J=this.beginTurnOpen($,Z)}catch(Y){j(`session "${this.sessionName}": mid-turn open ownership conflict: ${E(Y)}`);return}let Q=this.pendingMidTurnMsgs;this.pendingMidTurnMsgs=[];try{for(let H of Q)if(this.pendingTurnInputs.push(H.text),H.msgId){let G=this.pendingReactionIds.get(H.msgId)??"";this.currentBatchReactionIds.set(H.msgId,G),this.pendingReactionIds.delete(H.msgId)}let Y=Q.map((H)=>H.wireText).join(`
336
336
 
337
- `),X=Q[Q.length-1]?.userOpenId??this.lastUserOpenId,z=await this.openTurnCard(J,X,"user_message");if(!z||this.currentTurn!==z){for(let H of Q){if(!H.msgId)continue;let G=this.currentBatchReactionIds.get(H.msgId);if(this.currentBatchReactionIds.delete(H.msgId),G)g0(H.msgId,G)}this.status="idle";return}if(this.proc!==$||this.procEpoch!==Z||!$.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);for(let H of Q){if(!H.msgId)continue;let G=this.currentBatchReactionIds.get(H.msgId);if(this.currentBatchReactionIds.delete(H.msgId),G)g0(H.msgId,G)}this.status="stopped";return}try{if(!await this.sendClaimedUserText($,Y))return}catch(H){j(`session "${this.sessionName}": mid-turn sendUserText failed after card open: ${H}`),await this.closeTurnCard(`❌ ${this.backendLabel($.provider)} 接收消息失败`),await h(this.chatId,`❌ ${this.backendLabel($.provider)} 接收消息失败: ${E(H)}。这批消息未开始处理,请重发。`),this.status="idle";return}this.status="working"}finally{if(this.releaseTurnOpen(J),!this.currentTurn&&this.pendingMidTurnMsgs.length>0&&this.proc===$&&this.procEpoch===Z&&$.isAlive())this.drainMidTurnAndOpen()}}async terminalizeSupersededCard($,Z,J){let Q=[],Y=(H)=>{Q.push(H)},V=J?await D0($,C.footer,this.footerElement(Z),{onFailure:Y}):!0;e0($);let X=await m0($,o2({suffix:Z}),Y);if(V&&X){await N$($);return}let z=`footer=${V?"ok":"MISS"}, settings=${X?"ok":"MISS"}`;j(`session "${this.sessionName}": superseded card terminal transaction incomplete card=${$.slice(0,12)} ${z}`),await h(this.chatId,`⚠️ 已作废卡片未能正常关闭 (${z})。
338
- ${D9(Q)}`)}async openTurnCard($,Z,J,Q={}){if(!this.ownsTurnOpen($))return null;this.bgResumePending=!1;let Y=++this.turnCounter,V=this.pendingTurnInputs;this.pendingTurnInputs=[],this.lastTurnUserPreview=V[0]?.slice(0,80)??this.lastTurnUserPreview,j(`session "${this.sessionName}": openTurnCard turn=${Y} trigger=${J} inputs=${V.length}`);let X=this.runtimeModelSelection(),z=this.withModel(Q.initialFooter??"Waiting...(0s)",X),H=L6({sessionName:this.sessionName,turn:Y,provider:X.provider,model:X.model??void 0,effort:X.effort??"MISS",kind:J,userInputs:V,initialFooter:z,directStart:Q.directStart}),G,W=await o(this.chatId,H,(L)=>{G=L});if(!W){if(!this.ownsTurnOpen($))return null;if(j(`session "${this.sessionName}": openTurnCard sendCard failed — surfacing via raw text`),J==="user_message")await h(this.chatId,`❌ 创建对话卡片失败。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。
337
+ `),X=Q[Q.length-1]?.userOpenId??this.lastUserOpenId,z=await this.openTurnCard(J,X,"user_message");if(!z||this.currentTurn!==z){for(let H of Q){if(!H.msgId)continue;let G=this.currentBatchReactionIds.get(H.msgId);if(this.currentBatchReactionIds.delete(H.msgId),G)g0(H.msgId,G)}this.status="idle";return}if(this.proc!==$||this.procEpoch!==Z||!$.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);for(let H of Q){if(!H.msgId)continue;let G=this.currentBatchReactionIds.get(H.msgId);if(this.currentBatchReactionIds.delete(H.msgId),G)g0(H.msgId,G)}this.status="stopped";return}try{if(!await this.sendClaimedUserText($,Y))return}catch(H){j(`session "${this.sessionName}": mid-turn sendUserText failed after card open: ${H}`),await this.closeTurnCard(`❌ ${this.backendLabel($.provider)} 接收消息失败`),await h(this.chatId,`❌ ${this.backendLabel($.provider)} 接收消息失败: ${E(H)}。这批消息未开始处理,请重发。`),this.status="idle";return}this.status="working"}finally{if(this.releaseTurnOpen(J),!this.currentTurn&&this.pendingMidTurnMsgs.length>0&&this.proc===$&&this.procEpoch===Z&&$.isAlive())this.drainMidTurnAndOpen()}}async terminalizeSupersededCard($,Z,J){let Q=[],Y=(H)=>{Q.push(H)},V=J?await F0($,C.footer,this.footerElement(Z),{onFailure:Y}):!0;e0($);let X=await m0($,o2({suffix:Z}),Y);if(V&&X){await N$($);return}let z=`footer=${V?"ok":"MISS"}, settings=${X?"ok":"MISS"}`;j(`session "${this.sessionName}": superseded card terminal transaction incomplete card=${$.slice(0,12)} ${z}`),await h(this.chatId,`⚠️ 已作废卡片未能正常关闭 (${z})。
338
+ ${F9(Q)}`)}async openTurnCard($,Z,J,Q={}){if(!this.ownsTurnOpen($))return null;this.bgResumePending=!1;let Y=++this.turnCounter,V=this.pendingTurnInputs;this.pendingTurnInputs=[],this.lastTurnUserPreview=V[0]?.slice(0,80)??this.lastTurnUserPreview,j(`session "${this.sessionName}": openTurnCard turn=${Y} trigger=${J} inputs=${V.length}`);let X=this.runtimeModelSelection(),z=this.withModel(Q.initialFooter??"Waiting...(0s)",X),H=L6({sessionName:this.sessionName,turn:Y,provider:X.provider,model:X.model??void 0,effort:X.effort??"MISS",kind:J,userInputs:V,initialFooter:z,directStart:Q.directStart}),G,W=await o(this.chatId,H,(L)=>{G=L});if(!W){if(!this.ownsTurnOpen($))return null;if(j(`session "${this.sessionName}": openTurnCard sendCard failed — surfacing via raw text`),J==="user_message")await h(this.chatId,`❌ 创建对话卡片失败。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。
339
339
  ${w(G)}`);return null}let K;try{K=await e$(W)}catch(L){if(j(`session "${this.sessionName}": id_convert failed: ${L}`),J==="user_message"&&this.ownsTurnOpen($))await h(this.chatId,`❌ 对话卡片初始化失败。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。
340
340
  ${w(L)}`);return null}let B=(J==="bg_task_resume"||J==="scheduled_wakeup"?1:0)+(V.length>0?1:0)+1;if(!this.ownsTurnOpen($))return h$(K,B),await this.terminalizeSupersededCard(K,"⚠️ 会话已切换,本卡已作废",!0),null;let _={cardId:K,...X,messageId:W,userOpenId:Z,trigger:J,toolCount:0,toolByUseId:new Map,planSteps:[],planExplanation:null,planUpdateCount:0,goalUpdateCount:0,contextCompactCount:0,contextCompactionPending:new Map,contextCompactionCompleted:new Set,contextCompactionCompleting:new Set,contextCompactionEndOnly:new Map,lastContextCompactionCompletedAt:0,lastContextCompactionWasAnonymous:!1,toolBatches:new Map,openBatchI:null,taskCreateI:null,taskUpdateI:null,taskBoardResetThisTurn:!1,taskLiveInserted:!1,planLiveInserted:!1,assistantSegmentCount:0,currentAssistantSegmentId:null,currentAssistantText:"",segmentTexts:new Map,startedAt:Date.now(),footerStatusHandle:null,footerStatusStartedAt:0,footerStatusLabel:null,rotating:null,rotateCount:0,failureRotateCount:0,cardCapacityFailures:new Map,cardWriteFailureNotices:new Set,cardRotationFailed:!1,outboundSeenPaths:new Set,outboundSentPaths:new Set,fileDeliveryMode:J==="user_message"&&this.pendingUserMessageCount===0?void 0:this.proc?this.procFileDeliveryModes.get(this.proc):void 0};if(h$(K,B,(L,q)=>{this.onCardWriteFailure(_,K,L,q)}),this.currentTurn=_,Q.startThinking!==!1)this.startThinkingFooter(_);if($.pendingCompactions.length>0){let L=$.pendingCompactions.splice(0);j(`session "${this.sessionName}": replay ${L.length} context compaction event(s) buffered during card open`);for(let q of L)this.handleContextCompacted(q)}let P=this.takeOrphanAssistantText();if(P)this.appendAssistant(P),this.finalizeCurrentAssistantSegment();return _}maybeMidTurnRotate(){let $=this.currentTurn;if(!$)return;if($.rotating)return;if(!$.cardRotationFailed&&U8($.cardId)<PE)return;this.startMidTurnRotate($)}reportCardWriteFailure($,Z,J,Q){let Y=qE(Z,J);if($.cardWriteFailureNotices.has(Y))return;$.cardWriteFailureNotices.add(Y);let V=J?.operation??"unknown operation",X=J?.elementId?` element=${J.elementId}`:"";h(this.chatId,`⚠️ 对话卡片写入失败(${V}${X})。${Q}同类错误本轮合并提示,完整诊断保留在日志。
341
341
  ${w({...J,code:Z})}`)}onCardWriteFailure($,Z,J,Q){let Y=this.currentTurn;if(Y!==$){j(`session "${this.sessionName}": ignore stale card failure card=${Z.slice(0,12)} code=${J??"n/a"} (turn owner changed)`);return}if(Y.cardId!==Z){j(`session "${this.sessionName}": ignore retired-card failure card=${Z.slice(0,12)} current=${Y.cardId.slice(0,12)} code=${J??"n/a"}`);return}if(Y.rotating)return;if(Y.cardRotationFailed)return;if(!m2(J,Q)){let X=Q?.operation??"unknown operation",z=Q?.elementId?` element=${Q.elementId}`:"";j(`session "${this.sessionName}": non-capacity card write failure card=${Z.slice(0,12)} operation=${X}${z} code=${J??"n/a"} — not rotating`),this.reportCardWriteFailure(Y,J,Q,"未识别为卡片容量超限,未自动换卡;其余输出继续处理。");return}let V=Q?.capacityFingerprint;if(V){let X=Y.cardCapacityFailures.get(V);if(X!==void 0){if(j(`session "${this.sessionName}": unchanged content still exceeds card capacity card=${Z} operation=${Q.operation} element=${Q.elementId??"MISS"} code=${J??"MISS"}`),!X)Y.cardCapacityFailures.set(V,!0),h(this.chatId,`⚠️ 有一项内容换卡后仍超出飞书容量,写入失败(${Q.operation}, element=${Q.elementId??"MISS"});其余输出继续处理。
342
342
  ${w({...Q,code:J})}`);return}Y.cardCapacityFailures.set(V,!1)}j(`session "${this.sessionName}": confirmed card capacity limit (${J}) on card=${Y.cardId.slice(0,8)}… — rotating to fresh card`),Y.failureRotateCount++,this.startMidTurnRotate(Y)}startMidTurnRotate($,Z={}){if($.rotating)return;let J=Z.userInputs!==void 0;$.rotateCount++;let{cardId:Q,toolByUseId:Y,toolBatches:V}=$,X={value:null},z=(H,G)=>{if(!X.value)X.value={code:H,failure:G}};$.rotating=(async()=>{try{j(`session "${this.sessionName}": mid-turn rotate triggered card=${Q.slice(0,8)}… elementCount=${U8(Q)}`);let H=L6({sessionName:this.sessionName,turn:this.turnCounter,provider:$.provider,model:$.model??void 0,effort:$.effort??"MISS",kind:J?"user_steering":"card_full",userInputs:Z.userInputs??[]}),G,W=await o(this.chatId,H,(U)=>{G=U});if(!W){if(j(`session "${this.sessionName}": mid-turn rotate sendCard failed reason=${J?"user_steering":"capacity"}`),!J&&this.currentTurn===$)$.cardRotationFailed=!0,this.stopFooterStatus($);await h(this.chatId,`${J?"⚠️ 追加消息已交给 Agent,但新卡片发送失败。":"⚠️ 续卡发送失败,后续内容到达时会再次尝试。"}
343
343
  ${w(G)}`);return}Z.onCardSent?.();let K;try{K=await e$(W)}catch(U){if(j(`session "${this.sessionName}": mid-turn rotate id_convert failed: ${U}`),J||this.currentTurn===$){if(!J)$.cardRotationFailed=!0,this.stopFooterStatus($);await h(this.chatId,`${J?"⚠️ 追加消息已交给 Agent,但新卡片初始化失败。":"⚠️ 续卡已发送,但 Card Kit 初始化失败;后续内容到达时会再次尝试。"}
344
- ${w(U)}`)}return}let B=1+(J?Z.userInputs.length>0?1:0:1);h$(K,B,(U,A)=>{if($.rotating){z(U,A);return}this.onCardWriteFailure($,K,U,A)});let _=$.assistantWriteInflight?.get(Q);if(_?.size)await Promise.allSettled([..._]);this.stopFooterStatus($),$.cardId=K,$.cardRotationFailed=!1,$.messageId=W,$.toolCount=0,$.toolByUseId=new Map,$.toolBatches=new Map,$.openBatchI=null,$.planUpdateCount=0,$.goalUpdateCount=0;let P=$.currentAssistantSegmentId,L=$.currentAssistantText??"",q=$.segmentTexts;if($.assistantSegmentCount=0,$.currentAssistantSegmentId=null,$.currentAssistantText="",$.segmentTexts=new Map,P&&L){let U=C.assistant($.assistantSegmentCount++);$.currentAssistantSegmentId=U,$.currentAssistantText=L,$.segmentTexts.set(U,L)}if(L)this.startWritingFooter($);else this.startThinkingFooter($);if($.taskLiveInserted)v0($.cardId,t2(this.taskBoard),{type:"insert_before",targetElementId:C.footer});if($.planLiveInserted)v0($.cardId,v8($.planSteps,$.planExplanation,C.planLive),{type:"insert_before",targetElementId:$.taskLiveInserted?C.taskBoardLive:C.footer});for(let U of $.contextCompactionPending.values()){if(U.cardId!==Q)continue;U.cardId=K,U.created=!1,U.createFailure=void 0;let A=C.contextCompact(U.i);U.createPromise=$9(K,w8(U.i,U.notice,A),{type:"insert_before",targetElementId:p0($)}).then((O)=>{if(U.cardId===K)U.created=O.landed,U.createFailure=O.failure;return O.landed})}for(let[U,A]of q){if(P&&L&&U===P)continue;if(!e4(Q,U))continue;let O=$.assistantSegmentCount++,N=C.assistant(O);$.segmentTexts.set(N,A),await this.addCompletedAssistantSegment($,N,A)}PV(this,Q,K,Y,V,$),await d1(Q),PV(this,Q,K,Y,V,$);let D=new Set([C.taskBoardLive,C.planLive,...[...$.contextCompactionPending.values()].map((U)=>C.contextCompact(U.i))]);if(P)D.add(P);for(let U of Y.values())if(U.output==null)D.add(C.tool(U.i));if(cW(Q).some((U)=>!D.has(U)))$.cardCapacityFailures.clear();await d1(K);try{await _V($,Q);let U=$.mathRenderInflight?.get(Q);if(U?.size)await Promise.allSettled([...U]);await d1(Q);let A=$.mathRendered?.get(Q);for(let[m,b]of q){if(P&&L&&m===P)continue;if(e4(Q,m))continue;if(A?.has(m))continue;await R0(Q,m,this.completedAssistantElement(m,b))}let O=$.contextCompactCount>0?` · \uD83D\uDEA8 压缩×${$.contextCompactCount}`:"",N=[],S=(m)=>{N.push(m)},T=await D0(Q,C.footer,this.footerElement(this.withModel(`\uD83D\uDCE8 已续至下一张卡 ↓${O}`)),{notifyCardFailure:!1,onFailure:S});e0(Q);let y=await m0(Q,o2({suffix:"\uD83D\uDCE8 转下一张"}),S);if(T&&y)await N$(Q);else j(`session "${this.sessionName}": rotate old-card terminal MISS footer=${T} settings=${y}`),await h(this.chatId,`⚠️ 上一张对话卡未能正常关闭 (footer=${T?"ok":"MISS"}, settings=${y?"ok":"MISS"}),本轮输出已续到新卡。
345
- ${D9(N)}`)}catch(U){j(`session "${this.sessionName}": mid-turn rotate close-old failed: ${U}`)}j(`session "${this.sessionName}": mid-turn rotate done old=${Q.slice(0,8)}… new=${K.slice(0,8)}…`)}finally{$.rotating=null;let H=X.value;if(H&&this.currentTurn===$)this.onCardWriteFailure($,$.cardId,H.code,H.failure)}})()}addPlanSnapshotOnCurrentTurn(){let $=this.currentTurn;if(!$||$.planSteps.length===0)return;this.maybeMidTurnRotate();let Z=$.cardId,J=C.planUpdate($.planUpdateCount++);v0(Z,VY($.planSteps,$.planExplanation,"",J),{type:"insert_before",targetElementId:p0($)})}addGoalUpdateOnCurrentTurn($){let Z=this.currentTurn;if(!Z)return;this.maybeMidTurnRotate();let J=C.goalUpdate(Z.goalUpdateCount++);v0(Z.cardId,XY($,J),{type:"insert_before",targetElementId:p0(Z)})}addGoalClearedOnCurrentTurn(){let $=this.currentTurn;if(!$)return;this.maybeMidTurnRotate();let Z=C.goalUpdate($.goalUpdateCount++);v0($.cardId,{tag:"markdown",element_id:Z,content:`**\uD83C\uDFAF 当前目标**
344
+ ${w(U)}`)}return}let B=1+(J?Z.userInputs.length>0?1:0:1);h$(K,B,(U,A)=>{if($.rotating){z(U,A);return}this.onCardWriteFailure($,K,U,A)});let _=$.assistantWriteInflight?.get(Q);if(_?.size)await Promise.allSettled([..._]);this.stopFooterStatus($),$.cardId=K,$.cardRotationFailed=!1,$.messageId=W,$.toolCount=0,$.toolByUseId=new Map,$.toolBatches=new Map,$.openBatchI=null,$.planUpdateCount=0,$.goalUpdateCount=0;let P=$.currentAssistantSegmentId,L=$.currentAssistantText??"",q=$.segmentTexts;if($.assistantSegmentCount=0,$.currentAssistantSegmentId=null,$.currentAssistantText="",$.segmentTexts=new Map,P&&L){let U=C.assistant($.assistantSegmentCount++);$.currentAssistantSegmentId=U,$.currentAssistantText=L,$.segmentTexts.set(U,L)}if(L)this.startWritingFooter($);else this.startThinkingFooter($);if($.taskLiveInserted)v0($.cardId,t2(this.taskBoard),{type:"insert_before",targetElementId:C.footer});if($.planLiveInserted)v0($.cardId,v8($.planSteps,$.planExplanation,C.planLive),{type:"insert_before",targetElementId:$.taskLiveInserted?C.taskBoardLive:C.footer});for(let U of $.contextCompactionPending.values()){if(U.cardId!==Q)continue;U.cardId=K,U.created=!1,U.createFailure=void 0;let A=C.contextCompact(U.i);U.createPromise=$9(K,w8(U.i,U.notice,A),{type:"insert_before",targetElementId:p0($)}).then((O)=>{if(U.cardId===K)U.created=O.landed,U.createFailure=O.failure;return O.landed})}for(let[U,A]of q){if(P&&L&&U===P)continue;if(!e4(Q,U))continue;let O=$.assistantSegmentCount++,N=C.assistant(O);$.segmentTexts.set(N,A),await this.addCompletedAssistantSegment($,N,A)}PV(this,Q,K,Y,V,$),await d1(Q),PV(this,Q,K,Y,V,$);let F=new Set([C.taskBoardLive,C.planLive,...[...$.contextCompactionPending.values()].map((U)=>C.contextCompact(U.i))]);if(P)F.add(P);for(let U of Y.values())if(U.output==null)F.add(C.tool(U.i));if(cW(Q).some((U)=>!F.has(U)))$.cardCapacityFailures.clear();await d1(K);try{await _V($,Q);let U=$.mathRenderInflight?.get(Q);if(U?.size)await Promise.allSettled([...U]);await d1(Q);let A=$.mathRendered?.get(Q);for(let[m,b]of q){if(P&&L&&m===P)continue;if(e4(Q,m))continue;if(A?.has(m))continue;await R0(Q,m,this.completedAssistantElement(m,b))}let O=$.contextCompactCount>0?` · \uD83D\uDEA8 压缩×${$.contextCompactCount}`:"",N=[],S=(m)=>{N.push(m)},T=await F0(Q,C.footer,this.footerElement(this.withModel(`\uD83D\uDCE8 已续至下一张卡 ↓${O}`)),{notifyCardFailure:!1,onFailure:S});e0(Q);let f=await m0(Q,o2({suffix:"\uD83D\uDCE8 转下一张"}),S);if(T&&f)await N$(Q);else j(`session "${this.sessionName}": rotate old-card terminal MISS footer=${T} settings=${f}`),await h(this.chatId,`⚠️ 上一张对话卡未能正常关闭 (footer=${T?"ok":"MISS"}, settings=${f?"ok":"MISS"}),本轮输出已续到新卡。
345
+ ${F9(N)}`)}catch(U){j(`session "${this.sessionName}": mid-turn rotate close-old failed: ${U}`)}j(`session "${this.sessionName}": mid-turn rotate done old=${Q.slice(0,8)}… new=${K.slice(0,8)}…`)}finally{$.rotating=null;let H=X.value;if(H&&this.currentTurn===$)this.onCardWriteFailure($,$.cardId,H.code,H.failure)}})()}addPlanSnapshotOnCurrentTurn(){let $=this.currentTurn;if(!$||$.planSteps.length===0)return;this.maybeMidTurnRotate();let Z=$.cardId,J=C.planUpdate($.planUpdateCount++);v0(Z,VY($.planSteps,$.planExplanation,"",J),{type:"insert_before",targetElementId:p0($)})}addGoalUpdateOnCurrentTurn($){let Z=this.currentTurn;if(!Z)return;this.maybeMidTurnRotate();let J=C.goalUpdate(Z.goalUpdateCount++);v0(Z.cardId,XY($,J),{type:"insert_before",targetElementId:p0(Z)})}addGoalClearedOnCurrentTurn(){let $=this.currentTurn;if(!$)return;this.maybeMidTurnRotate();let Z=C.goalUpdate($.goalUpdateCount++);v0($.cardId,{tag:"markdown",element_id:Z,content:`**\uD83C\uDFAF 当前目标**
346
346
 
347
- 已清除`},{type:"insert_before",targetElementId:p0($)})}handleContextCompacted($){let Z=l_($);if(this.manualContextCompactionPending){if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");if($.phase!=="start")this.lastManualContextCompactionCompletedAt=Date.now(),this.lastManualContextCompactionWasAnonymous=Z.length===0;j(`session "${this.sessionName}": manual context compaction ${$.phase??"event"} handled by command status card`);return}if($.phase==="start")this.lastManualContextCompactionWasAnonymous=!1;else if((Z.length===0||this.lastManualContextCompactionWasAnonymous)&&Date.now()-this.lastManualContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": late anonymous manual compaction duplicate ignored`);return}let J=this.currentTurn,Q=$.itemId?`item:${$.itemId}`:void 0,Y=Z.find((M)=>M.startsWith("turn:")),V=Q??Y,X=V?this.contextCompactionReceipts.get(V):void 0;if(Q&&!X&&$.phase!=="start"&&Y){let M=this.contextCompactionReceipts.get(Y);if(!M?.hasItemAlias&&M?.completed&&Date.now()-M.completedAt<G5||!M?.hasItemAlias&&M?.completionKey&&J?.contextCompactionCompleting.has(M.completionKey))V=Y,X=M,M.hasItemAlias=!0,this.contextCompactionReceipts.delete(Q),this.contextCompactionReceipts.set(Q,M)}if(!J){if(this.openingTurnOwner?.backendTurnStarted){this.openingTurnOwner.pendingCompactions.push($),j(`session "${this.sessionName}": buffer context compaction ${$.phase??"event"} while turn card opens`);return}if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");j(`session "${this.sessionName}": context compaction ${$.phase??"event"} with no current turn thread=${$.threadId??"-"} turn=${$.turnId??"-"} item=${$.itemId??"-"}`);return}if(V&&X?.completed){j(`session "${this.sessionName}": duplicate context compaction ${$.phase??"event"} ignored receipt=${V}`);return}let z=this.contextCompactionOwnerId(J);if(V&&X&&X.ownerId!==z){this.rememberContextCompactionReceipt(Z,null,!0),j(`session "${this.sessionName}": late context compaction ${$.phase??"event"} ignored receipt=${V} (turn owner changed)`);return}if(V&&X?.completionKey&&J.contextCompactionCompleting.has(X.completionKey)){j(`session "${this.sessionName}": context compaction alias already writing receipt=${V}`);return}if($.phase!=="start"&&Z.length>0&&J.contextCompactionPending.size===0&&J.contextCompactionCompleting.has("__anonymous__")){j(`session "${this.sessionName}": identified context compaction duplicate ignored while anonymous completion writes`);return}if($.phase!=="start"&&Z.length>0&&J.contextCompactionPending.size===0&&J.lastContextCompactionWasAnonymous&&Date.now()-J.lastContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": identified context compaction duplicate ignored after anonymous completion`);return}if($.phase==="start"){let M=WE($);if(J.contextCompactionPending.has(M)||J.contextCompactionCompleted.has(M)){j(`session "${this.sessionName}": duplicate context compaction start ignored key=${M}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();if(J.openBatchI=null,this.maybeMidTurnRotate(),J.lastContextCompactionWasAnonymous=!1,Z.length>0)this.rememberContextCompactionReceipt(Z,z,!1);let U=J.contextCompactCount++,A=J.cardId,O=C.contextCompact(U),N={i:U,cardId:A,notice:$,created:!1,createFailure:void 0,createPromise:Promise.resolve(!1)};N.createPromise=$9(A,w8(U,$,O),{type:"insert_before",targetElementId:p0(J)}).then((S)=>{if(N.cardId===A)N.created=S.landed,N.createFailure=S.failure;return S.landed}),J.contextCompactionPending.set(M,N),j(`session "${this.sessionName}": context compaction start #${U+1} key=${M}`),Z9(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionCompleting.size>0){j(`session "${this.sessionName}": anonymous context compaction duplicate ignored while completion writes`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionPending.size===0&&Date.now()-J.lastContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": immediate anonymous context compaction duplicate ignored`);return}let H=$.itemId||$.turnId;if(H&&J.contextCompactionCompleted.has(H)){j(`session "${this.sessionName}": duplicate context compaction completion ignored key=${H}`);return}let G=$.itemId?J.contextCompactionPending.has($.itemId)?$.itemId:null:KE(J),W=G?J.contextCompactionPending.get(G):void 0,K=G??H??"__anonymous__";if(J.contextCompactionCompleting.has(K)){j(`session "${this.sessionName}": context compaction completion already writing key=${K}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();J.openBatchI=null,this.maybeMidTurnRotate();let B=BE(W?.notice,$),_=J.contextCompactionEndOnly.get(K),P=W?.i??_??J.contextCompactCount++;if(!W&&_===void 0)J.contextCompactionEndOnly.set(K,P);J.contextCompactionCompleting.add(K);let L=[...new Set([...l_(W?.notice??{}),...Z])];if(L.length>0)this.rememberContextCompactionReceipt(L,z,!1,K);let q=C.contextCompact(P),D=w8(P,B,q);j(`session "${this.sessionName}": context compaction completion write #${P+1} key=${K}`),(async()=>{let M=!1;if(!W)while(!0){let U=J.cardId;if(M=await c2(U,D,{type:"insert_before",targetElementId:p0(J)}),M)break;let A=J.rotating;if(A){await A;continue}if(J.cardId!==U)continue;break}else while(!0){let U=W.cardId;if(await W.createPromise,W.cardId!==U)continue;if(W.created)M=await D0(U,q,D);else{if(UQ(W.createFailure?.code,W.createFailure))uW(U,q),M=await D0(U,q,D,{notifyCardFailure:!1});if(!M)M=await c2(U,D,{type:"insert_before",targetElementId:p0(J)})}if(W.cardId!==U)continue;if(M){W.created=!0;break}let A=J.rotating;if(A){await A;continue}if(W.cardId!==U)continue;break}if(J.contextCompactionCompleting.delete(K),!M){j(`session "${this.sessionName}": context compaction completion write MISS #${P+1} key=${K}`);return}if(G&&J.contextCompactionPending.get(G)===W)J.contextCompactionPending.delete(G);if(J.contextCompactionEndOnly.delete(K),K!=="__anonymous__")J.contextCompactionCompleted.add(K);if(J.lastContextCompactionCompletedAt=Date.now(),J.lastContextCompactionWasAnonymous=K==="__anonymous__",L.length>0){let U=[...this.contextCompactionReceipts.entries()].filter(([,A])=>A.completionKey===K).map(([A])=>A);this.rememberContextCompactionReceipt([...new Set([...L,...U])],null,!0)}j(`session "${this.sessionName}": context compaction completed #${P+1} key=${K}`)})().catch((M)=>{J.contextCompactionCompleting.delete(K),j(`session "${this.sessionName}": context compaction completion transaction failed: ${E(M)}`)}),Z9(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`)}contextCompactionOwnerId($){let Z=this.contextCompactionOwnerIds.get($);if(Z!==void 0)return Z;let J=++this.contextCompactionOwnerSequence;return this.contextCompactionOwnerIds.set($,J),J}rememberContextCompactionReceipt($,Z,J,Q){let Y={ownerId:J?null:Z,completed:J,completedAt:J?Date.now():0,...J||!Q?{}:{completionKey:Q},hasItemAlias:$.some((V)=>V.startsWith("item:"))};for(let V of $)this.contextCompactionReceipts.delete(V),this.contextCompactionReceipts.set(V,Y);while(this.contextCompactionReceipts.size>LE){let V;for(let X of this.contextCompactionReceipts.values()){if(X.completed){V=X;break}V??=X}if(!V)break;for(let[X,z]of this.contextCompactionReceipts)if(z===V)this.contextCompactionReceipts.delete(X)}}handleTurnPlanUpdated($){let Z=this.currentTurn;if(!Z){j(`session "${this.sessionName}": turn/plan/updated with no current turn`);return}if(this.startWorkingFooter(Z),Z.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();if(Z.openBatchI=null,!Array.isArray($.plan))j(`session "${this.sessionName}": turn/plan/updated missing plan array`),Z.planSteps=[];else Z.planSteps=$.plan.map((J)=>({step:typeof J.step==="string"&&J.step?J.step:"MISS",status:typeof J.status==="string"&&J.status?J.status:"MISS"}));if(Z.planExplanation=typeof $.explanation==="string"?$.explanation:null,Z.planSteps.length>0)if(!Z.planLiveInserted){let J=Z.taskLiveInserted?C.taskBoardLive:C.footer;Z.planLiveInserted=!0,v0(Z.cardId,v8(Z.planSteps,Z.planExplanation,C.planLive),{type:"insert_before",targetElementId:J})}else D0(Z.cardId,C.planLive,v8(Z.planSteps,Z.planExplanation,C.planLive),{notifyCardFailure:!1});this.addPlanSnapshotOnCurrentTurn()}handlePlanDelta($){if(typeof $.delta!=="string"||!$.delta){j(`session "${this.sessionName}": item/plan/delta missing delta text`);return}if(typeof $.itemId!=="string"||!$.itemId)j(`session "${this.sessionName}": item/plan/delta missing itemId`)}handleThreadGoalUpdated($){if(!$||typeof $.objective!=="string"){j(`session "${this.sessionName}": thread/goal/updated missing objective`);return}if($.tokenBudget!=null&&typeof $.tokenBudget!=="number")j(`session "${this.sessionName}": thread/goal/updated invalid tokenBudget`);let Z=this.currentGoal,J={objective:$.objective,status:typeof $.status==="string"&&$.status?$.status:"MISS",tokenBudget:typeof $.tokenBudget==="number"?$.tokenBudget:$.tokenBudget===null?null:Number.NaN,tokensUsed:typeof $.tokensUsed==="number"?$.tokensUsed:Number.NaN,timeUsedSeconds:typeof $.timeUsedSeconds==="number"?$.timeUsedSeconds:Number.NaN};if(this.currentGoal=J,Z&&P6(Z)===P6(J))return;let Q=this.currentTurn;if(Q){if(this.startWorkingFooter(Q),Q.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();Q.openBatchI=null}this.addGoalUpdateOnCurrentTurn(J)}handleThreadGoalCleared(){if(!this.currentGoal)return;this.currentGoal=null;let $=this.currentTurn;if(!$)return;if(this.startWorkingFooter($),$.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();$.openBatchI=null,this.addGoalClearedOnCurrentTurn()}appendAssistant($){if(!this.currentTurn){if(this.openingTurn||this.bgResumeCardless)this.orphanAssistantCurrent+=$;return}let Z=this.currentTurn;if(this.startWritingFooter(Z),!Z.currentAssistantSegmentId){Z.openBatchI=null,this.maybeMidTurnRotate();let V=Z.assistantSegmentCount++,X=C.assistant(V);Z.currentAssistantSegmentId=X,Z.currentAssistantText=""}Z.currentAssistantText+=$;let J=Z.currentAssistantSegmentId;if(!J)return;Z.segmentTexts.set(J,Z.currentAssistantText),this.processOutboundMarkers(Z.currentAssistantText);let Y=this.cleanAssistantTextForDisplay(Z.currentAssistantText).slice(0,40);Z9(Z.cardId,Y)}takeOrphanAssistantText(){let $=[...this.orphanAssistantSegments];if(this.orphanAssistantCurrent.trim())$.push(this.orphanAssistantCurrent);return this.orphanAssistantSegments=[],this.orphanAssistantCurrent="",$.join(`
347
+ 已清除`},{type:"insert_before",targetElementId:p0($)})}handleContextCompacted($){let Z=l_($);if(this.manualContextCompactionPending){if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");if($.phase!=="start")this.lastManualContextCompactionCompletedAt=Date.now(),this.lastManualContextCompactionWasAnonymous=Z.length===0;j(`session "${this.sessionName}": manual context compaction ${$.phase??"event"} handled by command status card`);return}if($.phase==="start")this.lastManualContextCompactionWasAnonymous=!1;else if((Z.length===0||this.lastManualContextCompactionWasAnonymous)&&Date.now()-this.lastManualContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": late anonymous manual compaction duplicate ignored`);return}let J=this.currentTurn,Q=$.itemId?`item:${$.itemId}`:void 0,Y=Z.find((M)=>M.startsWith("turn:")),V=Q??Y,X=V?this.contextCompactionReceipts.get(V):void 0;if(Q&&!X&&$.phase!=="start"&&Y){let M=this.contextCompactionReceipts.get(Y);if(!M?.hasItemAlias&&M?.completed&&Date.now()-M.completedAt<G5||!M?.hasItemAlias&&M?.completionKey&&J?.contextCompactionCompleting.has(M.completionKey))V=Y,X=M,M.hasItemAlias=!0,this.contextCompactionReceipts.delete(Q),this.contextCompactionReceipts.set(Q,M)}if(!J){if(this.openingTurnOwner?.backendTurnStarted){this.openingTurnOwner.pendingCompactions.push($),j(`session "${this.sessionName}": buffer context compaction ${$.phase??"event"} while turn card opens`);return}if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");j(`session "${this.sessionName}": context compaction ${$.phase??"event"} with no current turn thread=${$.threadId??"-"} turn=${$.turnId??"-"} item=${$.itemId??"-"}`);return}if(V&&X?.completed){j(`session "${this.sessionName}": duplicate context compaction ${$.phase??"event"} ignored receipt=${V}`);return}let z=this.contextCompactionOwnerId(J);if(V&&X&&X.ownerId!==z){this.rememberContextCompactionReceipt(Z,null,!0),j(`session "${this.sessionName}": late context compaction ${$.phase??"event"} ignored receipt=${V} (turn owner changed)`);return}if(V&&X?.completionKey&&J.contextCompactionCompleting.has(X.completionKey)){j(`session "${this.sessionName}": context compaction alias already writing receipt=${V}`);return}if($.phase!=="start"&&Z.length>0&&J.contextCompactionPending.size===0&&J.contextCompactionCompleting.has("__anonymous__")){j(`session "${this.sessionName}": identified context compaction duplicate ignored while anonymous completion writes`);return}if($.phase!=="start"&&Z.length>0&&J.contextCompactionPending.size===0&&J.lastContextCompactionWasAnonymous&&Date.now()-J.lastContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": identified context compaction duplicate ignored after anonymous completion`);return}if($.phase==="start"){let M=WE($);if(J.contextCompactionPending.has(M)||J.contextCompactionCompleted.has(M)){j(`session "${this.sessionName}": duplicate context compaction start ignored key=${M}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();if(J.openBatchI=null,this.maybeMidTurnRotate(),J.lastContextCompactionWasAnonymous=!1,Z.length>0)this.rememberContextCompactionReceipt(Z,z,!1);let U=J.contextCompactCount++,A=J.cardId,O=C.contextCompact(U),N={i:U,cardId:A,notice:$,created:!1,createFailure:void 0,createPromise:Promise.resolve(!1)};N.createPromise=$9(A,w8(U,$,O),{type:"insert_before",targetElementId:p0(J)}).then((S)=>{if(N.cardId===A)N.created=S.landed,N.createFailure=S.failure;return S.landed}),J.contextCompactionPending.set(M,N),j(`session "${this.sessionName}": context compaction start #${U+1} key=${M}`),Z9(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionCompleting.size>0){j(`session "${this.sessionName}": anonymous context compaction duplicate ignored while completion writes`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionPending.size===0&&Date.now()-J.lastContextCompactionCompletedAt<G5){j(`session "${this.sessionName}": immediate anonymous context compaction duplicate ignored`);return}let H=$.itemId||$.turnId;if(H&&J.contextCompactionCompleted.has(H)){j(`session "${this.sessionName}": duplicate context compaction completion ignored key=${H}`);return}let G=$.itemId?J.contextCompactionPending.has($.itemId)?$.itemId:null:KE(J),W=G?J.contextCompactionPending.get(G):void 0,K=G??H??"__anonymous__";if(J.contextCompactionCompleting.has(K)){j(`session "${this.sessionName}": context compaction completion already writing key=${K}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();J.openBatchI=null,this.maybeMidTurnRotate();let B=BE(W?.notice,$),_=J.contextCompactionEndOnly.get(K),P=W?.i??_??J.contextCompactCount++;if(!W&&_===void 0)J.contextCompactionEndOnly.set(K,P);J.contextCompactionCompleting.add(K);let L=[...new Set([...l_(W?.notice??{}),...Z])];if(L.length>0)this.rememberContextCompactionReceipt(L,z,!1,K);let q=C.contextCompact(P),F=w8(P,B,q);j(`session "${this.sessionName}": context compaction completion write #${P+1} key=${K}`),(async()=>{let M=!1;if(!W)while(!0){let U=J.cardId;if(M=await c2(U,F,{type:"insert_before",targetElementId:p0(J)}),M)break;let A=J.rotating;if(A){await A;continue}if(J.cardId!==U)continue;break}else while(!0){let U=W.cardId;if(await W.createPromise,W.cardId!==U)continue;if(W.created)M=await F0(U,q,F);else{if(UQ(W.createFailure?.code,W.createFailure))uW(U,q),M=await F0(U,q,F,{notifyCardFailure:!1});if(!M)M=await c2(U,F,{type:"insert_before",targetElementId:p0(J)})}if(W.cardId!==U)continue;if(M){W.created=!0;break}let A=J.rotating;if(A){await A;continue}if(W.cardId!==U)continue;break}if(J.contextCompactionCompleting.delete(K),!M){j(`session "${this.sessionName}": context compaction completion write MISS #${P+1} key=${K}`);return}if(G&&J.contextCompactionPending.get(G)===W)J.contextCompactionPending.delete(G);if(J.contextCompactionEndOnly.delete(K),K!=="__anonymous__")J.contextCompactionCompleted.add(K);if(J.lastContextCompactionCompletedAt=Date.now(),J.lastContextCompactionWasAnonymous=K==="__anonymous__",L.length>0){let U=[...this.contextCompactionReceipts.entries()].filter(([,A])=>A.completionKey===K).map(([A])=>A);this.rememberContextCompactionReceipt([...new Set([...L,...U])],null,!0)}j(`session "${this.sessionName}": context compaction completed #${P+1} key=${K}`)})().catch((M)=>{J.contextCompactionCompleting.delete(K),j(`session "${this.sessionName}": context compaction completion transaction failed: ${E(M)}`)}),Z9(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`)}contextCompactionOwnerId($){let Z=this.contextCompactionOwnerIds.get($);if(Z!==void 0)return Z;let J=++this.contextCompactionOwnerSequence;return this.contextCompactionOwnerIds.set($,J),J}rememberContextCompactionReceipt($,Z,J,Q){let Y={ownerId:J?null:Z,completed:J,completedAt:J?Date.now():0,...J||!Q?{}:{completionKey:Q},hasItemAlias:$.some((V)=>V.startsWith("item:"))};for(let V of $)this.contextCompactionReceipts.delete(V),this.contextCompactionReceipts.set(V,Y);while(this.contextCompactionReceipts.size>LE){let V;for(let X of this.contextCompactionReceipts.values()){if(X.completed){V=X;break}V??=X}if(!V)break;for(let[X,z]of this.contextCompactionReceipts)if(z===V)this.contextCompactionReceipts.delete(X)}}handleTurnPlanUpdated($){let Z=this.currentTurn;if(!Z){j(`session "${this.sessionName}": turn/plan/updated with no current turn`);return}if(this.startWorkingFooter(Z),Z.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();if(Z.openBatchI=null,!Array.isArray($.plan))j(`session "${this.sessionName}": turn/plan/updated missing plan array`),Z.planSteps=[];else Z.planSteps=$.plan.map((J)=>({step:typeof J.step==="string"&&J.step?J.step:"MISS",status:typeof J.status==="string"&&J.status?J.status:"MISS"}));if(Z.planExplanation=typeof $.explanation==="string"?$.explanation:null,Z.planSteps.length>0)if(!Z.planLiveInserted){let J=Z.taskLiveInserted?C.taskBoardLive:C.footer;Z.planLiveInserted=!0,v0(Z.cardId,v8(Z.planSteps,Z.planExplanation,C.planLive),{type:"insert_before",targetElementId:J})}else F0(Z.cardId,C.planLive,v8(Z.planSteps,Z.planExplanation,C.planLive),{notifyCardFailure:!1});this.addPlanSnapshotOnCurrentTurn()}handlePlanDelta($){if(typeof $.delta!=="string"||!$.delta){j(`session "${this.sessionName}": item/plan/delta missing delta text`);return}if(typeof $.itemId!=="string"||!$.itemId)j(`session "${this.sessionName}": item/plan/delta missing itemId`)}handleThreadGoalUpdated($){if(!$||typeof $.objective!=="string"){j(`session "${this.sessionName}": thread/goal/updated missing objective`);return}if($.tokenBudget!=null&&typeof $.tokenBudget!=="number")j(`session "${this.sessionName}": thread/goal/updated invalid tokenBudget`);let Z=this.currentGoal,J={objective:$.objective,status:typeof $.status==="string"&&$.status?$.status:"MISS",tokenBudget:typeof $.tokenBudget==="number"?$.tokenBudget:$.tokenBudget===null?null:Number.NaN,tokensUsed:typeof $.tokensUsed==="number"?$.tokensUsed:Number.NaN,timeUsedSeconds:typeof $.timeUsedSeconds==="number"?$.timeUsedSeconds:Number.NaN};if(this.currentGoal=J,Z&&P6(Z)===P6(J))return;let Q=this.currentTurn;if(Q){if(this.startWorkingFooter(Q),Q.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();Q.openBatchI=null}this.addGoalUpdateOnCurrentTurn(J)}handleThreadGoalCleared(){if(!this.currentGoal)return;this.currentGoal=null;let $=this.currentTurn;if(!$)return;if(this.startWorkingFooter($),$.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();$.openBatchI=null,this.addGoalClearedOnCurrentTurn()}appendAssistant($){if(!this.currentTurn){if(this.openingTurn||this.bgResumeCardless)this.orphanAssistantCurrent+=$;return}let Z=this.currentTurn;if(this.startWritingFooter(Z),!Z.currentAssistantSegmentId){Z.openBatchI=null,this.maybeMidTurnRotate();let V=Z.assistantSegmentCount++,X=C.assistant(V);Z.currentAssistantSegmentId=X,Z.currentAssistantText=""}Z.currentAssistantText+=$;let J=Z.currentAssistantSegmentId;if(!J)return;Z.segmentTexts.set(J,Z.currentAssistantText),this.processOutboundMarkers(Z.currentAssistantText);let Y=this.cleanAssistantTextForDisplay(Z.currentAssistantText).slice(0,40);Z9(Z.cardId,Y)}takeOrphanAssistantText(){let $=[...this.orphanAssistantSegments];if(this.orphanAssistantCurrent.trim())$.push(this.orphanAssistantCurrent);return this.orphanAssistantSegments=[],this.orphanAssistantCurrent="",$.join(`
348
348
 
349
349
  `).trim()}discardOrphanAssistant(){this.orphanAssistantSegments=[],this.orphanAssistantCurrent="",this.bgResumeCardless=!1}flushOrphanAssistantToChat($){let Z=this.takeOrphanAssistantText();if(!Z)return;let J=this.cleanAssistantTextForDisplay(Z).trim();if(!J)return;j(`session "${this.sessionName}": flushing ${J.length} chars of orphan assistant text (${$})`),k(this.chatId,`\uD83D\uDCC4 后台轮输出(未能建卡,纯文本兜底):
350
350
 
351
- ${J}`)}completedAssistantElement($,Z){if(XV(Z))return this.mathAssistantContainer($,[{type:"markdown",text:Z}]);return{tag:"markdown",element_id:$,content:this.cleanAssistantTextForDisplay(Z).trim()||" "}}mathAssistantContainer($,Z){let J=Z.map((Q)=>Q.type==="markdown"?{tag:"markdown",content:this.cleanAssistantTextForDisplay(Q.text).trim()||" "}:{...Q.element});return{tag:"column_set",element_id:$,flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:J.length?J:[{tag:"markdown",content:" "}]}]}}async replaceSegmentWithMathImgs($,Z,J,Q){let Y=await Kj(Q);if(!await D0(Z,J,this.mathAssistantContainer(J,Y.blocks),{notifyCardFailure:!1})){j(`session "${this.sessionName}": math render ${J} write dropped (card closed/element dead) — raw text stays`);return}$.mathRendered??=new Map,$.mathRendered.get(Z)??$.mathRendered.set(Z,new Set),$.mathRendered.get(Z).add(J),j(`session "${this.sessionName}": math rendered ${J} (${Y.renderedImageCount} img, ${Y.blocks.length} blocks)`)}addCompletedAssistantSegment($,Z,J){let Q=$.cardId,Y=p0($),V=(async()=>{if(!await c2(Q,this.completedAssistantElement(Z,J),{type:"insert_before",targetElementId:Y}))return j(`session "${this.sessionName}": assistant segment ${Z} raw write failed on card=${Q}`),!1;if(XV(J)){let z=this.replaceSegmentWithMathImgs($,Q,Z,J).catch((H)=>j(`session "${this.sessionName}": math render ${Z} failed: ${H}`));$.mathRenderInflight??=new Map,$.mathRenderInflight.get(Q)??$.mathRenderInflight.set(Q,new Set),$.mathRenderInflight.get(Q).add(z),z.finally(()=>$.mathRenderInflight?.get(Q)?.delete(z))}return!0})();return $.assistantWriteInflight??=new Map,$.assistantWriteInflight.get(Q)??$.assistantWriteInflight.set(Q,new Set),$.assistantWriteInflight.get(Q).add(V),V.finally(()=>$.assistantWriteInflight?.get(Q)?.delete(V)),V}async sendAssistantTextFallback($,Z){let J=$.trim();if(!J)return;let Q=`⚠️ 对话卡片正文写入失败(${Z}),以下为 agent 原始回复:
351
+ ${J}`)}completedAssistantElement($,Z){if(XV(Z))return this.mathAssistantContainer($,[{type:"markdown",text:Z}]);return{tag:"markdown",element_id:$,content:this.cleanAssistantTextForDisplay(Z).trim()||" "}}mathAssistantContainer($,Z){let J=Z.map((Q)=>Q.type==="markdown"?{tag:"markdown",content:this.cleanAssistantTextForDisplay(Q.text).trim()||" "}:{...Q.element});return{tag:"column_set",element_id:$,flex_mode:"none",columns:[{tag:"column",width:"weighted",weight:1,elements:J.length?J:[{tag:"markdown",content:" "}]}]}}async replaceSegmentWithMathImgs($,Z,J,Q){let Y=await Kj(Q);if(!await F0(Z,J,this.mathAssistantContainer(J,Y.blocks),{notifyCardFailure:!1})){j(`session "${this.sessionName}": math render ${J} write dropped (card closed/element dead) — raw text stays`);return}$.mathRendered??=new Map,$.mathRendered.get(Z)??$.mathRendered.set(Z,new Set),$.mathRendered.get(Z).add(J),j(`session "${this.sessionName}": math rendered ${J} (${Y.renderedImageCount} img, ${Y.blocks.length} blocks)`)}addCompletedAssistantSegment($,Z,J){let Q=$.cardId,Y=p0($),V=(async()=>{if(!await c2(Q,this.completedAssistantElement(Z,J),{type:"insert_before",targetElementId:Y}))return j(`session "${this.sessionName}": assistant segment ${Z} raw write failed on card=${Q}`),!1;if(XV(J)){let z=this.replaceSegmentWithMathImgs($,Q,Z,J).catch((H)=>j(`session "${this.sessionName}": math render ${Z} failed: ${H}`));$.mathRenderInflight??=new Map,$.mathRenderInflight.get(Q)??$.mathRenderInflight.set(Q,new Set),$.mathRenderInflight.get(Q).add(z),z.finally(()=>$.mathRenderInflight?.get(Q)?.delete(z))}return!0})();return $.assistantWriteInflight??=new Map,$.assistantWriteInflight.get(Q)??$.assistantWriteInflight.set(Q,new Set),$.assistantWriteInflight.get(Q).add(V),V.finally(()=>$.assistantWriteInflight?.get(Q)?.delete(V)),V}async sendAssistantTextFallback($,Z){let J=$.trim();if(!J)return;let Q=`⚠️ 对话卡片正文写入失败(${Z}),以下为 agent 原始回复:
352
352
 
353
- ${J}`;if(!await k(this.chatId,Q))j(`session "${this.sessionName}": ASSISTANT_TEXT_PRESERVATION_FAILED (${Z}, ${J.length} chars)`)}finalizeCurrentAssistantSegment(){let $=this.currentTurn;if(!$){if(this.orphanAssistantCurrent.trim())this.orphanAssistantSegments.push(this.orphanAssistantCurrent);this.orphanAssistantCurrent="";return}if($.cardRotationFailed)this.maybeMidTurnRotate();if($.rotating)return;let Z=$.currentAssistantSegmentId,J=$.currentAssistantText??"";if(Z&&J.trim())this.addCompletedAssistantSegment($,Z,J),this.startWorkingFooter($);$.currentAssistantSegmentId=null,$.currentAssistantText=""}processOutboundMarkers($){for(let Z of nB($))this.sendOutboundPath(Z,"send marker")}cleanAssistantTextForDisplay($){return G0($)}sendOutboundPath($,Z){let J=l6($.trim());if(!J)return;let Q=this.currentTurn;if(Q?.outboundSeenPaths.has(J))return;if(Q?.outboundSeenPaths.add(J),!GE(J)){j(`session "${this.sessionName}": ignore non-absolute outbound path from ${Z}: ${J}`);return}j(`session "${this.sessionName}": outbound send from ${Z}: ${J}`);try{let Y=Q?.fileDeliveryMode??(this.proc?this.procFileDeliveryModes.get(this.proc):void 0)??this.getFileDeliveryMode();if(Q)Q.fileDeliveryMode=Y;if(Y==="chat"){Q?.outboundSentPaths.add(J),j8(this.chatId,J);return}if(!Q)throw Error("当前没有可关联的交付轮次");if(!Q.fileDelivery)Q.fileDelivery=this.createFileDeliveryForTurn(Q),this.fileDeliveries.add(Q.fileDelivery);Q.fileDelivery.add(J)}catch(Y){j(`session "${this.sessionName}": file delivery rejected: ${E(Y)}`),k(this.chatId,`❌ 文件交付失败:${E(Y)}`)}}createFileDeliveryForTurn($){return __({chatId:this.chatId,managerOpenId:$.userOpenId,projectName:this.sessionName,createdAt:$.startedAt})}startFooterStatus($,Z){if($.cardRotationFailed)return;let J=$.provider==="codex"?this.proc?.turnRetry:null;if(J){let V=J.reason==="stream_disconnected"?"连接中断":J.reason==="compact_connection_failed"?"压缩连接中断":J.reason==="transient_error"?"服务暂时异常":"模型满载";Z=J.reason==="quota"?`⏳ ${J.message}`:J.phase==="waiting"?`⏳ ${V} · ${J.delayMs/1000}s 后重试 #${J.attempt}`:`⏳ ${V} · 正在重试 #${J.attempt}`}if($.footerStatusLabel===Z)return;this.stopFooterStatus($),$.footerStatusLabel=Z,$.footerStatusStartedAt=Date.now();let Q=()=>{if($.footerStatusLabel!==Z)return;let V=$.cardId;if($.footerStatusWriteCardId===V){$.footerStatusPendingRender=Q;return}$.footerStatusPendingRender=void 0;let{label:X}=V9(Date.now()-$.footerStatusStartedAt,W5()),z=Z===d_?this.proc?.lastThinkingTokens:null,H=typeof z==="number"?` · 约 ${z} tokens`:"";$.footerStatusWriteCardId=V,this.replaceFooterContent(V,this.withModel(`${Z}${H} (${X})`)).then((G)=>{if($.footerStatusWriteCardId===V)$.footerStatusWriteCardId=void 0;if($.cardId!==V||$.footerStatusLabel===null)return;if(G.landed){let K=$.footerStatusPendingRender;$.footerStatusPendingRender=void 0,K?.();return}if($.footerStatusFailedCardId=V,$.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null;let W=$.footerStatusPendingRender;if($.footerStatusPendingRender=void 0,$.footerStatusLabel!==Z)W?.()})},Y=()=>{if($.footerStatusLabel!==Z||$.footerStatusFailedCardId===$.cardId)return;let{nextDelayMs:V}=V9(Date.now()-$.footerStatusStartedAt,W5());$.footerStatusHandle=setTimeout(()=>{Q(),Y()},Math.max(1,Math.ceil(V)))};Q(),Y()}startThinkingFooter($){this.startFooterStatus($,d_)}startWritingFooter($){this.startFooterStatus($,jE)}startWorkingFooter($){this.startFooterStatus($,_E)}stopFooterStatus($){if(!$)return;if($.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null,$.footerStatusStartedAt=0,$.footerStatusLabel=null,$.footerStatusPendingRender=void 0}async footerUsageSuffix($,Z,J,Q,Y,V){if(J&&(!Q||!Q.enabled||Q.agent!==$))return" | 额度 MISS";if(Q?.agent===$&&Q.enabled&&($==="claude"||$==="dsh"||Q.codexApiProvider)){let X=await Q.readUsage();if(X.state==="ok"&&X.kind!=="balance"){let z=X.windows.find((G)=>G.kind==="fiveHour");if(Q.kind==="claude-subscription"){let G=zW(X,V),W={percent:null,resetsAt:null};return this.fmtDualWindowSuffix(z??W,G??W)}let H=X.windows.find((G)=>G.kind==="weekly");if(z||H)return this.fmtDualWindowSuffix(z??null,H??null)}return` | ${TY(X)}`}if($==="codex"){let X=Y??(Z?.provider==="codex"?SZ(M$(Z)):null);if(!X)return" | 额度 MISS";let z=X.read();if(!z)return" | 额度 MISS";let H=O1(z.credits);return this.fmtDualWindowSuffix(z.fiveHour,z.weekly)+(H?` · ${H}`:"")}return" | 额度 MISS"}fmtDualWindowSuffix($,Z){let J=(V)=>{if(!V)return null;if(V.percent==null)return"MISS";let X=V.resetsAt&&V.resetsAt.getTime()>Date.now()?$1(V.resetsAt):"",z=`${Math.round(V.percent)}%`;return X?`${X}·${z}`:z},Q=J($),Y=J(Z);if(Q&&Y)return` | ${Q}·[${Y}]`;if(Q)return` | ${Q}`;if(Y)return` | [${Y}]`;return" | 额度 MISS"}waitForTurnCloses(){let $=[...this.turnCloseInflight];if($.length===0)return Promise.resolve();return Promise.allSettled($).then((Z)=>{let J=Z.filter((Q)=>Q.status==="rejected").map((Q)=>Q.reason);if(J.length===1)throw J[0];if(J.length>1)throw AggregateError(J,`turn close failed: ${J.map(E).join("; ")}`)})}releaseTurnCloseReactions($){for(let[Z,J]of[...$.currentBatchReactionIds.entries(),...$.pendingReactionIds.entries()])if(J)g0(Z,J)}closeTurnCard($,Z={}){let J=this.currentTurn;if(!J)return this.waitForTurnCloses();if(this.steeringBoundary?.turn===J)this.steeringBoundary.start();if(!$&&J.cardRotationFailed)this.maybeMidTurnRotate();this.currentTurn=null,this.stopFooterStatus(J);let Q=this.proc,Y={turn:J,proc:Q,procEpoch:this.procEpoch,contextTokens:this.currentContextTokens(Q),contextLimit:this.contextLimitForDisplay(Q),lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,tokenSourceId:this.selectedTokenSourceId,tokenSource:Q?.provider==="codex"?j0(Q.tokenSourceId??this.selectedTokenSourceId,M$(Q)):this.currentTokenSource(),codexUsage:Q?.provider==="codex"&&!M0(Q.tokenSourceId)?.codexApiProvider?SZ(M$(Q)):null,currentBatchReactionIds:this.currentBatchReactionIds,pendingReactionIds:this.pendingReactionIds};this.currentBatchReactionIds=new Map,this.pendingReactionIds=new Map;let V=this.finishTurnCardClose(Y,$,Z).finally(()=>this.releaseTurnCloseReactions(Y));return this.turnCloseInflight.add(V),V.then(()=>{this.turnCloseInflight.delete(V)},()=>{this.turnCloseInflight.delete(V)}),V}async finishTurnCardClose($,Z,J={}){let{turn:Q}=$;if(Q.steeringInflight?.size)await Promise.all([...Q.steeringInflight]);if(Q.rotating)await Q.rotating;if(await _V(Q),Q.fileDelivery)try{for(let O of await Q.fileDelivery.finish())Q.outboundSentPaths.add(O)}catch(O){j(`session "${this.sessionName}": file delivery close failed: ${E(O)}`),await h(this.chatId,`❌ 文件交付收尾失败:${E(O)}`)}finally{this.fileDeliveries.delete(Q.fileDelivery)}this.stopFooterStatus(Q);let Y=(Date.now()-Q.startedAt)/1000,V=Q.cardId,X=Q.segmentTexts;await d1(V);let z=new Map;if(Q.currentAssistantSegmentId&&Q.currentAssistantText.trim()){let{currentAssistantSegmentId:O,currentAssistantText:N}=Q;if(!await this.addCompletedAssistantSegment(Q,O,N))z.set(O,N);Q.currentAssistantSegmentId=null,Q.currentAssistantText=""}let H=Q.assistantWriteInflight?.get(V);if(H?.size)await Promise.allSettled([...H]);let G=Q.mathRenderInflight?.get(V);if(G?.size)await Promise.allSettled([...G]);let W=Q.mathRendered?.get(V);for(let[O,N]of X){if(e4(V,O)){z.set(O,N);continue}if(W?.has(O))continue;await R0(V,O,this.completedAssistantElement(O,N))}if(Q.cardRotationFailed)for(let[O,N]of X)z.set(O,N);let K=Z?Z:"✅",B=[`${K} ⏱ ${f0(Y)}`];if(J.hasFreshResult){let{contextTokens:O,contextLimit:N}=$,S=Q.provider==="claude",T=QY(O,N,S?0:void 0);if(T)B.push(`\uD83E\uDDE0 ${T}`);let y=$.lastTurnDelta?.costUsd??0;if(y>0)B.push(`\uD83D\uDCB0 $${y.toFixed(3)}`)}if(Q.contextCompactCount>0)B.push(`\uD83D\uDEA8 压缩×${Q.contextCompactCount}`);if(Q.outboundSentPaths.size>0)B.push(`\uD83D\uDCCE ${Q.outboundSentPaths.size}`);let _=this.modelLine(Q);if(_)B.push(_);let P=B.join(" | "),L=J.hasFreshResult?YY($.lastTurnUsage)+(Q.cardRotationFailed?"":await this.footerUsageSuffix(Q.provider,$.proc,$.tokenSourceId,$.tokenSource,$.codexUsage,Q.model)):"",q=L?`${P}
354
- ${L}`:P,D=[],M=(O)=>{D.push(O)},U=await D0(V,C.footer,this.footerElement(q),{onFailure:M});e0(V);let A=await m0(V,o2({durationSec:Y,outputTokens:J.hasFreshResult?$.lastTurnUsage?.output_tokens:void 0,suffix:Z}),M);if(U&&A)await N$(V);else{let O=`footer=${U?"ok":"MISS"}, settings=${A?"ok":"MISS"}`;j(`session "${this.sessionName}": terminal card transaction incomplete card=${V.slice(0,12)} ${O}`),await h(this.chatId,`⚠️ 对话卡片终态写入失败 (${O})。本轮已结束: ${K}
355
- ${D9(D)}`)}for(let O of z.values())await this.sendAssistantTextFallback(O,"CardKit 元素未落地");if((J.forcePush||!Z)&&Q.userOpenId&&Q.messageId&&!Q.cardRotationFailed)w2(Q.messageId,[Q.userOpenId])}}});function C$($){return{card:{type:"raw",data:$}}}import{randomUUID as DE}from"node:crypto";function gV($){return{session_name:$.sessionName,chat_id:$.chatId,status:$.status,running:$.isRunning(),translation:{enabled:$.proc?.translationEnabled===!0},native_session_id:$.proc?.sessionId??null,codex_account:$.proc?.provider==="codex"&&$.proc.isAlive()?{name:v.get(M$($.proc)).name,mode:$.proc.codexAccountSelectionMode?.()??"native",policy:"highest-score-plus-5h-ultra-pro-0.5"}:null,busy:!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount||$.pendingMidTurnMsgs.length),awaiting_model_input:!!$.modelCustomPrompt,last_result:$.proc?{anchor:$.proc.lastAssistantUuid,subtype:$.proc.lastResult.subtype,is_error:$.proc.lastResult.is_error}:null,selection:{provider:$.selectedProvider,source_id:$.selectedTokenSourceId,model:$.selectedModel,effort:$.selectedEffort},panels:[...$.modelPanels].map(([Z,J])=>({panel_id:Z,message_id:J.messageId,source_id:J.sourceId,mode:J.mode,editable:J.editable,total_models:J.catalog?.length,page:J.page,total_pages:J.totalPages,models:J.models.map((Q)=>({model:Q.model,provider:Q.provider,source_id:Q.sourceId,efforts:Q.efforts.map((Y)=>Y.effort),origin:Q.origin}))})),sources:s0().map((Z)=>({id:Z.id,display:Z.display,agent:Z.agent,enabled:Z.enabled,validates_custom_model:!!Z.verifyModel,status:Z.modelCatalogState?.status,error:Z.modelCatalogState?.error,models:Z.models.map((J)=>({model:J.model,efforts:J.efforts,default_effort:J.defaultEffort,unavailable_reason:J.unavailableReason,origin:J.origin}))}))}}function a_($,Z,J,Q,Y){if(!$||typeof $!=="object"||Array.isArray($))throw Error("bad action body");let V=$;if(!Z.chat_id.startsWith("oc_")||!Z.sender_open_id.startsWith("ou_"))throw Error("invalid debug context");if(V.chat_id!==Z.chat_id)throw Error("debug chat mismatch");if(typeof V.message_id!=="string"||!V.message_id.startsWith("om_"))throw Error("message_id required");if(!Y||V.message_id!==Y)throw Error("stale or mismatched model panel");if(!J||J.message_id!==V.message_id||J.chat_id!==Z.chat_id||J.msg_type!=="interactive"||J.sender?.sender_type!=="app"||J.sender.id!==Q)throw Error("model card must belong to this app and debug chat");if(!V.value||typeof V.value!=="object"||Array.isArray(V.value))throw Error("action value required");let X={};for(let[z,H]of Object.entries(V.value)){if(!ME.has(z))throw Error(`unsupported model action field: ${z}`);if(z==="page"){if(typeof H!=="number"||!Number.isSafeInteger(H)||H<0)throw Error("invalid page");X.page=H}else{if(typeof H!=="string"||!H.trim()||H.length>1024)throw Error(`invalid ${z}`);X[z]=H.trim()}}if(!FE.has(String(X.kind)))throw Error("only model panel actions are supported");for(let z of["panel_id","source_id"])if(!X[z])throw Error(`${z} required`);if(["model_select","model_effort_select","model_add","model_remove","model_custom_remove"].includes(String(X.kind))&&!X.model)throw Error("model required");if(X.kind==="model_effort_select"&&!X.effort)throw Error("effort required");if(X.kind==="model_page"&&X.page===void 0)throw Error("page required");if(X.kind==="model_list_open"&&X.mode!=="select"&&X.mode!=="add")throw Error("invalid model list mode");if(X.provider!==void 0&&!a$(X.provider))throw Error("invalid provider");return{event_id:`debug-model-${DE()}`,operator:{open_id:Z.sender_open_id},context:{open_chat_id:Z.chat_id,open_message_id:V.message_id},action:{tag:"button",value:X}}}var FE,ME;var o_=R(()=>{P0();X0();F0();FE=new Set(["provider_select","model_select","model_effort_select","model_page","model_list_open","model_add","model_remove","model_custom_remove","model_custom_prompt","model_panel_cancel"]),ME=new Set(["kind","panel_id","source_id","model","effort","provider","page","mode"])});import{createServer as UE}from"node:http";import{randomUUID as OE}from"node:crypto";function r_($){if($.allowReply&&$.buttons?.length)throw Error(t_);let Z=$.level==="error"?"red":$.level==="warn"?"yellow":"blue",J=$.level==="error"?"❌":$.level==="warn"?"⚠️":"\uD83D\uDD14",Q=!!(($.buttons?.length||$.allowReply)&&$.notifyId),Y=new Date,V=`${String(Y.getHours()).padStart(2,"0")}:${String(Y.getMinutes()).padStart(2,"0")}`,X=[];for(let H of $.images??[])if(H.key)X.push({tag:"img",img_key:H.key,alt:{tag:"plain_text",content:"screenshot"}});else{let G=H.error?`
356
- ${G0(H.error)}`:"";X.push({tag:"markdown",content:`<font color='red'>\uD83D\uDCF7 图片上传失败: ${H.src}${G}</font>`})}if(X.push({tag:"markdown",content:DJ($.text??"")||"_(空消息)_"}),$.resolution){let H=$.resolution,G=H.kind==="text"?"已回复":`已选择:${H.text}`,W;if(H.status==="processing")W=`<font color='blue'>⏳ ${G} · 推送中…</font>`;else if(H.status==="failed")W=`<font color='red'>⚠️ ${H.kind==="text"?G:`已选:${H.text}`} · 回调失败:${G0(H.detail??"未知")} · ${V}</font>`;else if(H.status==="delivered")W=`<font color='green'>✅ ${G} · 反馈已送达 · ${V}</font>`;else if(H.status==="unknown")W=`<font color='red'>⚠️ ${G} · 送达状态未知,禁止自动重试 · ${V}</font>`;else W=`<font color='green'>✅ ${G} · ${V}</font>`;if(X.push({tag:"markdown",content:W}),H.status==="delivered"&&H.reply)X.push({tag:"markdown",content:G0(H.reply)})}let z=Q&&(!$.resolution||$.resolution.status==="failed");if(z&&$.buttons?.length)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:$.buttons.map((H)=>({tag:"button",text:{tag:"plain_text",content:H.text},type:H.type,behaviors:[{type:"callback",value:{kind:"notify_callback",notify_id:$.notifyId,button_id:H.id}}]}))}]});if(X.push({tag:"hr"}),X.push({tag:"markdown",content:`<font color='grey'>via notify · ${V}</font>`}),z&&$.allowReply)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"回复"},type:"primary",behaviors:[{type:"callback",value:{kind:"notify_reply",notify_id:$.notifyId}}]}]}]});return{schema:"2.0",config:Q?{update_multi:!0}:{},header:{title:{tag:"plain_text",content:`${J} ${$.title}`},template:Z},body:{elements:X}}}function J2($,Z,J){let Q=J?.status??Z.status,Y={waiting:"等待用户输入",sending:"正在发送回复",processing:"正在发送回复",delivered:"回复已送达",done:"回复已记录",failed:"回复发送失败",cancelled:"已取消回复",unknown:"回复送达状态未知"},V=[{tag:"markdown",content:`通知:${G0($.title)}`}];if(Z.response)V.push({tag:"markdown",content:G0(Z.response.text)});if(Q==="waiting")V.push({tag:"markdown",content:`<at id=${Z.openId}></at> 请在群里发送一条文字消息作为回复。
357
- 你的下一条文字优先用于这条通知,完成后再回答 Agent 的提问。点击其他通知的「回复」会放弃本次回复;群控制命令仍然优先。`}),V.push({tag:"button",text:{tag:"plain_text",content:"取消回复"},type:"default",behaviors:[{type:"callback",value:{kind:"notify_reply_cancel",notify_id:$.notifyId,reply_id:Z.id}}]});if(Q==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let X=J?.detail??Z.error;if(X)V.push({tag:"markdown",content:`<font color='red'>${G0(X)}</font>`});if(Q==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Q==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:G0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Y[Q]},template:Q==="failed"||Q==="unknown"?"red":Q==="delivered"||Q==="done"?"green":"blue"},body:{elements:V}}}function TE($){if($===void 0||$===null)return{buttons:[]};if(!Array.isArray($))return{error:'"buttons" must be an array'};if($.length===0)return{buttons:[]};let Z=new Set,J=[];for(let Q of $){if(!Q||typeof Q!=="object")return{error:"each button must be an object"};let Y=String(Q.id??"").trim(),V=String(Q.text??"").trim();if(!RE.test(Y))return{error:`button id "${Y.slice(0,32)}" invalid (need ^[A-Za-z0-9_-]{1,64}$)`};if(!V)return{error:`button "${Y}" missing text`};if(V.length>s_)return{error:`button "${Y}" text > ${s_} chars`};if(Z.has(Y))return{error:`button id "${Y}" duplicated`};Z.add(Y);let X=String(Q.type??"default").toLowerCase(),z=NE.has(X)?X:"default";J.push({id:Y,text:V,type:z})}return{buttons:J}}function EE($){if($===void 0||$===null)return{};let Z=String($).trim();if(!Z)return{};let J;try{J=new URL(Z)}catch{return{error:`"callback" bad URL: "${Z.slice(0,64)}"`}}if(J.protocol!=="http:")return{error:`"callback" must be http (本机内), got "${J.protocol}"`};let Q=J.hostname.replace(/^\[|]$/g,"");if(Q!=="127.0.0.1"&&Q!=="localhost"&&Q!=="::1")return{error:`"callback" must be loopback (本机内), got "${J.hostname}"`};return{url:Z}}function e_($){try{let Z=UE((J,Q)=>{Promise.resolve().then(async()=>{let V;try{V=new URL(J.url??"/","http://localhost")}catch{Q.statusCode=400,Q.end("bad request URL");return}if(!await $.extraHandler?.(J,Q,V))await SE(J,Q)}).catch((V)=>{if(j(`notify: handler crash: ${V?.message??V}`),!Q.headersSent)Q.statusCode=500,Q.setHeader("content-type","text/plain; charset=utf-8"),Q.end(V instanceof l0?w(V):"internal error");else try{Q.end()}catch{}})});return Z.on("error",(J)=>{j(`notify: server bind failed (${$.bind}:${$.port}): ${J.message}`)}),Z.listen($.port,$.bind,()=>{j(`notify: HTTP listening at http://${$.bind}:${$.port}/notify`)}),Z}catch(Z){j(`notify: server bind failed (${$.bind}:${$.port}): ${Z}`)}}async function SE($,Z,J=z0){let Q=new URL($.url??"/","http://localhost"),Y=(l,f)=>{Z.statusCode=l,Z.setHeader("content-type","text/plain; charset=utf-8"),Z.end(f)},V=(l,f)=>{Z.statusCode=l,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(f))};if($.method==="GET"&&Q.pathname==="/")return Y(200,`lodestar notify
353
+ ${J}`;if(!await k(this.chatId,Q))j(`session "${this.sessionName}": ASSISTANT_TEXT_PRESERVATION_FAILED (${Z}, ${J.length} chars)`)}finalizeCurrentAssistantSegment(){let $=this.currentTurn;if(!$){if(this.orphanAssistantCurrent.trim())this.orphanAssistantSegments.push(this.orphanAssistantCurrent);this.orphanAssistantCurrent="";return}if($.cardRotationFailed)this.maybeMidTurnRotate();if($.rotating)return;let Z=$.currentAssistantSegmentId,J=$.currentAssistantText??"";if(Z&&J.trim())this.addCompletedAssistantSegment($,Z,J),this.startWorkingFooter($);$.currentAssistantSegmentId=null,$.currentAssistantText=""}processOutboundMarkers($){for(let Z of nB($))this.sendOutboundPath(Z,"send marker")}cleanAssistantTextForDisplay($){return G0($)}sendOutboundPath($,Z){let J=l6($.trim());if(!J)return;let Q=this.currentTurn;if(Q?.outboundSeenPaths.has(J))return;if(Q?.outboundSeenPaths.add(J),!GE(J)){j(`session "${this.sessionName}": ignore non-absolute outbound path from ${Z}: ${J}`);return}j(`session "${this.sessionName}": outbound send from ${Z}: ${J}`);try{let Y=Q?.fileDeliveryMode??(this.proc?this.procFileDeliveryModes.get(this.proc):void 0)??this.getFileDeliveryMode();if(Q)Q.fileDeliveryMode=Y;if(Y==="chat"){Q?.outboundSentPaths.add(J),j8(this.chatId,J);return}if(!Q)throw Error("当前没有可关联的交付轮次");if(!Q.fileDelivery)Q.fileDelivery=this.createFileDeliveryForTurn(Q),this.fileDeliveries.add(Q.fileDelivery);Q.fileDelivery.add(J)}catch(Y){j(`session "${this.sessionName}": file delivery rejected: ${E(Y)}`),k(this.chatId,`❌ 文件交付失败:${E(Y)}`)}}createFileDeliveryForTurn($){return __({chatId:this.chatId,managerOpenId:$.userOpenId,projectName:this.sessionName,createdAt:$.startedAt})}startFooterStatus($,Z){if($.cardRotationFailed)return;let J=$.provider==="codex"?this.proc?.turnRetry:null;if(J){let V=J.reason==="stream_disconnected"?"连接中断":J.reason==="compact_connection_failed"?"压缩连接中断":J.reason==="transient_error"?"服务暂时异常":"模型满载";Z=J.reason==="quota"?`⏳ ${J.message}`:J.phase==="waiting"?`⏳ ${V} · ${J.delayMs/1000}s 后重试 #${J.attempt}`:`⏳ ${V} · 正在重试 #${J.attempt}`}if($.footerStatusLabel===Z)return;this.stopFooterStatus($),$.footerStatusLabel=Z,$.footerStatusStartedAt=Date.now();let Q=()=>{if($.footerStatusLabel!==Z)return;let V=$.cardId;if($.footerStatusWriteCardId===V){$.footerStatusPendingRender=Q;return}$.footerStatusPendingRender=void 0;let{label:X}=V9(Date.now()-$.footerStatusStartedAt,W5()),z=Z===d_?this.proc?.lastThinkingTokens:null,H=typeof z==="number"?` · 约 ${z} tokens`:"";$.footerStatusWriteCardId=V,this.replaceFooterContent(V,this.withModel(`${Z}${H} (${X})`)).then((G)=>{if($.footerStatusWriteCardId===V)$.footerStatusWriteCardId=void 0;if($.cardId!==V||$.footerStatusLabel===null)return;if(G.landed){let K=$.footerStatusPendingRender;$.footerStatusPendingRender=void 0,K?.();return}if($.footerStatusFailedCardId=V,$.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null;let W=$.footerStatusPendingRender;if($.footerStatusPendingRender=void 0,$.footerStatusLabel!==Z)W?.()})},Y=()=>{if($.footerStatusLabel!==Z||$.footerStatusFailedCardId===$.cardId)return;let{nextDelayMs:V}=V9(Date.now()-$.footerStatusStartedAt,W5());$.footerStatusHandle=setTimeout(()=>{Q(),Y()},Math.max(1,Math.ceil(V)))};Q(),Y()}startThinkingFooter($){this.startFooterStatus($,d_)}startWritingFooter($){this.startFooterStatus($,jE)}startWorkingFooter($){this.startFooterStatus($,_E)}stopFooterStatus($){if(!$)return;if($.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null,$.footerStatusStartedAt=0,$.footerStatusLabel=null,$.footerStatusPendingRender=void 0}async footerUsageSuffix($,Z,J,Q,Y,V){if(J&&(!Q||!Q.enabled||Q.agent!==$))return" | 额度 MISS";if(Q?.agent===$&&Q.enabled&&($==="claude"||$==="dsh"||Q.codexApiProvider)){let X=await Q.readUsage();if(X.state==="ok"&&X.kind!=="balance"){let z=X.windows.find((G)=>G.kind==="fiveHour");if(Q.kind==="claude-subscription"){let G=zW(X,V),W={percent:null,resetsAt:null};return this.fmtDualWindowSuffix(z??W,G??W)}let H=X.windows.find((G)=>G.kind==="weekly");if(z||H)return this.fmtDualWindowSuffix(z??null,H??null)}return` | ${TY(X)}`}if($==="codex"){let X=Y??(Z?.provider==="codex"?SZ(M$(Z)):null);if(!X)return" | 额度 MISS";let z=X.read();if(!z)return" | 额度 MISS";let H=O1(z.credits);return this.fmtDualWindowSuffix(z.fiveHour,z.weekly)+(H?` · ${H}`:"")}return" | 额度 MISS"}fmtDualWindowSuffix($,Z){let J=(V)=>{if(!V)return null;if(V.percent==null)return"MISS";let X=V.resetsAt&&V.resetsAt.getTime()>Date.now()?$1(V.resetsAt):"",z=`${Math.round(V.percent)}%`;return X?`${X}·${z}`:z},Q=J($),Y=J(Z);if(Q&&Y)return` | ${Q}·[${Y}]`;if(Q)return` | ${Q}`;if(Y)return` | [${Y}]`;return" | 额度 MISS"}waitForTurnCloses(){let $=[...this.turnCloseInflight];if($.length===0)return Promise.resolve();return Promise.allSettled($).then((Z)=>{let J=Z.filter((Q)=>Q.status==="rejected").map((Q)=>Q.reason);if(J.length===1)throw J[0];if(J.length>1)throw AggregateError(J,`turn close failed: ${J.map(E).join("; ")}`)})}releaseTurnCloseReactions($){for(let[Z,J]of[...$.currentBatchReactionIds.entries(),...$.pendingReactionIds.entries()])if(J)g0(Z,J)}closeTurnCard($,Z={}){let J=this.currentTurn;if(!J)return this.waitForTurnCloses();if(this.steeringBoundary?.turn===J)this.steeringBoundary.start();if(!$&&J.cardRotationFailed)this.maybeMidTurnRotate();this.currentTurn=null,this.stopFooterStatus(J);let Q=this.proc,Y={turn:J,proc:Q,procEpoch:this.procEpoch,contextTokens:this.currentContextTokens(Q),contextLimit:this.contextLimitForDisplay(Q),lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,tokenSourceId:this.selectedTokenSourceId,tokenSource:Q?.provider==="codex"?j0(Q.tokenSourceId??this.selectedTokenSourceId,M$(Q)):this.currentTokenSource(),codexUsage:Q?.provider==="codex"&&!M0(Q.tokenSourceId)?.codexApiProvider?SZ(M$(Q)):null,currentBatchReactionIds:this.currentBatchReactionIds,pendingReactionIds:this.pendingReactionIds};this.currentBatchReactionIds=new Map,this.pendingReactionIds=new Map;let V=this.finishTurnCardClose(Y,$,Z).finally(()=>this.releaseTurnCloseReactions(Y));return this.turnCloseInflight.add(V),V.then(()=>{this.turnCloseInflight.delete(V)},()=>{this.turnCloseInflight.delete(V)}),V}async finishTurnCardClose($,Z,J={}){let{turn:Q}=$;if(Q.steeringInflight?.size)await Promise.all([...Q.steeringInflight]);if(Q.rotating)await Q.rotating;if(await _V(Q),Q.fileDelivery)try{for(let O of await Q.fileDelivery.finish())Q.outboundSentPaths.add(O)}catch(O){j(`session "${this.sessionName}": file delivery close failed: ${E(O)}`),await h(this.chatId,`❌ 文件交付收尾失败:${E(O)}`)}finally{this.fileDeliveries.delete(Q.fileDelivery)}this.stopFooterStatus(Q);let Y=(Date.now()-Q.startedAt)/1000,V=Q.cardId,X=Q.segmentTexts;await d1(V);let z=new Map;if(Q.currentAssistantSegmentId&&Q.currentAssistantText.trim()){let{currentAssistantSegmentId:O,currentAssistantText:N}=Q;if(!await this.addCompletedAssistantSegment(Q,O,N))z.set(O,N);Q.currentAssistantSegmentId=null,Q.currentAssistantText=""}let H=Q.assistantWriteInflight?.get(V);if(H?.size)await Promise.allSettled([...H]);let G=Q.mathRenderInflight?.get(V);if(G?.size)await Promise.allSettled([...G]);let W=Q.mathRendered?.get(V);for(let[O,N]of X){if(e4(V,O)){z.set(O,N);continue}if(W?.has(O))continue;await R0(V,O,this.completedAssistantElement(O,N))}if(Q.cardRotationFailed)for(let[O,N]of X)z.set(O,N);let K=Z?Z:"✅",B=[`${K} ⏱ ${y0(Y)}`];if(J.hasFreshResult){let{contextTokens:O,contextLimit:N}=$,S=Q.provider==="claude",T=QY(O,N,S?0:void 0);if(T)B.push(`\uD83E\uDDE0 ${T}`);let f=$.lastTurnDelta?.costUsd??0;if(f>0)B.push(`\uD83D\uDCB0 $${f.toFixed(3)}`)}if(Q.contextCompactCount>0)B.push(`\uD83D\uDEA8 压缩×${Q.contextCompactCount}`);if(Q.outboundSentPaths.size>0)B.push(`\uD83D\uDCCE ${Q.outboundSentPaths.size}`);let _=this.modelLine(Q);if(_)B.push(_);let P=B.join(" | "),L=J.hasFreshResult?YY($.lastTurnUsage)+(Q.cardRotationFailed?"":await this.footerUsageSuffix(Q.provider,$.proc,$.tokenSourceId,$.tokenSource,$.codexUsage,Q.model)):"",q=L?`${P}
354
+ ${L}`:P,F=[],M=(O)=>{F.push(O)},U=await F0(V,C.footer,this.footerElement(q),{onFailure:M});e0(V);let A=await m0(V,o2({durationSec:Y,outputTokens:J.hasFreshResult?$.lastTurnUsage?.output_tokens:void 0,suffix:Z}),M);if(U&&A)await N$(V);else{let O=`footer=${U?"ok":"MISS"}, settings=${A?"ok":"MISS"}`;j(`session "${this.sessionName}": terminal card transaction incomplete card=${V.slice(0,12)} ${O}`),await h(this.chatId,`⚠️ 对话卡片终态写入失败 (${O})。本轮已结束: ${K}
355
+ ${F9(F)}`)}for(let O of z.values())await this.sendAssistantTextFallback(O,"CardKit 元素未落地");if((J.forcePush||!Z)&&Q.userOpenId&&Q.messageId&&!Q.cardRotationFailed)w2(Q.messageId,[Q.userOpenId])}}});function C$($){return{card:{type:"raw",data:$}}}import{randomUUID as FE}from"node:crypto";function gV($){return{session_name:$.sessionName,chat_id:$.chatId,status:$.status,running:$.isRunning(),translation:{enabled:$.proc?.translationEnabled===!0},native_session_id:$.proc?.sessionId??null,codex_account:$.proc?.provider==="codex"&&$.proc.isAlive()?{name:v.get(M$($.proc)).name,mode:$.proc.codexAccountSelectionMode?.()??"native",policy:"highest-score-plus-5h-ultra-pro-0.5"}:null,busy:!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount||$.pendingMidTurnMsgs.length),awaiting_model_input:!!$.modelCustomPrompt,last_result:$.proc?{anchor:$.proc.lastAssistantUuid,subtype:$.proc.lastResult.subtype,is_error:$.proc.lastResult.is_error}:null,selection:{provider:$.selectedProvider,source_id:$.selectedTokenSourceId,model:$.selectedModel,effort:$.selectedEffort},panels:[...$.modelPanels].map(([Z,J])=>({panel_id:Z,message_id:J.messageId,source_id:J.sourceId,mode:J.mode,editable:J.editable,total_models:J.catalog?.length,page:J.page,total_pages:J.totalPages,models:J.models.map((Q)=>({model:Q.model,provider:Q.provider,source_id:Q.sourceId,efforts:Q.efforts.map((Y)=>Y.effort),origin:Q.origin}))})),sources:s0().map((Z)=>({id:Z.id,display:Z.display,agent:Z.agent,enabled:Z.enabled,validates_custom_model:!!Z.verifyModel,status:Z.modelCatalogState?.status,error:Z.modelCatalogState?.error,models:Z.models.map((J)=>({model:J.model,efforts:J.efforts,default_effort:J.defaultEffort,unavailable_reason:J.unavailableReason,origin:J.origin}))}))}}function a_($,Z,J,Q,Y){if(!$||typeof $!=="object"||Array.isArray($))throw Error("bad action body");let V=$;if(!Z.chat_id.startsWith("oc_")||!Z.sender_open_id.startsWith("ou_"))throw Error("invalid debug context");if(V.chat_id!==Z.chat_id)throw Error("debug chat mismatch");if(typeof V.message_id!=="string"||!V.message_id.startsWith("om_"))throw Error("message_id required");if(!Y||V.message_id!==Y)throw Error("stale or mismatched model panel");if(!J||J.message_id!==V.message_id||J.chat_id!==Z.chat_id||J.msg_type!=="interactive"||J.sender?.sender_type!=="app"||J.sender.id!==Q)throw Error("model card must belong to this app and debug chat");if(!V.value||typeof V.value!=="object"||Array.isArray(V.value))throw Error("action value required");let X={};for(let[z,H]of Object.entries(V.value)){if(!ME.has(z))throw Error(`unsupported model action field: ${z}`);if(z==="page"){if(typeof H!=="number"||!Number.isSafeInteger(H)||H<0)throw Error("invalid page");X.page=H}else{if(typeof H!=="string"||!H.trim()||H.length>1024)throw Error(`invalid ${z}`);X[z]=H.trim()}}if(!DE.has(String(X.kind)))throw Error("only model panel actions are supported");for(let z of["panel_id","source_id"])if(!X[z])throw Error(`${z} required`);if(["model_select","model_effort_select","model_add","model_remove","model_custom_remove"].includes(String(X.kind))&&!X.model)throw Error("model required");if(X.kind==="model_effort_select"&&!X.effort)throw Error("effort required");if(X.kind==="model_page"&&X.page===void 0)throw Error("page required");if(X.kind==="model_list_open"&&X.mode!=="select"&&X.mode!=="add")throw Error("invalid model list mode");if(X.provider!==void 0&&!a$(X.provider))throw Error("invalid provider");return{event_id:`debug-model-${FE()}`,operator:{open_id:Z.sender_open_id},context:{open_chat_id:Z.chat_id,open_message_id:V.message_id},action:{tag:"button",value:X}}}var DE,ME;var o_=R(()=>{P0();X0();D0();DE=new Set(["provider_select","model_select","model_effort_select","model_page","model_list_open","model_add","model_remove","model_custom_remove","model_custom_prompt","model_panel_cancel"]),ME=new Set(["kind","panel_id","source_id","model","effort","provider","page","mode"])});import{createServer as UE}from"node:http";import{randomUUID as OE}from"node:crypto";function r_($){if($.allowReply&&$.buttons?.length)throw Error(t_);let Z=$.level==="error"?"red":$.level==="warn"?"yellow":"blue",J=$.level==="error"?"❌":$.level==="warn"?"⚠️":"\uD83D\uDD14",Q=!!(($.buttons?.length||$.allowReply)&&$.notifyId),Y=new Date,V=`${String(Y.getHours()).padStart(2,"0")}:${String(Y.getMinutes()).padStart(2,"0")}`,X=[];for(let H of $.images??[])if(H.key)X.push({tag:"img",img_key:H.key,alt:{tag:"plain_text",content:"screenshot"}});else{let G=H.error?`
356
+ ${G0(H.error)}`:"";X.push({tag:"markdown",content:`<font color='red'>\uD83D\uDCF7 图片上传失败: ${H.src}${G}</font>`})}if(X.push({tag:"markdown",content:FJ($.text??"")||"_(空消息)_"}),$.resolution){let H=$.resolution,G=H.kind==="text"?"已回复":`已选择:${H.text}`,W;if(H.status==="processing")W=`<font color='blue'>⏳ ${G} · 推送中…</font>`;else if(H.status==="failed")W=`<font color='red'>⚠️ ${H.kind==="text"?G:`已选:${H.text}`} · 回调失败:${G0(H.detail??"未知")} · ${V}</font>`;else if(H.status==="delivered")W=`<font color='green'>✅ ${G} · 反馈已送达 · ${V}</font>`;else if(H.status==="unknown")W=`<font color='red'>⚠️ ${G} · 送达状态未知,禁止自动重试 · ${V}</font>`;else W=`<font color='green'>✅ ${G} · ${V}</font>`;if(X.push({tag:"markdown",content:W}),H.status==="delivered"&&H.reply)X.push({tag:"markdown",content:G0(H.reply)})}let z=Q&&(!$.resolution||$.resolution.status==="failed");if(z&&$.buttons?.length)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:$.buttons.map((H)=>({tag:"button",text:{tag:"plain_text",content:H.text},type:H.type,behaviors:[{type:"callback",value:{kind:"notify_callback",notify_id:$.notifyId,button_id:H.id}}]}))}]});if(X.push({tag:"hr"}),X.push({tag:"markdown",content:`<font color='grey'>via notify · ${V}</font>`}),z&&$.allowReply)X.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"回复"},type:"primary",behaviors:[{type:"callback",value:{kind:"notify_reply",notify_id:$.notifyId}}]}]}]});return{schema:"2.0",config:Q?{update_multi:!0}:{},header:{title:{tag:"plain_text",content:`${J} ${$.title}`},template:Z},body:{elements:X}}}function J2($,Z,J){let Q=J?.status??Z.status,Y={waiting:"等待用户输入",sending:"正在发送回复",processing:"正在发送回复",delivered:"回复已送达",done:"回复已记录",failed:"回复发送失败",cancelled:"已取消回复",unknown:"回复送达状态未知"},V=[{tag:"markdown",content:`通知:${G0($.title)}`}];if(Z.response)V.push({tag:"markdown",content:G0(Z.response.text)});if(Q==="waiting")V.push({tag:"markdown",content:`<at id=${Z.openId}></at> 请在群里发送一条文字消息作为回复。
357
+ 你的下一条文字优先用于这条通知,完成后再回答 Agent 的提问。点击其他通知的「回复」会放弃本次回复;群控制命令仍然优先。`}),V.push({tag:"button",text:{tag:"plain_text",content:"取消回复"},type:"default",behaviors:[{type:"callback",value:{kind:"notify_reply_cancel",notify_id:$.notifyId,reply_id:Z.id}}]});if(Q==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let X=J?.detail??Z.error;if(X)V.push({tag:"markdown",content:`<font color='red'>${G0(X)}</font>`});if(Q==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Q==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:G0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Y[Q]},template:Q==="failed"||Q==="unknown"?"red":Q==="delivered"||Q==="done"?"green":"blue"},body:{elements:V}}}function TE($){if($===void 0||$===null)return{buttons:[]};if(!Array.isArray($))return{error:'"buttons" must be an array'};if($.length===0)return{buttons:[]};let Z=new Set,J=[];for(let Q of $){if(!Q||typeof Q!=="object")return{error:"each button must be an object"};let Y=String(Q.id??"").trim(),V=String(Q.text??"").trim();if(!RE.test(Y))return{error:`button id "${Y.slice(0,32)}" invalid (need ^[A-Za-z0-9_-]{1,64}$)`};if(!V)return{error:`button "${Y}" missing text`};if(V.length>s_)return{error:`button "${Y}" text > ${s_} chars`};if(Z.has(Y))return{error:`button id "${Y}" duplicated`};Z.add(Y);let X=String(Q.type??"default").toLowerCase(),z=NE.has(X)?X:"default";J.push({id:Y,text:V,type:z})}return{buttons:J}}function EE($){if($===void 0||$===null)return{};let Z=String($).trim();if(!Z)return{};let J;try{J=new URL(Z)}catch{return{error:`"callback" bad URL: "${Z.slice(0,64)}"`}}if(J.protocol!=="http:")return{error:`"callback" must be http (本机内), got "${J.protocol}"`};let Q=J.hostname.replace(/^\[|]$/g,"");if(Q!=="127.0.0.1"&&Q!=="localhost"&&Q!=="::1")return{error:`"callback" must be loopback (本机内), got "${J.hostname}"`};return{url:Z}}function e_($){try{let Z=UE((J,Q)=>{Promise.resolve().then(async()=>{let V;try{V=new URL(J.url??"/","http://localhost")}catch{Q.statusCode=400,Q.end("bad request URL");return}if(!await $.extraHandler?.(J,Q,V))await SE(J,Q)}).catch((V)=>{if(j(`notify: handler crash: ${V?.message??V}`),!Q.headersSent)Q.statusCode=500,Q.setHeader("content-type","text/plain; charset=utf-8"),Q.end(V instanceof l0?w(V):"internal error");else try{Q.end()}catch{}})});return Z.on("error",(J)=>{j(`notify: server bind failed (${$.bind}:${$.port}): ${J.message}`)}),Z.listen($.port,$.bind,()=>{j(`notify: HTTP listening at http://${$.bind}:${$.port}/notify`)}),Z}catch(Z){j(`notify: server bind failed (${$.bind}:${$.port}): ${Z}`)}}async function SE($,Z,J=z0){let Q=new URL($.url??"/","http://localhost"),Y=(l,y)=>{Z.statusCode=l,Z.setHeader("content-type","text/plain; charset=utf-8"),Z.end(y)},V=(l,y)=>{Z.statusCode=l,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(y))};if($.method==="GET"&&Q.pathname==="/")return Y(200,`lodestar notify
358
358
  `+`POST /notify body={project,text,title?,level?,images?,buttons?,allow_reply?,callback?} → push card to group
359
359
  `+`GET /notify/result/<notify_id> → poll a button choice or text reply (pull mode, no callback server)
360
360
  `+`GET /agents/identities; POST/GET/DELETE /agents/runs[/<id>] → capability-protected delegated Agents
361
361
  `+`levels: info|warn|error (default info); images=[/abs/*.png] uploaded + embedded
362
362
  card types: plain (neither field), selection (buttons), text reply (allow_reply:true); do not combine buttons and allow_reply:true
363
363
  `+`all types support text + images; callback=http://127.0.0.1:PORT/path optional for selection/reply (push) — omit to poll
364
- `);if($.method==="GET"&&Q.pathname.startsWith("/notify/result/")){let l;try{l=decodeURIComponent(Q.pathname.slice(15)).trim()}catch{return Y(400,"invalid notify_id encoding")}if(!l)return Y(400,"missing notify_id in path");let f=R1(l);if(!f)return V(404,{error:"unknown notify_id",notify_id:l});return V(200,Uj(f))}if($.method!=="POST"||Q.pathname!=="/notify")return Y(405,"use POST /notify");let X="",z=0;$.setEncoding("utf8");for await(let l of $)if(z+=Buffer.byteLength(l),z<=mV)X+=l;else X="";if(z>mV)return Y(413,`request body exceeds ${mV} bytes`);let H={};try{H=JSON.parse(X)}catch{return Y(400,"bad json")}if(!H||typeof H!=="object"||Array.isArray(H))return Y(400,"body must be an object");if(H.allow_reply!==void 0&&typeof H.allow_reply!=="boolean")return Y(400,'"allow_reply" must be a boolean');let G=H.allow_reply===!0,W=String(H.project??"").trim(),K=String(H.text??""),B=String(H.title??"").trim(),_=String(H.level??"info").toLowerCase();if(!W)return Y(400,'missing "project"');if(!K)return Y(400,'missing "text"');let{buttons:P,error:L}=TE(H.buttons);if(L)return Y(400,L);let{url:q,error:D}=EE(H.callback);if(D)return Y(400,D);let M=!!(P&&P.length);if(M&&G)return Y(400,t_);let U=M||G,A=q??"",O=AE.has(_)?_:"info",N=B||W,S=J.sanitizeSessionName(W),T=J.chatIdForSession(S);if(!T)return j(`notify: project "${W}" (sanitized "${S}") has no chat binding → 404`),Y(404,`project "${W}" not bound — send any message in that Feishu group at least once after the daemon started, then retry`);let y=Array.isArray(H.images)?H.images:[],m=[];for(let l of y){let f=String(l??"").trim();if(!f)continue;let Q0,t=await J.uploadImageKey(f,(K0)=>{Q0=K0});m.push({key:t??"",src:f,...Q0===void 0?{}:{error:w(Q0)}})}let b=U?`nf_${OE()}`:"",p=r_({title:N,text:K,level:O,images:m,buttons:P,allowReply:G,notifyId:b}),c,J0=await J.sendCard(T,p,(l)=>{c=l});if(!J0)return j(`notify: sendCard failed → 502 (project="${W}" chat=${T.slice(0,8)}…)`),Y(502,`feishu sendCard failed: ${w(c)}`);if(U&&b){let l={notifyId:b,callbackUrl:A,chatId:T,messageId:J0,project:W,title:N,text:K,level:O,imageKeys:m,buttons:P,allowReply:G,createdAt:Date.now()};qj(l)}j(`notify: → ${W} (${T.slice(0,8)}…) level=${O} bytes=${K.length} images=${m.length} buttons=${P?.length??0} allowReply=${G} push=${U&&!!A?1:0} msg=${J0}`),V(200,{ok:!0,chat_id:T,message_id:J0,...b?{notify_id:b}:{}})}function Q2($,Z){return r_({title:$.title,text:$.text,level:$.level,images:$.imageKeys,buttons:$.buttons,allowReply:$.allowReply,notifyId:$.notifyId,resolution:Z})}var AE,NE,RE,s_=64,t_='"buttons" and "allow_reply":true are mutually exclusive; choose button selection or text reply',mV=4194304;var K5=R(()=>{I();Y0();j4();d0();Z3();AE=new Set(["info","warn","error"]),NE=new Set(["default","primary","danger"]),RE=/^[A-Za-z0-9_-]{1,64}$/});var JP=YX((zc,ZP)=>{var{readFileSync:CE,rmSync:xE}=z4("node:fs"),{homedir:$P}=z4("node:os"),{join:X3}=z4("node:path"),{managedClaudePluginDir:bE}=S5();function kE($,Z,J=console.log){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){J(`skill: sync disabled, skip removal ${$}`);return}let Q=Z??[X3($P(),".codex","skills"),X3($P(),".claude","skills"),X3(bE(),"skills")],Y=[];for(let V of Q){let X=X3(V,$),z=X3(X,"SKILL.md"),H;try{H=CE(z,"utf8")}catch(K){if(K.code==="ENOENT")continue;let B=Error(`skill: obsolete removal failed (${z}): ${K}`,{cause:K});J(B.message),Y.push(B);continue}let G=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(H)?.[1],W=/^name:[ \t]*(?:"([^"]*)"|'([^']*)'|([^\s#]+))[ \t]*$/m.exec(G??"");if(!W||(W[1]??W[2]??W[3])!==$){J(`skill: obsolete path preserved because ownership is unclear ${z}`);continue}try{xE(X,{recursive:!0,force:!1}),J(`skill: removed obsolete ${X}`)}catch(K){let B=Error(`skill: obsolete removal failed (${X}): ${K}`,{cause:K});J(B.message),Y.push(B)}}if(Y.length)throw AggregateError(Y,`Failed to remove obsolete Skill ${$}`)}ZP.exports={removeManagedSkill:kE}});import{existsSync as YP,readFileSync as VP}from"node:fs";import{homedir as QP}from"node:os";import{join as z3}from"node:path";function B5($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip ${$.name}`);return}let J=Z??[z3(QP(),".codex","skills"),z3(QP(),".claude","skills")];for(let Q of J){let Y=z3(Q,$.name,"SKILL.md");try{let V=YP(Y)?VP(Y,"utf8"):null;if(V===$.body)continue;Q$(Y,$.body),j(`skill: ${V===null?"installed":"updated"} ${Y}`)}catch(V){j(`skill: sync failed (${Y}): ${V}`)}}if(!Z)wE($,G4)}function wE($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip Claude plugin ${$.name}`);return}let J=z3(Z,".claude-plugin","plugin.json"),Q=z3(Z,"skills",$.name,"SKILL.md"),Y=JSON.stringify({name:"lodestar-managed",description:"Lodestar daemon-managed Skills for Claude Agent SDK sessions",version:"1.0.0",author:{name:"Lodestar"}},null,2)+`
364
+ `);if($.method==="GET"&&Q.pathname.startsWith("/notify/result/")){let l;try{l=decodeURIComponent(Q.pathname.slice(15)).trim()}catch{return Y(400,"invalid notify_id encoding")}if(!l)return Y(400,"missing notify_id in path");let y=R1(l);if(!y)return V(404,{error:"unknown notify_id",notify_id:l});return V(200,Uj(y))}if($.method!=="POST"||Q.pathname!=="/notify")return Y(405,"use POST /notify");let X="",z=0;$.setEncoding("utf8");for await(let l of $)if(z+=Buffer.byteLength(l),z<=mV)X+=l;else X="";if(z>mV)return Y(413,`request body exceeds ${mV} bytes`);let H={};try{H=JSON.parse(X)}catch{return Y(400,"bad json")}if(!H||typeof H!=="object"||Array.isArray(H))return Y(400,"body must be an object");if(H.allow_reply!==void 0&&typeof H.allow_reply!=="boolean")return Y(400,'"allow_reply" must be a boolean');let G=H.allow_reply===!0,W=String(H.project??"").trim(),K=String(H.text??""),B=String(H.title??"").trim(),_=String(H.level??"info").toLowerCase();if(!W)return Y(400,'missing "project"');if(!K)return Y(400,'missing "text"');let{buttons:P,error:L}=TE(H.buttons);if(L)return Y(400,L);let{url:q,error:F}=EE(H.callback);if(F)return Y(400,F);let M=!!(P&&P.length);if(M&&G)return Y(400,t_);let U=M||G,A=q??"",O=AE.has(_)?_:"info",N=B||W,S=J.sanitizeSessionName(W),T=J.chatIdForSession(S);if(!T)return j(`notify: project "${W}" (sanitized "${S}") has no chat binding → 404`),Y(404,`project "${W}" not bound — send any message in that Feishu group at least once after the daemon started, then retry`);let f=Array.isArray(H.images)?H.images:[],m=[];for(let l of f){let y=String(l??"").trim();if(!y)continue;let Q0,t=await J.uploadImageKey(y,(K0)=>{Q0=K0});m.push({key:t??"",src:y,...Q0===void 0?{}:{error:w(Q0)}})}let b=U?`nf_${OE()}`:"",p=r_({title:N,text:K,level:O,images:m,buttons:P,allowReply:G,notifyId:b}),c,J0=await J.sendCard(T,p,(l)=>{c=l});if(!J0)return j(`notify: sendCard failed → 502 (project="${W}" chat=${T.slice(0,8)}…)`),Y(502,`feishu sendCard failed: ${w(c)}`);if(U&&b){let l={notifyId:b,callbackUrl:A,chatId:T,messageId:J0,project:W,title:N,text:K,level:O,imageKeys:m,buttons:P,allowReply:G,createdAt:Date.now()};qj(l)}j(`notify: → ${W} (${T.slice(0,8)}…) level=${O} bytes=${K.length} images=${m.length} buttons=${P?.length??0} allowReply=${G} push=${U&&!!A?1:0} msg=${J0}`),V(200,{ok:!0,chat_id:T,message_id:J0,...b?{notify_id:b}:{}})}function Q2($,Z){return r_({title:$.title,text:$.text,level:$.level,images:$.imageKeys,buttons:$.buttons,allowReply:$.allowReply,notifyId:$.notifyId,resolution:Z})}var AE,NE,RE,s_=64,t_='"buttons" and "allow_reply":true are mutually exclusive; choose button selection or text reply',mV=4194304;var K5=R(()=>{I();Y0();j4();d0();Z3();AE=new Set(["info","warn","error"]),NE=new Set(["default","primary","danger"]),RE=/^[A-Za-z0-9_-]{1,64}$/});var JP=YX((zc,ZP)=>{var{readFileSync:CE,rmSync:xE}=z4("node:fs"),{homedir:$P}=z4("node:os"),{join:X3}=z4("node:path"),{managedClaudePluginDir:bE}=S5();function kE($,Z,J=console.log){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){J(`skill: sync disabled, skip removal ${$}`);return}let Q=Z??[X3($P(),".codex","skills"),X3($P(),".claude","skills"),X3(bE(),"skills")],Y=[];for(let V of Q){let X=X3(V,$),z=X3(X,"SKILL.md"),H;try{H=CE(z,"utf8")}catch(K){if(K.code==="ENOENT")continue;let B=Error(`skill: obsolete removal failed (${z}): ${K}`,{cause:K});J(B.message),Y.push(B);continue}let G=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(H)?.[1],W=/^name:[ \t]*(?:"([^"]*)"|'([^']*)'|([^\s#]+))[ \t]*$/m.exec(G??"");if(!W||(W[1]??W[2]??W[3])!==$){J(`skill: obsolete path preserved because ownership is unclear ${z}`);continue}try{xE(X,{recursive:!0,force:!1}),J(`skill: removed obsolete ${X}`)}catch(K){let B=Error(`skill: obsolete removal failed (${X}): ${K}`,{cause:K});J(B.message),Y.push(B)}}if(Y.length)throw AggregateError(Y,`Failed to remove obsolete Skill ${$}`)}ZP.exports={removeManagedSkill:kE}});import{existsSync as YP,readFileSync as VP}from"node:fs";import{homedir as QP}from"node:os";import{join as z3}from"node:path";function B5($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip ${$.name}`);return}let J=Z??[z3(QP(),".codex","skills"),z3(QP(),".claude","skills")];for(let Q of J){let Y=z3(Q,$.name,"SKILL.md");try{let V=YP(Y)?VP(Y,"utf8"):null;if(V===$.body)continue;Q$(Y,$.body),j(`skill: ${V===null?"installed":"updated"} ${Y}`)}catch(V){j(`skill: sync failed (${Y}): ${V}`)}}if(!Z)wE($,G4)}function wE($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){j(`skill: sync disabled, skip Claude plugin ${$.name}`);return}let J=z3(Z,".claude-plugin","plugin.json"),Q=z3(Z,"skills",$.name,"SKILL.md"),Y=JSON.stringify({name:"lodestar-managed",description:"Lodestar daemon-managed Skills for Claude Agent SDK sessions",version:"1.0.0",author:{name:"Lodestar"}},null,2)+`
365
365
  `;for(let[V,X]of[[J,Y],[Q,$.body]])try{let z=YP(V)?VP(V,"utf8"):null;if(z===X)continue;Q$(V,X),j(`skill: ${z===null?"installed":"updated"} ${V}`)}catch(z){j(`skill: Claude plugin sync failed (${V}): ${z}`)}}function j5($,Z){XP.removeManagedSkill($,Z,j)}var XP;var _5=R(()=>{I();b0();H0();XP=QX(JP(),1)});function vE($){let Z=`Push a one-shot notification card to a Feishu (Lark) group via the local lodestar daemon's HTTP endpoint. Auto-trigger whenever the user asks to "通知飞书", "推送到飞书", "推到飞书群", "飞书推送", "发到飞书", "脚本跑完通知我", "进程完成发个消息", "send to feishu", "feishu notify", "lodestar notify", "post to lark group", or wants any local script / cron / long-running process to ping a Feishu group (build done, deploy finished, trade filled, monitor alert, error caught). Encodes the call shape — POST http://127.0.0.1:${$}/notify with \`{project, text, level}\` — so consumers do not have to re-derive it. Also covers interactive buttons: add \`buttons\` and either pledge a loopback \`callback\` URL (daemon POSTs the click back) or omit it and poll \`GET /notify/result/NOTIFY_ID\`; all on localhost.`;return`---
366
366
  name: ${zP}
367
367
  description: ${JSON.stringify(Z+" Also receive free-text replies with allow_reply:true: a fixed 回复 button opens a waiting card, then the user types in the group and the daemon returns the text through the same callback or result endpoint.")}
@@ -622,20 +622,20 @@ is the script's acknowledgement, distinct from the user's response.
622
622
  Hand-edits will be overwritten — set
623
623
  \`LODESTAR_DISABLE_SKILL_SYNC=1\` and restart the daemon if you want
624
624
  to maintain the file yourself.
625
- `}function HP(){B5({name:zP,body:vE(g.notify.port)})}var zP="feishu-notify";var GP=R(()=>{k0();_5()});import{randomUUID as fE}from"node:crypto";function WP($){let Z=(V)=>V instanceof Error?V.message:String(V),J=(V,X,z)=>{if(!V)return"通知已过期或已移除";if(!z)return"无法识别回复人,操作未执行";if(X&&X!==V.chatId)return"通知不属于当前群,操作未执行";if(!V.allowReply)return"此通知未开启文字回复";if(V.unknownAt)return`回复送达状态未知,禁止自动重试:${V.unknownReason}`;if(V.resolvedAt)return"此通知已处理";if(K9(V.notifyId))return"通知正在处理中";return null},Q=async(V,X)=>{$.log(`notify-reply: ${X}`);let z;if(!await $.sendText(V,`❌ ${X}`,(H)=>{z=H}))throw Error(`通知回复错误提示发送失败: ${w(z)};原错误:${X}`)},Y=async(V,X,z,H)=>{try{await $.updateCard(X,z)}catch(G){await Q(V.chatId,`${H},卡片更新失败:${w(G)}`)}};return{async recover(V){if(V.dispatchState&&V.unknownAt){let H=V.dispatchState,G=V.buttons.find((W)=>W.id===H.buttonId);await Y(V,V.messageId,Q2(V,{status:"unknown",buttonId:H.buttonId,text:G?.text??H.buttonId,operatorOpenId:H.openId,detail:V.unknownReason}),"按钮回调送达状态未知");return}let X=V.replyState;if(!X||!V.unknownAt)return;let z={kind:"text",status:"unknown",text:X.response?.text??"",operatorOpenId:X.openId,detail:V.unknownReason};await Y(V,X.promptMessageId,J2(V,X,z),"回复送达状态未知"),await Y(V,V.messageId,Q2(V,z),"回复送达状态未知")},async open(V,X,z){let H=R1(V),G=J(H,X,z);if(G||!H)return{ok:!1,message:G};if(H.replyState?.status==="waiting"||H.replyState?.status==="sending")return{ok:!1,message:"此通知正在等待回复,请先在群里输入或由回复人取消"};let W=HV(H.chatId);if(W.some((K)=>K.replyState?.status==="sending"||K9(K.notifyId)))return{ok:!1,message:"上一条通知回复正在发送,请稍后切换"};t8(V);try{for(let P of W){let L={...P.replyState,status:"cancelled",cancelReason:"switched"};B9(P.notifyId,L),await Y(P,L.promptMessageId,J2(P,L),"已放弃上一条回复并切换通知")}let K={id:fE(),openId:z,promptMessageId:"",openedAt:Date.now(),status:"waiting"},B,_=await $.sendCard(H.chatId,J2(H,K),(P)=>{B=P});if(!_)return{ok:!1,message:`等待输入卡片发送失败,未开始接收回复,请重新点击「回复」
626
- ${w(B)}`};K.promptMessageId=_;try{B9(V,K)}catch(P){let L=`等待输入状态保存失败,未开始接收回复:${Z(P)}`;return await Y(H,_,J2(H,K,{status:"failed",detail:L}),L),{ok:!1,message:L,presented:!0}}return{ok:!0,message:"等待输入卡片已发送,请在群里回复一条文字",presented:!0}}finally{r8(V),$.onWaitingChanged(H.chatId)}},async cancel(V,X,z,H){let G=R1(V),W=J(G,z,H);if(W||!G)return{ok:!1,message:W};let K=G.replyState;if(!K||K.id!==X||K.status!=="waiting")return{ok:!1,message:"此回复已结束或正在发送,无法取消"};if(K.openId!==H)return{ok:!1,message:"仅点击「回复」的人可以取消"};let B={...K,status:"cancelled"};return B9(V,B),$.onWaitingChanged(G.chatId),await Y(G,K.promptMessageId,J2(G,B),"回复已取消"),{ok:!0,message:"已取消回复",presented:!0}},async consume(V){let{chatId:X,openId:z,messageId:H,text:G,createTime:W}=V;if(!z||!H||!G.trim())return!1;if(Mj(X,H))return!0;let K=e8(X,z);if(!K?.replyState)return!1;let B=K.replyState;if(W>0&&W<B.openedAt)return!1;if(B.status!=="waiting"||K9(K.notifyId))return await Q(X,"上一条通知回复正在发送,这条文字未提交,请稍后重发"),!0;let _={text:G,message_id:H,prompt_message_id:B.promptMessageId},P={...B,status:"sending",response:_};t8(K.notifyId);try{try{B9(K.notifyId,P)}catch(M){return await Q(X,`回复保存失败,尚未回传,请重新输入:${Z(M)}`),!0}let L;try{try{await $.updateCard(B.promptMessageId,J2(K,P))}catch(M){throw Error(w(M))}if(K.callbackUrl)L=await $.dispatch(K,_,z);else $3(K.notifyId,void 0,z),L={ok:!0,detail:"已记录"}}catch(M){L={ok:!1,detail:Z(M)}}let q;if(L.ok){let M=K.callbackUrl?i6(K.notifyId,void 0,z):{state:"complete"};q={kind:"text",text:G,operatorOpenId:z,status:M.state==="unknown"?"unknown":K.callbackUrl?"delivered":"done",...M.state==="unknown"?{detail:M.detail}:{reply:L.reply}}}else{q={kind:"text",text:G,operatorOpenId:z,status:"failed",detail:L.detail};try{B9(K.notifyId,{...P,status:"failed",error:L.detail})}catch(M){let U=`${L.detail};失败状态保存失败:${Z(M)}`;try{d6(K.notifyId,void 0,z,U)}catch(A){$.log(`notify-reply: UNKNOWN persistence failed: ${Z(A)}`)}q={...q,status:"unknown",detail:U}}}let D=q.status==="delivered"?"回复已送达":q.status==="done"?"回复已记录":q.status==="unknown"?`回复送达状态未知:${q.detail}`:`回复未送达:${q.detail}`;return await Y(K,B.promptMessageId,J2(K,P,q),D),await Y(K,K.messageId,Q2(K,q),D),$.log(`notify-reply: notify_id=${K.notifyId} status=${q.status}`),!0}finally{r8(K.notifyId),$.onWaitingChanged(K.chatId)}}}}var KP=R(()=>{Z3();K5()});function BP($){let Z=pV($,"agent run request"),J=Array.isArray(Z.identity_ids)?Z.identity_ids.map(String):Array.isArray(Z.identityIds)?Z.identityIds.map(String):[],Q=[...new Set(J.map((G)=>G.trim()).filter(Boolean))],Y=Z.session_id!==void 0?Z.session_id:Z.sessionId,V=F9(Y);if(Y!==void 0&&!V)throw Error("agent session_id must be a non-empty string");if(Z.session_id!==void 0&&Z.sessionId!==void 0&&Z.session_id!==Z.sessionId)throw Error("conflicting agent session_id and sessionId");if(V&&Q.length>1)throw Error("agent session continuation accepts at most one identity_id");if(!V&&Q.length===0)throw Error("agent run requires at least one identity_id");let X=qP(Z.prompt,'agent run requires "prompt"'),z=F9(Z.effort),H=PP(Z);return{identityIds:Q,description:M9(Z.description),prompt:X,...z?{effort:z}:{},...V?{sessionId:V}:{},...H!==void 0?{workDir:H}:{},..._P(Z)}}function jP($){let Z=pV($,"agent follow-up request"),J=qP(Z.prompt,'agent follow-up requires "prompt"'),Q=F9(Z.identity_id??Z.identityId),Y=F9(Z.effort),V=PP(Z);return{description:M9(Z.description),prompt:J,...Q?{identityId:Q}:{},...Y?{effort:Y}:{},...V!==void 0?{workDir:V}:{},..._P(Z)}}function _P($){let Z={};for(let[J,Q]of[["request_id","requestId"],["requester_open_id","requesterOpenId"]]){if($[J]===void 0)continue;let Y=$[J];if(typeof Y!=="string"||!Y.trim()||Y.length>200||/[\x00-\x1f]/.test(Y))throw Error(`invalid ${J}`);Z[Q]=Y.trim()}return Z}function L$($){return $.owner??{kind:"session",name:$.sessionName,chatId:$.chatId,workDir:$.sessionWorkDir??$.workDir}}function Y4($){return JSON.stringify([$.kind,$.name,$.chatId,$.workDir])}function P5($){if(typeof $!=="string"||!$.trim()||$.includes("\x00"))throw Error("agent work_dir must be a non-empty path without null bytes");return $}function PP($){if($.work_dir!==void 0&&$.workDir!==void 0&&$.work_dir!==$.workDir)throw Error("conflicting agent work_dir and workDir");let Z=$.work_dir!==void 0?$.work_dir:$.workDir;return Z===void 0?void 0:P5(Z)}function M9($){if(typeof $!=="string"||!$.trim())throw Error('agent run requires "description" (CLI: --description)');let Z=$.trim();if(/[\r\n\u2028\u2029]/.test(Z))throw Error("agent description must be a single line");if([...Z].length>60)throw Error("agent description exceeds 60 characters");return Z}function LP($){let Z=pV($,"agent answer request"),J=F9(Z.identity_id??Z.identityId),Q=F9(Z.request_id??Z.requestId);if(!Q)throw Error("agent answer requires request_id");if(!Z.answers||typeof Z.answers!=="object"||Array.isArray(Z.answers))throw Error("agent answer requires an answers object");let Y={};for(let[V,X]of Object.entries(Z.answers)){if(!V.trim())throw Error("agent answer contains an empty question key");Y[V]=String(X)}if(Object.keys(Y).length===0)throw Error("agent answer requires at least one answer");return{requestId:Q,answers:Y,...J?{identityId:J}:{}}}function pV($,Z){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${Z} must be an object`);return $}function qP($,Z){let J=String($??"");if(!J.trim())throw Error(Z);return J}function F9($){return(typeof $==="string"?$.trim():"")||void 0}var Q4="project Agent calls are non-interactive and have no question or answer interface; complete the supplied goal autonomously";function yE(){return["---",`name: ${DP}`,`description: ${JSON.stringify("Lodestar Agent calls: Agents use their inherited managed context; independent services and applications bind calls to a project. Main Agents, delegated Agents and native subagents may delegate further. Resume native session IDs only within the same project and group.")}`,"---","","# lodestar-agent","","Use Lodestar to call the Agent represented by a selected live identity.","Each identity resolves to its configured Token Source, provider Agent backend,","model, and effort. The caller-supplied prompt becomes that Agent run's task.","","## 调用归属(强制)","","| 调用场景 | 必须使用的绑定 |","| --- | --- |","| 主 Agent、委派 Agent 或原生子 Agent 需要调用另一个 Agent / 模型 | 使用继承的受管上下文:普通 `lodestar-agent` 命令,不传 `--project` |","| 独立服务、定时任务或其他软件直接调用 | 绑定项目:每个命令都显式传 `--project <项目名>` |","","- Agent 通过 Shell、Python、脚本或 HTTP 发起的调用仍然属于 Agent 执行任务,必须沿用受管上下文及其项目、群归属。","- 不得把当前任务中的调用包装成“外部服务”,不得清除会话环境变量、复制项目凭据或使用 `--project` 脱离会话生命周期。","- 没有有效会话上下文时,Agent 调用必须报错;项目入口不是会话凭据缺失、过期或失败时的替代路径。","- 独立服务和软件不借用任何主 Agent 的会话凭据,统一使用项目入口。项目任务有自己的卡片和取消入口,不依赖主会话存活。","- 项目入口不提供提问或回答接口:新建和续跑均须自主执行必要步骤并验证,直至完整完成调用方目标,不以计划、部分工作或索取输入结束;`answer` 供会话归属的各层委派使用。","","## 会话 ID 与恢复范围(强制)","","- `session_id`(JSON 的 `workers[].session_id`)是原生会话的唯一 ID,续跑保持不变。","- `run_id` 只标识某一次调用记录,不是另一个会话 ID;不要为绑定方式或续跑创建第二套会话标识。","- 会话始终归属项目和群。同一项目、同一群内的会话 ID 可以互相恢复,包括会话绑定和项目绑定产生的会话。","- 禁止跨项目或跨群恢复。项目按登记的规范工作目录识别,执行子目录不改变项目归属;群必须是同一个 chat_id。","- 无法确认项目和群归属的 ID 必须报错,不能因传入 `--project`、`--identity` 或某个目录就认定它属于当前项目。","- `--workdir` 可以调整到本项目内的现有目录;`--identity` 可以选择原后端下的其他模型或来源。原生会话不能更换所属后端。","- 恢复本轮的绑定由调用场景决定,旧调用记录不迁移;切换绑定方式不建立相互取消关系。","- 同一个原生会话不能同时执行两轮,恢复失败必须显示,不得自动新建会话。","","## Delegation","","- Main Agents, delegated Agents and native subagents may delegate further.","- Lodestar does not impose a delegation depth limit or disable native delegation tools.","- `LODESTAR_AGENT_ROLE=worker` identifies a delegated process, not a prohibition on delegation.","- Nested calls inherit the project, group, interaction policy and caller-owned file delivery."," Lodestar records their ancestry so cancellation reaches descendant tasks.","- Complete and verify delegated work as part of the overall assigned task.","","## Choosing a delegation method","","- Each Agent chooses between native Agent/subagent capabilities and"," `lodestar-agent` based on the task and available capabilities.","- Both methods are allowed when calling your own model or Agent.","- The Agent workflow below always uses the inherited managed context. `--project` is reserved"," for genuinely independent service/application clients, not Agent task execution.","","## Required workflow","","1. When using Lodestar, query the live identity catalog immediately before"," every new task:","","```bash","# desc: 查询当前可用的 Agent 身份","lodestar-agent identities --json","```","",'2. Select only identities with `status: "ready"`. Never invent, cache,'," substitute, or silently downgrade an identity/model/effort.","3. Give the child the complete task, relevant context, authority boundaries,"," expected deliverable, and verification requirements in the raw prompt."," Every run and follow-up also requires `--description`: a short, user-facing"," single-line task summary (at most 60 characters). The card shows this line"," with status; the full prompt, progress and results stay collapsed.","4. For the same prompt sent to several identities, pass them to one run"," with repeated `--identity`; the daemon starts them concurrently without local"," concurrency or task-count limits. Upstream API limits still apply: report"," rate-limit errors and do not immediately retry the whole batch.","5. Wait for the result. Attribute each result to its actual model and surface"," failures. Child file changes are live in the same workspace.","6. When the same work needs another step, review the returned content and"," continue with `run --session <session-id>` plus the new input. Use as many"," turns as the authorized task needs; assess completion against the overall"," task and its verification requirements, not just one run ending.","","## Run a task","","```bash","# desc: 把完整任务交给指定 Agent","lodestar-agent run --identity '<identity-id>' --description '完成指定任务' --stdin <<'EOF'","<raw task prompt written by the main Agent>","EOF","```","","### Working directory","","First-level tasks default to the main Agent working directory; nested tasks reuse the calling Agent directory, even if the calling","shell has changed directory. Use `--workdir <path>` to select an existing","subdirectory. Relative paths are resolved from the main Agent directory;","absolute paths are also accepted within that directory. Symlinks are resolved","and paths outside the main directory, missing paths and files are rejected.","All identities in one run use the same directory; use separate runs for different directories.","","```bash","# desc: 在主 Agent 工作目录的子目录中执行任务","lodestar-agent run --identity '<identity-id>' --description '检查应用代码' --workdir 'packages/app' --prompt 'Inspect the application and report the results.'","```","","`run --session` and `follow-up` may select an existing directory within the same project.","Without `--workdir`, reuse the recorded execution directory. A different project","directory or unknown session ownership is an error. Results report `Work directory:`","(JSON: `work_dir`). The HTTP API accepts `work_dir` on run/follow-up requests.","","## Complete one work item across multiple turns","","A single work item can span multiple turns in the same native Agent session.","Use this for staged implementation, revisions based on feedback, or further","verification of previous results. The main Agent reads each result and sends","the next step. A delegated Agent may also manage further delegated work.","","Keep the returned `Session:` id (JSON: `workers[].session_id`) together with","the worker output. For turn 2 and later, send that id and only the new input:","","```bash","# desc: 用历史会话 ID 继续下一轮","lodestar-agent run --session '<session-id>' --description '继续下一步任务' --stdin <<'EOF'","<new input for the next turn>","EOF","```","","This resumes the provider-native conversation. Recorded identity and effort","are reused when omitted. Explicit `--identity` may select another model/source in the same backend;","a changed identity uses its default effort unless `--effort` is given. The run returns a new","`run_id` and the same native `session_id`; repeat to continue further turns.","Only ids registered to the current project and group can be resumed. The original","invocation may have been session-bound or project-bound; unknown ownership is rejected.","The new run belongs to the current caller; previous ownership is not transferred.","Changing binding mode within the project does not join cancellation trees. Backend resume failures","remain errors. Wait for that worker to exit; other workers in its run need not finish.","Concurrent turns on the same provider/native session are rejected.","","Use `--json` with `run`, `follow-up` or `status` for structured results:","`workers[].session_id` is the conversation id and `workers[].output` is the","returned content. `--prompt <text>` supplies inline input instead of stdin.","A parallel run returns one session id per worker; continue each separately.","","For example, after turn 1 implements the requested change using the run form","above, continue the same work with feedback and then verification:","","```bash","# desc: 第二轮根据上一轮结果和反馈继续修改","lodestar-agent run --session '<session-id>' --description '根据反馈修改' --prompt 'Revise the previous implementation using this feedback: <specific feedback>.' --json","```","","Read turn 2's result before choosing turn 3's input, using the same session id:","","```bash","# desc: 第三轮验证同一项工作的最终结果","lodestar-agent run --session '<session-id>' --description '验证最终结果' --prompt 'Verify the revised implementation against the original requirements and report the results and any remaining issues.' --json","```","","These turns retain the earlier conversation; send only the new requirements,","feedback or next step. Omitting `--session` starts a fresh conversation.","Empty ids, unknown project/group ownership, and cross-project/group ids are rejected.","The original backend then determines whether the native conversation can be resumed;","failures are reported and never converted into a fresh session.","","If you kept the `run_id`, the existing follow-up form also resumes its worker:","","```bash","# desc: 在同一原生 Agent 会话中继续任务","lodestar-agent follow-up '<run-id>' --identity '<identity-id>' --description '完成指定任务' --stdin <<'EOF'","<follow-up prompt>","EOF","```","","## Answer a child question","","Only session-bound delegation can return `Status: needs_input`; project-bound service calls never ask for input and do not support `answer`.","When a session-bound run returns `Status: needs_input`, answer the exact request id. JSON","keys may be the question id or the full question text:","","```bash","# desc: 回答 Agent 的阻塞问题并继续运行","lodestar-agent answer '<run-id>' --identity '<identity-id>' --request '<request-id>' --stdin <<'EOF'",'{"question-id":"answer"}',"EOF","```","","## Boundaries","","- Do not invoke provider CLIs or provider HTTP APIs directly for delegation.","- Never expose `LODESTAR_AGENT_CAPABILITY` in prompts, output, logs, or args.","- Never read or copy daemon project-client credentials to bypass delegation restrictions.","- A non-zero command exit is a real failure. Do not claim the child succeeded.","- Scope the Agent task and authorized actions to the user request.","- Both session-bound and project-bound Agents return results and local artifact paths to the caller.","- The caller owns file delivery. Agent output markers do not upload files or grant sharing permissions.",""].join(`
627
- `)}function AP(){j5("lodestar-consult"),B5({name:DP,body:yE()})}var DP="lodestar-agent",FP,MP,UP,OP;var cV=R(()=>{_5();FP=["You may delegate work through Lodestar or provider-native Agent/subagent tools, including from a delegated task.","Use the inherited Lodestar context for nested calls and preserve the task project, group, interaction policy, and caller-owned file delivery.","Complete and verify the overall task, including any delegated work, before returning the final result.","This policy replaces earlier Lodestar instructions prohibiting further delegation, including in resumed conversations."],MP=["Return task results and local artifact paths to the caller; the caller is responsible for delivering files to the user.","Do not emit file-delivery markers or upload, share, or send generated files to Feishu.","These rules replace any earlier Lodestar file-delivery instructions, including those in a resumed conversation."],UP=["You are a delegated Agent working on a task assigned by the main Agent.",...FP,"If clarification is necessary, you may use question tools to ask the main Agent. This session-bound interaction policy replaces any non-interactive project-call policy from earlier turns.",...MP].join(`
628
- `),OP=["You are executing a project task for the calling service or application through Lodestar.","This is a non-interactive execution entry point with no question or answer interface. The caller is traditional software; nobody is available to answer questions.","Do not ask the user or caller questions, request clarification or confirmation, or wait for input. Do not use question tools or other channels to solicit a reply.","The supplied goal is your completion requirement. Execute every necessary step and verify the result; keep working until the entire goal is achieved within the authorized scope. A plan, partial work, or a request for another turn is not completion.","Resolve missing context by inspecting the available project, files, tools, and task inputs. Make routine implementation decisions yourself. Do not stop merely because you would prefer clarification or more instructions.","Only when a concrete blocker prevents further authorized progress, return an explicit failure reason with evidence of the blocker and the work already performed. Never invent missing facts or claim an incomplete goal is complete.","These non-interactive rules apply to this invocation and replace earlier instructions to ask questions, including instructions in a resumed conversation.",...FP,"Manage any delegated work yourself; do not return requests for the caller to arrange additional Agent work.",...MP].join(`
625
+ `}function HP(){B5({name:zP,body:vE(g.notify.port)})}var zP="feishu-notify";var GP=R(()=>{k0();_5()});import{randomUUID as yE}from"node:crypto";function WP($){let Z=(V)=>V instanceof Error?V.message:String(V),J=(V,X,z)=>{if(!V)return"通知已过期或已移除";if(!z)return"无法识别回复人,操作未执行";if(X&&X!==V.chatId)return"通知不属于当前群,操作未执行";if(!V.allowReply)return"此通知未开启文字回复";if(V.unknownAt)return`回复送达状态未知,禁止自动重试:${V.unknownReason}`;if(V.resolvedAt)return"此通知已处理";if(K9(V.notifyId))return"通知正在处理中";return null},Q=async(V,X)=>{$.log(`notify-reply: ${X}`);let z;if(!await $.sendText(V,`❌ ${X}`,(H)=>{z=H}))throw Error(`通知回复错误提示发送失败: ${w(z)};原错误:${X}`)},Y=async(V,X,z,H)=>{try{await $.updateCard(X,z)}catch(G){await Q(V.chatId,`${H},卡片更新失败:${w(G)}`)}};return{async recover(V){if(V.dispatchState&&V.unknownAt){let H=V.dispatchState,G=V.buttons.find((W)=>W.id===H.buttonId);await Y(V,V.messageId,Q2(V,{status:"unknown",buttonId:H.buttonId,text:G?.text??H.buttonId,operatorOpenId:H.openId,detail:V.unknownReason}),"按钮回调送达状态未知");return}let X=V.replyState;if(!X||!V.unknownAt)return;let z={kind:"text",status:"unknown",text:X.response?.text??"",operatorOpenId:X.openId,detail:V.unknownReason};await Y(V,X.promptMessageId,J2(V,X,z),"回复送达状态未知"),await Y(V,V.messageId,Q2(V,z),"回复送达状态未知")},async open(V,X,z){let H=R1(V),G=J(H,X,z);if(G||!H)return{ok:!1,message:G};if(H.replyState?.status==="waiting"||H.replyState?.status==="sending")return{ok:!1,message:"此通知正在等待回复,请先在群里输入或由回复人取消"};let W=HV(H.chatId);if(W.some((K)=>K.replyState?.status==="sending"||K9(K.notifyId)))return{ok:!1,message:"上一条通知回复正在发送,请稍后切换"};t8(V);try{for(let P of W){let L={...P.replyState,status:"cancelled",cancelReason:"switched"};B9(P.notifyId,L),await Y(P,L.promptMessageId,J2(P,L),"已放弃上一条回复并切换通知")}let K={id:yE(),openId:z,promptMessageId:"",openedAt:Date.now(),status:"waiting"},B,_=await $.sendCard(H.chatId,J2(H,K),(P)=>{B=P});if(!_)return{ok:!1,message:`等待输入卡片发送失败,未开始接收回复,请重新点击「回复」
626
+ ${w(B)}`};K.promptMessageId=_;try{B9(V,K)}catch(P){let L=`等待输入状态保存失败,未开始接收回复:${Z(P)}`;return await Y(H,_,J2(H,K,{status:"failed",detail:L}),L),{ok:!1,message:L,presented:!0}}return{ok:!0,message:"等待输入卡片已发送,请在群里回复一条文字",presented:!0}}finally{r8(V),$.onWaitingChanged(H.chatId)}},async cancel(V,X,z,H){let G=R1(V),W=J(G,z,H);if(W||!G)return{ok:!1,message:W};let K=G.replyState;if(!K||K.id!==X||K.status!=="waiting")return{ok:!1,message:"此回复已结束或正在发送,无法取消"};if(K.openId!==H)return{ok:!1,message:"仅点击「回复」的人可以取消"};let B={...K,status:"cancelled"};return B9(V,B),$.onWaitingChanged(G.chatId),await Y(G,K.promptMessageId,J2(G,B),"回复已取消"),{ok:!0,message:"已取消回复",presented:!0}},async consume(V){let{chatId:X,openId:z,messageId:H,text:G,createTime:W}=V;if(!z||!H||!G.trim())return!1;if(Mj(X,H))return!0;let K=e8(X,z);if(!K?.replyState)return!1;let B=K.replyState;if(W>0&&W<B.openedAt)return!1;if(B.status!=="waiting"||K9(K.notifyId))return await Q(X,"上一条通知回复正在发送,这条文字未提交,请稍后重发"),!0;let _={text:G,message_id:H,prompt_message_id:B.promptMessageId},P={...B,status:"sending",response:_};t8(K.notifyId);try{try{B9(K.notifyId,P)}catch(M){return await Q(X,`回复保存失败,尚未回传,请重新输入:${Z(M)}`),!0}let L;try{try{await $.updateCard(B.promptMessageId,J2(K,P))}catch(M){throw Error(w(M))}if(K.callbackUrl)L=await $.dispatch(K,_,z);else $3(K.notifyId,void 0,z),L={ok:!0,detail:"已记录"}}catch(M){L={ok:!1,detail:Z(M)}}let q;if(L.ok){let M=K.callbackUrl?i6(K.notifyId,void 0,z):{state:"complete"};q={kind:"text",text:G,operatorOpenId:z,status:M.state==="unknown"?"unknown":K.callbackUrl?"delivered":"done",...M.state==="unknown"?{detail:M.detail}:{reply:L.reply}}}else{q={kind:"text",text:G,operatorOpenId:z,status:"failed",detail:L.detail};try{B9(K.notifyId,{...P,status:"failed",error:L.detail})}catch(M){let U=`${L.detail};失败状态保存失败:${Z(M)}`;try{d6(K.notifyId,void 0,z,U)}catch(A){$.log(`notify-reply: UNKNOWN persistence failed: ${Z(A)}`)}q={...q,status:"unknown",detail:U}}}let F=q.status==="delivered"?"回复已送达":q.status==="done"?"回复已记录":q.status==="unknown"?`回复送达状态未知:${q.detail}`:`回复未送达:${q.detail}`;return await Y(K,B.promptMessageId,J2(K,P,q),F),await Y(K,K.messageId,Q2(K,q),F),$.log(`notify-reply: notify_id=${K.notifyId} status=${q.status}`),!0}finally{r8(K.notifyId),$.onWaitingChanged(K.chatId)}}}}var KP=R(()=>{Z3();K5()});function BP($){let Z=pV($,"agent run request"),J=Array.isArray(Z.identity_ids)?Z.identity_ids.map(String):Array.isArray(Z.identityIds)?Z.identityIds.map(String):[],Q=[...new Set(J.map((G)=>G.trim()).filter(Boolean))],Y=Z.session_id!==void 0?Z.session_id:Z.sessionId,V=D9(Y);if(Y!==void 0&&!V)throw Error("agent session_id must be a non-empty string");if(Z.session_id!==void 0&&Z.sessionId!==void 0&&Z.session_id!==Z.sessionId)throw Error("conflicting agent session_id and sessionId");if(V&&Q.length>1)throw Error("agent session continuation accepts at most one identity_id");if(!V&&Q.length===0)throw Error("agent run requires at least one identity_id");let X=qP(Z.prompt,'agent run requires "prompt"'),z=D9(Z.effort),H=PP(Z);return{identityIds:Q,description:M9(Z.description),prompt:X,...z?{effort:z}:{},...V?{sessionId:V}:{},...H!==void 0?{workDir:H}:{},..._P(Z)}}function jP($){let Z=pV($,"agent follow-up request"),J=qP(Z.prompt,'agent follow-up requires "prompt"'),Q=D9(Z.identity_id??Z.identityId),Y=D9(Z.effort),V=PP(Z);return{description:M9(Z.description),prompt:J,...Q?{identityId:Q}:{},...Y?{effort:Y}:{},...V!==void 0?{workDir:V}:{},..._P(Z)}}function _P($){let Z={};for(let[J,Q]of[["request_id","requestId"],["requester_open_id","requesterOpenId"]]){if($[J]===void 0)continue;let Y=$[J];if(typeof Y!=="string"||!Y.trim()||Y.length>200||/[\x00-\x1f]/.test(Y))throw Error(`invalid ${J}`);Z[Q]=Y.trim()}return Z}function L$($){return $.owner??{kind:"session",name:$.sessionName,chatId:$.chatId,workDir:$.sessionWorkDir??$.workDir}}function Y4($){return JSON.stringify([$.kind,$.name,$.chatId,$.workDir])}function P5($){if(typeof $!=="string"||!$.trim()||$.includes("\x00"))throw Error("agent work_dir must be a non-empty path without null bytes");return $}function PP($){if($.work_dir!==void 0&&$.workDir!==void 0&&$.work_dir!==$.workDir)throw Error("conflicting agent work_dir and workDir");let Z=$.work_dir!==void 0?$.work_dir:$.workDir;return Z===void 0?void 0:P5(Z)}function M9($){if(typeof $!=="string"||!$.trim())throw Error('agent run requires "description" (CLI: --description)');let Z=$.trim();if(/[\r\n\u2028\u2029]/.test(Z))throw Error("agent description must be a single line");if([...Z].length>60)throw Error("agent description exceeds 60 characters");return Z}function LP($){let Z=pV($,"agent answer request"),J=D9(Z.identity_id??Z.identityId),Q=D9(Z.request_id??Z.requestId);if(!Q)throw Error("agent answer requires request_id");if(!Z.answers||typeof Z.answers!=="object"||Array.isArray(Z.answers))throw Error("agent answer requires an answers object");let Y={};for(let[V,X]of Object.entries(Z.answers)){if(!V.trim())throw Error("agent answer contains an empty question key");Y[V]=String(X)}if(Object.keys(Y).length===0)throw Error("agent answer requires at least one answer");return{requestId:Q,answers:Y,...J?{identityId:J}:{}}}function pV($,Z){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${Z} must be an object`);return $}function qP($,Z){let J=String($??"");if(!J.trim())throw Error(Z);return J}function D9($){return(typeof $==="string"?$.trim():"")||void 0}var Q4="project Agent calls are non-interactive and have no question or answer interface; complete the supplied goal autonomously";function fE(){return["---",`name: ${FP}`,`description: ${JSON.stringify("Lodestar Agent calls: Agents use their inherited managed context; independent services and applications bind calls to a project. Main Agents, delegated Agents and native subagents may delegate further. Resume native session IDs only within the same project and group.")}`,"---","","# lodestar-agent","","Use Lodestar to call the Agent represented by a selected live identity.","Each identity resolves to its configured Token Source, provider Agent backend,","model, and effort. The caller-supplied prompt becomes that Agent run's task.","","## 调用归属(强制)","","| 调用场景 | 必须使用的绑定 |","| --- | --- |","| 主 Agent、委派 Agent 或原生子 Agent 需要调用另一个 Agent / 模型 | 使用继承的受管上下文:普通 `lodestar-agent` 命令,不传 `--project` |","| 独立服务、定时任务或其他软件直接调用 | 绑定项目:每个命令都显式传 `--project <项目名>` |","","- Agent 通过 Shell、Python、脚本或 HTTP 发起的调用仍然属于 Agent 执行任务,必须沿用受管上下文及其项目、群归属。","- 不得把当前任务中的调用包装成“外部服务”,不得清除会话环境变量、复制项目凭据或使用 `--project` 脱离会话生命周期。","- 没有有效会话上下文时,Agent 调用必须报错;项目入口不是会话凭据缺失、过期或失败时的替代路径。","- 独立服务和软件不借用任何主 Agent 的会话凭据,统一使用项目入口。项目任务有自己的卡片和取消入口,不依赖主会话存活。","- 项目入口不提供提问或回答接口:新建和续跑均须自主执行必要步骤并验证,直至完整完成调用方目标,不以计划、部分工作或索取输入结束;`answer` 供会话归属的各层委派使用。","","## 会话 ID 与恢复范围(强制)","","- `session_id`(JSON 的 `workers[].session_id`)是原生会话的唯一 ID,续跑保持不变。","- `run_id` 只标识某一次调用记录,不是另一个会话 ID;不要为绑定方式或续跑创建第二套会话标识。","- 会话始终归属项目和群。同一项目、同一群内的会话 ID 可以互相恢复,包括会话绑定和项目绑定产生的会话。","- 禁止跨项目或跨群恢复。项目按登记的规范工作目录识别,执行子目录不改变项目归属;群必须是同一个 chat_id。","- 无法确认项目和群归属的 ID 必须报错,不能因传入 `--project`、`--identity` 或某个目录就认定它属于当前项目。","- `--workdir` 可以调整到本项目内的现有目录;`--identity` 可以选择原后端下的其他模型或来源。原生会话不能更换所属后端。","- 恢复本轮的绑定由调用场景决定,旧调用记录不迁移;切换绑定方式不建立相互取消关系。","- 同一个原生会话不能同时执行两轮,恢复失败必须显示,不得自动新建会话。","","## Delegation","","- Main Agents, delegated Agents and native subagents may delegate further.","- Lodestar does not impose a delegation depth limit or disable native delegation tools.","- `LODESTAR_AGENT_ROLE=worker` identifies a delegated process, not a prohibition on delegation.","- Nested calls inherit the project, group, interaction policy and caller-owned file delivery."," Lodestar records their ancestry so cancellation reaches descendant tasks.","- Complete and verify delegated work as part of the overall assigned task.","","## Choosing a delegation method","","- Each Agent chooses between native Agent/subagent capabilities and"," `lodestar-agent` based on the task and available capabilities.","- Both methods are allowed when calling your own model or Agent.","- The Agent workflow below always uses the inherited managed context. `--project` is reserved"," for genuinely independent service/application clients, not Agent task execution.","","## Required workflow","","1. When using Lodestar, query the live identity catalog immediately before"," every new task:","","```bash","# desc: 查询当前可用的 Agent 身份","lodestar-agent identities --json","```","",'2. Select only identities with `status: "ready"`. Never invent, cache,'," substitute, or silently downgrade an identity/model/effort.","3. Give the child the complete task, relevant context, authority boundaries,"," expected deliverable, and verification requirements in the raw prompt."," Every run and follow-up also requires `--description`: a short, user-facing"," single-line task summary (at most 60 characters). The card shows this line"," with status; the full prompt, progress and results stay collapsed.","4. For the same prompt sent to several identities, pass them to one run"," with repeated `--identity`; the daemon starts them concurrently without local"," concurrency or task-count limits. Upstream API limits still apply: report"," rate-limit errors and do not immediately retry the whole batch.","5. Wait for the result. Attribute each result to its actual model and surface"," failures. Child file changes are live in the same workspace.","6. When the same work needs another step, review the returned content and"," continue with `run --session <session-id>` plus the new input. Use as many"," turns as the authorized task needs; assess completion against the overall"," task and its verification requirements, not just one run ending.","","## Run a task","","```bash","# desc: 把完整任务交给指定 Agent","lodestar-agent run --identity '<identity-id>' --description '完成指定任务' --stdin <<'EOF'","<raw task prompt written by the main Agent>","EOF","```","","### Working directory","","First-level tasks default to the main Agent working directory; nested tasks reuse the calling Agent directory, even if the calling","shell has changed directory. Use `--workdir <path>` to select an existing","subdirectory. Relative paths are resolved from the main Agent directory;","absolute paths are also accepted within that directory. Symlinks are resolved","and paths outside the main directory, missing paths and files are rejected.","All identities in one run use the same directory; use separate runs for different directories.","","```bash","# desc: 在主 Agent 工作目录的子目录中执行任务","lodestar-agent run --identity '<identity-id>' --description '检查应用代码' --workdir 'packages/app' --prompt 'Inspect the application and report the results.'","```","","`run --session` and `follow-up` may select an existing directory within the same project.","Without `--workdir`, reuse the recorded execution directory. A different project","directory or unknown session ownership is an error. Results report `Work directory:`","(JSON: `work_dir`). The HTTP API accepts `work_dir` on run/follow-up requests.","","## Complete one work item across multiple turns","","A single work item can span multiple turns in the same native Agent session.","Use this for staged implementation, revisions based on feedback, or further","verification of previous results. The main Agent reads each result and sends","the next step. A delegated Agent may also manage further delegated work.","","Keep the returned `Session:` id (JSON: `workers[].session_id`) together with","the worker output. For turn 2 and later, send that id and only the new input:","","```bash","# desc: 用历史会话 ID 继续下一轮","lodestar-agent run --session '<session-id>' --description '继续下一步任务' --stdin <<'EOF'","<new input for the next turn>","EOF","```","","This resumes the provider-native conversation. Recorded identity and effort","are reused when omitted. Explicit `--identity` may select another model/source in the same backend;","a changed identity uses its default effort unless `--effort` is given. The run returns a new","`run_id` and the same native `session_id`; repeat to continue further turns.","Only ids registered to the current project and group can be resumed. The original","invocation may have been session-bound or project-bound; unknown ownership is rejected.","The new run belongs to the current caller; previous ownership is not transferred.","Changing binding mode within the project does not join cancellation trees. Backend resume failures","remain errors. Wait for that worker to exit; other workers in its run need not finish.","Concurrent turns on the same provider/native session are rejected.","","Use `--json` with `run`, `follow-up` or `status` for structured results:","`workers[].session_id` is the conversation id and `workers[].output` is the","returned content. `--prompt <text>` supplies inline input instead of stdin.","A parallel run returns one session id per worker; continue each separately.","","For example, after turn 1 implements the requested change using the run form","above, continue the same work with feedback and then verification:","","```bash","# desc: 第二轮根据上一轮结果和反馈继续修改","lodestar-agent run --session '<session-id>' --description '根据反馈修改' --prompt 'Revise the previous implementation using this feedback: <specific feedback>.' --json","```","","Read turn 2's result before choosing turn 3's input, using the same session id:","","```bash","# desc: 第三轮验证同一项工作的最终结果","lodestar-agent run --session '<session-id>' --description '验证最终结果' --prompt 'Verify the revised implementation against the original requirements and report the results and any remaining issues.' --json","```","","These turns retain the earlier conversation; send only the new requirements,","feedback or next step. Omitting `--session` starts a fresh conversation.","Empty ids, unknown project/group ownership, and cross-project/group ids are rejected.","The original backend then determines whether the native conversation can be resumed;","failures are reported and never converted into a fresh session.","","If you kept the `run_id`, the existing follow-up form also resumes its worker:","","```bash","# desc: 在同一原生 Agent 会话中继续任务","lodestar-agent follow-up '<run-id>' --identity '<identity-id>' --description '完成指定任务' --stdin <<'EOF'","<follow-up prompt>","EOF","```","","## Answer a child question","","Only session-bound delegation can return `Status: needs_input`; project-bound service calls never ask for input and do not support `answer`.","When a session-bound run returns `Status: needs_input`, answer the exact request id. JSON","keys may be the question id or the full question text:","","```bash","# desc: 回答 Agent 的阻塞问题并继续运行","lodestar-agent answer '<run-id>' --identity '<identity-id>' --request '<request-id>' --stdin <<'EOF'",'{"question-id":"answer"}',"EOF","```","","## Boundaries","","- Do not invoke provider CLIs or provider HTTP APIs directly for delegation.","- Never expose `LODESTAR_AGENT_CAPABILITY` in prompts, output, logs, or args.","- Never read or copy daemon project-client credentials to bypass delegation restrictions.","- A non-zero command exit is a real failure. Do not claim the child succeeded.","- Scope the Agent task and authorized actions to the user request.","- Both session-bound and project-bound Agents return results and local artifact paths to the caller.","- The caller owns file delivery. Agent output markers do not upload files or grant sharing permissions.",""].join(`
627
+ `)}function AP(){j5("lodestar-consult"),B5({name:FP,body:fE()})}var FP="lodestar-agent",DP,MP,UP,OP;var cV=R(()=>{_5();DP=["You may delegate work through Lodestar or provider-native Agent/subagent tools, including from a delegated task.","Use the inherited Lodestar context for nested calls and preserve the task project, group, interaction policy, and caller-owned file delivery.","Complete and verify the overall task, including any delegated work, before returning the final result.","This policy replaces earlier Lodestar instructions prohibiting further delegation, including in resumed conversations."],MP=["Return task results and local artifact paths to the caller; the caller is responsible for delivering files to the user.","Do not emit file-delivery markers or upload, share, or send generated files to Feishu.","These rules replace any earlier Lodestar file-delivery instructions, including those in a resumed conversation."],UP=["You are a delegated Agent working on a task assigned by the main Agent.",...DP,"If clarification is necessary, you may use question tools to ask the main Agent. This session-bound interaction policy replaces any non-interactive project-call policy from earlier turns.",...MP].join(`
628
+ `),OP=["You are executing a project task for the calling service or application through Lodestar.","This is a non-interactive execution entry point with no question or answer interface. The caller is traditional software; nobody is available to answer questions.","Do not ask the user or caller questions, request clarification or confirmation, or wait for input. Do not use question tools or other channels to solicit a reply.","The supplied goal is your completion requirement. Execute every necessary step and verify the result; keep working until the entire goal is achieved within the authorized scope. A plan, partial work, or a request for another turn is not completion.","Resolve missing context by inspecting the available project, files, tools, and task inputs. Make routine implementation decisions yourself. Do not stop merely because you would prefer clarification or more instructions.","Only when a concrete blocker prevents further authorized progress, return an explicit failure reason with evidence of the blocker and the work already performed. Never invent missing facts or claim an incomplete goal is complete.","These non-interactive rules apply to this invocation and replace earlier instructions to ask questions, including instructions in a resumed conversation.",...DP,"Manage any delegated work yourself; do not return requests for the caller to arrange additional Agent work.",...MP].join(`
629
629
  `)});function TP($){let Z=j0($.identity.tokenSourceId,$.codexAccountId);if(!Z)throw Error(`agent token source not found: ${$.identity.tokenSourceId}`);if($.identity.spawnRevision&&Z.spawnRevision!==$.identity.spawnRevision)throw Error(`agent token source changed after identity discovery: ${Z.id}`);if(!$.identity.supportedEfforts.includes($.effort))throw Error(`${$.identity.displayName} does not support effort ${$.effort}`);let J=$.resumeSessionId?{kind:"resume",source:{provider:$.identity.provider,sessionId:$.resumeSessionId,cwd:$.workDir}}:{kind:"fresh"},{process:Q}=k8({provider:$.identity.provider,workDir:$.workDir,tokenSourceId:$.identity.tokenSourceId,codexAccountId:$.codexAccountId,...$.identity.provider==="codex"&&$.identity.tokenSourceId==="codex-sub"?{codexAccountPreference:null}:{},model:$.identity.model,effort:$.effort,launch:J,developerInstructions:[$.developerInstructions,$.projectBound?OP:UP].filter(Boolean).join(`
630
630
 
631
- `),allowUserInput:!$.projectBound,profile:$.profile,managedSkillPluginPath:$.managedSkillPluginPath,hostEnv:{...$.hostEnv,LODESTAR_AGENT_ROLE:"worker"},serviceName:"lodestar-agent"});return hE(Q,$.prompt,$.callbacks,void 0,$.resumeSessionId,!$.projectBound,$.description?{description:$.description,prompt:$.prompt}:void 0)}function hE($,Z,J={},Q=bz,Y,V=!0,X){let z=[],H=[],G=v$($),W=G,K=null,B=!1,_=null,P=null,L=new AbortController,q=[],D,M,U=Date.now(),A=new Promise((x,u)=>{D=x,M=u}),O=(x)=>{if(!x)return null;try{if(!Y||x!==Y)Q($.provider,x);if(Y&&x!==Y)throw Error(`native resume returned session ${x}, expected ${Y}; refusing to treat it as a resumed conversation`);return J.onSession?.(x),null}catch(u){return u instanceof Error?u:Error(String(u))}},N=()=>{if($.off("assistant_text",T),$.off("tool_use",m),$.off("tool_result",b),$.off("subagent_step",p),$.off("can_use_tool",c),$.off("hook_callback",J0),$.off("init",l),!$.isAlive())$.off("error",f);$.off("turn_retry",t),$.off("codex_account_changed",Q0),$.off("result",K0),$.off("exit",p$)},S=(x,u)=>{if(_)return _;return B=!0,L.abort(Error("delegated agent turn ended")),q.length=0,_=Promise.resolve().then(async()=>{let J$=O($.sessionId);try{await $.kill(3000)}catch(b$){P=b$ instanceof Error?b$:Error(String(b$))}N();let B0=[x,J$,P].filter((b$)=>!!b$),G3=B0.length>1?AggregateError(B0,B0.map((b$)=>b$.message).join("; ")):B0[0];if(G3){M(new H3(G3,z.join("").trim(),$.sessionId,W?H.join("").trim():void 0,u?.displayError===void 0?void 0:[u.displayError,...B0.filter((b$)=>b$!==x).map((b$)=>b$.message)].join("; ")));return}let ZX=$.sessionId;if(!ZX){M(new H3(Error("delegated agent completed without a native session id"),z.join("").trim(),null,W?H.join("").trim():void 0));return}let ML=z.join("").trim(),JX=gE(u?.checkpoint,$);D({output:ML,...W?{displayOutput:H.join("").trim()}:{},outputTruncated:!1,sessionId:ZX,...JX?{checkpointId:JX}:{},durationMs:Date.now()-U,usage:$.lastUsage?{...$.lastUsage}:null})}),_},T=(x)=>{if(B||x?.parentToolUseId||typeof x?.text!=="string")return;if(z.push(x.text),G&&typeof x.displayText!=="string"){S(Error("Claude subscription delegated output is missing verified translation"));return}W||=typeof x.displayText==="string",H.push(x.displayText??x.text)},y=(x)=>{if(B)return;try{J.onProgress?.(x)}catch(u){S(u instanceof Error?u:Error(String(u)))}},m=(x)=>y({at:new Date().toISOString(),phase:"started",tool:String(x?.name??"tool"),detail:x.displayInput?NP(x.input):"",...x.displayInput?{displayDetail:NP(x.displayInput)}:{}}),b=(x)=>y({at:new Date().toISOString(),phase:"completed",tool:x?.is_error?"tool error":"tool result",detail:""}),p=(x)=>y({at:new Date().toISOString(),phase:x?.phase??"info",tool:String(x?.tool??"subagent"),detail:""}),c=(x)=>{if(B)return;if(x.tool_name!=="AskUserQuestion"){try{$.sendPermissionResponse(x.request_id,"allow",{updatedInput:x.input??{}})}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)))}return}let u,J$;try{if(u=RP({...x,input:x.originalInput??x.input}),x.originalInput){if(J$=RP(x),J$.questions.length!==u.questions.length)throw Error("translated question count does not match native questions");J$.questions=J$.questions.map((B0,G3)=>({...B0,id:u.questions[G3].id}))}else if(G)throw Error("Claude subscription delegated question is missing verified translation");if(!V)throw Error(`${Q4}: ${u.questions.map((B0)=>B0.question).join("; ")}`)}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)));return}if(q.some((B0)=>B0.request.requestId===u.requestId))return;q.push({request:u,displayRequest:J$,originalInput:x.originalInput??x.input??{}});try{if(q.length===1)J.onNeedsInput?.(u,J$)}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)))}},J0=(x)=>{if(B)return;try{$.sendHookResponse(String(x.request_id),{})}catch(u){S(u instanceof Error?u:Error(String(u)))}},l=(x)=>{let u=O(x?.session_id??$.sessionId);if(u)S(u)},f=(x)=>{K=x instanceof Error?x:Error(String(x))},Q0=(x)=>{if(B)return;try{J.onCodexAccount?.(x.accountId)}catch(u){S(u instanceof Error?u:Error(String(u)))}if(x.diagnostics.length)j(`agent-runner: selected Codex account=${x.accountId}; diagnostics: ${x.diagnostics.join(";")}`)},t=(x)=>{let u=x.reason==="quota"?"Codex 额度换号":x.reason==="stream_disconnected"?"Codex 连接中断重试":x.reason==="compact_connection_failed"?"Codex 压缩连接中断重试":x.reason==="transient_error"?"Codex 临时故障重试":"Codex 容量重试";y({at:new Date().toISOString(),phase:"info",tool:u,detail:x.phase==="waiting"?`${x.message} · ${x.delayMs/1000}s 后重试 #${x.attempt}`:`正在重试 #${x.attempt}`})},K0=(x)=>{let u=x?.is_error?Error(String(x.error??x.subtype??$.lastResult.subtype??"delegated agent failed")):void 0;S(u,x)},p$=(x)=>{if(B)return;let u=`code=${x?.code??"null"} signal=${x?.signal??"null"}`;S(K??Error(`delegated agent exited before result (${u})`))};if($.on("assistant_text",T),$.on("tool_use",m),$.on("tool_result",b),$.on("subagent_step",p),$.on("can_use_tool",c),$.on("hook_callback",J0),$.on("init",l),$.on("error",f),$.on("turn_retry",t),$.on("codex_account_changed",Q0),$.on("result",K0),$.on("exit",p$),G)$.setTranslationPresentationPolicy?.((x)=>{if(B)return"hidden";if(x.kind==="assistant_text")return x.parentToolUseId?"hidden":"worker";if(x.kind==="tool_input")return"worker";return"hidden"});try{if($.sendInitialize(),G&&X)(async()=>{if(!$.translateDisplayFields)throw Error("Claude subscription delegated context translation is unavailable");if(await $.translateDisplayFields([X.description,X.prompt],L.signal,(x)=>{if(B||!J.onDisplayContext)return!1;if(x.length!==2||x.some((u)=>typeof u!=="string"))throw Error("Claude subscription delegated context translation returned invalid fields");if(J.onDisplayContext({description:x[0],prompt:x[1]})===!1)throw Error("Delegated task display was not accepted");return!B}),B)return;$.sendUserText(Z)})().catch((x)=>{if(!B)S(x instanceof Error?x:Error(String(x)))});else $.sendUserText(Z)}catch(x){S(x instanceof Error?x:Error(String(x)))}return{done:A,isAlive:()=>$.isAlive(),pendingInput:()=>q[0]?.request??null,displayPendingInput:()=>q[0]?.displayRequest??null,answer(x,u){let J$=q[0];if(!J$)throw Error("delegated agent is not waiting for input");if(J$.request.requestId!==x)throw Error(`delegated agent input request mismatch: expected ${J$.request.requestId}`);if($.sendPermissionResponse(x,"allow",{updatedInput:{...J$.originalInput,answers:u}}),q.shift(),q[0])J.onNeedsInput?.(q[0].request,q[0].displayRequest)},async cancel(x="delegated agent cancelled"){let u=B;if(await S(Error(x)),await A.catch(()=>{}),u){if($.isAlive())await $.kill(3000);P=null,N()}if(P)throw P}}}function NP($){if(!$)return"";if(typeof $.__displayDescription==="string")return $.__displayDescription;if(typeof $.description==="string")return $.description;let Z=$.command??$.cmd??$.script;if(typeof Z==="string")return B1(Z).description;if(typeof $.subject==="string")return $.subject;return""}function RP($){let Z=$.input??{},Q=(Array.isArray(Z.questions)?Z.questions:[Z]).map((Y,V)=>IE(Y,V));if(Q.length===0)throw Error("delegated agent input request contains no questions");return{requestId:String($.request_id),...$.tool_use_id?{toolUseId:$.tool_use_id}:{},questions:Q}}function IE($,Z){let J=$&&typeof $==="object"?$:{question:$},Q=String(J.question??J.prompt??J.title??"").trim();if(!Q)throw Error(`delegated agent input question ${Z+1} is empty`);let Y=String(J.id??Q),V=Array.isArray(J.options)?J.options.map((X)=>{if(typeof X==="string")return{label:X};let z=X&&typeof X==="object"?X:{};return{label:String(z.label??z.value??""),...z.description?{description:String(z.description)}:{}}}).filter((X)=>X.label):[];return{id:Y,...J.header?{header:String(J.header)}:{},question:Q,options:V}}function gE($,Z){if(typeof $?.id==="string"&&$.id)return $.id;if((Z.provider==="codex"||Z.provider==="dsh")&&typeof Z.lastCompletedTurnId==="string"&&Z.lastCompletedTurnId)return Z.lastCompletedTurnId;if(Z.provider==="claude"&&Z.lastAssistantUuid)return Z.lastAssistantUuid;return}var H3;var EP=R(()=>{P0();tQ();y9();X0();cV();I();A4();H3=class H3 extends Error{output;sessionId;displayOutput;displayError;constructor($,Z,J,Q,Y){super($.message,{cause:$});this.output=Z;this.sessionId=J;this.displayOutput=Q;this.displayError=Y;this.name="AgentWorkerFailure"}}});function q$($){if($.kind!=="session")return $.context;let Z=$.session;return{owner:{kind:"session",name:Z.sessionName,chatId:Z.chatId,workDir:Z.workDir},codexAccountId:Z.codexAccountId(),sessionInstructions:(J)=>Z.delegatedAgentDeveloperInstructions(J)}}import{createHash as SP,randomBytes as mE,randomUUID as pE}from"node:crypto";import{existsSync as cE,readdirSync as uE,readFileSync as vP,realpathSync as F5,statSync as lE}from"node:fs";import{isAbsolute as dE,join as M5,relative as iE,resolve as fP,sep as nE}from"node:path";class dV{deps;presentation;runs=new Map;capabilities=new Map;cancellationEpochBySession=new Map;startingNativeSessions=new Set;pendingRunCreations=new Set;requests=new Map;shuttingDown=!1;constructor($=aE){this.deps=$;this.presentation=new a8($),this.loadDurableRuns()}rootPrincipal($){return{kind:"session",session:$,depth:-1}}projectPrincipal($){if($.owner.kind!=="project")throw Error("project principal requires project ownership");return{kind:"project",context:$,depth:-1}}principalForCapability($){return this.capabilities.get($)??null}startRun($,Z){return this.withRequestId($,Z,"run",(J)=>this.startRunOnce($,Z,J))}async startRunOnce($,Z,J){if(this.assertAcceptingRuns(),M9(Z.description),Z.sessionId!==void 0){if(!Z.sessionId.trim())throw Error("agent session_id must be a non-empty string");if(Z.identityIds.length>1)throw Error("agent session continuation accepts at most one identity_id");let Y=this.findSessionHistory($,Z.sessionId),V=Z.identityIds[0]?this.requireIdentity($,Z.identityIds[0]):void 0;return this.resumeRun($,Z,J,Y,V)}let Q=q$($);return this.createRun(Q,Z,{...J,...this.delegationParent($),depth:$.depth+1,cancellationEpoch:this.currentCancellationEpoch(Q)})}followUp($,Z,J){return this.withRequestId($,J,`follow-up:${Z}`,(Q)=>this.followUpOnce($,Z,J,Q))}async followUpOnce($,Z,J,Q){this.assertAcceptingRuns(),M9(J.description);let Y=this.runs.get(Z);if(!Y)throw Error(`agent run not found: ${Z}`);this.assertResumeProject($,Y);let V=Y.snapshot.workers.length===1?Y.snapshot.workers[0]:kP(Y.snapshot,J.identityId);if(Y.handles.get(V.identityId)?.isAlive?.())throw Error("Agent process has not stopped; cannot start follow-up yet");if(!V.sessionId)throw Error(`${V.identityName} has no resumable native session id`);this.findSessionHistory($,V.sessionId);let X=J.identityId?this.requireIdentity($,J.identityId):void 0;return this.resumeRun($,{...J,identityIds:J.identityId?[J.identityId]:[],sessionId:V.sessionId},Q,{run:Y,worker:V},X)}requireIdentity($,Z){let J=this.deps.getCatalog(q$($).codexAccountId).identities.find((Q)=>Q.id===Z);if(!J)throw Error(`agent identity not found: ${Z}`);if(J.status!=="ready")throw Error(`${J.displayName}: ${J.reason??J.status}`);return J}async resumeRun($,Z,J,Q,Y){let V=q$($);this.assertResumeProject($,Q.run);let X=Y??this.requireIdentity($,Q.worker.identityId);if(X.provider!==Q.worker.provider)throw Error("native session belongs to a different Agent backend");let z=Y4(L$(Q.run.snapshot))===Y4(V.owner),H=Z.effort??(Q.worker.identityId===X.id?Q.worker.effort:void 0),G=Z.workDir??Q.run.snapshot.workDir,W=this.reserveNativeSession({provider:X.provider,sessionId:Z.sessionId});try{return await this.createRun(V,{identityIds:[X.id],description:Z.description,prompt:Z.prompt,effort:H,workDir:G,requesterOpenId:Z.requesterOpenId??(z?Q.run.snapshot.requesterOpenId:void 0)},{...J,...$.kind==="worker"?this.delegationParent($):z?{parentRunId:Q.run.snapshot.runId,parentKind:"follow_up"}:{},depth:$.depth+1,resumedFromRunId:Q.run.snapshot.runId,cancellationEpoch:this.currentCancellationEpoch(V),resumeSessionId:Z.sessionId})}finally{W()}}async answer($,Z,J){if(q$($).owner.kind==="project")throw Error(Q4);let Q=this.requireMutableDescendant($,Z),Y=kP(Q.snapshot,J.identityId);if(Y.status!=="needs_input"||!Y.pendingInput)throw Error(`${Y.identityName} is not waiting for input`);if(Y.pendingInput.requestId!==J.requestId)throw Error(`input request mismatch: expected ${Y.pendingInput.requestId}`);let V=Q.handles.get(Y.identityId);if(!V)throw Error("waiting agent process is no longer alive; start a follow-up run");V.answer(J.requestId,J.answers);let X=V.pendingInput();if(Y.status=X?"needs_input":"running",X)Y.pendingInput=X;else delete Y.pendingInput;let z=V.displayPendingInput?.();if(z)Y.displayPendingInput=z;else delete Y.displayPendingInput;return delete Y.queuedReason,this.refreshNonterminalStatus(Q),this.persist(Q),await this.updateWorkerCard(Q,Y),this.readSnapshot(Q)}getRun($,Z){return this.readSnapshot(this.requireAccessibleRun($,Z))}async cancelRun($,Z,J="agent run cancelled"){let Q=this.requireMutableDescendant($,Z);if(!this.treeHasActiveRun(Q))return!1;return await this.cancelTree(Q,J),!0}async cancelSessionRuns($,Z,J){this.bumpCancellationEpoch($,Z);let Q=[...this.runs.values()].filter((V)=>L$(V.snapshot).kind==="session"&&V.snapshot.sessionName===$&&V.snapshot.chatId===Z&&!V.snapshot.parentRunId&&this.treeHasActiveRun(V)),Y=await Promise.allSettled(Q.map((V)=>this.cancelTree(V,J)));uV(Y)}async cancelProjectRunFromCard($,Z,J,Q){let Y=this.runs.get($);if(!Y||L$(Y.snapshot).kind!=="project"||!Q||!J||Y.snapshot.chatId!==Z||Y.snapshot.cardMessageId!==J)throw Error("项目任务卡片无效或不属于当前群");return this.cancelRun(this.projectPrincipal({owner:L$(Y.snapshot)}),$,"用户通过项目任务卡取消")}async withRequestId($,Z,J,Q){if((Z.requestId||Z.requesterOpenId)&&$.kind!=="project")throw Error("request_id and requester_open_id require explicit project mode");if(!Z.requestId)return Q({});let Y=Y4(q$($).owner),V=JSON.stringify([Y,Z.requestId]),X=SP("sha256").update(JSON.stringify({operation:J,prompt:Z.prompt,description:Z.description,effort:Z.effort,workDir:Z.workDir,requesterOpenId:Z.requesterOpenId,identityIds:"identityIds"in Z?Z.identityIds:void 0,identityId:"identityId"in Z?Z.identityId:void 0,sessionId:"sessionId"in Z?Z.sessionId:void 0})).digest("hex"),z=[...this.runs.values()].find((W)=>W.snapshot.requestId===Z.requestId&&Y4(L$(W.snapshot))===Y);if(z){if(z.snapshot.requestHash!==X)throw Error("request_id was already used with different input");return this.readSnapshot(z)}let H=this.requests.get(V);if(H){if(H.hash!==X)throw Error("request_id is in use with different input");return H.promise}let G=Promise.resolve().then(()=>Q({requestId:Z.requestId,requestHash:X}));this.requests.set(V,{hash:X,promise:G});try{return await G}finally{this.requests.delete(V)}}async shutdown($){this.shuttingDown=!0;let Z=new Set([...this.runs.values()].map((X)=>`${X.snapshot.sessionName}\x00${X.snapshot.chatId}`));for(let X of Z){let[z,H]=X.split("\x00");this.bumpCancellationEpoch(z,H)}let J=[...this.runs.values()].filter((X)=>!X.snapshot.parentRunId&&this.treeHasActiveRun(X)),Q=await Promise.allSettled([...J.map((X)=>this.cancelTree(X,$)),...[...this.pendingRunCreations].map((X)=>X.then(()=>{}))]),Y=[...this.runs.values()].flatMap((X)=>[...X.handles.values()]),V=Q.some((X)=>X.status==="rejected")?[]:await Promise.allSettled(Y.map((X)=>X.cancel($)));uV([...Q,...V]);for(let X of new Set([...this.runs.values()].map((z)=>z.snapshot.chatId)))await this.presentation.closeChat(X)}assertAcceptingRuns(){if(this.shuttingDown)throw Error("Agent service is shutting down; cannot start new runs")}delegationParent($){if($.kind!=="worker")return{};let Z=this.requireAccessibleRun($,$.runId);if(!Z.capabilityByIdentity.has($.identityId))throw Error("calling Agent capability is no longer active");return{parentRunId:Z.snapshot.runId,parentKind:"delegate"}}createRun($,Z,J){let Q=J.parentRunId?this.runs.get(J.parentRunId):void 0;if(Q)Q.pendingChildCreations++;let Y=this.createRunInternal($,Z,J);this.pendingRunCreations.add(Y);let V=()=>{if(this.pendingRunCreations.delete(Y),Q)Q.pendingChildCreations--};return Y.then(V,V),Y}async createRunInternal($,Z,J){let{owner:Q}=$,Y;if(J.parentRunId){if(Y=this.runs.get(J.parentRunId),!Y)throw Error(`parent agent run not found: ${J.parentRunId}`);this.assertSameOwner(Y,$)}let V=[];for(let D=Y;D;D=D.snapshot.parentRunId?this.runs.get(D.snapshot.parentRunId):void 0)V.push([D,D.cancellationEpoch]);let X=Z.workDir??(J.parentKind==="delegate"?Y?.snapshot.workDir:void 0),z=J.resumeSessionId?bP(Q.workDir,X):lV(Q.workDir,X),H=F5(z),G=$.codexAccountId,W=this.deps.getCatalog(G),K=Z.identityIds.map((D)=>{let M=W.identities.find((U)=>U.id===D);if(!M)throw Error(`agent identity not found: ${D}`);if(M.status!=="ready")throw Error(`${M.displayName}: ${M.reason??M.status}`);return M}),B=K.map((D)=>oE(D,sE(D,Z.effort),J.resumeSessionId,D.provider==="claude"&&i1(D.tokenSourceId,D.model))),_=`agent_${pE()}`,P={runId:_,codexAccountId:G,owner:{...Q},sessionName:Q.name,chatId:Q.chatId,sessionWorkDir:Q.workDir,...J.requestId?{requestId:J.requestId,requestHash:J.requestHash}:{},...Q.kind==="project"?{...Z.requesterOpenId?{requesterOpenId:Z.requesterOpenId}:{}}:{},workDir:z,prompt:Z.prompt,description:M9(Z.description),...J.parentRunId?{parentRunId:J.parentRunId}:{},...J.parentKind?{parentKind:J.parentKind}:{},...J.resumedFromRunId?{resumedFromRunId:J.resumedFromRunId}:{},depth:J.depth,status:"queued",workers:B,createdAt:new Date().toISOString()},L={snapshot:P,context:$,handles:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,pendingChildCreations:0,cancelled:!1,cancellationEpoch:0,finalizing:!1,finalized:!1,persistedArtifacts:new Set,artifactsUnloaded:!1};try{await this.presentation.add(P)}catch(D){if(this.runs.set(_,L),J.parentRunId)Y?.children.add(_);let M=`Agent 卡片初始化失败,Agent 未启动: ${$$(D)}`;for(let U of B)U.status="failed",U.error=M;throw await this.finalizeRun(L,"failed",M),await this.deps.sendTextRaw(Q.chatId,`❌ ${M}`),D}if(this.runs.set(_,L),J.parentRunId)Y?.children.add(_);if(this.shuttingDown||this.currentCancellationEpoch($)!==J.cancellationEpoch||V.some(([D,M])=>D.cancellationEpoch!==M)){L.cancelled=!0;let D="任务已在启动前取消";for(let M of L.snapshot.workers)M.status="cancelled",M.error=D,M.finishedAt=new Date().toISOString();return this.persist(L),await Promise.all(L.snapshot.workers.map((M)=>this.updateWorkerCard(L,M))),await this.finalizeRun(L,"cancelled",D),this.readSnapshot(L)}this.persist(L);for(let D of K){let M=J.resumeSessionId;this.executeWorker(L,D,Z.prompt,H,M).catch((U)=>{j(`agent: run=${_} worker=${D.id} crashed: ${$$(U)}`)})}return this.readSnapshot(L)}async executeWorker($,Z,J,Q,Y){let V=$.snapshot.workers.find((z)=>z.identityId===Z.id);if($.cancelled)return;let X="";try{if(X=mE(32).toString("base64url"),this.capabilities.set(X,{kind:"worker",context:$.context,runId:$.snapshot.runId,identityId:Z.id,depth:$.snapshot.depth}),$.capabilityByIdentity.set(Z.id,X),V.status="running",V.startedAt=new Date().toISOString(),delete V.queuedReason,this.refreshNonterminalStatus($),this.persist($),await this.updateWorkerCard($,V),$.cancelled)return;this.assertSameOwner($,$.context);let z=Y?bP($.context.owner.workDir,$.snapshot.workDir):lV($.context.owner.workDir,$.snapshot.workDir);if(z!==$.snapshot.workDir||F5(z)!==Q)throw Error("agent work_dir changed before the worker could start");let H=this.deps.startWorker({identity:Z,codexAccountId:$.snapshot.codexAccountId,effort:V.effort,workDir:$.snapshot.workDir,prompt:J,description:$.snapshot.description,resumeSessionId:Y,projectBound:$.context.owner.kind==="project",...$.context.owner.kind==="session"?{developerInstructions:$.context.sessionInstructions(Z.provider)}:{},profile:eE(z8($.snapshot.workDir)),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:G4},hostEnv:{LODESTAR_AGENT_URL:z9(g.notify.bind,g.notify.port),LODESTAR_AGENT_CAPABILITY:X,LODESTAR_AGENT_SESSION:$.snapshot.sessionName},callbacks:{onNeedsInput:(W,K)=>{if($.cancelled)return;if($.context.owner.kind==="project")throw Error(Q4);if(V.status="needs_input",V.pendingInput=W,K)V.displayPendingInput=K;else delete V.displayPendingInput;this.refreshNonterminalStatus($),this.persist($),this.updateWorkerCard($,V)},onDisplayContext:(W)=>{if($.cancelled)return!1;return V.displayDescription=W.description,V.displayPrompt=W.prompt,this.persist($),this.updateWorkerCard($,V),!0},onProgress:(W)=>this.recordStep($,V,W),onCodexAccount:(W)=>{if($.cancelled)return;V.codexAccountId=W,this.persist($)},onSession:(W)=>{if(V.sessionId===W)return;V.sessionId=W,this.persist($)}}});$.handles.set(Z.id,H);let G=await H.done;if($.cancelled)return;if(this.clearProgressTimer($,Z.id),V.output=G.output,G.displayOutput!==void 0)V.displayOutput=G.displayOutput;if(V.outputTruncated=G.outputTruncated,V.sessionId=G.sessionId,V.checkpointId=G.checkpointId,V.durationMs=G.durationMs,V.usage=G.usage,V.finishedAt=new Date().toISOString(),delete V.pendingInput,delete V.displayPendingInput,$.cancelled)return;V.status="completed",this.persist($),await this.updateWorkerCard($,V)}catch(z){if(z instanceof H3){if(V.output=z.output,z.displayOutput!==void 0)V.displayOutput=z.displayOutput;if(z.displayError!==void 0)V.displayError=z.displayError;if(V.outputTruncated=!1,z.sessionId)V.sessionId=z.sessionId;this.persist($)}if(!$.cancelled){if(this.clearProgressTimer($,Z.id),V.status="failed",V.error=$$(z),V.finishedAt=new Date().toISOString(),V.startedAt)V.durationMs=Date.now()-Date.parse(V.startedAt);delete V.pendingInput,delete V.displayPendingInput,this.persist($),await this.updateWorkerCard($,V)}}finally{if(!$.handles.get(Z.id)?.isAlive?.())$.handles.delete(Z.id);if(X)this.capabilities.delete(X);$.capabilityByIdentity.delete(Z.id),this.recomputeRun($)}}recordStep($,Z,J){if($.cancelled||$.finalizing||$.finalized||q5(Z.status))return;if(Z.steps.push(J),Z.steps.length>xP)Z.steps.splice(0,Z.steps.length-xP);if($.progressTimers.has(Z.identityId))return;let Q=setTimeout(()=>{$.progressTimers.delete(Z.identityId),this.updateWorkerCard($,Z,"progress")},250);$.progressTimers.set(Z.identityId,Q)}clearProgressTimer($,Z){let J=$.progressTimers.get(Z);if(J)clearTimeout(J);$.progressTimers.delete(Z)}refreshNonterminalStatus($){if($.cancelled)return;if($.snapshot.workers.some((Z)=>Z.status==="needs_input"))$.snapshot.status="needs_input";else if($.snapshot.workers.some((Z)=>Z.status==="running"))$.snapshot.status="running";else $.snapshot.status="queued";delete $.snapshot.finishedAt}recomputeRun($){if($.cancelled||$.finalized||$.finalizing)return;let Z=$.snapshot.workers;if(Z.some((Q)=>Q.status==="needs_input"||Q.status==="running"||Q.status==="queued")){this.refreshNonterminalStatus($),this.persist($);return}let J=Z.some((Q)=>Q.status==="failed")?"failed":"completed";this.finalizeRun($,J,J==="failed"?"一个或多个 Agent 失败":void 0).catch((Q)=>{$.finalizing=!1,$.finalized=!1,$.snapshot.status="failed",$.snapshot.error=`Agent terminal persistence failed: ${$$(Q)}`,j(`agent: terminal finalization failed run=${$.snapshot.runId}: ${$$(Q)}`),this.deps.sendTextRaw($.snapshot.chatId,`❌ agent ${$.snapshot.runId} 收尾失败: ${$$(Q)}`).catch((Y)=>j(`agent: terminal failure delivery failed: ${$$(Y)}`))})}async cancelTree($,Z){$.cancellationEpoch++;let J=!L5($.snapshot.status)&&!$.cancelled||$.handles.size>0,Q=[];if(J){$.cancelled=!0;for(let X of[...$.progressTimers.keys()])this.clearProgressTimer($,X);for(let X of $.capabilityByIdentity.values())this.capabilities.delete(X);$.capabilityByIdentity.clear()}let Y=new Set;while(!0){let X=[...$.children].map((H)=>this.runs.get(H)).filter((H)=>!!H&&!Y.has(H.snapshot.runId)&&this.treeHasActiveRun(H));if(X.length===0)break;for(let H of X)Y.add(H.snapshot.runId);let z=await Promise.allSettled(X.map((H)=>this.cancelTree(H,Z)));if(Q.push(...z),z.some((H)=>H.status==="rejected"))break}if(!J){uV(Q);return}if(Q.push(...await Promise.allSettled([...$.handles].map(async([X,z])=>{if(await z.cancel(Z),z.isAlive?.())throw Error(`${X}: Agent process is still alive after cancellation`);$.handles.delete(X)}))),Q.some((X)=>X.status==="rejected")){let X=yP(Q);throw $.snapshot.status="failed",$.snapshot.error=X.message,this.persist($),await this.deps.sendTextRaw($.snapshot.chatId,`❌ Agent 取消未完成: ${X.message}`).catch((z)=>j(`agent: cancellation failure notice failed: ${$$(z)}`)),X}let V=[];for(let X of $.snapshot.workers)if(!q5(X.status))X.status="cancelled",X.error=Z,X.finishedAt=new Date().toISOString(),delete X.pendingInput,delete X.displayPendingInput,V.push(X);await Promise.all(V.map((X)=>this.updateWorkerCard($,X))),await this.finalizeRun($,"cancelled",Z)}async finalizeRun($,Z,J){if($.finalized||$.finalizing)return;$.finalizing=!0;for(let Q of[...$.progressTimers.keys()])this.clearProgressTimer($,Q);if($.snapshot.status=Z,$.snapshot.finishedAt=new Date().toISOString(),J)$.snapshot.error=J;try{await this.presentation.update($.snapshot,!0)}catch(Q){this.recordPresentationError($,`agent card finalization failed: ${$$(Q)}`)}if($.finalizing=!1,this.persist($),$.finalized=!0,this.pruneRunArtifacts(),$.snapshot.presentationErrors?.length){let Q=$.snapshot.presentationErrors.map((V,X)=>`${X+1}. ${V}`).join(`
631
+ `),allowUserInput:!$.projectBound,profile:$.profile,managedSkillPluginPath:$.managedSkillPluginPath,hostEnv:{...$.hostEnv,LODESTAR_AGENT_ROLE:"worker"},serviceName:"lodestar-agent"});return hE(Q,$.prompt,$.callbacks,void 0,$.resumeSessionId,!$.projectBound,$.description?{description:$.description,prompt:$.prompt}:void 0)}function hE($,Z,J={},Q=bz,Y,V=!0,X){let z=[],H=[],G=v$($),W=G,K=null,B=!1,_=null,P=null,L=new AbortController,q=[],F,M,U=Date.now(),A=new Promise((x,u)=>{F=x,M=u}),O=(x)=>{if(!x)return null;try{if(!Y||x!==Y)Q($.provider,x);if(Y&&x!==Y)throw Error(`native resume returned session ${x}, expected ${Y}; refusing to treat it as a resumed conversation`);return J.onSession?.(x),null}catch(u){return u instanceof Error?u:Error(String(u))}},N=()=>{if($.off("assistant_text",T),$.off("tool_use",m),$.off("tool_result",b),$.off("subagent_step",p),$.off("can_use_tool",c),$.off("hook_callback",J0),$.off("init",l),!$.isAlive())$.off("error",y);$.off("turn_retry",t),$.off("codex_account_changed",Q0),$.off("result",K0),$.off("exit",p$)},S=(x,u)=>{if(_)return _;return B=!0,L.abort(Error("delegated agent turn ended")),q.length=0,_=Promise.resolve().then(async()=>{let J$=O($.sessionId);try{await $.kill(3000)}catch(b$){P=b$ instanceof Error?b$:Error(String(b$))}N();let B0=[x,J$,P].filter((b$)=>!!b$),G3=B0.length>1?AggregateError(B0,B0.map((b$)=>b$.message).join("; ")):B0[0];if(G3){M(new H3(G3,z.join("").trim(),$.sessionId,W?H.join("").trim():void 0,u?.displayError===void 0?void 0:[u.displayError,...B0.filter((b$)=>b$!==x).map((b$)=>b$.message)].join("; ")));return}let ZX=$.sessionId;if(!ZX){M(new H3(Error("delegated agent completed without a native session id"),z.join("").trim(),null,W?H.join("").trim():void 0));return}let ML=z.join("").trim(),JX=gE(u?.checkpoint,$);F({output:ML,...W?{displayOutput:H.join("").trim()}:{},outputTruncated:!1,sessionId:ZX,...JX?{checkpointId:JX}:{},durationMs:Date.now()-U,usage:$.lastUsage?{...$.lastUsage}:null})}),_},T=(x)=>{if(B||x?.parentToolUseId||typeof x?.text!=="string")return;if(z.push(x.text),G&&typeof x.displayText!=="string"){S(Error("Claude subscription delegated output is missing verified translation"));return}W||=typeof x.displayText==="string",H.push(x.displayText??x.text)},f=(x)=>{if(B)return;try{J.onProgress?.(x)}catch(u){S(u instanceof Error?u:Error(String(u)))}},m=(x)=>f({at:new Date().toISOString(),phase:"started",tool:String(x?.name??"tool"),detail:x.displayInput?NP(x.input):"",...x.displayInput?{displayDetail:NP(x.displayInput)}:{}}),b=(x)=>f({at:new Date().toISOString(),phase:"completed",tool:x?.is_error?"tool error":"tool result",detail:""}),p=(x)=>f({at:new Date().toISOString(),phase:x?.phase??"info",tool:String(x?.tool??"subagent"),detail:""}),c=(x)=>{if(B)return;if(x.tool_name!=="AskUserQuestion"){try{$.sendPermissionResponse(x.request_id,"allow",{updatedInput:x.input??{}})}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)))}return}let u,J$;try{if(u=RP({...x,input:x.originalInput??x.input}),x.originalInput){if(J$=RP(x),J$.questions.length!==u.questions.length)throw Error("translated question count does not match native questions");J$.questions=J$.questions.map((B0,G3)=>({...B0,id:u.questions[G3].id}))}else if(G)throw Error("Claude subscription delegated question is missing verified translation");if(!V)throw Error(`${Q4}: ${u.questions.map((B0)=>B0.question).join("; ")}`)}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)));return}if(q.some((B0)=>B0.request.requestId===u.requestId))return;q.push({request:u,displayRequest:J$,originalInput:x.originalInput??x.input??{}});try{if(q.length===1)J.onNeedsInput?.(u,J$)}catch(B0){S(B0 instanceof Error?B0:Error(String(B0)))}},J0=(x)=>{if(B)return;try{$.sendHookResponse(String(x.request_id),{})}catch(u){S(u instanceof Error?u:Error(String(u)))}},l=(x)=>{let u=O(x?.session_id??$.sessionId);if(u)S(u)},y=(x)=>{K=x instanceof Error?x:Error(String(x))},Q0=(x)=>{if(B)return;try{J.onCodexAccount?.(x.accountId)}catch(u){S(u instanceof Error?u:Error(String(u)))}if(x.diagnostics.length)j(`agent-runner: selected Codex account=${x.accountId}; diagnostics: ${x.diagnostics.join(";")}`)},t=(x)=>{let u=x.reason==="quota"?"Codex 额度换号":x.reason==="stream_disconnected"?"Codex 连接中断重试":x.reason==="compact_connection_failed"?"Codex 压缩连接中断重试":x.reason==="transient_error"?"Codex 临时故障重试":"Codex 容量重试";f({at:new Date().toISOString(),phase:"info",tool:u,detail:x.phase==="waiting"?`${x.message} · ${x.delayMs/1000}s 后重试 #${x.attempt}`:`正在重试 #${x.attempt}`})},K0=(x)=>{let u=x?.is_error?Error(String(x.error??x.subtype??$.lastResult.subtype??"delegated agent failed")):void 0;S(u,x)},p$=(x)=>{if(B)return;let u=`code=${x?.code??"null"} signal=${x?.signal??"null"}`;S(K??Error(`delegated agent exited before result (${u})`))};if($.on("assistant_text",T),$.on("tool_use",m),$.on("tool_result",b),$.on("subagent_step",p),$.on("can_use_tool",c),$.on("hook_callback",J0),$.on("init",l),$.on("error",y),$.on("turn_retry",t),$.on("codex_account_changed",Q0),$.on("result",K0),$.on("exit",p$),G)$.setTranslationPresentationPolicy?.((x)=>{if(B)return"hidden";if(x.kind==="assistant_text")return x.parentToolUseId?"hidden":"worker";if(x.kind==="tool_input")return"worker";return"hidden"});try{if($.sendInitialize(),G&&X)(async()=>{if(!$.translateDisplayFields)throw Error("Claude subscription delegated context translation is unavailable");if(await $.translateDisplayFields([X.description,X.prompt],L.signal,(x)=>{if(B||!J.onDisplayContext)return!1;if(x.length!==2||x.some((u)=>typeof u!=="string"))throw Error("Claude subscription delegated context translation returned invalid fields");if(J.onDisplayContext({description:x[0],prompt:x[1]})===!1)throw Error("Delegated task display was not accepted");return!B}),B)return;$.sendUserText(Z)})().catch((x)=>{if(!B)S(x instanceof Error?x:Error(String(x)))});else $.sendUserText(Z)}catch(x){S(x instanceof Error?x:Error(String(x)))}return{done:A,isAlive:()=>$.isAlive(),pendingInput:()=>q[0]?.request??null,displayPendingInput:()=>q[0]?.displayRequest??null,answer(x,u){let J$=q[0];if(!J$)throw Error("delegated agent is not waiting for input");if(J$.request.requestId!==x)throw Error(`delegated agent input request mismatch: expected ${J$.request.requestId}`);if($.sendPermissionResponse(x,"allow",{updatedInput:{...J$.originalInput,answers:u}}),q.shift(),q[0])J.onNeedsInput?.(q[0].request,q[0].displayRequest)},async cancel(x="delegated agent cancelled"){let u=B;if(await S(Error(x)),await A.catch(()=>{}),u){if($.isAlive())await $.kill(3000);P=null,N()}if(P)throw P}}}function NP($){if(!$)return"";if(typeof $.__displayDescription==="string")return $.__displayDescription;if(typeof $.description==="string")return $.description;let Z=$.command??$.cmd??$.script;if(typeof Z==="string")return B1(Z).description;if(typeof $.subject==="string")return $.subject;return""}function RP($){let Z=$.input??{},Q=(Array.isArray(Z.questions)?Z.questions:[Z]).map((Y,V)=>IE(Y,V));if(Q.length===0)throw Error("delegated agent input request contains no questions");return{requestId:String($.request_id),...$.tool_use_id?{toolUseId:$.tool_use_id}:{},questions:Q}}function IE($,Z){let J=$&&typeof $==="object"?$:{question:$},Q=String(J.question??J.prompt??J.title??"").trim();if(!Q)throw Error(`delegated agent input question ${Z+1} is empty`);let Y=String(J.id??Q),V=Array.isArray(J.options)?J.options.map((X)=>{if(typeof X==="string")return{label:X};let z=X&&typeof X==="object"?X:{};return{label:String(z.label??z.value??""),...z.description?{description:String(z.description)}:{}}}).filter((X)=>X.label):[];return{id:Y,...J.header?{header:String(J.header)}:{},question:Q,options:V}}function gE($,Z){if(typeof $?.id==="string"&&$.id)return $.id;if((Z.provider==="codex"||Z.provider==="dsh")&&typeof Z.lastCompletedTurnId==="string"&&Z.lastCompletedTurnId)return Z.lastCompletedTurnId;if(Z.provider==="claude"&&Z.lastAssistantUuid)return Z.lastAssistantUuid;return}var H3;var EP=R(()=>{P0();tQ();f9();X0();cV();I();A4();H3=class H3 extends Error{output;sessionId;displayOutput;displayError;constructor($,Z,J,Q,Y){super($.message,{cause:$});this.output=Z;this.sessionId=J;this.displayOutput=Q;this.displayError=Y;this.name="AgentWorkerFailure"}}});function q$($){if($.kind!=="session")return $.context;let Z=$.session;return{owner:{kind:"session",name:Z.sessionName,chatId:Z.chatId,workDir:Z.workDir},codexAccountId:Z.codexAccountId(),sessionInstructions:(J)=>Z.delegatedAgentDeveloperInstructions(J)}}import{createHash as SP,randomBytes as mE,randomUUID as pE}from"node:crypto";import{existsSync as cE,readdirSync as uE,readFileSync as vP,realpathSync as D5,statSync as lE}from"node:fs";import{isAbsolute as dE,join as M5,relative as iE,resolve as yP,sep as nE}from"node:path";class dV{deps;presentation;runs=new Map;capabilities=new Map;cancellationEpochBySession=new Map;startingNativeSessions=new Set;pendingRunCreations=new Set;requests=new Map;shuttingDown=!1;constructor($=aE){this.deps=$;this.presentation=new a8($),this.loadDurableRuns()}rootPrincipal($){return{kind:"session",session:$,depth:-1}}projectPrincipal($){if($.owner.kind!=="project")throw Error("project principal requires project ownership");return{kind:"project",context:$,depth:-1}}principalForCapability($){return this.capabilities.get($)??null}startRun($,Z){return this.withRequestId($,Z,"run",(J)=>this.startRunOnce($,Z,J))}async startRunOnce($,Z,J){if(this.assertAcceptingRuns(),M9(Z.description),Z.sessionId!==void 0){if(!Z.sessionId.trim())throw Error("agent session_id must be a non-empty string");if(Z.identityIds.length>1)throw Error("agent session continuation accepts at most one identity_id");let Y=this.findSessionHistory($,Z.sessionId),V=Z.identityIds[0]?this.requireIdentity($,Z.identityIds[0]):void 0;return this.resumeRun($,Z,J,Y,V)}let Q=q$($);return this.createRun(Q,Z,{...J,...this.delegationParent($),depth:$.depth+1,cancellationEpoch:this.currentCancellationEpoch(Q)})}followUp($,Z,J){return this.withRequestId($,J,`follow-up:${Z}`,(Q)=>this.followUpOnce($,Z,J,Q))}async followUpOnce($,Z,J,Q){this.assertAcceptingRuns(),M9(J.description);let Y=this.runs.get(Z);if(!Y)throw Error(`agent run not found: ${Z}`);this.assertResumeProject($,Y);let V=Y.snapshot.workers.length===1?Y.snapshot.workers[0]:kP(Y.snapshot,J.identityId);if(Y.handles.get(V.identityId)?.isAlive?.())throw Error("Agent process has not stopped; cannot start follow-up yet");if(!V.sessionId)throw Error(`${V.identityName} has no resumable native session id`);this.findSessionHistory($,V.sessionId);let X=J.identityId?this.requireIdentity($,J.identityId):void 0;return this.resumeRun($,{...J,identityIds:J.identityId?[J.identityId]:[],sessionId:V.sessionId},Q,{run:Y,worker:V},X)}requireIdentity($,Z){let J=this.deps.getCatalog(q$($).codexAccountId).identities.find((Q)=>Q.id===Z);if(!J)throw Error(`agent identity not found: ${Z}`);if(J.status!=="ready")throw Error(`${J.displayName}: ${J.reason??J.status}`);return J}async resumeRun($,Z,J,Q,Y){let V=q$($);this.assertResumeProject($,Q.run);let X=Y??this.requireIdentity($,Q.worker.identityId);if(X.provider!==Q.worker.provider)throw Error("native session belongs to a different Agent backend");let z=Y4(L$(Q.run.snapshot))===Y4(V.owner),H=Z.effort??(Q.worker.identityId===X.id?Q.worker.effort:void 0),G=Z.workDir??Q.run.snapshot.workDir,W=this.reserveNativeSession({provider:X.provider,sessionId:Z.sessionId});try{return await this.createRun(V,{identityIds:[X.id],description:Z.description,prompt:Z.prompt,effort:H,workDir:G,requesterOpenId:Z.requesterOpenId??(z?Q.run.snapshot.requesterOpenId:void 0)},{...J,...$.kind==="worker"?this.delegationParent($):z?{parentRunId:Q.run.snapshot.runId,parentKind:"follow_up"}:{},depth:$.depth+1,resumedFromRunId:Q.run.snapshot.runId,cancellationEpoch:this.currentCancellationEpoch(V),resumeSessionId:Z.sessionId})}finally{W()}}async answer($,Z,J){if(q$($).owner.kind==="project")throw Error(Q4);let Q=this.requireMutableDescendant($,Z),Y=kP(Q.snapshot,J.identityId);if(Y.status!=="needs_input"||!Y.pendingInput)throw Error(`${Y.identityName} is not waiting for input`);if(Y.pendingInput.requestId!==J.requestId)throw Error(`input request mismatch: expected ${Y.pendingInput.requestId}`);let V=Q.handles.get(Y.identityId);if(!V)throw Error("waiting agent process is no longer alive; start a follow-up run");V.answer(J.requestId,J.answers);let X=V.pendingInput();if(Y.status=X?"needs_input":"running",X)Y.pendingInput=X;else delete Y.pendingInput;let z=V.displayPendingInput?.();if(z)Y.displayPendingInput=z;else delete Y.displayPendingInput;return delete Y.queuedReason,this.refreshNonterminalStatus(Q),this.persist(Q),await this.updateWorkerCard(Q,Y),this.readSnapshot(Q)}getRun($,Z){return this.readSnapshot(this.requireAccessibleRun($,Z))}async cancelRun($,Z,J="agent run cancelled"){let Q=this.requireMutableDescendant($,Z);if(!this.treeHasActiveRun(Q))return!1;return await this.cancelTree(Q,J),!0}async cancelSessionRuns($,Z,J){this.bumpCancellationEpoch($,Z);let Q=[...this.runs.values()].filter((V)=>L$(V.snapshot).kind==="session"&&V.snapshot.sessionName===$&&V.snapshot.chatId===Z&&!V.snapshot.parentRunId&&this.treeHasActiveRun(V)),Y=await Promise.allSettled(Q.map((V)=>this.cancelTree(V,J)));uV(Y)}async cancelProjectRunFromCard($,Z,J,Q){let Y=this.runs.get($);if(!Y||L$(Y.snapshot).kind!=="project"||!Q||!J||Y.snapshot.chatId!==Z||Y.snapshot.cardMessageId!==J)throw Error("项目任务卡片无效或不属于当前群");return this.cancelRun(this.projectPrincipal({owner:L$(Y.snapshot)}),$,"用户通过项目任务卡取消")}async withRequestId($,Z,J,Q){if((Z.requestId||Z.requesterOpenId)&&$.kind!=="project")throw Error("request_id and requester_open_id require explicit project mode");if(!Z.requestId)return Q({});let Y=Y4(q$($).owner),V=JSON.stringify([Y,Z.requestId]),X=SP("sha256").update(JSON.stringify({operation:J,prompt:Z.prompt,description:Z.description,effort:Z.effort,workDir:Z.workDir,requesterOpenId:Z.requesterOpenId,identityIds:"identityIds"in Z?Z.identityIds:void 0,identityId:"identityId"in Z?Z.identityId:void 0,sessionId:"sessionId"in Z?Z.sessionId:void 0})).digest("hex"),z=[...this.runs.values()].find((W)=>W.snapshot.requestId===Z.requestId&&Y4(L$(W.snapshot))===Y);if(z){if(z.snapshot.requestHash!==X)throw Error("request_id was already used with different input");return this.readSnapshot(z)}let H=this.requests.get(V);if(H){if(H.hash!==X)throw Error("request_id is in use with different input");return H.promise}let G=Promise.resolve().then(()=>Q({requestId:Z.requestId,requestHash:X}));this.requests.set(V,{hash:X,promise:G});try{return await G}finally{this.requests.delete(V)}}async shutdown($){this.shuttingDown=!0;let Z=new Set([...this.runs.values()].map((X)=>`${X.snapshot.sessionName}\x00${X.snapshot.chatId}`));for(let X of Z){let[z,H]=X.split("\x00");this.bumpCancellationEpoch(z,H)}let J=[...this.runs.values()].filter((X)=>!X.snapshot.parentRunId&&this.treeHasActiveRun(X)),Q=await Promise.allSettled([...J.map((X)=>this.cancelTree(X,$)),...[...this.pendingRunCreations].map((X)=>X.then(()=>{}))]),Y=[...this.runs.values()].flatMap((X)=>[...X.handles.values()]),V=Q.some((X)=>X.status==="rejected")?[]:await Promise.allSettled(Y.map((X)=>X.cancel($)));uV([...Q,...V]);for(let X of new Set([...this.runs.values()].map((z)=>z.snapshot.chatId)))await this.presentation.closeChat(X)}assertAcceptingRuns(){if(this.shuttingDown)throw Error("Agent service is shutting down; cannot start new runs")}delegationParent($){if($.kind!=="worker")return{};let Z=this.requireAccessibleRun($,$.runId);if(!Z.capabilityByIdentity.has($.identityId))throw Error("calling Agent capability is no longer active");return{parentRunId:Z.snapshot.runId,parentKind:"delegate"}}createRun($,Z,J){let Q=J.parentRunId?this.runs.get(J.parentRunId):void 0;if(Q)Q.pendingChildCreations++;let Y=this.createRunInternal($,Z,J);this.pendingRunCreations.add(Y);let V=()=>{if(this.pendingRunCreations.delete(Y),Q)Q.pendingChildCreations--};return Y.then(V,V),Y}async createRunInternal($,Z,J){let{owner:Q}=$,Y;if(J.parentRunId){if(Y=this.runs.get(J.parentRunId),!Y)throw Error(`parent agent run not found: ${J.parentRunId}`);this.assertSameOwner(Y,$)}let V=[];for(let F=Y;F;F=F.snapshot.parentRunId?this.runs.get(F.snapshot.parentRunId):void 0)V.push([F,F.cancellationEpoch]);let X=Z.workDir??(J.parentKind==="delegate"?Y?.snapshot.workDir:void 0),z=J.resumeSessionId?bP(Q.workDir,X):lV(Q.workDir,X),H=D5(z),G=$.codexAccountId,W=this.deps.getCatalog(G),K=Z.identityIds.map((F)=>{let M=W.identities.find((U)=>U.id===F);if(!M)throw Error(`agent identity not found: ${F}`);if(M.status!=="ready")throw Error(`${M.displayName}: ${M.reason??M.status}`);return M}),B=K.map((F)=>oE(F,sE(F,Z.effort),J.resumeSessionId,F.provider==="claude"&&i1(F.tokenSourceId,F.model))),_=`agent_${pE()}`,P={runId:_,codexAccountId:G,owner:{...Q},sessionName:Q.name,chatId:Q.chatId,sessionWorkDir:Q.workDir,...J.requestId?{requestId:J.requestId,requestHash:J.requestHash}:{},...Q.kind==="project"?{...Z.requesterOpenId?{requesterOpenId:Z.requesterOpenId}:{}}:{},workDir:z,prompt:Z.prompt,description:M9(Z.description),...J.parentRunId?{parentRunId:J.parentRunId}:{},...J.parentKind?{parentKind:J.parentKind}:{},...J.resumedFromRunId?{resumedFromRunId:J.resumedFromRunId}:{},depth:J.depth,status:"queued",workers:B,createdAt:new Date().toISOString()},L={snapshot:P,context:$,handles:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,pendingChildCreations:0,cancelled:!1,cancellationEpoch:0,finalizing:!1,finalized:!1,persistedArtifacts:new Set,artifactsUnloaded:!1};try{await this.presentation.add(P)}catch(F){if(this.runs.set(_,L),J.parentRunId)Y?.children.add(_);let M=`Agent 卡片初始化失败,Agent 未启动: ${$$(F)}`;for(let U of B)U.status="failed",U.error=M;throw await this.finalizeRun(L,"failed",M),await this.deps.sendTextRaw(Q.chatId,`❌ ${M}`),F}if(this.runs.set(_,L),J.parentRunId)Y?.children.add(_);if(this.shuttingDown||this.currentCancellationEpoch($)!==J.cancellationEpoch||V.some(([F,M])=>F.cancellationEpoch!==M)){L.cancelled=!0;let F="任务已在启动前取消";for(let M of L.snapshot.workers)M.status="cancelled",M.error=F,M.finishedAt=new Date().toISOString();return this.persist(L),await Promise.all(L.snapshot.workers.map((M)=>this.updateWorkerCard(L,M))),await this.finalizeRun(L,"cancelled",F),this.readSnapshot(L)}this.persist(L);for(let F of K){let M=J.resumeSessionId;this.executeWorker(L,F,Z.prompt,H,M).catch((U)=>{j(`agent: run=${_} worker=${F.id} crashed: ${$$(U)}`)})}return this.readSnapshot(L)}async executeWorker($,Z,J,Q,Y){let V=$.snapshot.workers.find((z)=>z.identityId===Z.id);if($.cancelled)return;let X="";try{if(X=mE(32).toString("base64url"),this.capabilities.set(X,{kind:"worker",context:$.context,runId:$.snapshot.runId,identityId:Z.id,depth:$.snapshot.depth}),$.capabilityByIdentity.set(Z.id,X),V.status="running",V.startedAt=new Date().toISOString(),delete V.queuedReason,this.refreshNonterminalStatus($),this.persist($),await this.updateWorkerCard($,V),$.cancelled)return;this.assertSameOwner($,$.context);let z=Y?bP($.context.owner.workDir,$.snapshot.workDir):lV($.context.owner.workDir,$.snapshot.workDir);if(z!==$.snapshot.workDir||D5(z)!==Q)throw Error("agent work_dir changed before the worker could start");let H=this.deps.startWorker({identity:Z,codexAccountId:$.snapshot.codexAccountId,effort:V.effort,workDir:$.snapshot.workDir,prompt:J,description:$.snapshot.description,resumeSessionId:Y,projectBound:$.context.owner.kind==="project",...$.context.owner.kind==="session"?{developerInstructions:$.context.sessionInstructions(Z.provider)}:{},profile:eE(z8($.snapshot.workDir)),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:G4},hostEnv:{LODESTAR_AGENT_URL:z9(g.notify.bind,g.notify.port),LODESTAR_AGENT_CAPABILITY:X,LODESTAR_AGENT_SESSION:$.snapshot.sessionName},callbacks:{onNeedsInput:(W,K)=>{if($.cancelled)return;if($.context.owner.kind==="project")throw Error(Q4);if(V.status="needs_input",V.pendingInput=W,K)V.displayPendingInput=K;else delete V.displayPendingInput;this.refreshNonterminalStatus($),this.persist($),this.updateWorkerCard($,V)},onDisplayContext:(W)=>{if($.cancelled)return!1;return V.displayDescription=W.description,V.displayPrompt=W.prompt,this.persist($),this.updateWorkerCard($,V),!0},onProgress:(W)=>this.recordStep($,V,W),onCodexAccount:(W)=>{if($.cancelled)return;V.codexAccountId=W,this.persist($)},onSession:(W)=>{if(V.sessionId===W)return;V.sessionId=W,this.persist($)}}});$.handles.set(Z.id,H);let G=await H.done;if($.cancelled)return;if(this.clearProgressTimer($,Z.id),V.output=G.output,G.displayOutput!==void 0)V.displayOutput=G.displayOutput;if(V.outputTruncated=G.outputTruncated,V.sessionId=G.sessionId,V.checkpointId=G.checkpointId,V.durationMs=G.durationMs,V.usage=G.usage,V.finishedAt=new Date().toISOString(),delete V.pendingInput,delete V.displayPendingInput,$.cancelled)return;V.status="completed",this.persist($),await this.updateWorkerCard($,V)}catch(z){if(z instanceof H3){if(V.output=z.output,z.displayOutput!==void 0)V.displayOutput=z.displayOutput;if(z.displayError!==void 0)V.displayError=z.displayError;if(V.outputTruncated=!1,z.sessionId)V.sessionId=z.sessionId;this.persist($)}if(!$.cancelled){if(this.clearProgressTimer($,Z.id),V.status="failed",V.error=$$(z),V.finishedAt=new Date().toISOString(),V.startedAt)V.durationMs=Date.now()-Date.parse(V.startedAt);delete V.pendingInput,delete V.displayPendingInput,this.persist($),await this.updateWorkerCard($,V)}}finally{if(!$.handles.get(Z.id)?.isAlive?.())$.handles.delete(Z.id);if(X)this.capabilities.delete(X);$.capabilityByIdentity.delete(Z.id),this.recomputeRun($)}}recordStep($,Z,J){if($.cancelled||$.finalizing||$.finalized||q5(Z.status))return;if(Z.steps.push(J),Z.steps.length>xP)Z.steps.splice(0,Z.steps.length-xP);if($.progressTimers.has(Z.identityId))return;let Q=setTimeout(()=>{$.progressTimers.delete(Z.identityId),this.updateWorkerCard($,Z,"progress")},250);$.progressTimers.set(Z.identityId,Q)}clearProgressTimer($,Z){let J=$.progressTimers.get(Z);if(J)clearTimeout(J);$.progressTimers.delete(Z)}refreshNonterminalStatus($){if($.cancelled)return;if($.snapshot.workers.some((Z)=>Z.status==="needs_input"))$.snapshot.status="needs_input";else if($.snapshot.workers.some((Z)=>Z.status==="running"))$.snapshot.status="running";else $.snapshot.status="queued";delete $.snapshot.finishedAt}recomputeRun($){if($.cancelled||$.finalized||$.finalizing)return;let Z=$.snapshot.workers;if(Z.some((Q)=>Q.status==="needs_input"||Q.status==="running"||Q.status==="queued")){this.refreshNonterminalStatus($),this.persist($);return}let J=Z.some((Q)=>Q.status==="failed")?"failed":"completed";this.finalizeRun($,J,J==="failed"?"一个或多个 Agent 失败":void 0).catch((Q)=>{$.finalizing=!1,$.finalized=!1,$.snapshot.status="failed",$.snapshot.error=`Agent terminal persistence failed: ${$$(Q)}`,j(`agent: terminal finalization failed run=${$.snapshot.runId}: ${$$(Q)}`),this.deps.sendTextRaw($.snapshot.chatId,`❌ agent ${$.snapshot.runId} 收尾失败: ${$$(Q)}`).catch((Y)=>j(`agent: terminal failure delivery failed: ${$$(Y)}`))})}async cancelTree($,Z){$.cancellationEpoch++;let J=!L5($.snapshot.status)&&!$.cancelled||$.handles.size>0,Q=[];if(J){$.cancelled=!0;for(let X of[...$.progressTimers.keys()])this.clearProgressTimer($,X);for(let X of $.capabilityByIdentity.values())this.capabilities.delete(X);$.capabilityByIdentity.clear()}let Y=new Set;while(!0){let X=[...$.children].map((H)=>this.runs.get(H)).filter((H)=>!!H&&!Y.has(H.snapshot.runId)&&this.treeHasActiveRun(H));if(X.length===0)break;for(let H of X)Y.add(H.snapshot.runId);let z=await Promise.allSettled(X.map((H)=>this.cancelTree(H,Z)));if(Q.push(...z),z.some((H)=>H.status==="rejected"))break}if(!J){uV(Q);return}if(Q.push(...await Promise.allSettled([...$.handles].map(async([X,z])=>{if(await z.cancel(Z),z.isAlive?.())throw Error(`${X}: Agent process is still alive after cancellation`);$.handles.delete(X)}))),Q.some((X)=>X.status==="rejected")){let X=fP(Q);throw $.snapshot.status="failed",$.snapshot.error=X.message,this.persist($),await this.deps.sendTextRaw($.snapshot.chatId,`❌ Agent 取消未完成: ${X.message}`).catch((z)=>j(`agent: cancellation failure notice failed: ${$$(z)}`)),X}let V=[];for(let X of $.snapshot.workers)if(!q5(X.status))X.status="cancelled",X.error=Z,X.finishedAt=new Date().toISOString(),delete X.pendingInput,delete X.displayPendingInput,V.push(X);await Promise.all(V.map((X)=>this.updateWorkerCard($,X))),await this.finalizeRun($,"cancelled",Z)}async finalizeRun($,Z,J){if($.finalized||$.finalizing)return;$.finalizing=!0;for(let Q of[...$.progressTimers.keys()])this.clearProgressTimer($,Q);if($.snapshot.status=Z,$.snapshot.finishedAt=new Date().toISOString(),J)$.snapshot.error=J;try{await this.presentation.update($.snapshot,!0)}catch(Q){this.recordPresentationError($,`agent card finalization failed: ${$$(Q)}`)}if($.finalizing=!1,this.persist($),$.finalized=!0,this.pruneRunArtifacts(),$.snapshot.presentationErrors?.length){let Q=$.snapshot.presentationErrors.map((V,X)=>`${X+1}. ${V}`).join(`
632
632
  `),Y=Q.length>3000?`${Q.slice(0,3000)}
633
633
  …完整错误已保存在任务记录中。`:Q;await this.deps.sendTextRaw($.snapshot.chatId,`⚠️ 委派卡片出现更新错误 · ${$.snapshot.description??$.snapshot.runId}
634
634
  结果已保存,卡片更新期间出现 ${$.snapshot.presentationErrors.length} 个错误:
635
635
  ${Y}
636
- 任务:${$.snapshot.runId}`).catch((V)=>j(`agent: warning delivery failed run=${$.snapshot.runId}: ${$$(V)}`))}}async updateWorkerCard($,Z,J="state"){if($.finalized)return;let Q=$.snapshot.cardMessageId;try{await this.presentation.update($.snapshot,!1,J==="progress")}catch(Y){this.recordPresentationError($,`agent worker card update failed (${Z.identityName}): ${$$(Y)}`)}finally{if($.snapshot.cardMessageId!==Q)this.persist($)}}recordPresentationError($,Z){let J=$.snapshot.presentationErrors??[];if(!J.includes(Z))J.push(Z);$.snapshot.presentationErrors=J,j(`agent: ${Z} run=${$.snapshot.runId}`)}persist($){if(!$.snapshot.promptArtifact)$.snapshot.promptArtifact=`${$.snapshot.runId}.prompt.txt`;this.persistTextArtifact($,$.snapshot.promptArtifact,$.snapshot.prompt);for(let J of $.snapshot.workers){if(!J.output)continue;if(!J.outputArtifact){let Q=SP("sha256").update(J.identityId).digest("hex").slice(0,16);J.outputArtifact=`${$.snapshot.runId}.${Q}.output.txt`}this.persistTextArtifact($,J.outputArtifact,J.output)}let Z=wP($.snapshot);D5(Z),Z.prompt="";for(let J of Z.workers)J.output="";this.deps.writeArtifact(M5(X2,`${$.snapshot.runId}.json`),Z)}persistTextArtifact($,Z,J){if($.persistedArtifacts.has(Z))return;gP(Z),this.deps.writeTextArtifact(M5(X2,Z),J),$.persistedArtifacts.add(Z)}readSnapshot($){let Z=wP($.snapshot);if(D5(Z),$.artifactsUnloaded)hP(Z,Z.runId,this.deps.readTextArtifact);return Z}requireAccessibleRun($,Z){let J=this.runs.get(Z);if(!J||!this.canAccess($,J))throw Error(`agent run not found: ${Z}`);if(this.assertSameOwner(J,q$($)),!J.context)J.context=q$($);return J}assertResumeProject($,Z){let J=q$($).owner,Q=L$(Z.snapshot);if(J.chatId!==Q.chatId||H$(J.workDir)!==H$(Q.workDir))throw Error("agent session belongs to a different project or group; cross-project and cross-group resume is not allowed")}findSessionHistory($,Z){let J=[...this.runs.values()].flatMap((V)=>V.snapshot.workers.filter((X)=>X.sessionId===Z).map((X)=>({run:V,worker:X})));if(!J.length)throw Error("agent session project/group ownership is unknown; only registered sessions in this project and group can be resumed");for(let{run:V}of J)this.assertResumeProject($,V);if(new Set(J.map(({worker:V})=>V.provider)).size>1)throw Error("native session id has conflicting backend records; its unique identity cannot be established");let Q=new Set(J.flatMap(({run:V})=>[V.snapshot.resumedFromRunId,V.snapshot.parentRunId])),Y=J.filter(({run:V})=>!Q.has(V.snapshot.runId)).sort((V,X)=>Date.parse(X.run.snapshot.createdAt)-Date.parse(V.run.snapshot.createdAt))[0];if(!Y)throw Error(`agent session history has no latest run: ${Z}`);return Y}reserveNativeSession($){let Z=JSON.stringify([$.provider,$.sessionId]),J=[...this.runs.values()].some((Q)=>Q.snapshot.workers.some((Y)=>{if(Y.provider!==$.provider||Y.sessionId!==$.sessionId)return!1;let V=Q.handles.get(Y.identityId);return!q5(Y.status)||!!V&&V.isAlive?.()!==!1}));if(this.startingNativeSessions.has(Z)||J)throw Error("agent session is already running or starting; wait for the current turn to finish");return this.startingNativeSessions.add(Z),()=>{this.startingNativeSessions.delete(Z)}}requireMutableDescendant($,Z){let J=this.requireAccessibleRun($,Z);if($.kind==="worker"&&J.snapshot.runId===$.runId)throw Error("worker capability cannot mutate its containing run");return J}canAccess($,Z){let J=L$(Z.snapshot),Q=q$($).owner;if(J.kind!==Q.kind||J.name!==Q.name||J.chatId!==Q.chatId)return!1;if($.kind!=="worker")return!0;let Y=Z;while(Y){if(Y.snapshot.runId===$.runId)return!0;Y=Y.snapshot.parentRunId?this.runs.get(Y.snapshot.parentRunId):void 0}return!1}assertSameOwner($,Z){if(Y4(L$($.snapshot))!==Y4(Z.owner))throw Error("agent run belongs to a different Session or project")}treeHasActiveRun($){if($.pendingChildCreations>0)return!0;if($.handles.size>0)return!0;if(!L5($.snapshot.status))return!0;for(let Z of $.children){let J=this.runs.get(Z);if(J&&this.treeHasActiveRun(J))return!0}return!1}sessionKey($,Z){return`${$}\x00${Z}`}currentCancellationEpoch($){if($.owner.kind==="project")return 0;return this.cancellationEpochBySession.get(this.sessionKey($.owner.name,$.owner.chatId))??0}bumpCancellationEpoch($,Z){let J=this.sessionKey($,Z);this.cancellationEpochBySession.set(J,(this.cancellationEpochBySession.get(J)??0)+1)}loadDurableRuns(){for(let $ of this.deps.loadArtifacts()){if(D5($),!L5($.status)){$.status="failed",$.error="daemon restarted before this Agent run reached a terminal state",$.finishedAt=new Date().toISOString();for(let J of $.workers)if(!q5(J.status))J.status="failed",J.error=$.error,J.finishedAt=$.finishedAt,delete J.pendingInput,delete J.displayPendingInput}let Z={snapshot:$,context:null,handles:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,pendingChildCreations:0,cancelled:$.status==="cancelled",cancellationEpoch:0,finalizing:!1,finalized:!0,artifactsUnloaded:!1,persistedArtifacts:new Set([...$.promptArtifact?[$.promptArtifact]:[],...$.workers.flatMap((J)=>J.outputArtifact?[J.outputArtifact]:[])])};this.runs.set($.runId,Z),this.persist(Z)}for(let $ of this.runs.values())if($.snapshot.parentRunId)this.runs.get($.snapshot.parentRunId)?.children.add($.snapshot.runId);this.pruneRunArtifacts()}pruneRunArtifacts(){if(this.runs.size<=CP)return;let $=[...this.runs.values()].filter((Z)=>!Z.artifactsUnloaded&&Z.finalized&&!Z.finalizing&&L5(Z.snapshot.status)&&Z.handles.size===0).sort((Z,J)=>Date.parse(Z.snapshot.finishedAt??Z.snapshot.createdAt)-Date.parse(J.snapshot.finishedAt??J.snapshot.createdAt));for(let Z of $.slice(0,Math.max(0,$.length-CP))){Z.snapshot.prompt="";for(let J of Z.snapshot.workers)J.output="";D5(Z.snapshot),Z.artifactsUnloaded=!0}}}function lV($,Z){let J=F5($),Q=F5(fP($,Z===void 0?".":P5(Z))),Y=iE(J,Q);if(Y===".."||Y.startsWith(`..${nE}`)||dE(Y))throw Error("agent work_dir must be the main Agent working directory or one of its subdirectories");if(!lE(Q).isDirectory())throw Error(`agent work_dir is not a directory: ${Q}`);return Y===""?$:Q}function bP($,Z){let J=Z===void 0?$:fP($,P5(Z));return lV($,J),J}function oE($,Z,J,Q=!1){return{identityId:$.id,identityName:$.displayName,tokenSourceId:$.tokenSourceId,...Q?{translationEnabled:!0}:{},provider:$.provider,model:$.model,effort:Z,status:"queued",output:"",...J?{sessionId:J}:{},steps:[]}}function sE($,Z){let J=Z??$.defaultEffort;if(!J)throw Error(`${$.displayName} default effort MISS; specify effort explicitly`);if(!$.supportedEfforts.includes(J))throw Error(`${$.displayName} does not support effort ${J}`);return J}function kP($,Z){if(Z){let J=$.workers.find((Q)=>Q.identityId===Z);if(!J)throw Error(`agent identity is not part of run ${$.runId}: ${Z}`);return J}if($.workers.length!==1)throw Error("run has multiple Agents; specify identity_id");return $.workers[0]}function L5($){return $==="completed"||$==="failed"||$==="cancelled"}function q5($){return $==="completed"||$==="failed"||$==="cancelled"}function wP($){return JSON.parse(JSON.stringify($))}function D5($){for(let Z of $.workers){delete Z.translationEnabled,delete Z.displayOutput,delete Z.displayDescription,delete Z.displayPrompt,delete Z.displayPendingInput,delete Z.displayError,Reflect.deleteProperty(Z,"displayOutputArtifact"),Reflect.deleteProperty(Z,"displayPromptArtifact");for(let J of Z.steps)delete J.displayDetail}}function tE(){if(!cE(X2))return[];let $=[];for(let Z of uE(X2).filter((J)=>J.endsWith(".json")).sort()){let J=M5(X2,Z),Q;try{Q=JSON.parse(vP(J,"utf8"))}catch(Y){throw Error(`agent run artifact is unreadable (${J}): ${$$(Y)}`)}if(!rE(Q))throw Error(`agent run artifact is invalid: ${J}`);hP(Q,J),$.push(Q)}return $}function rE($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.runId==="string"&&Z.runId.startsWith("agent_")&&typeof Z.sessionName==="string"&&typeof Z.chatId==="string"&&typeof Z.workDir==="string"&&(Z.owner===void 0||!!Z.owner&&["session","project"].includes(Z.owner.kind)&&Z.owner.name===Z.sessionName&&Z.owner.chatId===Z.chatId&&typeof Z.owner.workDir==="string"&&Z.owner.workDir===Z.sessionWorkDir)&&(Z.resumedFromRunId===void 0||typeof Z.resumedFromRunId==="string")&&(Z.requestId===void 0||typeof Z.requestId==="string"&&typeof Z.requestHash==="string")&&(Z.deliveryMode===void 0||Z.deliveryMode==="chat"||Z.deliveryMode==="drive")&&(Z.sessionWorkDir===void 0||typeof Z.sessionWorkDir==="string")&&typeof Z.prompt==="string"&&(Z.description===void 0||typeof Z.description==="string")&&typeof Z.depth==="number"&&typeof Z.status==="string"&&Array.isArray(Z.workers)&&typeof Z.createdAt==="string"}function yP($){let Z=$.flatMap((J)=>J.status==="rejected"?[J.reason]:[]);return AggregateError(Z,`Agent cancellation failed: ${Z.map($$).join("; ")}`)}function uV($){if($.some((Z)=>Z.status==="rejected"))throw yP($)}function $$($){return $ instanceof Error?$.message:String($)}function eE($){return $?{...$,tools:void 0,strictMcp:!1,loadProjectMcp:!0}:{strictMcp:!1,loadProjectMcp:!0}}function hP($,Z,J=IP){if($.promptArtifact)$.prompt=J($.promptArtifact,`prompt for ${Z}`);for(let Q of $.workers)if(Q.outputArtifact)Q.output=J(Q.outputArtifact,`output for ${Z}`)}function IP($,Z){gP($);try{return vP(M5(X2,$),"utf8")}catch(J){throw Error(`${Z} is unreadable (${$}): ${$$(J)}`)}}function gP($){if(!/^[A-Za-z0-9._-]+$/.test($))throw Error(`invalid Agent artifact name: ${$}`)}var CP=512,xP=50,aE;var mP=R(()=>{sY();rY();Y0();k0();b8();e6();EP();m4();H0();b0();I();aE={...tY,getCatalog:J3,startWorker:TP,sendTextRaw:h,writeArtifact:r,writeTextArtifact:Q$,readTextArtifact:IP,loadArtifacts:tE}});import{randomBytes as $S,timingSafeEqual as ZS}from"node:crypto";function pP($,Z=KX){let J={baseUrl:$,capability:$S(32).toString("base64url")};return r(Z,J),J}function cP($,Z){let J=Buffer.from(Z),Q=Buffer.from($.capability);return J.length===Q.length&&ZS(J,Q)}var uP=R(()=>{H0();b0()});import{realpathSync as JS,statSync as QS}from"node:fs";function lP($,Z=z0){let J=$.trim();if(!J||Z.sanitizeSessionName(J)!==J||_J(J)!==J)throw Error("请指定项目或 worktree 名称,不能指定 BTW/FK 临时会话");let Q=Z.chatIdForSession(J);if(!Q)throw Error(`项目 ${J} 没有明确的群绑定`);let Y=JS(Z.resolveProjectDir(J));if(!QS(Y).isDirectory())throw Error(`项目工作目录不是文件夹: ${Y}`);return{owner:{kind:"project",name:J,chatId:Q,workDir:Y}}}var dP=R(()=>{Y0();m4()});async function iP($,Z,J,Q){if(J.pathname!=="/agents"&&!J.pathname.startsWith("/agents/"))return!1;let Y=(W,K)=>{return Z.statusCode=W,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(K)),!0},V=XS($.headers.authorization);if(!V)return Y(401,{error:"missing bearer capability"});let X;try{let W=J.searchParams.getAll("project");if(W.length>1||W.length&&!W[0].trim())return Y(400,{error:"invalid project selector"});X=W.length?Q.authorizeProject?.(V,W[0])??null:YS(Q,V)}catch(W){return Y(409,{error:nV(W)})}if(!X)return Y(403,{error:"invalid or stale agent capability"});if($.method==="GET"&&J.pathname==="/agents/identities")return Y(200,zS(await dj(q$(X).codexAccountId)));if($.method==="POST"&&J.pathname==="/agents/runs")try{let W=await Q.service.startRun(X,BP(await iV($)));return Y(202,U5(W))}catch(W){return Y(409,{error:nV(W)})}let z=J.pathname.match(/^\/agents\/runs\/([^/]+)(?:\/(follow-up|answer))?$/);if(!z)return Y(405,{error:"unsupported agent endpoint"});let H=VS(z[1]);if(!H)return Y(400,{error:"invalid agent run id encoding"});let G=z[2];try{if(!G&&$.method==="GET")return Y(200,U5(Q.service.getRun(X,H)));if(!G&&$.method==="DELETE"){let W=await Q.service.cancelRun(X,H,"cancelled by agent client");return Y(W?200:409,W?{ok:!0,run_id:H}:{error:"agent run is already terminal",run_id:H})}if(G==="follow-up"&&$.method==="POST"){let W=await Q.service.followUp(X,H,jP(await iV($)));return Y(202,U5(W))}if(G==="answer"&&$.method==="POST"){if(q$(X).owner.kind==="project")return Y(409,{error:Q4});let W=await Q.service.answer(X,H,LP(await iV($)));return Y(200,U5(W))}}catch(W){return Y(409,{error:nV(W)})}return Y(405,{error:"unsupported agent endpoint"})}function YS($,Z){let J=$.authorizeSession(Z);if(J)return $.service.rootPrincipal(J);return $.service.principalForCapability(Z)}function VS($){try{return decodeURIComponent($)}catch{return null}}function XS($){return $?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()??""}async function iV($){let Z="";$.setEncoding("utf8");for await(let J of $)Z+=J;try{return JSON.parse(Z||"{}")}catch{throw Error("bad json")}}function zS($){return{catalog_generation:$.catalogGeneration,identities:$.identities.map((Z)=>({id:Z.id,display_name:Z.displayName,token_source_id:Z.tokenSourceId,token_source_display:Z.tokenSourceDisplay,provider:Z.provider,model:Z.model,model_display:Z.modelDisplay,default_effort:Z.defaultEffort,supported_efforts:Z.supportedEfforts,source_default:Z.sourceDefault,status:Z.status,reason:Z.reason})),source_failures:$.sourceFailures.map((Z)=>({token_source_id:Z.tokenSourceId,display:Z.display,status:Z.status,reason:Z.reason}))}}function U5($){return{run_id:$.runId,binding:L$($).kind,...L$($).kind==="project"?{project:L$($).name}:{session_name:$.sessionName},...$.requestId?{request_id:$.requestId}:{},work_dir:$.workDir,prompt:$.prompt,description:$.description,parent_run_id:$.parentRunId,resumed_from_run_id:$.resumedFromRunId,parent_kind:$.parentKind,depth:$.depth,status:$.status,workers:$.workers.map((Z)=>({identity_id:Z.identityId,identity_name:Z.identityName,token_source_id:Z.tokenSourceId,provider:Z.provider,model:Z.model,effort:Z.effort,status:Z.status,output:Z.output,output_truncated:Z.outputTruncated,session_id:Z.sessionId,checkpoint_id:Z.checkpointId,pending_input:Z.pendingInput&&{request_id:Z.pendingInput.requestId,tool_use_id:Z.pendingInput.toolUseId,questions:Z.pendingInput.questions},queued_reason:Z.queuedReason,steps:Z.steps,error:Z.error,started_at:Z.startedAt,finished_at:Z.finishedAt,duration_ms:Z.durationMs,usage:Z.usage})),created_at:$.createdAt,finished_at:$.finishedAt,error:$.error,presentation_errors:$.presentationErrors,card_message_id:$.cardMessageId}}function nV($){return $ instanceof Error?$.message:String($)}var nP=R(()=>{e6()});import{chmodSync as HS,existsSync as aV,readFileSync as sP,realpathSync as GS,unlinkSync as WS}from"node:fs";import{homedir as KS}from"node:os";import{basename as BS,dirname as jS,join as Y2,resolve as _S}from"node:path";function PS($={}){let Z=GS(_S($.daemonEntry??process.argv[1]??"")),J=$.runtime??process.execPath,Q=$.exists??aV,Y=jS(Z),V=Y2(Y,"src","agent-cli.ts"),X=Y2(Y,"lodestar-agent.js"),z=Y2(Y,"dist","lodestar-agent.js"),G=/^bun(?:\.exe)?$/i.test(BS(J))?[V,X,z]:[X,z],W=G.find(Q);if(!W)throw Error(`lodestar-agent entry not found beside daemon: ${G.join(", ")}`);return{runtime:J,entry:W}}function tP($={}){let Z=$.platform??process.platform,J=$.env??process.env,Q=$.targetDir??qS(Z,$.homeDir??KS(),$.localAppData??process.env.LOCALAPPDATA),Y=$.launch??PS(),V=Y2(Q,Z==="win32"?"lodestar-agent.cmd":"lodestar-agent"),X=Z==="win32"?`@"${oP(Y.runtime)}" "${oP(Y.entry)}" %*\r
636
+ 任务:${$.snapshot.runId}`).catch((V)=>j(`agent: warning delivery failed run=${$.snapshot.runId}: ${$$(V)}`))}}async updateWorkerCard($,Z,J="state"){if($.finalized)return;let Q=$.snapshot.cardMessageId;try{await this.presentation.update($.snapshot,!1,J==="progress")}catch(Y){this.recordPresentationError($,`agent worker card update failed (${Z.identityName}): ${$$(Y)}`)}finally{if($.snapshot.cardMessageId!==Q)this.persist($)}}recordPresentationError($,Z){let J=$.snapshot.presentationErrors??[];if(!J.includes(Z))J.push(Z);$.snapshot.presentationErrors=J,j(`agent: ${Z} run=${$.snapshot.runId}`)}persist($){if(!$.snapshot.promptArtifact)$.snapshot.promptArtifact=`${$.snapshot.runId}.prompt.txt`;this.persistTextArtifact($,$.snapshot.promptArtifact,$.snapshot.prompt);for(let J of $.snapshot.workers){if(!J.output)continue;if(!J.outputArtifact){let Q=SP("sha256").update(J.identityId).digest("hex").slice(0,16);J.outputArtifact=`${$.snapshot.runId}.${Q}.output.txt`}this.persistTextArtifact($,J.outputArtifact,J.output)}let Z=wP($.snapshot);F5(Z),Z.prompt="";for(let J of Z.workers)J.output="";this.deps.writeArtifact(M5(X2,`${$.snapshot.runId}.json`),Z)}persistTextArtifact($,Z,J){if($.persistedArtifacts.has(Z))return;gP(Z),this.deps.writeTextArtifact(M5(X2,Z),J),$.persistedArtifacts.add(Z)}readSnapshot($){let Z=wP($.snapshot);if(F5(Z),$.artifactsUnloaded)hP(Z,Z.runId,this.deps.readTextArtifact);return Z}requireAccessibleRun($,Z){let J=this.runs.get(Z);if(!J||!this.canAccess($,J))throw Error(`agent run not found: ${Z}`);if(this.assertSameOwner(J,q$($)),!J.context)J.context=q$($);return J}assertResumeProject($,Z){let J=q$($).owner,Q=L$(Z.snapshot);if(J.chatId!==Q.chatId||H$(J.workDir)!==H$(Q.workDir))throw Error("agent session belongs to a different project or group; cross-project and cross-group resume is not allowed")}findSessionHistory($,Z){let J=[...this.runs.values()].flatMap((V)=>V.snapshot.workers.filter((X)=>X.sessionId===Z).map((X)=>({run:V,worker:X})));if(!J.length)throw Error("agent session project/group ownership is unknown; only registered sessions in this project and group can be resumed");for(let{run:V}of J)this.assertResumeProject($,V);if(new Set(J.map(({worker:V})=>V.provider)).size>1)throw Error("native session id has conflicting backend records; its unique identity cannot be established");let Q=new Set(J.flatMap(({run:V})=>[V.snapshot.resumedFromRunId,V.snapshot.parentRunId])),Y=J.filter(({run:V})=>!Q.has(V.snapshot.runId)).sort((V,X)=>Date.parse(X.run.snapshot.createdAt)-Date.parse(V.run.snapshot.createdAt))[0];if(!Y)throw Error(`agent session history has no latest run: ${Z}`);return Y}reserveNativeSession($){let Z=JSON.stringify([$.provider,$.sessionId]),J=[...this.runs.values()].some((Q)=>Q.snapshot.workers.some((Y)=>{if(Y.provider!==$.provider||Y.sessionId!==$.sessionId)return!1;let V=Q.handles.get(Y.identityId);return!q5(Y.status)||!!V&&V.isAlive?.()!==!1}));if(this.startingNativeSessions.has(Z)||J)throw Error("agent session is already running or starting; wait for the current turn to finish");return this.startingNativeSessions.add(Z),()=>{this.startingNativeSessions.delete(Z)}}requireMutableDescendant($,Z){let J=this.requireAccessibleRun($,Z);if($.kind==="worker"&&J.snapshot.runId===$.runId)throw Error("worker capability cannot mutate its containing run");return J}canAccess($,Z){let J=L$(Z.snapshot),Q=q$($).owner;if(J.kind!==Q.kind||J.name!==Q.name||J.chatId!==Q.chatId)return!1;if($.kind!=="worker")return!0;let Y=Z;while(Y){if(Y.snapshot.runId===$.runId)return!0;Y=Y.snapshot.parentRunId?this.runs.get(Y.snapshot.parentRunId):void 0}return!1}assertSameOwner($,Z){if(Y4(L$($.snapshot))!==Y4(Z.owner))throw Error("agent run belongs to a different Session or project")}treeHasActiveRun($){if($.pendingChildCreations>0)return!0;if($.handles.size>0)return!0;if(!L5($.snapshot.status))return!0;for(let Z of $.children){let J=this.runs.get(Z);if(J&&this.treeHasActiveRun(J))return!0}return!1}sessionKey($,Z){return`${$}\x00${Z}`}currentCancellationEpoch($){if($.owner.kind==="project")return 0;return this.cancellationEpochBySession.get(this.sessionKey($.owner.name,$.owner.chatId))??0}bumpCancellationEpoch($,Z){let J=this.sessionKey($,Z);this.cancellationEpochBySession.set(J,(this.cancellationEpochBySession.get(J)??0)+1)}loadDurableRuns(){for(let $ of this.deps.loadArtifacts()){if(F5($),!L5($.status)){$.status="failed",$.error="daemon restarted before this Agent run reached a terminal state",$.finishedAt=new Date().toISOString();for(let J of $.workers)if(!q5(J.status))J.status="failed",J.error=$.error,J.finishedAt=$.finishedAt,delete J.pendingInput,delete J.displayPendingInput}let Z={snapshot:$,context:null,handles:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,pendingChildCreations:0,cancelled:$.status==="cancelled",cancellationEpoch:0,finalizing:!1,finalized:!0,artifactsUnloaded:!1,persistedArtifacts:new Set([...$.promptArtifact?[$.promptArtifact]:[],...$.workers.flatMap((J)=>J.outputArtifact?[J.outputArtifact]:[])])};this.runs.set($.runId,Z),this.persist(Z)}for(let $ of this.runs.values())if($.snapshot.parentRunId)this.runs.get($.snapshot.parentRunId)?.children.add($.snapshot.runId);this.pruneRunArtifacts()}pruneRunArtifacts(){if(this.runs.size<=CP)return;let $=[...this.runs.values()].filter((Z)=>!Z.artifactsUnloaded&&Z.finalized&&!Z.finalizing&&L5(Z.snapshot.status)&&Z.handles.size===0).sort((Z,J)=>Date.parse(Z.snapshot.finishedAt??Z.snapshot.createdAt)-Date.parse(J.snapshot.finishedAt??J.snapshot.createdAt));for(let Z of $.slice(0,Math.max(0,$.length-CP))){Z.snapshot.prompt="";for(let J of Z.snapshot.workers)J.output="";F5(Z.snapshot),Z.artifactsUnloaded=!0}}}function lV($,Z){let J=D5($),Q=D5(yP($,Z===void 0?".":P5(Z))),Y=iE(J,Q);if(Y===".."||Y.startsWith(`..${nE}`)||dE(Y))throw Error("agent work_dir must be the main Agent working directory or one of its subdirectories");if(!lE(Q).isDirectory())throw Error(`agent work_dir is not a directory: ${Q}`);return Y===""?$:Q}function bP($,Z){let J=Z===void 0?$:yP($,P5(Z));return lV($,J),J}function oE($,Z,J,Q=!1){return{identityId:$.id,identityName:$.displayName,tokenSourceId:$.tokenSourceId,...Q?{translationEnabled:!0}:{},provider:$.provider,model:$.model,effort:Z,status:"queued",output:"",...J?{sessionId:J}:{},steps:[]}}function sE($,Z){let J=Z??$.defaultEffort;if(!J)throw Error(`${$.displayName} default effort MISS; specify effort explicitly`);if(!$.supportedEfforts.includes(J))throw Error(`${$.displayName} does not support effort ${J}`);return J}function kP($,Z){if(Z){let J=$.workers.find((Q)=>Q.identityId===Z);if(!J)throw Error(`agent identity is not part of run ${$.runId}: ${Z}`);return J}if($.workers.length!==1)throw Error("run has multiple Agents; specify identity_id");return $.workers[0]}function L5($){return $==="completed"||$==="failed"||$==="cancelled"}function q5($){return $==="completed"||$==="failed"||$==="cancelled"}function wP($){return JSON.parse(JSON.stringify($))}function F5($){for(let Z of $.workers){delete Z.translationEnabled,delete Z.displayOutput,delete Z.displayDescription,delete Z.displayPrompt,delete Z.displayPendingInput,delete Z.displayError,Reflect.deleteProperty(Z,"displayOutputArtifact"),Reflect.deleteProperty(Z,"displayPromptArtifact");for(let J of Z.steps)delete J.displayDetail}}function tE(){if(!cE(X2))return[];let $=[];for(let Z of uE(X2).filter((J)=>J.endsWith(".json")).sort()){let J=M5(X2,Z),Q;try{Q=JSON.parse(vP(J,"utf8"))}catch(Y){throw Error(`agent run artifact is unreadable (${J}): ${$$(Y)}`)}if(!rE(Q))throw Error(`agent run artifact is invalid: ${J}`);hP(Q,J),$.push(Q)}return $}function rE($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.runId==="string"&&Z.runId.startsWith("agent_")&&typeof Z.sessionName==="string"&&typeof Z.chatId==="string"&&typeof Z.workDir==="string"&&(Z.owner===void 0||!!Z.owner&&["session","project"].includes(Z.owner.kind)&&Z.owner.name===Z.sessionName&&Z.owner.chatId===Z.chatId&&typeof Z.owner.workDir==="string"&&Z.owner.workDir===Z.sessionWorkDir)&&(Z.resumedFromRunId===void 0||typeof Z.resumedFromRunId==="string")&&(Z.requestId===void 0||typeof Z.requestId==="string"&&typeof Z.requestHash==="string")&&(Z.deliveryMode===void 0||Z.deliveryMode==="chat"||Z.deliveryMode==="drive")&&(Z.sessionWorkDir===void 0||typeof Z.sessionWorkDir==="string")&&typeof Z.prompt==="string"&&(Z.description===void 0||typeof Z.description==="string")&&typeof Z.depth==="number"&&typeof Z.status==="string"&&Array.isArray(Z.workers)&&typeof Z.createdAt==="string"}function fP($){let Z=$.flatMap((J)=>J.status==="rejected"?[J.reason]:[]);return AggregateError(Z,`Agent cancellation failed: ${Z.map($$).join("; ")}`)}function uV($){if($.some((Z)=>Z.status==="rejected"))throw fP($)}function $$($){return $ instanceof Error?$.message:String($)}function eE($){return $?{...$,tools:void 0,strictMcp:!1,loadProjectMcp:!0}:{strictMcp:!1,loadProjectMcp:!0}}function hP($,Z,J=IP){if($.promptArtifact)$.prompt=J($.promptArtifact,`prompt for ${Z}`);for(let Q of $.workers)if(Q.outputArtifact)Q.output=J(Q.outputArtifact,`output for ${Z}`)}function IP($,Z){gP($);try{return vP(M5(X2,$),"utf8")}catch(J){throw Error(`${Z} is unreadable (${$}): ${$$(J)}`)}}function gP($){if(!/^[A-Za-z0-9._-]+$/.test($))throw Error(`invalid Agent artifact name: ${$}`)}var CP=512,xP=50,aE;var mP=R(()=>{sY();rY();Y0();k0();b8();e6();EP();m4();H0();b0();I();aE={...tY,getCatalog:J3,startWorker:TP,sendTextRaw:h,writeArtifact:r,writeTextArtifact:Q$,readTextArtifact:IP,loadArtifacts:tE}});import{randomBytes as $S,timingSafeEqual as ZS}from"node:crypto";function pP($,Z=KX){let J={baseUrl:$,capability:$S(32).toString("base64url")};return r(Z,J),J}function cP($,Z){let J=Buffer.from(Z),Q=Buffer.from($.capability);return J.length===Q.length&&ZS(J,Q)}var uP=R(()=>{H0();b0()});import{realpathSync as JS,statSync as QS}from"node:fs";function lP($,Z=z0){let J=$.trim();if(!J||Z.sanitizeSessionName(J)!==J||_J(J)!==J)throw Error("请指定项目或 worktree 名称,不能指定 BTW/FK 临时会话");let Q=Z.chatIdForSession(J);if(!Q)throw Error(`项目 ${J} 没有明确的群绑定`);let Y=JS(Z.resolveProjectDir(J));if(!QS(Y).isDirectory())throw Error(`项目工作目录不是文件夹: ${Y}`);return{owner:{kind:"project",name:J,chatId:Q,workDir:Y}}}var dP=R(()=>{Y0();m4()});async function iP($,Z,J,Q){if(J.pathname!=="/agents"&&!J.pathname.startsWith("/agents/"))return!1;let Y=(W,K)=>{return Z.statusCode=W,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(K)),!0},V=XS($.headers.authorization);if(!V)return Y(401,{error:"missing bearer capability"});let X;try{let W=J.searchParams.getAll("project");if(W.length>1||W.length&&!W[0].trim())return Y(400,{error:"invalid project selector"});X=W.length?Q.authorizeProject?.(V,W[0])??null:YS(Q,V)}catch(W){return Y(409,{error:nV(W)})}if(!X)return Y(403,{error:"invalid or stale agent capability"});if($.method==="GET"&&J.pathname==="/agents/identities")return Y(200,zS(await dj(q$(X).codexAccountId)));if($.method==="POST"&&J.pathname==="/agents/runs")try{let W=await Q.service.startRun(X,BP(await iV($)));return Y(202,U5(W))}catch(W){return Y(409,{error:nV(W)})}let z=J.pathname.match(/^\/agents\/runs\/([^/]+)(?:\/(follow-up|answer))?$/);if(!z)return Y(405,{error:"unsupported agent endpoint"});let H=VS(z[1]);if(!H)return Y(400,{error:"invalid agent run id encoding"});let G=z[2];try{if(!G&&$.method==="GET")return Y(200,U5(Q.service.getRun(X,H)));if(!G&&$.method==="DELETE"){let W=await Q.service.cancelRun(X,H,"cancelled by agent client");return Y(W?200:409,W?{ok:!0,run_id:H}:{error:"agent run is already terminal",run_id:H})}if(G==="follow-up"&&$.method==="POST"){let W=await Q.service.followUp(X,H,jP(await iV($)));return Y(202,U5(W))}if(G==="answer"&&$.method==="POST"){if(q$(X).owner.kind==="project")return Y(409,{error:Q4});let W=await Q.service.answer(X,H,LP(await iV($)));return Y(200,U5(W))}}catch(W){return Y(409,{error:nV(W)})}return Y(405,{error:"unsupported agent endpoint"})}function YS($,Z){let J=$.authorizeSession(Z);if(J)return $.service.rootPrincipal(J);return $.service.principalForCapability(Z)}function VS($){try{return decodeURIComponent($)}catch{return null}}function XS($){return $?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()??""}async function iV($){let Z="";$.setEncoding("utf8");for await(let J of $)Z+=J;try{return JSON.parse(Z||"{}")}catch{throw Error("bad json")}}function zS($){return{catalog_generation:$.catalogGeneration,identities:$.identities.map((Z)=>({id:Z.id,display_name:Z.displayName,token_source_id:Z.tokenSourceId,token_source_display:Z.tokenSourceDisplay,provider:Z.provider,model:Z.model,model_display:Z.modelDisplay,default_effort:Z.defaultEffort,supported_efforts:Z.supportedEfforts,source_default:Z.sourceDefault,status:Z.status,reason:Z.reason})),source_failures:$.sourceFailures.map((Z)=>({token_source_id:Z.tokenSourceId,display:Z.display,status:Z.status,reason:Z.reason}))}}function U5($){return{run_id:$.runId,binding:L$($).kind,...L$($).kind==="project"?{project:L$($).name}:{session_name:$.sessionName},...$.requestId?{request_id:$.requestId}:{},work_dir:$.workDir,prompt:$.prompt,description:$.description,parent_run_id:$.parentRunId,resumed_from_run_id:$.resumedFromRunId,parent_kind:$.parentKind,depth:$.depth,status:$.status,workers:$.workers.map((Z)=>({identity_id:Z.identityId,identity_name:Z.identityName,token_source_id:Z.tokenSourceId,provider:Z.provider,model:Z.model,effort:Z.effort,status:Z.status,output:Z.output,output_truncated:Z.outputTruncated,session_id:Z.sessionId,checkpoint_id:Z.checkpointId,pending_input:Z.pendingInput&&{request_id:Z.pendingInput.requestId,tool_use_id:Z.pendingInput.toolUseId,questions:Z.pendingInput.questions},queued_reason:Z.queuedReason,steps:Z.steps,error:Z.error,started_at:Z.startedAt,finished_at:Z.finishedAt,duration_ms:Z.durationMs,usage:Z.usage})),created_at:$.createdAt,finished_at:$.finishedAt,error:$.error,presentation_errors:$.presentationErrors,card_message_id:$.cardMessageId}}function nV($){return $ instanceof Error?$.message:String($)}var nP=R(()=>{e6()});import{chmodSync as HS,existsSync as aV,readFileSync as sP,realpathSync as GS,unlinkSync as WS}from"node:fs";import{homedir as KS}from"node:os";import{basename as BS,dirname as jS,join as Y2,resolve as _S}from"node:path";function PS($={}){let Z=GS(_S($.daemonEntry??process.argv[1]??"")),J=$.runtime??process.execPath,Q=$.exists??aV,Y=jS(Z),V=Y2(Y,"src","agent-cli.ts"),X=Y2(Y,"lodestar-agent.js"),z=Y2(Y,"dist","lodestar-agent.js"),G=/^bun(?:\.exe)?$/i.test(BS(J))?[V,X,z]:[X,z],W=G.find(Q);if(!W)throw Error(`lodestar-agent entry not found beside daemon: ${G.join(", ")}`);return{runtime:J,entry:W}}function tP($={}){let Z=$.platform??process.platform,J=$.env??process.env,Q=$.targetDir??qS(Z,$.homeDir??KS(),$.localAppData??process.env.LOCALAPPDATA),Y=$.launch??PS(),V=Y2(Q,Z==="win32"?"lodestar-agent.cmd":"lodestar-agent"),X=Z==="win32"?`@"${oP(Y.runtime)}" "${oP(Y.entry)}" %*\r
637
637
  `:`#!/bin/sh
638
638
  exec ${aP(Y.runtime)} ${aP(Y.entry)} "$@"
639
- `,z=aV(V)?sP(V,"utf8"):null;if(z!==X)lX(V,X),j(`command: ${z===null?"installed":"updated"} ${V}`);else HS(V,448);return DS(J,Q,Z),LS(Q,Z),V}function LS($,Z){let J=Y2($,Z==="win32"?"lodestar-consult.cmd":"lodestar-consult");if(!aV(J))return;try{let Q=sP(J,"utf8");if(!Q.includes("lodestar-consult")&&!Q.includes("consult-cli")){j(`command: obsolete path preserved because ownership is unclear ${J}`);return}WS(J),j(`command: removed obsolete ${J}`)}catch(Q){j(`command: obsolete removal failed (${J}): ${Q}`)}}function qS($,Z,J){if($==="win32")return Y2(J??Y2(Z,"AppData","Local"),"Lodestar","bin");return Y2(Z,".local","bin")}function DS($,Z,J){let Q=J==="win32"?Object.keys($).find((z)=>z.toLowerCase()==="path")??"Path":"PATH",Y=J==="win32"?";":":",V=$[Q]??"",X=(z)=>J==="win32"?z.toLowerCase():z;if(V.split(Y).some((z)=>X(z)===X(Z)))return;$[Q]=V?`${Z}${Y}${V}`:Z}function aP($){return`'${$.replaceAll("'",`'"'"'`)}'`}function oP($){return $.replaceAll('"','""')}var rP=R(()=>{I();b0()});function eP($,Z,J){return $>0&&Z-$>J}async function $L($){if(await $.reply())return!0;if(!$.hasQuestion())return!1;return await $.answerQuestion(),!0}function ZL($){let Z=$==="media"?"视频":$==="image"?"图片":"文件";return`❌ 收到的${Z}下载失败,未转交给 Agent。备注:可能是${Z}超过飞书消息资源 100 MB 下载上限。`}function oV($){return typeof $==="string"&&$.length>0?$:void 0}function JL($,Z){if(!Z||typeof Z!=="object")return null;let J=Z;if($==="image"){let X=oV(J.image_key);return X?{key:X,type:"image",displayText:""}:null}if($!=="file"&&$!=="media")return null;let Q=oV(J.file_key);if(!Q)return null;let Y=oV(J.file_name);return{key:Q,type:"file",...Y?{name:Y}:{},displayText:Y?`(${$==="media"?"video":"file"}: ${Y})`:""}}function QL($,Z){return $.add(Z),Z.then(()=>{$.delete(Z)},()=>{$.delete(Z)}),Z}async function YL($){while(!0){let Z=[...$()];if(Z.length===0)return;await Promise.allSettled(Z)}}class sV{deps;pending=null;shutdownSnapshot=null;revival=null;restartContinuationAttempted=!1;constructor($){this.deps=$}load(){if(this.pending)throw Error("session recovery already loaded");this.pending=new Set(this.deps.readMarker())}transferPending($){if(!this.pending)throw Error("session recovery not loaded");if(!this.pending.has($.sessionName))return;$.requireDaemonRestore(),this.pending.delete($.sessionName)}currentNames(){let $=new Set(this.pending);for(let Z of this.deps.sessions())if(Z.shouldRevive())$.add(Z.sessionName);return[...$]}persist(){if(!this.pending)return;this.deps.writeMarker(this.shutdownSnapshot??this.currentNames())}freezeForShutdown(){if(!this.pending)return;this.shutdownSnapshot??=this.currentNames(),this.persist()}enqueue(){if(!this.pending)throw Error("session recovery not loaded");if(this.revival)return this.revival;if(this.deps.isShuttingDown())return Promise.resolve();let $=[...this.pending];return this.deps.log(`revive: ${$.length} session(s) marked alive on shutdown: ${$.join(", ")}`),this.revival=Promise.all($.map((Z)=>{let J=this.deps.chatIdForSession(Z);if(!J)return this.deps.log(`revive: no chatId binding for "${Z}"; recovery remains pending`),Promise.resolve();return this.deps.actor.enqueue(J,async()=>{if(this.deps.isShuttingDown())return;let Q;try{Q=this.deps.sessionFor(J,Z);let Y=await Q.restoreAfterDaemonRestart();this.deps.log(`revive: "${Z}" ${Y?"restored":"did not start"}`);let V=this.deps.restartContinuation;if(Y&&!this.deps.isShuttingDown()&&!this.restartContinuationAttempted&&V?.chatId===J){this.restartContinuationAttempted=!0;try{await V.send(Q),this.deps.log(`revive: restart continuation for "${Z}" submitted`)}catch(X){this.deps.log(`revive: restart continuation for "${Z}" failed: ${X}`)}}}catch(Y){this.deps.log(`revive: restore "${Z}" failed: ${Y}`)}finally{if(Q)this.pending.delete(Z);this.persist()}})})).then(()=>{}),this.revival}}function C1($){return $ instanceof Error?$.message:String($)}function VL($,Z,J){if(!J.disbanded||!J.chatId)throw Error(`飞书未确认删除临时群 "${$}"`);if(Z&&J.chatId!==Z)throw Error(`飞书删除结果 chat_id 不匹配: expected=${Z} actual=${J.chatId}`);return J.chatId}function XL($){let Z=(Y,V)=>{let X=$.registry.get(Y);if(X&&X.sessionName!==V)throw Error(`chat ${Y} is already owned by session "${X.sessionName}", not "${V}"`);if(!X)X=$.createSession(V,Y),$.registry.set(Y,X);return X};return{sessionFor:Z,createTempSession:async(Y)=>{let V;try{if(E0(Y.launch,Y.routing.provider,Y.workDir),Y.launch.kind==="resume")throw Error("temporary groups must start fresh or fork; resume is not allowed");if(V=await $.ensureChatForSession(Y.chatName,Y.userOpenId),!V.created)return{ok:!1,chatId:V.chatId,error:"临时会话必须使用新群;既有群保留,未执行加入、启动或删除"}}catch(z){let H=C1(z);return $.log(`temp-session: create "${Y.chatName}" failed: ${H}`),{ok:!1,error:H}}let X=async()=>{let z=null;try{if($.registerTempSessionLease(Y.chatName,V.chatId),z=Z(V.chatId,Y.chatName),z.isRunning())return{ok:!1,error:`${Y.chatName} 已有会话在跑,先 bye 解散再重试`};if(z.workDir!==Y.workDir)throw Error(`临时群 cwd 不匹配: source=${Y.workDir} target=${z.workDir}`);if(z.applyConversationRouting(Y.routing),!(Y.launch.kind==="fork"?await z.startForked(Y.launch,{announce:!1}):await z.start({announce:!1})))throw Error(`${z.backendLabel()} 启动失败`);return $.replaceTurnAnchors(Y.chatName,Y.seedAnchors??[],Y.branchBase),{ok:!0,chatId:V.chatId}}catch(H){let G=C1(H);if($.log(`temp-session: initialize "${Y.chatName}" failed: ${G}`),z)try{await z.stop("临时群启动失败清理",{announce:!1})}catch(K){let B=C1(K);return $.log(`temp-session: failed-create stop "${Y.chatName}" failed: ${B}`),{ok:!1,chatId:V.chatId,error:`${G};无法确认 Session 已停止,临时群/session 仍保留: ${B}`}}if(!V.created)return{ok:!1,error:`${G};既有群保留,未执行删除`};let W;try{let K=await $.disbandChatForSessionExact(Y.chatName,V.chatId);W=VL(Y.chatName,V.chatId,K)}catch(K){let B=C1(K);return $.log(`temp-session: create cleanup "${Y.chatName}" failed: ${B}`),{ok:!1,chatId:V.chatId,error:`${G};自动解散失败,临时群/session 仍保留: ${B}`}}try{$.registry.delete(W),z?.dispose(),$.clearSessionConversationState(Y.chatName)}catch(K){let B=C1(K);return $.log(`temp-session: local cleanup "${Y.chatName}" failed: ${B}`),{ok:!1,error:`${G};临时群已确认解散,但本地状态清理失败: ${B}`}}return{ok:!1,error:`${G};本次新建的临时群已确认解散`}}};try{return $.runExclusive?await $.runExclusive(V.chatId,X):await X()}catch(z){let H=C1(z);return $.log(`temp-session: target actor "${Y.chatName}" failed: ${H}`),{ok:!1,chatId:V.chatId,error:`${H};临时群/session 仍保留`}}},disbandTempSession:async(Y,V)=>{let X=$.chatIdForSession(Y);if(!V||X!==V){let G=`临时群 chat_id 已变化: expected=${V||"-"} bound=${X??"-"}`;return $.log(`temp-session: disband identity rejected "${Y}": ${G}`),{ok:!1,error:`${G};未执行停止或删群`}}if(!$.hasTempSessionLease(Y,V)){let G=`群 ${V} 没有 Lodestar 临时会话 lease,拒绝解散`;return $.log(`temp-session: disband lease rejected "${Y}": ${G}`),{ok:!1,error:`${G};未执行停止或删群`}}let z=$.registry.get(X);try{if(z)await z.stop("bye 解散",{announce:!1})}catch(G){let W=C1(G);return $.log(`temp-session: stop before disband "${Y}" failed: ${W}`),{ok:!1,error:`${W};无法确认 Session 已停止,未执行删群`}}let H;try{let G=await $.disbandChatForSessionExact(Y,X);H=VL(Y,X,G)}catch(G){let W=C1(G);return $.log(`temp-session: disband "${Y}" failed: ${W}`),{ok:!1,error:`${W};临时群/session 仍保留`}}try{return $.registry.delete(H),z?.dispose(),$.clearSessionConversationState(Y),{ok:!0}}catch(G){let W=C1(G);return $.log(`temp-session: local cleanup after disband "${Y}" failed: ${W}`),{ok:!1,error:`临时群已确认解散,但本地状态清理失败: ${W}`}}}}}var zL=R(()=>{K2()});var mS={};import*as A9 from"@larksuiteoapi/node-sdk";import{chmodSync as FS,existsSync as rV,mkdirSync as MS,readFileSync as US,unlinkSync as N5,writeFileSync as OS}from"node:fs";import{dirname as AS}from"node:path";function N9($,Z){if(V2=Math.max(V2,Z),O5)return O5;Z$=!0,Wz();let J=l9.stop().then((Q)=>({status:"fulfilled",value:Q}),(Q)=>({status:"rejected",reason:Q}));KL?.(),x1.close();for(let Q of x$.values())Q.closeModelSettingsChanges();try{BL?.()}catch(Q){V2=1,j(`shutdown WebSocket close failed: ${Q}`)}try{X4.persist()}catch(Q){j(`shutdown alive marker write failed: ${Q}`),V2=1}return O5=(async()=>{j(`${$}: staged shutdown begin sessions=${x$.size}`);try{let Q=(async()=>{await YL(()=>[...x1.pending(),..._L,...WK()]),X4.freezeForShutdown();let z=await Promise.allSettled([O9.shutdown(`daemon ${$}`),v2.shutdown()]),H=await Promise.allSettled([RQ()]),G=await Promise.allSettled([...x$.values()].map((W)=>W.stop(`daemon ${$}`,{announce:!1})));return[await J,...z,...H,...G]})(),Y=null,V=new Promise((z)=>{Y=setTimeout(()=>z("deadline"),GL)}),X=await Promise.race([Q.then((z)=>{for(let H of z)if(H.status==="rejected")V2=1,j(`shutdown session stop failed: ${H.reason}`);return"stopped"}),V]);if(Y)clearTimeout(Y);if(X==="deadline")V2=1,j(`${$}: shutdown deadline ${GL}ms reached; forcing exit`);else j(`${$}: all sessions stopped`)}catch(Q){j(`${$}: staged shutdown failed: ${Q}`),V2=1}finally{jL(),process.exit(V2)}})(),O5}function eV($){return QL(_L,$)}function PL($,Z="ws"){if(Z$)return j(`${Z}: reject inbound message: daemon shutdown in progress`),!1;let J=String($?.message?.chat_id??""),Q=RS.accept($);if(!Q.accepted)return j(`${Z}: reject inbound message${J?"":" without chat_id"}: actor ${Q.reason}`),!1;return Q.completion.catch((Y)=>{j(`${Z}: handleMessage rejected chat=${J.slice(0,8)}…: ${Y}`)}),!0}function TS(){X4.persist()}function LL($,Z){return $X.sessionFor($,Z)}async function ES($){return await $X.createTempSession($)}async function SS($,Z){return await $X.disbandTempSession($,Z)}function CS($){let Z=[],J=[],Q=[],Y=typeof $?.title==="string"?$.title.trim():"";if(Y)Q.push(`# ${Y}`);let V=Array.isArray($?.content)?$.content:[];for(let X of V){if(!Array.isArray(X))continue;let z=[];for(let G of X){if(!G||typeof G!=="object")continue;switch(G.tag){case"text":{let W=String(G.text??""),K=Array.isArray(G.style)?G.style:[];if(K.includes("bold"))W=`**${W}**`;if(K.includes("italic"))W=`*${W}*`;if(K.includes("lineThrough")||K.includes("strikethrough"))W=`~~${W}~~`;z.push(W);break}case"a":{let W=String(G.href??""),K=String(G.text??W);z.push(`[${K}](${W})`);break}case"at":{let W=String(G.user_name??G.user_id??"");z.push(`@${W}`);break}case"code_inline":z.push(`\`${String(G.text??"")}\``);break;case"hr":z.push("---");break;case"img":if(G.image_key)Z.push(String(G.image_key));break;case"media":if(G.file_key)J.push({key:String(G.file_key),name:G.file_name});break;case"emotion":break;default:if(typeof G.text==="string")z.push(G.text)}}let H=z.join("");if(H.trim())Q.push(H)}return{markdown:Q.join(`
639
+ `,z=aV(V)?sP(V,"utf8"):null;if(z!==X)lX(V,X),j(`command: ${z===null?"installed":"updated"} ${V}`);else HS(V,448);return FS(J,Q,Z),LS(Q,Z),V}function LS($,Z){let J=Y2($,Z==="win32"?"lodestar-consult.cmd":"lodestar-consult");if(!aV(J))return;try{let Q=sP(J,"utf8");if(!Q.includes("lodestar-consult")&&!Q.includes("consult-cli")){j(`command: obsolete path preserved because ownership is unclear ${J}`);return}WS(J),j(`command: removed obsolete ${J}`)}catch(Q){j(`command: obsolete removal failed (${J}): ${Q}`)}}function qS($,Z,J){if($==="win32")return Y2(J??Y2(Z,"AppData","Local"),"Lodestar","bin");return Y2(Z,".local","bin")}function FS($,Z,J){let Q=J==="win32"?Object.keys($).find((z)=>z.toLowerCase()==="path")??"Path":"PATH",Y=J==="win32"?";":":",V=$[Q]??"",X=(z)=>J==="win32"?z.toLowerCase():z;if(V.split(Y).some((z)=>X(z)===X(Z)))return;$[Q]=V?`${Z}${Y}${V}`:Z}function aP($){return`'${$.replaceAll("'",`'"'"'`)}'`}function oP($){return $.replaceAll('"','""')}var rP=R(()=>{I();b0()});function eP($,Z,J){return $>0&&Z-$>J}async function $L($){if(await $.reply())return!0;if(!$.hasQuestion())return!1;return await $.answerQuestion(),!0}function ZL($){let Z=$==="media"?"视频":$==="image"?"图片":"文件";return`❌ 收到的${Z}下载失败,未转交给 Agent。备注:可能是${Z}超过飞书消息资源 100 MB 下载上限。`}function oV($){return typeof $==="string"&&$.length>0?$:void 0}function JL($,Z){if(!Z||typeof Z!=="object")return null;let J=Z;if($==="image"){let X=oV(J.image_key);return X?{key:X,type:"image",displayText:""}:null}if($!=="file"&&$!=="media")return null;let Q=oV(J.file_key);if(!Q)return null;let Y=oV(J.file_name);return{key:Q,type:"file",...Y?{name:Y}:{},displayText:Y?`(${$==="media"?"video":"file"}: ${Y})`:""}}function QL($,Z){return $.add(Z),Z.then(()=>{$.delete(Z)},()=>{$.delete(Z)}),Z}async function YL($){while(!0){let Z=[...$()];if(Z.length===0)return;await Promise.allSettled(Z)}}class sV{deps;pending=null;shutdownSnapshot=null;revival=null;restartContinuationAttempted=!1;constructor($){this.deps=$}load(){if(this.pending)throw Error("session recovery already loaded");this.pending=new Set(this.deps.readMarker())}transferPending($){if(!this.pending)throw Error("session recovery not loaded");if(!this.pending.has($.sessionName))return;$.requireDaemonRestore(),this.pending.delete($.sessionName)}currentNames(){let $=new Set(this.pending);for(let Z of this.deps.sessions())if(Z.shouldRevive())$.add(Z.sessionName);return[...$]}persist(){if(!this.pending)return;this.deps.writeMarker(this.shutdownSnapshot??this.currentNames())}freezeForShutdown(){if(!this.pending)return;this.shutdownSnapshot??=this.currentNames(),this.persist()}enqueue(){if(!this.pending)throw Error("session recovery not loaded");if(this.revival)return this.revival;if(this.deps.isShuttingDown())return Promise.resolve();let $=[...this.pending];return this.deps.log(`revive: ${$.length} session(s) marked alive on shutdown: ${$.join(", ")}`),this.revival=Promise.all($.map((Z)=>{let J=this.deps.chatIdForSession(Z);if(!J)return this.deps.log(`revive: no chatId binding for "${Z}"; recovery remains pending`),Promise.resolve();return this.deps.actor.enqueue(J,async()=>{if(this.deps.isShuttingDown())return;let Q;try{Q=this.deps.sessionFor(J,Z);let Y=await Q.restoreAfterDaemonRestart();this.deps.log(`revive: "${Z}" ${Y?"restored":"did not start"}`);let V=this.deps.restartContinuation;if(Y&&!this.deps.isShuttingDown()&&!this.restartContinuationAttempted&&V?.chatId===J){this.restartContinuationAttempted=!0;try{await V.send(Q),this.deps.log(`revive: restart continuation for "${Z}" submitted`)}catch(X){this.deps.log(`revive: restart continuation for "${Z}" failed: ${X}`)}}}catch(Y){this.deps.log(`revive: restore "${Z}" failed: ${Y}`)}finally{if(Q)this.pending.delete(Z);this.persist()}})})).then(()=>{}),this.revival}}function C1($){return $ instanceof Error?$.message:String($)}function VL($,Z,J){if(!J.disbanded||!J.chatId)throw Error(`飞书未确认删除临时群 "${$}"`);if(Z&&J.chatId!==Z)throw Error(`飞书删除结果 chat_id 不匹配: expected=${Z} actual=${J.chatId}`);return J.chatId}function XL($){let Z=(Y,V)=>{let X=$.registry.get(Y);if(X&&X.sessionName!==V)throw Error(`chat ${Y} is already owned by session "${X.sessionName}", not "${V}"`);if(!X)X=$.createSession(V,Y),$.registry.set(Y,X);return X};return{sessionFor:Z,createTempSession:async(Y)=>{let V;try{if(E0(Y.launch,Y.routing.provider,Y.workDir),Y.launch.kind==="resume")throw Error("temporary groups must start fresh or fork; resume is not allowed");if(V=await $.ensureChatForSession(Y.chatName,Y.userOpenId),!V.created)return{ok:!1,chatId:V.chatId,error:"临时会话必须使用新群;既有群保留,未执行加入、启动或删除"}}catch(z){let H=C1(z);return $.log(`temp-session: create "${Y.chatName}" failed: ${H}`),{ok:!1,error:H}}let X=async()=>{let z=null;try{if($.registerTempSessionLease(Y.chatName,V.chatId),z=Z(V.chatId,Y.chatName),z.isRunning())return{ok:!1,error:`${Y.chatName} 已有会话在跑,先 bye 解散再重试`};if(z.workDir!==Y.workDir)throw Error(`临时群 cwd 不匹配: source=${Y.workDir} target=${z.workDir}`);if(z.applyConversationRouting(Y.routing),!(Y.launch.kind==="fork"?await z.startForked(Y.launch,{announce:!1}):await z.start({announce:!1})))throw Error(`${z.backendLabel()} 启动失败`);return $.replaceTurnAnchors(Y.chatName,Y.seedAnchors??[],Y.branchBase),{ok:!0,chatId:V.chatId}}catch(H){let G=C1(H);if($.log(`temp-session: initialize "${Y.chatName}" failed: ${G}`),z)try{await z.stop("临时群启动失败清理",{announce:!1})}catch(K){let B=C1(K);return $.log(`temp-session: failed-create stop "${Y.chatName}" failed: ${B}`),{ok:!1,chatId:V.chatId,error:`${G};无法确认 Session 已停止,临时群/session 仍保留: ${B}`}}if(!V.created)return{ok:!1,error:`${G};既有群保留,未执行删除`};let W;try{let K=await $.disbandChatForSessionExact(Y.chatName,V.chatId);W=VL(Y.chatName,V.chatId,K)}catch(K){let B=C1(K);return $.log(`temp-session: create cleanup "${Y.chatName}" failed: ${B}`),{ok:!1,chatId:V.chatId,error:`${G};自动解散失败,临时群/session 仍保留: ${B}`}}try{$.registry.delete(W),z?.dispose(),$.clearSessionConversationState(Y.chatName)}catch(K){let B=C1(K);return $.log(`temp-session: local cleanup "${Y.chatName}" failed: ${B}`),{ok:!1,error:`${G};临时群已确认解散,但本地状态清理失败: ${B}`}}return{ok:!1,error:`${G};本次新建的临时群已确认解散`}}};try{return $.runExclusive?await $.runExclusive(V.chatId,X):await X()}catch(z){let H=C1(z);return $.log(`temp-session: target actor "${Y.chatName}" failed: ${H}`),{ok:!1,chatId:V.chatId,error:`${H};临时群/session 仍保留`}}},disbandTempSession:async(Y,V)=>{let X=$.chatIdForSession(Y);if(!V||X!==V){let G=`临时群 chat_id 已变化: expected=${V||"-"} bound=${X??"-"}`;return $.log(`temp-session: disband identity rejected "${Y}": ${G}`),{ok:!1,error:`${G};未执行停止或删群`}}if(!$.hasTempSessionLease(Y,V)){let G=`群 ${V} 没有 Lodestar 临时会话 lease,拒绝解散`;return $.log(`temp-session: disband lease rejected "${Y}": ${G}`),{ok:!1,error:`${G};未执行停止或删群`}}let z=$.registry.get(X);try{if(z)await z.stop("bye 解散",{announce:!1})}catch(G){let W=C1(G);return $.log(`temp-session: stop before disband "${Y}" failed: ${W}`),{ok:!1,error:`${W};无法确认 Session 已停止,未执行删群`}}let H;try{let G=await $.disbandChatForSessionExact(Y,X);H=VL(Y,X,G)}catch(G){let W=C1(G);return $.log(`temp-session: disband "${Y}" failed: ${W}`),{ok:!1,error:`${W};临时群/session 仍保留`}}try{return $.registry.delete(H),z?.dispose(),$.clearSessionConversationState(Y),{ok:!0}}catch(G){let W=C1(G);return $.log(`temp-session: local cleanup after disband "${Y}" failed: ${W}`),{ok:!1,error:`临时群已确认解散,但本地状态清理失败: ${W}`}}}}}var zL=R(()=>{K2()});var mS={};import*as A9 from"@larksuiteoapi/node-sdk";import{chmodSync as DS,existsSync as rV,mkdirSync as MS,readFileSync as US,unlinkSync as N5,writeFileSync as OS}from"node:fs";import{dirname as AS}from"node:path";function N9($,Z){if(V2=Math.max(V2,Z),O5)return O5;Z$=!0,Wz();let J=l9.stop().then((Q)=>({status:"fulfilled",value:Q}),(Q)=>({status:"rejected",reason:Q}));KL?.(),x1.close();for(let Q of x$.values())Q.closeModelSettingsChanges();try{BL?.()}catch(Q){V2=1,j(`shutdown WebSocket close failed: ${Q}`)}try{X4.persist()}catch(Q){j(`shutdown alive marker write failed: ${Q}`),V2=1}return O5=(async()=>{j(`${$}: staged shutdown begin sessions=${x$.size}`);try{let Q=(async()=>{await YL(()=>[...x1.pending(),..._L,...WK()]),X4.freezeForShutdown();let z=await Promise.allSettled([O9.shutdown(`daemon ${$}`),v2.shutdown()]),H=await Promise.allSettled([RQ()]),G=await Promise.allSettled([...x$.values()].map((W)=>W.stop(`daemon ${$}`,{announce:!1})));return[await J,...z,...H,...G]})(),Y=null,V=new Promise((z)=>{Y=setTimeout(()=>z("deadline"),GL)}),X=await Promise.race([Q.then((z)=>{for(let H of z)if(H.status==="rejected")V2=1,j(`shutdown session stop failed: ${H.reason}`);return"stopped"}),V]);if(Y)clearTimeout(Y);if(X==="deadline")V2=1,j(`${$}: shutdown deadline ${GL}ms reached; forcing exit`);else j(`${$}: all sessions stopped`)}catch(Q){j(`${$}: staged shutdown failed: ${Q}`),V2=1}finally{jL(),process.exit(V2)}})(),O5}function eV($){return QL(_L,$)}function PL($,Z="ws"){if(Z$)return j(`${Z}: reject inbound message: daemon shutdown in progress`),!1;let J=String($?.message?.chat_id??""),Q=RS.accept($);if(!Q.accepted)return j(`${Z}: reject inbound message${J?"":" without chat_id"}: actor ${Q.reason}`),!1;return Q.completion.catch((Y)=>{j(`${Z}: handleMessage rejected chat=${J.slice(0,8)}…: ${Y}`)}),!0}function TS(){X4.persist()}function LL($,Z){return $X.sessionFor($,Z)}async function ES($){return await $X.createTempSession($)}async function SS($,Z){return await $X.disbandTempSession($,Z)}function CS($){let Z=[],J=[],Q=[],Y=typeof $?.title==="string"?$.title.trim():"";if(Y)Q.push(`# ${Y}`);let V=Array.isArray($?.content)?$.content:[];for(let X of V){if(!Array.isArray(X))continue;let z=[];for(let G of X){if(!G||typeof G!=="object")continue;switch(G.tag){case"text":{let W=String(G.text??""),K=Array.isArray(G.style)?G.style:[];if(K.includes("bold"))W=`**${W}**`;if(K.includes("italic"))W=`*${W}*`;if(K.includes("lineThrough")||K.includes("strikethrough"))W=`~~${W}~~`;z.push(W);break}case"a":{let W=String(G.href??""),K=String(G.text??W);z.push(`[${K}](${W})`);break}case"at":{let W=String(G.user_name??G.user_id??"");z.push(`@${W}`);break}case"code_inline":z.push(`\`${String(G.text??"")}\``);break;case"hr":z.push("---");break;case"img":if(G.image_key)Z.push(String(G.image_key));break;case"media":if(G.file_key)J.push({key:String(G.file_key),name:G.file_name});break;case"emotion":break;default:if(typeof G.text==="string")z.push(G.text)}}let H=z.join("");if(H.trim())Q.push(H)}return{markdown:Q.join(`
640
640
 
641
- `),imageKeys:Z,fileKeys:J}}async function bS($,Z=Date.now()){let J=$?.message;if(!J)return;let Y=($?.sender?.sender_id??$?.event?.sender?.sender_id??J?.sender?.sender_id)?.open_id??"",V=J.message_id;if(V&&U9.has(V))return;if(V){if(U9.add(V),U9.size>200){let U=[...U9];U9.clear();for(let A of U.slice(-100))U9.add(A)}}let X=Number(J.create_time??0);if(eP(X,Z,xS)){if(j(`drop stale message ${V} ageAtReceipt=${Math.round((Z-X)/1000)}s`),V)K$(V,"CrossMark");return}let z=J.chat_id,H={};try{H=JSON.parse(J.content??"{}")}catch{}let G=J.message_type==="text"?H.text??"":"";if(typeof G==="string"&&G.startsWith("[DEBUG]")){try{OS(j3,JSON.stringify({chat_id:z,sender_open_id:Y,seeded_at:new Date().toISOString(),seeded_msg_id:V??""},null,2)),j(`debug: seeded inject context chat=${z.slice(0,8)}… sender=${Y.slice(0,8)}…`)}catch(A){j(`debug: seed context failed: ${A}`)}let U=G.slice(7);H.text=U,J.content=JSON.stringify(H)}let W=O0.get(z);if(!W)await K8(),W=O0.get(z);if(!W)W=await iJ(z)??void 0;if(!W){j(`unknown chat ${z}, dropping message`),await k(z,"❌ 无法识别群名。请确认:① 机器人已被拉进本群;② 群已设置名称(未命名群拿不到群名,无法映射项目目录)。设置后再发一条消息即可。");return}let K=sJ(W);p4(K,z);let B=LL(z,K),_={};try{_=JSON.parse(J.content??"{}")}catch{}let P=J.message_type,L="",q=!1,D=[];if(P==="text")L=(_.text??"").trim();else if(P==="post"){let U=CS(_);q=U.imageKeys.length>0||U.fileKeys.length>0,L=U.markdown.trim();for(let A of U.imageKeys){let O=await B8(J.message_id,A,"image");if(O)D.push(O)}for(let A of U.fileKeys){let O=await B8(J.message_id,A.key,"file",A.name);if(O)D.push(O)}}if(P==="text"&&L){if(await B.runCommand(L,Y,V))return}if((P==="text"||P==="post")&&L&&!q&&await $L({reply:()=>R5.consume({chatId:z,openId:Y,messageId:V??"",text:L,createTime:X,parentId:J.parent_id}),hasQuestion:()=>B.hasPendingAsk(),answerQuestion:()=>B.onAskMessageAnswer(L,Y,V??"")}))return;if(P==="text"&&L&&await B.consumeModelCustomMessage(L,Y))return;let M=JL(P,_);if(M){let U=await B8(J.message_id,M.key,M.type,M.name);if(!U){await k(z,ZL(P));return}if(D.push(U),!L&&M.displayText)L=M.displayText}if(!L&&D.length===0){j(`drop empty message ${V} type=${P}`);return}if(await B.onMultiMessageInbound(L,D,Y,V??""))return;await B.onUserMessage(L||"(empty)",D,Y,V??"")}function T5($){return{permission:"权限决定",menu:"菜单选择",provider_select:"账号选择",model_page:"模型翻页",model_list_open:"模型列表",model_add:"显示模型",model_remove:"隐藏模型",model_custom_remove:"删除补录模型",model_select:"模型选择",model_custom_prompt:"模型补录",model_panel_cancel:"取消模型补录",model_effort_select:"模型 effort 选择",ask:"问题回答",worktree_disband:"worktree 解散",temp_fork_select:"会话分叉",temp_back_select:"会话回滚",temp_resume_select:"会话恢复",tasklist_enable:"启用任务清单",tasklist_delete_prompt:"删除任务清单",tasklist_delete_confirm:"确认删除任务清单",token_source_enable:"启用账号",agent_identity_page:"Agent 身份翻页",notify_callback:"通知反馈",notify_reply:"通知回复",notify_reply_cancel:"取消通知回复",agent_project_cancel:"停止项目任务"}[$]??$}function kS($){return $?.card?.type==="raw"&&$.card.data&&typeof $.card.data==="object"?$.card.data:null}function _0($,Z,J){return{...$,__businessOk:Z,...J?{__businessMessage:J}:{}}}function X1($,Z){return{...Z,__cardActionMessageId:$.messageId,__cardActionChatId:$.chatId}}function z1($){let Z=_0($.card?C$($.card):{toast:{type:$.ok?"success":"error",content:$.message}},$.ok,$.pending?void 0:$.message);if($.completion)Z.__modelActionCompletion=$.completion;return Z}async function V4($,Z){if(!$){j(`card-action: cannot send receipt without chat_id: ${Z}`);return}if(!await h($,Z))j(`card-action: visible receipt MISS chat=${$.slice(0,8)}… text=${Z.slice(0,120)}`)}async function WL($,Z){if(Z?.__cardActionPresented)return;let J=String($?.action?.value?.kind??"unknown"),Q=T5(J),Y=String(Z?.__cardActionChatId??$?.__cardActionChatId??$?.context?.open_chat_id??""),V=String(Z?.__cardActionMessageId??$?.context?.open_message_id??""),X=kS(Z),z=Z?.__businessOk===!1&&typeof Z?.__businessMessage==="string"?` 业务失败: ${Z.__businessMessage.replace(/\s+/g," ").trim().slice(0,300)}。`:"";if(X&&V)try{await n4(V,X);return}catch(_){j(`card-action: ${J} original-card update failed: ${_ instanceof Error?_.message:_}`),await V4(Y,`⚠️ ${Q}已处理,但原卡更新失败。${z}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":"请重新打开操作面板。"}`);return}if(X){await V4(Y,`⚠️ ${Q}已处理,但回调缺少原卡 message_id,无法更新。${z}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":""}`);return}if(J==="notify_callback"&&Z?.__cardActionCompletion)return;let H=Z?.toast,G=typeof H?.content==="string"&&H.content.trim()?H.content.trim():`${Q}已完成`,W=J==="permission"&&String($?.action?.value?.decision??"")==="deny",K=Z?.__businessOk===!1||H?.type==="error"&&!W;if(!K&&new Set(["permission","ask","token_source_enable"]).has(J))return;await V4(Y,`${K?"❌":"✅"} ${Q}: ${G}`)}async function wS($,Z){let J=String($?.action?.value?.kind??"unknown"),Q=Z instanceof Error?Z.message:String(Z);await V4(String($?.__cardActionChatId??$?.context?.open_chat_id??""),`❌ ${T5(J)}失败: ${Q}`)}function qL($){return vS.accept($)}async function fS($){let Z=$?.action,J=Z?.value;if(!J?.kind)return;let Q=$?.context?.open_chat_id??"",Y=$?.operator?.open_id??"";if(J.kind==="agent_project_cancel"){let X=await O9.cancelProjectRunFromCard(String(J.run_id??""),Q,String($?.context?.open_message_id??""),Y);return _0({toast:{type:"success",content:X?"项目任务已停止":"项目任务已结束"}},!0)}if(J.kind==="notify_callback"||J.kind==="notify_reply"||J.kind==="notify_reply_cancel"){let X=String(J.notify_id??""),z=R1(X);if(z)$.__cardActionChatId=z.chatId;if(J.kind==="notify_callback")return await yS(J,Q,Y);let H=J.kind==="notify_reply"?await R5.open(X,Q,Y):await R5.cancel(X,String(J.reply_id??""),Q,Y),G=_0({toast:{type:H.ok?"success":"error",content:H.message},__cardActionPresented:H.presented===!0},H.ok);return z?X1(z,G):G}let V=x$.get(Q);if(!V)return _0({toast:{type:"error",content:"会话不存在,请先发消息启动"}},!1);switch(J.kind){case"permission":{let X=String(J.decision??"");if(!["allow","allow_always","deny"].includes(X))return{toast:{type:"error",content:"无效的权限决定"}};let z=await V.onPermissionDecision(J.request_id,X,Y);return _0({toast:{type:z.ok?X==="deny"?"error":"success":"error",content:z.message}},z.ok)}case"menu":{let X=Number(J.choice??-1);try{if(!Number.isInteger(X)||X<0)throw Error("无效的菜单选项");return await V.onUserMessage(`(menu choice ${X+1})`),_0(C$(t1({title:"\uD83D\uDCCB 菜单选择",message:`已选择第 ${X+1} 项`,ok:!0})),!0)}catch(z){let H=z instanceof Error?z.message:String(z);return _0(C$(t1({title:"\uD83D\uDCCB 菜单选择",message:H,ok:!1})),!1)}}case"provider_select":{let X=await V.onProviderSelect(String(J.source_id??""),String(J.panel_id??""));return z1(X)}case"model_page":{let X=await V.onModelPage(String(J.panel_id??""),String(J.source_id??""),Number(J.page));return z1(X)}case"model_list_open":{let X=String(J.panel_id??""),z=String(J.source_id??"");if(J.mode!=="add"&&J.mode!=="select")throw Error("模型管理模式无效");return z1(await(J.mode==="add"?V.onModelAddOpen(X,z):V.onProviderSelect(z,X)))}case"model_add":case"model_remove":case"model_custom_remove":return z1(await V.onModelListEdit(String(J.panel_id??""),String(J.source_id??""),String(J.model??""),J.kind==="model_add"?"add":J.kind==="model_remove"?"remove":"delete"));case"model_select":{let X=await V.onModelSelect(String(J.model??""),String(J.panel_id??""),Y,J);return z1(X)}case"model_custom_prompt":{let X=await V.onModelCustomPrompt(String(J.source_id??""),String(J.panel_id??""),String($?.context?.open_message_id??""));return z1(X)}case"model_panel_cancel":{let X=await V.onModelPanelCancel(String(J.panel_id??""));return z1(X)}case"model_effort_select":{let X=await V.onModelEffortSelect(String(J.model??""),String(J.effort??""),String(J.panel_id??""),Y,String(J.provider??""));return z1(X)}case"ask":{let X=V.askBlockReason(String(J.tool_use_id??""));if(X)return _0({toast:{type:"error",content:X}},!1);if(J.custom){let G=(Z?.form_value??Z?.input??{})?.custom_answer??Z?.input_value??"",W=await V.onAskCustomAnswer(J.tool_use_id,J.question_idx??0,G,Y);return _0({toast:{type:W?"success":"error",content:W?"已回答":G.trim()?"问题已失效或答案未被接受":"请输入答案"}},W)}let z=await V.onAskAnswer(J.tool_use_id,J.question_idx??0,J.option_idx,Y);return _0({toast:{type:z?"success":"error",content:z?"已回答":"问题已失效或选项无效"}},z)}case"worktree_disband":{let X=await V.onWorktreeDisband(String(J.slug??""));return _0(C$(X.card),X.ok)}case"temp_fork_select":{let X=await V.onForkSelect(String(J.panel_id??""),String(J.choice_id??""),Y);return _0(X.replaceCard===!1?{toast:{type:"error",content:X.message}}:C$(t1({title:"\uD83D\uDD31 会话分叉",message:X.message,ok:X.ok})),X.ok)}case"temp_back_select":{let X=await V.onBackSelect(String(J.panel_id??""),String(J.choice_id??""),Y);return _0(X.replaceCard===!1?{toast:{type:"error",content:X.message}}:C$(t1({title:"⏪ 会话回滚",message:X.message,ok:X.ok})),X.ok)}case"temp_resume_select":{let X=await V.onResumeSelect(String(J.panel_id??""),String(J.choice_id??""),Y);if(X.replaceCard===!1)return _0({toast:{type:"error",content:X.message}},X.ok);if(!X.resumePresentation)throw Error("rs selection result missing trusted presentation snapshot");return _0(C$(hY({...X.resumePresentation,message:X.message,ok:X.ok})),X.ok,X.message)}case"tasklist_enable":{let X=await V.onTasklistEnable();return _0(C$(X.card),X.ok)}case"tasklist_delete_prompt":{let X=V.onTasklistDeletePrompt(String(J.guid??""));return _0(C$(X.card),X.ok)}case"tasklist_delete_confirm":{let X=await V.onTasklistDeleteConfirm(String(J.guid??""));return _0(C$(X.card),X.ok)}case"token_source_enable":{let{onTokenSourceEnable:X}=await Promise.resolve().then(() => ($6(),e7));return await X(V,String(J.source_id??"")),{toast:{type:"info",content:"已处理"}}}case"agent_identity_page":return z1(V.onAgentIdentityPage(String(J.panel_id??""),J.page,Y))}return{toast:{type:"info",content:"unknown action"}}}async function yS($,Z,J){let Q=String($?.notify_id??""),Y=String($?.button_id??"");if(!Q)return{toast:{type:"error",content:"回调缺少 notify_id"}};let V=R1(Q);if(!V)return j(`notify-callback: notify_id=${Q.slice(0,12)}… not found (expired or pre-restart)`),{toast:{type:"error",content:"通知已过期或已移除"}};if(V.unknownAt)return X1(V,_0({toast:{type:"error",content:`外部回调可能已成功,但本地确认状态未知,已禁止自动重试${V.unknownReason?`: ${V.unknownReason}`:""}`}},!0));if(V.resolvedAt)return X1(V,{toast:{type:"info",content:"已处理过"}});if(K9(Q))return X1(V,{toast:{type:"info",content:"处理中…"}});if(V.replyState?.status==="waiting"||V.replyState?.status==="sending")return X1(V,_0({toast:{type:"error",content:"正在等待文字回复,请先发送或取消回复,再选择按钮"}},!1));let X=V.buttons.find((G)=>G.id===Y);if(!X)return j(`notify-callback: notify_id=${Q.slice(0,12)}… unknown button_id="${Y}"`),X1(V,_0({toast:{type:"error",content:"未知按钮"}},!1));if(!V.callbackUrl){try{$3(V.notifyId,X.id,J)}catch(G){return X1(V,_0({toast:{type:"error",content:`保存反馈结果失败: ${G instanceof Error?G.message:G}`}},!1))}return j(`notify-callback: notify_id=${Q.slice(0,12)}… resolved button="${Y}" by=${J.slice(0,8)}… (no callback, pull/display)`),X1(V,{...C$(Q2(V,{status:"done",buttonId:X.id,text:X.text,operatorOpenId:J}))})}try{Dj(V.notifyId,X.id,J)}catch(G){return X1(V,_0({toast:{type:"error",content:`保存回调发送状态失败,未发送: ${G instanceof Error?G.message:G}`}},!1))}t8(V.notifyId);let z=eV(hS(V,X,J));z.catch((G)=>{j(`notify-callback: notify_id=${V.notifyId.slice(0,12)}… phase-2 rejected: ${G instanceof Error?G.message:G}`)});let H=z.then((G)=>G==="retry"?"retry":"complete").catch(()=>"retry");return X1(V,{toast:{type:"info",content:`⏳ 已选择:${X.text} · 推送中…`},__cardActionCompletion:H})}async function hS($,Z,J){try{let Q=Q2($,{status:"processing",buttonId:Z.id,text:Z.text,operatorOpenId:J});try{await n4($.messageId,Q)}catch(z){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-1 (processing) updateCard failed: ${z instanceof Error?z.message:z}`)}let Y=await GV($,Z,J),V=Y.ok?"complete":"retry",X;if(Y.ok){let z=i6($.notifyId,Z.id,J);if(z.state==="complete")X={status:"delivered",buttonId:Z.id,text:Z.text,operatorOpenId:J,reply:Y.reply};else{V="unknown",X={status:"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:z.detail},j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… callback succeeded but tombstone is UNKNOWN: ${z.detail}`);try{await V4($.chatId,`⚠️ 通知反馈的外部回调已成功,但本地确认状态未知;为避免重复副作用,已禁止自动重试。${z.detail}`)}catch(H){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… UNKNOWN warning receipt failed: ${H instanceof Error?H.message:H}`)}}}else{let z=Fj($.notifyId);V=z.state,X={status:z.state==="retry"?"failed":"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:z.state==="retry"?Y.detail:`${Y.detail}; ${z.detail}`}}try{let z=Q2($,X);await n4($.messageId,z)}catch(z){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-2 (final) presentation failed: ${z instanceof Error?z.message:z}`);try{await V4($.chatId,`⚠️ 通知反馈${V==="retry"?"失败且结果卡更新失败,可重新点击":V==="unknown"?"送达状态未知且结果卡更新失败,禁止自动重试":"已执行,但结果卡更新失败"}: ${z instanceof Error?z.message:z}`)}catch(H){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… final fallback receipt failed: ${H instanceof Error?H.message:H}`)}}return j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… button="${Z.id}" ${V==="complete"?"delivered":V==="unknown"?"unknown/non-retryable":`failed: ${Y.detail}`} by=${J.slice(0,8)}…`),V}finally{r8($.notifyId)}}function tV($){return $.map((Z)=>typeof Z==="string"?Z:JSON.stringify(Z)).join(" ")}function IS(){if(process.platform==="win32"){j("debug: inject socket skipped on Windows (dev-only feature)");return}if(typeof Bun>"u"){j("debug: inject socket skipped (Bun runtime only — npm/Node build does not include it)");return}try{if(rV(z2))N5(z2)}catch{}try{Bun.serve({unix:z2,fetch:async($)=>{let Z=new URL($.url),J=$.method==="GET"&&Z.pathname==="/model-state";if($.method!=="POST"&&!J)return new Response("unsupported debug method",{status:405});if(Z$)return new Response("daemon shutdown in progress",{status:503});let Q={};if($.method==="POST")try{Q=await $.json()}catch{return new Response("bad json",{status:400})}if(!rV(j3))return new Response("no debug context yet — send `[DEBUG]hi` from Feishu first",{status:412});let Y={};try{Y=JSON.parse(US(j3,"utf8"))}catch(W){return new Response(`ctx read failed: ${W}`,{status:500})}let V=J?Z.searchParams.get("chat_id"):Q.chat_id;if(V!==void 0&&V!==Y.chat_id||Z.pathname!=="/"&&!V)return new Response("explicit debug chat_id must match the seeded context",{status:409});if(J){let W=x$.get(Y.chat_id);return W?Response.json(gV(W)):new Response("send md to open a model panel first",{status:404})}if(Z.pathname==="/model-action"){let W=x$.get(Y.chat_id);if(!W)return new Response("debug session not found",{status:404});try{if(typeof Q.message_id!=="string"||!Q.message_id.startsWith("om_"))throw Error("message_id required");let K=typeof Q.value?.panel_id==="string"?Q.value.panel_id.trim():"",B=W.modelPanels.get(K);if(!B?.messageId||B.messageId!==Q.message_id)throw Error("stale or mismatched model panel");let _=await q0.im.v1.message.get({path:{message_id:Q.message_id}});if(_.code!==0)throw Error(`message.get failed: ${w(_)}`);let P=a_(Q,Y,_.data?.items?.[0],g.feishu.app_id,B.messageId);j(`debug: model action ${Q.value.kind} chat=${Y.chat_id.slice(0,8)}…`);let L=qL(P);return await x1.enqueue(Y.chat_id,async()=>{}),Response.json({admission:L,state:gV(W)})}catch(K){return new Response(K instanceof Error?K.message:String(K),{status:400})}}if(Z.pathname!=="/")return new Response("unknown debug endpoint",{status:404});let X=String(Q.text??"");if(!X)return new Response("text required",{status:400});let z=`【自动化测试】:${X}`,H=await k(Y.chat_id,z);if(!H)return new Response("sendText failed — see daemon log",{status:502});let G={sender:{sender_id:{open_id:Y.sender_open_id}},message:{message_id:H,chat_id:Y.chat_id,message_type:"text",content:JSON.stringify({text:X}),create_time:String(Date.now())}};if(j(`debug: inject text=${JSON.stringify(X).slice(0,80)} msg_id=${H}`),!PL(G,"debug"))return new Response("daemon shutdown in progress",{status:503});if(Q.wait_for_handling===!0)await x1.enqueue(Y.chat_id,async()=>{});return new Response(JSON.stringify({ok:!0,msg_id:H}),{headers:{"content-type":"application/json"}})}});try{FS(z2,384)}catch{}j(`debug: inject socket listening at ${z2}`)}catch($){j(`debug: socket bind failed: ${$}`)}}async function gS(){j(`lodestar-daemon: pid ${process.pid} starting`),X4.load();let{buildTokenSourcesFromConfig:$}=await Promise.resolve().then(() => (l7(),IW));if(Z$)return;$();let{refreshAllTokenSourceModels:Z,listTokenSourceAccounts:J}=await Promise.resolve().then(() => (X0(),WH));if(Z$)return;if(await Z(),await Promise.allSettled(J().map(QG)),Z$)return;if(Gz(),l9.start(),SJ(),bJ(),kJ(),vJ(),hJ(),await K8(),Z$)return;setInterval(()=>{K8()},1800000);let{reconcileTasklistDeletions:Q}=await Promise.resolve().then(() => (TV(),RV));if(Z$)return;try{await Q()}catch(f){j(`tasklist deletion reconcile failed: ${f instanceof Error?f.message:f}`)}if(Z$)return;let Y,V=Date.now(),X=0,z=!1,H=null,G=1500,W=90000,K=600000,B=3,_=null,P=0,L="",q=!1,D=(f)=>{j(`[ws] rebuild requested before WS init — ${f}`)},M=(f,Q0=0,t=!1)=>{if(Z$)return;let K0=Date.now()+Q0;if(_){if(q||=t,K0>=P){j(`[ws] rebuild already scheduled — ${f}`);return}clearTimeout(_)}P=K0,L=f,q=t,_=setTimeout(()=>{let p$=L,x=q;_=null,P=0,L="",q=!1,D(p$,x)},Q0)},U={error:(f)=>j(`[ws-sdk error] ${tV(f)}`),warn:(f)=>{let Q0=tV(f);if(j(`[ws-sdk warn] ${Q0}`),Q0.includes("no pong/inbound"))M("ping-timeout: SDK liveness watchdog fired",2000,Date.now()-V<K)},info:(f)=>j(`[ws-sdk] ${tV(f)}`),debug:(f)=>{},trace:(f)=>{}},A=new A9.EventDispatcher({}),O=()=>{if(V=Date.now(),X=0,H)clearTimeout(H),H=null};A.register({"im.message.receive_v1":async(f)=>{if(O(),!PL(f))throw Error("daemon shutdown in progress")}}),A.register({"card.action.trigger":async(f)=>{return O(),qL(f)}});let N=()=>new A9.WSClient({appId:g.feishu.app_id,appSecret:g.feishu.app_secret,loggerLevel:A9.LoggerLevel.info,logger:U,wsConfig:{pingTimeout:60},handshakeTimeoutMs:1e4,onReconnecting:()=>j("[ws] reconnecting — WS lost, SDK is retrying"),onReconnected:()=>T(),onError:(f)=>D(`SDK onError: ${f?.message??f}`)});D=(f,Q0=!1)=>{if(Z$)return;if(z){j(`[ws] rebuild skipped (already rebuilding) — ${f}`);return}if(_)clearTimeout(_),_=null,P=0;z=!0,X++,j(`[ws] rebuild #${X} (fresh WSClient) — ${f}`);let t=Y;try{t?.close({force:!0})}catch(K0){j(`[ws] rebuild: old close failed: ${K0}`)}if(Y=N(),Y.start({eventDispatcher:A}).catch((K0)=>{j(`[ws] rebuild start failed: ${K0}`),M(`fresh client start failed: ${K0}`,G,Q0)}),z=!1,Q0)S()};let S=()=>{if(H)clearTimeout(H);let f=Date.now();H=setTimeout(()=>{if(H=null,V>=f){X=0;return}if(X>=B){j(`[ws] STILL deaf after ${B} fresh rebuilds — auto-heal exhausted, `+"leaving last client up (no process exit). Restart the configured service or run lodestar-stop && lodestar-daemon"),X=0;return}D(`verify: no event ${Math.round((Date.now()-f)/1000)}s after rebuild`,!0)},W)},T=()=>{let f=Date.now()-V<K;j("[ws] reconnected — swapping in a fresh WSClient (cluster-routing precaution; "+`recentlyActive=${f})`),X=0,M("post-reconnect precaution",G,f)};Y=N();let y=15000,m=2,b=0,p=setInterval(()=>{if(Z$)return;let{state:f}=Y.getConnectionStatus();if(f==="connected"){b=0;return}if(f==="failed"||f==="idle"){b=0,D(`watchdog: state=${f}`);return}if(b++,j(`[ws] watchdog: state=${f} (${b}/${m})`),b>=m)b=0,D(`watchdog: stuck in '${f}' ~${Math.round(y*m/1000)}s`)},y);BL=()=>{if(clearInterval(p),_)clearTimeout(_);if(H)clearTimeout(H);Y.close({force:!0})};let c=Lj(),J0=pP(z9(g.notify.bind,g.notify.port));e_({bind:g.notify.bind,port:g.notify.port,extraHandler:(f,Q0,t)=>iP(f,Q0,t,{service:O9,authorizeProject:(K0,p$)=>cP(J0,K0)?O9.projectPrincipal(lP(p$)):null,authorizeSession:(K0)=>{for(let p$ of x$.values())if(p$.acceptsAgentCapability(K0))return p$;return null}})}),tP(),HP(),AP(),j5("lodestar-files");let l=X4.enqueue();KL=eX(j,{enabled:g.runtime.agent_auto_update}),Y.start({eventDispatcher:A}).catch((f)=>{j(`[ws] initial start failed: ${f}`),M(`initial start failed: ${f}`,G,!1)}),j(`lodestar-daemon: WS start requested, watching ${O0.size} groups`),IS();for(let f of c)eV(x1.enqueue(f.chatId,()=>R5.recover(f))).catch((Q0)=>j(`notify-reply recovery failed: ${Q0 instanceof Error?Q0.message:Q0}`));await l}var HL=!1,Z$=!1,O5=null,V2=0,KL,BL,GL=15000,jL=()=>{if(HL)return;HL=!0;try{X4.persist()}catch($){j(`alive marker write failed: ${$}`)}try{N5(D$)}catch{}try{N5(z2)}catch{}},x$,O9,x1,A5,X4,NS,_L,RS,$X,xS=30000,U9,R5,vS;var DL=R(()=>{YZ();hZ();W7();CQ();OV();Y0();S$();o_();Z3();K5();K5();GP();KP();mP();uP();dP();tJ();t7();nP();cV();_5();rP();k0();I();F4();H0();c5();XJ();zL();{let $=P3(D$);if($.state==="exit")console.error(`lodestar-daemon: already running (pid ${$.pid})`),process.exit(1);if(rV(D$))try{N5(D$)}catch{}}MS(AS(D$),{recursive:!0});FX(D$);process.on("exit",jL);process.on("SIGTERM",()=>{N9("SIGTERM",0)});process.on("SIGINT",()=>{N9("SIGINT",0)});if(process.platform==="win32")process.on("SIGBREAK",()=>{N9("SIGBREAK",0)});process.on("unhandledRejection",($)=>{j(`unhandledRejection: ${$ instanceof Error?$.stack??$.message:$}`),N9("unhandledRejection",1)});process.on("uncaughtException",($)=>{j(`uncaughtException: ${$.stack??$.message}`),N9("uncaughtException",1)});x$=new Map,O9=new dV,x1=new Y8,A5=process.env.LODESTAR_RESTART_CONTINUE_CHAT_ID?.trim(),X4=new sV({readMarker:pJ,writeMarker:mJ,sessions:()=>x$.values(),chatIdForSession:N7,sessionFor:LL,actor:x1,isShuttingDown:()=>Z$,restartContinuation:A5?{chatId:A5,send:async($)=>{let Z=x$.get(A5);if(!Z||Z!==$)throw Error("restart continuation session binding changed");try{await Z.continueAfterDaemonRestart()}catch(J){throw await k(A5,`⚠️ 重启自动续接失败:${J instanceof Error?J.message:J}`),J}}}:void 0,log:j}),NS=new VJ(30000),_L=new Set,RS=YG({actor:x1,key:($)=>String($?.message?.chat_id??""),execute:($,Z)=>bS($,Z)});$X=XL({registry:x$,createSession:($,Z)=>{let J=new g$($,Z,{agentCards:O9.presentation,onLifecycleChange:TS,onCreateTempSession:ES,onDisbandTempSession:SS,onCancelAgentRuns:(Q,Y,V)=>O9.cancelSessionRuns(Q,Y,V)});return X4.transferPending(J),J},ensureChatForSession:uJ,disbandChatForSessionExact:dJ,chatIdForSession:N7,clearSessionConversationState:gJ,registerTempSessionLease:CJ,hasTempSessionLease:xJ,replaceTurnAnchors:W$,runExclusive:($,Z)=>x1.enqueue($,Z),log:j});U9=new Set,R5=WP({sendCard:o,updateCard:n4,sendText:k,dispatch:GV,onWaitingChanged:($)=>x$.get($)?.refreshPendingAsks(),log:j});vS=VG({actor:x1,deduper:NS,scope:($)=>{let Z=String($?.action?.value?.kind??"");if(Z.startsWith("agent_identity_"))return"__agent_identities_global__";if(Z==="notify_callback"||Z==="notify_reply"||Z==="notify_reply_cancel"){let J=R1(String($?.action?.value?.notify_id??""));if(J)return J.chatId}return String($?.context?.open_chat_id??"")||"__notify_global__"},execute:($)=>{if(Z$)x$.get(String($?.context?.open_chat_id??""))?.closeModelSettingsChanges();return fS($)},present:WL,presentExecutionFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");j(`handleCardAction ${J}: ${Z instanceof Error?Z.stack??Z.message:Z}`),await wS($,Z)},presentPresentationFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");j(`card-action presentation ${J}: ${Z instanceof Error?Z.message:Z}`),await V4(String($?.context?.open_chat_id??""),`⚠️ ${T5(J)}已执行,但结果呈现失败。`)},businessSucceeded:($,Z)=>{if(typeof Z?.__businessOk==="boolean")return Z.__businessOk;return $?.action?.value?.kind==="permission"&&$?.action?.value?.decision==="deny"||Z?.toast?.type!=="error"},completion:($,Z)=>{let J=Z?.__modelActionCompletion;if(J)return Ez(J,(Y)=>WL($,z1(Y)));let Q=Z?.__cardActionCompletion;return Q&&typeof Q.then==="function"?Q:null},track:($)=>{eV($)},onBackgroundError:($)=>{j(`card-action background: ${$ instanceof Error?$.stack??$.message:$}`)},responses:{accepted:($)=>({toast:{type:"info",content:`⏳ ${T5(String($?.action?.value?.kind??"unknown"))}已接收,后台处理中…`}}),inflight:()=>({toast:{type:"info",content:"相同操作正在处理…"}}),completed:()=>({toast:{type:"info",content:"该操作近期已执行或尝试;为防重复暂不再次执行,请查看原卡或群消息"}}),closed:()=>({toast:{type:"error",content:"服务正在重启,请稍后重试"}}),invalid:($,Z)=>({toast:{type:"error",content:Z}})}});gS().catch(($)=>{j(`boot fatal: ${$}`),N9("boot fatal",1)})});H0();c5();import{existsSync as FL,unlinkSync as pS}from"node:fs";var m$={reset:"\x1B[0m",bold:"\x1B[1m",yellow:"\x1B[33m",green:"\x1B[32m",red:"\x1B[31m"};async function cS(){if(!FL(c0)){if(process.stdin.isTTY){console.log(),console.log(`${m$.bold}${m$.yellow}Lodestar: 未找到配置, 启动安装向导...${m$.reset}`);let{runSetup:Z}=await Promise.resolve().then(() => (Hz(),zz));await Z();return}console.error(`${m$.red}Lodestar: 未找到配置 ${c0}${m$.reset}`),console.error(`请在交互式 cmd / PowerShell 里运行 ${m$.green}lodestar-setup${m$.reset} 完成首次配置 (或直接运行 ${m$.green}lodestar-daemon${m$.reset} 也会触发同一个向导)。`),process.exit(1)}let $=P3(D$);if($.state==="exit")console.error(`${m$.yellow}Lodestar: 已经有一个 daemon 在运行 (pid ${$.pid})${m$.reset}`),console.error(" • 想看日志:"+(process.platform==="win32"?" %LOCALAPPDATA%\\Lodestar\\daemon-YYYY-MM-DD.log":" ~/.local/share/lodestar/daemon-YYYY-MM-DD.log")),console.error(" • 想停: 任务管理器结束 pid 上面那个号 (Windows) / `kill "+$.pid+"` (Linux/macOS)"),console.error(` • 误判 / 已经死了: 手删 ${D$} 后再跑`),process.exit(1);if(FL(D$))pS(D$);await Promise.resolve().then(() => (DL(),mS))}cS().catch(($)=>{console.error("lodestar fatal:",$?.message??$),process.exit(1)});
641
+ `),imageKeys:Z,fileKeys:J}}async function bS($,Z=Date.now()){let J=$?.message;if(!J)return;let Y=($?.sender?.sender_id??$?.event?.sender?.sender_id??J?.sender?.sender_id)?.open_id??"",V=J.message_id;if(V&&U9.has(V))return;if(V){if(U9.add(V),U9.size>200){let U=[...U9];U9.clear();for(let A of U.slice(-100))U9.add(A)}}let X=Number(J.create_time??0);if(eP(X,Z,xS)){if(j(`drop stale message ${V} ageAtReceipt=${Math.round((Z-X)/1000)}s`),V)K$(V,"CrossMark");return}let z=J.chat_id,H={};try{H=JSON.parse(J.content??"{}")}catch{}let G=J.message_type==="text"?H.text??"":"";if(typeof G==="string"&&G.startsWith("[DEBUG]")){try{OS(j3,JSON.stringify({chat_id:z,sender_open_id:Y,seeded_at:new Date().toISOString(),seeded_msg_id:V??""},null,2)),j(`debug: seeded inject context chat=${z.slice(0,8)}… sender=${Y.slice(0,8)}…`)}catch(A){j(`debug: seed context failed: ${A}`)}let U=G.slice(7);H.text=U,J.content=JSON.stringify(H)}let W=O0.get(z);if(!W)await K8(),W=O0.get(z);if(!W)W=await iJ(z)??void 0;if(!W){j(`unknown chat ${z}, dropping message`),await k(z,"❌ 无法识别群名。请确认:① 机器人已被拉进本群;② 群已设置名称(未命名群拿不到群名,无法映射项目目录)。设置后再发一条消息即可。");return}let K=sJ(W);p4(K,z);let B=LL(z,K),_={};try{_=JSON.parse(J.content??"{}")}catch{}let P=J.message_type,L="",q=!1,F=[];if(P==="text")L=(_.text??"").trim();else if(P==="post"){let U=CS(_);q=U.imageKeys.length>0||U.fileKeys.length>0,L=U.markdown.trim();for(let A of U.imageKeys){let O=await B8(J.message_id,A,"image");if(O)F.push(O)}for(let A of U.fileKeys){let O=await B8(J.message_id,A.key,"file",A.name);if(O)F.push(O)}}if(P==="text"&&L){if(await B.runCommand(L,Y,V))return}if((P==="text"||P==="post")&&L&&!q&&await $L({reply:()=>R5.consume({chatId:z,openId:Y,messageId:V??"",text:L,createTime:X,parentId:J.parent_id}),hasQuestion:()=>B.hasPendingAsk(),answerQuestion:()=>B.onAskMessageAnswer(L,Y,V??"")}))return;if(P==="text"&&L&&await B.consumeModelCustomMessage(L,Y))return;let M=JL(P,_);if(M){let U=await B8(J.message_id,M.key,M.type,M.name);if(!U){await k(z,ZL(P));return}if(F.push(U),!L&&M.displayText)L=M.displayText}if(!L&&F.length===0){j(`drop empty message ${V} type=${P}`);return}if(await B.onMultiMessageInbound(L,F,Y,V??""))return;await B.onUserMessage(L||"(empty)",F,Y,V??"")}function T5($){return{permission:"权限决定",menu:"菜单选择",provider_select:"账号选择",model_page:"模型翻页",model_list_open:"模型列表",model_add:"显示模型",model_remove:"隐藏模型",model_custom_remove:"删除补录模型",model_select:"模型选择",model_custom_prompt:"模型补录",model_panel_cancel:"取消模型补录",model_effort_select:"模型 effort 选择",ask:"问题回答",worktree_disband:"worktree 解散",temp_fork_select:"会话分叉",temp_back_select:"会话回滚",temp_resume_select:"会话恢复",tasklist_enable:"启用任务清单",tasklist_delete_prompt:"删除任务清单",tasklist_delete_confirm:"确认删除任务清单",token_source_enable:"启用账号",agent_identity_page:"Agent 身份翻页",notify_callback:"通知反馈",notify_reply:"通知回复",notify_reply_cancel:"取消通知回复",agent_project_cancel:"停止项目任务"}[$]??$}function kS($){return $?.card?.type==="raw"&&$.card.data&&typeof $.card.data==="object"?$.card.data:null}function _0($,Z,J){return{...$,__businessOk:Z,...J?{__businessMessage:J}:{}}}function X1($,Z){return{...Z,__cardActionMessageId:$.messageId,__cardActionChatId:$.chatId}}function z1($){let Z=_0($.card?C$($.card):{toast:{type:$.ok?"success":"error",content:$.message}},$.ok,$.pending?void 0:$.message);if($.completion)Z.__modelActionCompletion=$.completion;return Z}async function V4($,Z){if(!$){j(`card-action: cannot send receipt without chat_id: ${Z}`);return}if(!await h($,Z))j(`card-action: visible receipt MISS chat=${$.slice(0,8)}… text=${Z.slice(0,120)}`)}async function WL($,Z){if(Z?.__cardActionPresented)return;let J=String($?.action?.value?.kind??"unknown"),Q=T5(J),Y=String(Z?.__cardActionChatId??$?.__cardActionChatId??$?.context?.open_chat_id??""),V=String(Z?.__cardActionMessageId??$?.context?.open_message_id??""),X=kS(Z),z=Z?.__businessOk===!1&&typeof Z?.__businessMessage==="string"?` 业务失败: ${Z.__businessMessage.replace(/\s+/g," ").trim().slice(0,300)}。`:"";if(X&&V)try{await n4(V,X);return}catch(_){j(`card-action: ${J} original-card update failed: ${_ instanceof Error?_.message:_}`),await V4(Y,`⚠️ ${Q}已处理,但原卡更新失败。${z}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":"请重新打开操作面板。"}`);return}if(X){await V4(Y,`⚠️ ${Q}已处理,但回调缺少原卡 message_id,无法更新。${z}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":""}`);return}if(J==="notify_callback"&&Z?.__cardActionCompletion)return;let H=Z?.toast,G=typeof H?.content==="string"&&H.content.trim()?H.content.trim():`${Q}已完成`,W=J==="permission"&&String($?.action?.value?.decision??"")==="deny",K=Z?.__businessOk===!1||H?.type==="error"&&!W;if(!K&&new Set(["permission","ask","token_source_enable"]).has(J))return;await V4(Y,`${K?"❌":"✅"} ${Q}: ${G}`)}async function wS($,Z){let J=String($?.action?.value?.kind??"unknown"),Q=Z instanceof Error?Z.message:String(Z);await V4(String($?.__cardActionChatId??$?.context?.open_chat_id??""),`❌ ${T5(J)}失败: ${Q}`)}function qL($){return vS.accept($)}async function yS($){let Z=$?.action,J=Z?.value;if(!J?.kind)return;let Q=$?.context?.open_chat_id??"",Y=$?.operator?.open_id??"";if(J.kind==="agent_project_cancel"){let X=await O9.cancelProjectRunFromCard(String(J.run_id??""),Q,String($?.context?.open_message_id??""),Y);return _0({toast:{type:"success",content:X?"项目任务已停止":"项目任务已结束"}},!0)}if(J.kind==="notify_callback"||J.kind==="notify_reply"||J.kind==="notify_reply_cancel"){let X=String(J.notify_id??""),z=R1(X);if(z)$.__cardActionChatId=z.chatId;if(J.kind==="notify_callback")return await fS(J,Q,Y);let H=J.kind==="notify_reply"?await R5.open(X,Q,Y):await R5.cancel(X,String(J.reply_id??""),Q,Y),G=_0({toast:{type:H.ok?"success":"error",content:H.message},__cardActionPresented:H.presented===!0},H.ok);return z?X1(z,G):G}let V=x$.get(Q);if(!V)return _0({toast:{type:"error",content:"会话不存在,请先发消息启动"}},!1);switch(J.kind){case"permission":{let X=String(J.decision??"");if(!["allow","allow_always","deny"].includes(X))return{toast:{type:"error",content:"无效的权限决定"}};let z=await V.onPermissionDecision(J.request_id,X,Y);return _0({toast:{type:z.ok?X==="deny"?"error":"success":"error",content:z.message}},z.ok)}case"menu":{let X=Number(J.choice??-1);try{if(!Number.isInteger(X)||X<0)throw Error("无效的菜单选项");return await V.onUserMessage(`(menu choice ${X+1})`),_0(C$(t1({title:"\uD83D\uDCCB 菜单选择",message:`已选择第 ${X+1} 项`,ok:!0})),!0)}catch(z){let H=z instanceof Error?z.message:String(z);return _0(C$(t1({title:"\uD83D\uDCCB 菜单选择",message:H,ok:!1})),!1)}}case"provider_select":{let X=await V.onProviderSelect(String(J.source_id??""),String(J.panel_id??""));return z1(X)}case"model_page":{let X=await V.onModelPage(String(J.panel_id??""),String(J.source_id??""),Number(J.page));return z1(X)}case"model_list_open":{let X=String(J.panel_id??""),z=String(J.source_id??"");if(J.mode!=="add"&&J.mode!=="select")throw Error("模型管理模式无效");return z1(await(J.mode==="add"?V.onModelAddOpen(X,z):V.onProviderSelect(z,X)))}case"model_add":case"model_remove":case"model_custom_remove":return z1(await V.onModelListEdit(String(J.panel_id??""),String(J.source_id??""),String(J.model??""),J.kind==="model_add"?"add":J.kind==="model_remove"?"remove":"delete"));case"model_select":{let X=await V.onModelSelect(String(J.model??""),String(J.panel_id??""),Y,J);return z1(X)}case"model_custom_prompt":{let X=await V.onModelCustomPrompt(String(J.source_id??""),String(J.panel_id??""),String($?.context?.open_message_id??""));return z1(X)}case"model_panel_cancel":{let X=await V.onModelPanelCancel(String(J.panel_id??""));return z1(X)}case"model_effort_select":{let X=await V.onModelEffortSelect(String(J.model??""),String(J.effort??""),String(J.panel_id??""),Y,String(J.provider??""));return z1(X)}case"ask":{let X=V.askBlockReason(String(J.tool_use_id??""));if(X)return _0({toast:{type:"error",content:X}},!1);if(J.custom){let G=(Z?.form_value??Z?.input??{})?.custom_answer??Z?.input_value??"",W=await V.onAskCustomAnswer(J.tool_use_id,J.question_idx??0,G,Y);return _0({toast:{type:W?"success":"error",content:W?"已回答":G.trim()?"问题已失效或答案未被接受":"请输入答案"}},W)}let z=await V.onAskAnswer(J.tool_use_id,J.question_idx??0,J.option_idx,Y);return _0({toast:{type:z?"success":"error",content:z?"已回答":"问题已失效或选项无效"}},z)}case"worktree_disband":{let X=await V.onWorktreeDisband(String(J.slug??""));return _0(C$(X.card),X.ok)}case"temp_fork_select":{let X=await V.onForkSelect(String(J.panel_id??""),String(J.choice_id??""),Y);return _0(X.replaceCard===!1?{toast:{type:"error",content:X.message}}:C$(t1({title:"\uD83D\uDD31 会话分叉",message:X.message,ok:X.ok})),X.ok)}case"temp_back_select":{let X=await V.onBackSelect(String(J.panel_id??""),String(J.choice_id??""),Y);return _0(X.replaceCard===!1?{toast:{type:"error",content:X.message}}:C$(t1({title:"⏪ 会话回滚",message:X.message,ok:X.ok})),X.ok)}case"temp_resume_select":{let X=await V.onResumeSelect(String(J.panel_id??""),String(J.choice_id??""),Y);if(X.replaceCard===!1)return _0({toast:{type:"error",content:X.message}},X.ok);if(!X.resumePresentation)throw Error("rs selection result missing trusted presentation snapshot");return _0(C$(hY({...X.resumePresentation,message:X.message,ok:X.ok})),X.ok,X.message)}case"tasklist_enable":{let X=await V.onTasklistEnable();return _0(C$(X.card),X.ok)}case"tasklist_delete_prompt":{let X=V.onTasklistDeletePrompt(String(J.guid??""));return _0(C$(X.card),X.ok)}case"tasklist_delete_confirm":{let X=await V.onTasklistDeleteConfirm(String(J.guid??""));return _0(C$(X.card),X.ok)}case"token_source_enable":{let{onTokenSourceEnable:X}=await Promise.resolve().then(() => ($6(),e7));return await X(V,String(J.source_id??"")),{toast:{type:"info",content:"已处理"}}}case"agent_identity_page":return z1(V.onAgentIdentityPage(String(J.panel_id??""),J.page,Y))}return{toast:{type:"info",content:"unknown action"}}}async function fS($,Z,J){let Q=String($?.notify_id??""),Y=String($?.button_id??"");if(!Q)return{toast:{type:"error",content:"回调缺少 notify_id"}};let V=R1(Q);if(!V)return j(`notify-callback: notify_id=${Q.slice(0,12)}… not found (expired or pre-restart)`),{toast:{type:"error",content:"通知已过期或已移除"}};if(V.unknownAt)return X1(V,_0({toast:{type:"error",content:`外部回调可能已成功,但本地确认状态未知,已禁止自动重试${V.unknownReason?`: ${V.unknownReason}`:""}`}},!0));if(V.resolvedAt)return X1(V,{toast:{type:"info",content:"已处理过"}});if(K9(Q))return X1(V,{toast:{type:"info",content:"处理中…"}});if(V.replyState?.status==="waiting"||V.replyState?.status==="sending")return X1(V,_0({toast:{type:"error",content:"正在等待文字回复,请先发送或取消回复,再选择按钮"}},!1));let X=V.buttons.find((G)=>G.id===Y);if(!X)return j(`notify-callback: notify_id=${Q.slice(0,12)}… unknown button_id="${Y}"`),X1(V,_0({toast:{type:"error",content:"未知按钮"}},!1));if(!V.callbackUrl){try{$3(V.notifyId,X.id,J)}catch(G){return X1(V,_0({toast:{type:"error",content:`保存反馈结果失败: ${G instanceof Error?G.message:G}`}},!1))}return j(`notify-callback: notify_id=${Q.slice(0,12)}… resolved button="${Y}" by=${J.slice(0,8)}… (no callback, pull/display)`),X1(V,{...C$(Q2(V,{status:"done",buttonId:X.id,text:X.text,operatorOpenId:J}))})}try{Fj(V.notifyId,X.id,J)}catch(G){return X1(V,_0({toast:{type:"error",content:`保存回调发送状态失败,未发送: ${G instanceof Error?G.message:G}`}},!1))}t8(V.notifyId);let z=eV(hS(V,X,J));z.catch((G)=>{j(`notify-callback: notify_id=${V.notifyId.slice(0,12)}… phase-2 rejected: ${G instanceof Error?G.message:G}`)});let H=z.then((G)=>G==="retry"?"retry":"complete").catch(()=>"retry");return X1(V,{toast:{type:"info",content:`⏳ 已选择:${X.text} · 推送中…`},__cardActionCompletion:H})}async function hS($,Z,J){try{let Q=Q2($,{status:"processing",buttonId:Z.id,text:Z.text,operatorOpenId:J});try{await n4($.messageId,Q)}catch(z){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-1 (processing) updateCard failed: ${z instanceof Error?z.message:z}`)}let Y=await GV($,Z,J),V=Y.ok?"complete":"retry",X;if(Y.ok){let z=i6($.notifyId,Z.id,J);if(z.state==="complete")X={status:"delivered",buttonId:Z.id,text:Z.text,operatorOpenId:J,reply:Y.reply};else{V="unknown",X={status:"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:z.detail},j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… callback succeeded but tombstone is UNKNOWN: ${z.detail}`);try{await V4($.chatId,`⚠️ 通知反馈的外部回调已成功,但本地确认状态未知;为避免重复副作用,已禁止自动重试。${z.detail}`)}catch(H){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… UNKNOWN warning receipt failed: ${H instanceof Error?H.message:H}`)}}}else{let z=Dj($.notifyId);V=z.state,X={status:z.state==="retry"?"failed":"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:z.state==="retry"?Y.detail:`${Y.detail}; ${z.detail}`}}try{let z=Q2($,X);await n4($.messageId,z)}catch(z){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-2 (final) presentation failed: ${z instanceof Error?z.message:z}`);try{await V4($.chatId,`⚠️ 通知反馈${V==="retry"?"失败且结果卡更新失败,可重新点击":V==="unknown"?"送达状态未知且结果卡更新失败,禁止自动重试":"已执行,但结果卡更新失败"}: ${z instanceof Error?z.message:z}`)}catch(H){j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… final fallback receipt failed: ${H instanceof Error?H.message:H}`)}}return j(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… button="${Z.id}" ${V==="complete"?"delivered":V==="unknown"?"unknown/non-retryable":`failed: ${Y.detail}`} by=${J.slice(0,8)}…`),V}finally{r8($.notifyId)}}function tV($){return $.map((Z)=>typeof Z==="string"?Z:JSON.stringify(Z)).join(" ")}function IS(){if(process.platform==="win32"){j("debug: inject socket skipped on Windows (dev-only feature)");return}if(typeof Bun>"u"){j("debug: inject socket skipped (Bun runtime only — npm/Node build does not include it)");return}try{if(rV(z2))N5(z2)}catch{}try{Bun.serve({unix:z2,fetch:async($)=>{let Z=new URL($.url),J=$.method==="GET"&&Z.pathname==="/model-state";if($.method!=="POST"&&!J)return new Response("unsupported debug method",{status:405});if(Z$)return new Response("daemon shutdown in progress",{status:503});let Q={};if($.method==="POST")try{Q=await $.json()}catch{return new Response("bad json",{status:400})}if(!rV(j3))return new Response("no debug context yet — send `[DEBUG]hi` from Feishu first",{status:412});let Y={};try{Y=JSON.parse(US(j3,"utf8"))}catch(W){return new Response(`ctx read failed: ${W}`,{status:500})}let V=J?Z.searchParams.get("chat_id"):Q.chat_id;if(V!==void 0&&V!==Y.chat_id||Z.pathname!=="/"&&!V)return new Response("explicit debug chat_id must match the seeded context",{status:409});if(J){let W=x$.get(Y.chat_id);return W?Response.json(gV(W)):new Response("send md to open a model panel first",{status:404})}if(Z.pathname==="/model-action"){let W=x$.get(Y.chat_id);if(!W)return new Response("debug session not found",{status:404});try{if(typeof Q.message_id!=="string"||!Q.message_id.startsWith("om_"))throw Error("message_id required");let K=typeof Q.value?.panel_id==="string"?Q.value.panel_id.trim():"",B=W.modelPanels.get(K);if(!B?.messageId||B.messageId!==Q.message_id)throw Error("stale or mismatched model panel");let _=await q0.im.v1.message.get({path:{message_id:Q.message_id}});if(_.code!==0)throw Error(`message.get failed: ${w(_)}`);let P=a_(Q,Y,_.data?.items?.[0],g.feishu.app_id,B.messageId);j(`debug: model action ${Q.value.kind} chat=${Y.chat_id.slice(0,8)}…`);let L=qL(P);return await x1.enqueue(Y.chat_id,async()=>{}),Response.json({admission:L,state:gV(W)})}catch(K){return new Response(K instanceof Error?K.message:String(K),{status:400})}}if(Z.pathname!=="/")return new Response("unknown debug endpoint",{status:404});let X=String(Q.text??"");if(!X)return new Response("text required",{status:400});let z=`【自动化测试】:${X}`,H=await k(Y.chat_id,z);if(!H)return new Response("sendText failed — see daemon log",{status:502});let G={sender:{sender_id:{open_id:Y.sender_open_id}},message:{message_id:H,chat_id:Y.chat_id,message_type:"text",content:JSON.stringify({text:X}),create_time:String(Date.now())}};if(j(`debug: inject text=${JSON.stringify(X).slice(0,80)} msg_id=${H}`),!PL(G,"debug"))return new Response("daemon shutdown in progress",{status:503});if(Q.wait_for_handling===!0)await x1.enqueue(Y.chat_id,async()=>{});return new Response(JSON.stringify({ok:!0,msg_id:H}),{headers:{"content-type":"application/json"}})}});try{DS(z2,384)}catch{}j(`debug: inject socket listening at ${z2}`)}catch($){j(`debug: socket bind failed: ${$}`)}}async function gS(){j(`lodestar-daemon: pid ${process.pid} starting`),X4.load();let{buildTokenSourcesFromConfig:$}=await Promise.resolve().then(() => (l7(),IW));if(Z$)return;$();let{refreshAllTokenSourceModels:Z,listTokenSourceAccounts:J}=await Promise.resolve().then(() => (X0(),WH));if(Z$)return;if(await Z(),await Promise.allSettled(J().map(QG)),Z$)return;if(Gz(),l9.start(),SJ(),bJ(),kJ(),vJ(),hJ(),await K8(),Z$)return;setInterval(()=>{K8()},1800000);let{reconcileTasklistDeletions:Q}=await Promise.resolve().then(() => (TV(),RV));if(Z$)return;try{await Q()}catch(y){j(`tasklist deletion reconcile failed: ${y instanceof Error?y.message:y}`)}if(Z$)return;let Y,V=Date.now(),X=0,z=!1,H=null,G=1500,W=90000,K=600000,B=3,_=null,P=0,L="",q=!1,F=(y)=>{j(`[ws] rebuild requested before WS init — ${y}`)},M=(y,Q0=0,t=!1)=>{if(Z$)return;let K0=Date.now()+Q0;if(_){if(q||=t,K0>=P){j(`[ws] rebuild already scheduled — ${y}`);return}clearTimeout(_)}P=K0,L=y,q=t,_=setTimeout(()=>{let p$=L,x=q;_=null,P=0,L="",q=!1,F(p$,x)},Q0)},U={error:(y)=>j(`[ws-sdk error] ${tV(y)}`),warn:(y)=>{let Q0=tV(y);if(j(`[ws-sdk warn] ${Q0}`),Q0.includes("no pong/inbound"))M("ping-timeout: SDK liveness watchdog fired",2000,Date.now()-V<K)},info:(y)=>j(`[ws-sdk] ${tV(y)}`),debug:(y)=>{},trace:(y)=>{}},A=new A9.EventDispatcher({}),O=()=>{if(V=Date.now(),X=0,H)clearTimeout(H),H=null};A.register({"im.message.receive_v1":async(y)=>{if(O(),!PL(y))throw Error("daemon shutdown in progress")}}),A.register({"card.action.trigger":async(y)=>{return O(),qL(y)}});let N=()=>new A9.WSClient({appId:g.feishu.app_id,appSecret:g.feishu.app_secret,loggerLevel:A9.LoggerLevel.info,logger:U,wsConfig:{pingTimeout:60},handshakeTimeoutMs:1e4,onReconnecting:()=>j("[ws] reconnecting — WS lost, SDK is retrying"),onReconnected:()=>T(),onError:(y)=>F(`SDK onError: ${y?.message??y}`)});F=(y,Q0=!1)=>{if(Z$)return;if(z){j(`[ws] rebuild skipped (already rebuilding) — ${y}`);return}if(_)clearTimeout(_),_=null,P=0;z=!0,X++,j(`[ws] rebuild #${X} (fresh WSClient) — ${y}`);let t=Y;try{t?.close({force:!0})}catch(K0){j(`[ws] rebuild: old close failed: ${K0}`)}if(Y=N(),Y.start({eventDispatcher:A}).catch((K0)=>{j(`[ws] rebuild start failed: ${K0}`),M(`fresh client start failed: ${K0}`,G,Q0)}),z=!1,Q0)S()};let S=()=>{if(H)clearTimeout(H);let y=Date.now();H=setTimeout(()=>{if(H=null,V>=y){X=0;return}if(X>=B){j(`[ws] STILL deaf after ${B} fresh rebuilds — auto-heal exhausted, `+"leaving last client up (no process exit). Restart the configured service or run lodestar-stop && lodestar-daemon"),X=0;return}F(`verify: no event ${Math.round((Date.now()-y)/1000)}s after rebuild`,!0)},W)},T=()=>{let y=Date.now()-V<K;j("[ws] reconnected — swapping in a fresh WSClient (cluster-routing precaution; "+`recentlyActive=${y})`),X=0,M("post-reconnect precaution",G,y)};Y=N();let f=15000,m=2,b=0,p=setInterval(()=>{if(Z$)return;let{state:y}=Y.getConnectionStatus();if(y==="connected"){b=0;return}if(y==="failed"||y==="idle"){b=0,F(`watchdog: state=${y}`);return}if(b++,j(`[ws] watchdog: state=${y} (${b}/${m})`),b>=m)b=0,F(`watchdog: stuck in '${y}' ~${Math.round(f*m/1000)}s`)},f);BL=()=>{if(clearInterval(p),_)clearTimeout(_);if(H)clearTimeout(H);Y.close({force:!0})};let c=Lj(),J0=pP(z9(g.notify.bind,g.notify.port));e_({bind:g.notify.bind,port:g.notify.port,extraHandler:(y,Q0,t)=>iP(y,Q0,t,{service:O9,authorizeProject:(K0,p$)=>cP(J0,K0)?O9.projectPrincipal(lP(p$)):null,authorizeSession:(K0)=>{for(let p$ of x$.values())if(p$.acceptsAgentCapability(K0))return p$;return null}})}),tP(),HP(),AP(),j5("lodestar-files");let l=X4.enqueue();KL=eX(j,{enabled:g.runtime.agent_auto_update}),Y.start({eventDispatcher:A}).catch((y)=>{j(`[ws] initial start failed: ${y}`),M(`initial start failed: ${y}`,G,!1)}),j(`lodestar-daemon: WS start requested, watching ${O0.size} groups`),IS();for(let y of c)eV(x1.enqueue(y.chatId,()=>R5.recover(y))).catch((Q0)=>j(`notify-reply recovery failed: ${Q0 instanceof Error?Q0.message:Q0}`));await l}var HL=!1,Z$=!1,O5=null,V2=0,KL,BL,GL=15000,jL=()=>{if(HL)return;HL=!0;try{X4.persist()}catch($){j(`alive marker write failed: ${$}`)}try{N5(F$)}catch{}try{N5(z2)}catch{}},x$,O9,x1,A5,X4,NS,_L,RS,$X,xS=30000,U9,R5,vS;var FL=R(()=>{YZ();hZ();W7();CQ();OV();Y0();S$();o_();Z3();K5();K5();GP();KP();mP();uP();dP();tJ();t7();nP();cV();_5();rP();k0();I();D4();H0();c5();XJ();zL();{let $=P3(F$);if($.state==="exit")console.error(`lodestar-daemon: already running (pid ${$.pid})`),process.exit(1);if(rV(F$))try{N5(F$)}catch{}}MS(AS(F$),{recursive:!0});DX(F$);process.on("exit",jL);process.on("SIGTERM",()=>{N9("SIGTERM",0)});process.on("SIGINT",()=>{N9("SIGINT",0)});if(process.platform==="win32")process.on("SIGBREAK",()=>{N9("SIGBREAK",0)});process.on("unhandledRejection",($)=>{j(`unhandledRejection: ${$ instanceof Error?$.stack??$.message:$}`),N9("unhandledRejection",1)});process.on("uncaughtException",($)=>{j(`uncaughtException: ${$.stack??$.message}`),N9("uncaughtException",1)});x$=new Map,O9=new dV,x1=new Y8,A5=process.env.LODESTAR_RESTART_CONTINUE_CHAT_ID?.trim(),X4=new sV({readMarker:pJ,writeMarker:mJ,sessions:()=>x$.values(),chatIdForSession:N7,sessionFor:LL,actor:x1,isShuttingDown:()=>Z$,restartContinuation:A5?{chatId:A5,send:async($)=>{let Z=x$.get(A5);if(!Z||Z!==$)throw Error("restart continuation session binding changed");try{await Z.continueAfterDaemonRestart()}catch(J){throw await k(A5,`⚠️ 重启自动续接失败:${J instanceof Error?J.message:J}`),J}}}:void 0,log:j}),NS=new VJ(30000),_L=new Set,RS=YG({actor:x1,key:($)=>String($?.message?.chat_id??""),execute:($,Z)=>bS($,Z)});$X=XL({registry:x$,createSession:($,Z)=>{let J=new g$($,Z,{agentCards:O9.presentation,onLifecycleChange:TS,onCreateTempSession:ES,onDisbandTempSession:SS,onCancelAgentRuns:(Q,Y,V)=>O9.cancelSessionRuns(Q,Y,V)});return X4.transferPending(J),J},ensureChatForSession:uJ,disbandChatForSessionExact:dJ,chatIdForSession:N7,clearSessionConversationState:gJ,registerTempSessionLease:CJ,hasTempSessionLease:xJ,replaceTurnAnchors:W$,runExclusive:($,Z)=>x1.enqueue($,Z),log:j});U9=new Set,R5=WP({sendCard:o,updateCard:n4,sendText:k,dispatch:GV,onWaitingChanged:($)=>x$.get($)?.refreshPendingAsks(),log:j});vS=VG({actor:x1,deduper:NS,scope:($)=>{let Z=String($?.action?.value?.kind??"");if(Z.startsWith("agent_identity_"))return"__agent_identities_global__";if(Z==="notify_callback"||Z==="notify_reply"||Z==="notify_reply_cancel"){let J=R1(String($?.action?.value?.notify_id??""));if(J)return J.chatId}return String($?.context?.open_chat_id??"")||"__notify_global__"},execute:($)=>{if(Z$)x$.get(String($?.context?.open_chat_id??""))?.closeModelSettingsChanges();return yS($)},present:WL,presentExecutionFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");j(`handleCardAction ${J}: ${Z instanceof Error?Z.stack??Z.message:Z}`),await wS($,Z)},presentPresentationFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");j(`card-action presentation ${J}: ${Z instanceof Error?Z.message:Z}`),await V4(String($?.context?.open_chat_id??""),`⚠️ ${T5(J)}已执行,但结果呈现失败。`)},businessSucceeded:($,Z)=>{if(typeof Z?.__businessOk==="boolean")return Z.__businessOk;return $?.action?.value?.kind==="permission"&&$?.action?.value?.decision==="deny"||Z?.toast?.type!=="error"},completion:($,Z)=>{let J=Z?.__modelActionCompletion;if(J)return Ez(J,(Y)=>WL($,z1(Y)));let Q=Z?.__cardActionCompletion;return Q&&typeof Q.then==="function"?Q:null},track:($)=>{eV($)},onBackgroundError:($)=>{j(`card-action background: ${$ instanceof Error?$.stack??$.message:$}`)},responses:{accepted:($)=>({toast:{type:"info",content:`⏳ ${T5(String($?.action?.value?.kind??"unknown"))}已接收,后台处理中…`}}),inflight:()=>({toast:{type:"info",content:"相同操作正在处理…"}}),completed:()=>({toast:{type:"info",content:"该操作近期已执行或尝试;为防重复暂不再次执行,请查看原卡或群消息"}}),closed:()=>({toast:{type:"error",content:"服务正在重启,请稍后重试"}}),invalid:($,Z)=>({toast:{type:"error",content:Z}})}});gS().catch(($)=>{j(`boot fatal: ${$}`),N9("boot fatal",1)})});H0();c5();import{existsSync as DL,unlinkSync as pS}from"node:fs";var m$={reset:"\x1B[0m",bold:"\x1B[1m",yellow:"\x1B[33m",green:"\x1B[32m",red:"\x1B[31m"};async function cS(){if(!DL(c0)){if(process.stdin.isTTY){console.log(),console.log(`${m$.bold}${m$.yellow}Lodestar: 未找到配置, 启动安装向导...${m$.reset}`);let{runSetup:Z}=await Promise.resolve().then(() => (Hz(),zz));await Z();return}console.error(`${m$.red}Lodestar: 未找到配置 ${c0}${m$.reset}`),console.error(`请在交互式 cmd / PowerShell 里运行 ${m$.green}lodestar-setup${m$.reset} 完成首次配置 (或直接运行 ${m$.green}lodestar-daemon${m$.reset} 也会触发同一个向导)。`),process.exit(1)}let $=P3(F$);if($.state==="exit")console.error(`${m$.yellow}Lodestar: 已经有一个 daemon 在运行 (pid ${$.pid})${m$.reset}`),console.error(" • 想看日志:"+(process.platform==="win32"?" %LOCALAPPDATA%\\Lodestar\\daemon-YYYY-MM-DD.log":" ~/.local/share/lodestar/daemon-YYYY-MM-DD.log")),console.error(" • 想停: 任务管理器结束 pid 上面那个号 (Windows) / `kill "+$.pid+"` (Linux/macOS)"),console.error(` • 误判 / 已经死了: 手删 ${F$} 后再跑`),process.exit(1);if(DL(F$))pS(F$);await Promise.resolve().then(() => (FL(),mS))}cS().catch(($)=>{console.error("lodestar fatal:",$?.message??$),process.exit(1)});