@leviyuan/lodestar 0.18.1 → 0.18.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.
- package/dist/lodestar.js +174 -174
- package/package.json +1 -1
package/dist/lodestar.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
3
|
-
`),Y=parseInt((J[0]??"").trim(),10),Q=(J[1]??"").trim();if(!Number.isFinite(Y)||Y<=0)return{state:"continue"};if(!Q)try{return process.kill(Y,0),{state:"exit",pid:Y}}catch{return{state:"continue"}}if(
|
|
4
|
-
${
|
|
5
|
-
`).filter(Boolean).map((Q)=>{let V=Q.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=
|
|
6
|
-
`).filter((V)=>V.includes("=")).map((V)=>{let H=V.indexOf("=");return[V.slice(0,H).trim(),V.slice(H+1).trim()]})),Y=J.get("ProxyType")??"0";if(Y==="0"||Y==="4")return{};if(Y!=="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 Q={bypass:J.get("NoProxyFor")};for(let V of["http","https","socks"]){let H=J.get(`${V}Proxy`);if(!H)continue;let X=H.replace(/\s+(\d+)$/,":$1");Q[V==="socks"?"all":V]=/^[a-z][\w+.-]*:\/\//i.test(X)?X:`${V==="socks"?"socks":"http"}://${X}`}return Q}async function
|
|
2
|
+
import{createRequire as VK}from"node:module";var JK=Object.defineProperty;var YK=($)=>$;function QK($,Z){this[$]=YK.bind(null,Z)}var E$=($,Z)=>{for(var J in Z)JK($,J,{get:Z[J],enumerable:!0,configurable:!0,set:QK.bind(Z,J)})};var R=($,Z)=>()=>($&&(Z=$($=0)),Z);var HK=VK(import.meta.url);import{homedir as XK}from"node:os";import{join as n}from"node:path";function cJ($,Z,J){if($)return $;if(Z)return n(Z,"lodestar");return J}function zK(){if(pJ)return n(process.env.APPDATA??n(b9,"AppData","Roaming"),"Lodestar");return n(b9,".config","lodestar")}function WK(){if(pJ)return n(process.env.LOCALAPPDATA??n(b9,"AppData","Local"),"Lodestar");return n(b9,".local","share","lodestar")}var b9,pJ,Y7,r,N0,o0,J2,Q7,V7,H7,X7,z7,C9,P1,k9,D1,Y2,uJ,lJ,dJ,W7,iJ,nJ,G7,K7,aJ,B7,F1,y9;var Q0=R(()=>{b9=XK(),pJ=process.platform==="win32";Y7=cJ(process.env.LODESTAR_CONFIG_DIR,process.env.XDG_CONFIG_HOME,zK()),r=cJ(process.env.LODESTAR_DATA_DIR,process.env.XDG_DATA_HOME,WK()),N0=process.env.LODESTAR_CONFIG??n(Y7,"config.toml"),o0=n(r,"daemon.pid"),J2=n(r,"daemon.log"),Q7=n(r,"session-chat-map.json"),V7=n(r,"session-resume-map.json"),H7=n(r,"session-turns-map.json"),X7=n(r,"session-model-map.json"),z7=n(r,"temp-session-leases.json"),C9=n(r,"tasklist-map.json"),P1=n(r,"agent-runs"),k9=n(r,"agent-session-ids.json"),D1=n(r,"managed-claude-plugin"),Y2=n(r,"dsh"),uJ=n(r,"codex-accounts"),lJ=n(r,"codex-accounts.json"),dJ=n(r,"codex-quota-blocks.json"),W7=n(r,"agent-runtimes"),iJ=n(r,"context-window-cache.json"),nJ=n(r,"notify-callbacks.json"),G7=n(r,"alive-on-shutdown.json"),K7=n(r,"inbox"),aJ=n(r,"file-deliveries"),B7=n(r,"file-delivery-groups.json"),F1=n(r,"debug.sock"),y9=n(r,"debug-context.json")});import{execSync as oJ}from"node:child_process";import{readFileSync as rJ,writeFileSync as GK}from"node:fs";function KK(){return process.argv[1]??`pid:${process.pid}`}function BK($){try{if(process.platform==="linux")return rJ(`/proc/${$}/cmdline`,"utf8").replace(/\0/g," ").trim();if(process.platform==="darwin")return oJ(`ps -p ${$} -o args=`,{encoding:"utf8",timeout:2000}).trim();if(process.platform==="win32")return oJ(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${$}').CommandLine"`,{encoding:"utf8",timeout:5000}).trim()||null;return null}catch{return null}}function _K($,Z){if(!Number.isFinite($)||$<=0||!Z)return!1;let J=BK($);if(!J)return!1;if(process.platform==="win32")return J.toLowerCase().includes(Z.toLowerCase());return J.includes(Z)}function w9($){let Z="";try{Z=rJ($,"utf8")}catch{return{state:"continue"}}let J=Z.split(`
|
|
3
|
+
`),Y=parseInt((J[0]??"").trim(),10),Q=(J[1]??"").trim();if(!Number.isFinite(Y)||Y<=0)return{state:"continue"};if(!Q)try{return process.kill(Y,0),{state:"exit",pid:Y}}catch{return{state:"continue"}}if(_K(Y,Q))return{state:"exit",pid:Y};return{state:"continue"}}function sJ($){GK($,`${process.pid}
|
|
4
|
+
${KK()}`)}var _7=()=>{};import{execFile as jK}from"node:child_process";import{readFile as LK}from"node:fs/promises";import{homedir as qK}from"node:os";import{join as tJ}from"node:path";import{promisify as PK}from"node:util";import{Address4 as v9,Address6 as f9}from"ip-address";function Q2($,Z){return $[Z.toLowerCase()]?.trim()||$[Z]?.trim()||void 0}function m9($){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 j7($,Z=""){let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Y=$.port||($.protocol==="https:"?"443":"80");return Z.split(/[,;\s]+/).filter(Boolean).some((Q)=>{let V=Q.toLowerCase();if(V==="*")return!0;if(V==="<local>")return!J.includes(".")&&!J.includes(":");if(V.includes("/")){if(v9.isValid(V))return v9.isValid(J)&&new v9(J).isInSubnet(new v9(V));if(f9.isValid(V))return f9.isValid(J)&&new f9(J).isInSubnet(new f9(V));throw Error("network proxy: invalid IP range in bypass list")}let H=V.match(/^(\[[^\]]+\]|[^:]+):(\d+)$/);if(H&&H[2]!==Y)return!1;let X=(H?H[1]:V).replace(/^\[|\]$/g,"").replace(/^\*?\./,"");return J===X||J.endsWith(`.${X}`)})}function eJ($,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 $Y($,Z,J={}){if(!["http:","https:"].includes($.protocol))throw Error(`network: unsupported URL protocol ${$.protocol}`);if(m9($)||j7($,Q2(Z,"NO_PROXY")))return;let Y=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY",Q=Q2(Z,Y)||Q2(Z,"ALL_PROXY");if(Q)return eJ(Q,"environment");if(J.unsupported)throw Error(`network proxy: ${J.unsupported}`);if(j7($,J.bypass))return;let V=($.protocol==="https:"?J.https:J.http)||J.all;return V?eJ(V,"system settings"):void 0}function g9($,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 Y=$.includes(":")&&!$.startsWith("[")?`[${$}]`:$;return`${J}://${Y}:${Z}`}function FK($){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((Y)=>Y.trim()).filter(Boolean)){let Y=J.match(/^(http|https|socks)=(.+)$/i),Q=Y?Y[2]:J,V=/^[a-z][\w+.-]*:\/\//i.test(Q)?Q:`http://${Q}`;if(!Y)Z.all=V;else if(Y[1].toLowerCase()==="socks")Z.all=`socks://${Q.replace(/^socks\w*:\/\//,"")}`;else Z[Y[1].toLowerCase()]=V}return Z}function MK($){let Z=(Q)=>$.match(new RegExp(`^\\s*${Q}\\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=g9(Z("HTTPProxy"),Z("HTTPPort"));if(Z("HTTPSEnable")==="1")J.https=g9(Z("HTTPSProxy"),Z("HTTPSPort"));if(Z("SOCKSEnable")==="1")J.all=g9(Z("SOCKSProxy"),Z("SOCKSPort"),"socks");let Y=$.match(/ExceptionsList\s*:\s*<array>\s*\{([^}]*)\}/)?.[1]??"";if(J.bypass=[...Y.matchAll(/^\s*\d+\s*:\s*(.*?)\s*$/gm)].map((Q)=>Q[1]).join(","),Z("ExcludeSimpleHostnames")==="1")J.bypass+=",<local>";return J}function h9($){if($===void 0)return"";if(!/^(['"]).*\1$/.test($))throw Error("network proxy: invalid GNOME proxy string");return $.slice(1,-1).replace(/\\([\\'"])/g,"$1")}function UK($){let Z=new Map($.split(`
|
|
5
|
+
`).filter(Boolean).map((Q)=>{let V=Q.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=h9(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 Y={};for(let Q of["http","https","socks"]){let V=h9(Z.get(`.${Q}/host`));if(!V)continue;let H=new URL(g9(V,Z.get(`.${Q}/port`),Q==="socks"?"socks":"http"));if(Q==="http"&&Z.get(".http/use-authentication")==="true")H.username=h9(Z.get(".http/authentication-user")),H.password=h9(Z.get(".http/authentication-password"));Y[Q==="socks"?"all":Q]=H.href}if(Z.get("/use-same-proxy")==="true"&&Y.http)Y.https=Y.http;return Y.bypass=[...(Z.get("/ignore-hosts")??"").matchAll(/'((?:\\.|[^'])*)'/g)].map((Q)=>Q[1]).join(","),Y}function AK($){let Z=$.match(/^\[Proxy Settings\]\s*\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m)?.[1];if(Z===void 0)return;let J=new Map(Z.split(`
|
|
6
|
+
`).filter((V)=>V.includes("=")).map((V)=>{let H=V.indexOf("=");return[V.slice(0,H).trim(),V.slice(H+1).trim()]})),Y=J.get("ProxyType")??"0";if(Y==="0"||Y==="4")return{};if(Y!=="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 Q={bypass:J.get("NoProxyFor")};for(let V of["http","https","socks"]){let H=J.get(`${V}Proxy`);if(!H)continue;let X=H.replace(/\s+(\d+)$/,":$1");Q[V==="socks"?"all":V]=/^[a-z][\w+.-]*:\/\//i.test(X)?X:`${V==="socks"?"socks":"http"}://${X}`}return Q}async function I9($,Z){let{stdout:J}=await DK($,Z,{encoding:"utf8",timeout:5000,maxBuffer:262144,windowsHide:!0});return J}async function RK(){if(process.platform==="win32")return FK(JSON.parse(await I9("powershell.exe",["-NoProfile","-NonInteractive","-Command",OK])));if(process.platform==="darwin")return MK(await I9("/usr/sbin/scutil",["--proxy"]));if(process.platform==="linux"){let $=tJ(process.env.XDG_CONFIG_HOME||tJ(qK(),".config"),"kioslaverc");try{let J=AK(await LK($,"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 I9("gsettings",["list-schemas"])}catch(J){if(J?.code==="ENOENT")return{};throw J}if(!Z.split(/\r?\n/).includes("org.gnome.system.proxy"))return{};return UK(await I9("gsettings",["list-recursively","org.gnome.system.proxy"]))}return{}}function NK($=RK,Z=process.env,J=Date.now){let Y;return async(Q)=>{if(m9(Q)||j7(Q,Q2(Z,"NO_PROXY"))||Q2(Z,Q.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY")||Q2(Z,"ALL_PROXY"))return $Y(Q,Z);if(!Y||Y.until<=J()){let V=$().catch((H)=>{if(Y?.value===V)Y=void 0;if(H instanceof Error&&H.message.startsWith("network proxy:"))throw H;let X=H instanceof Error?H.code??H.name:"unknown error";throw Error(`network proxy: failed to read ${process.platform} system proxy settings (${X})`,{cause:H})});Y={until:J()+30000,value:V}}return $Y(Q,Z,await Y.value)}}var DK,OK,ZY;var JY=R(()=>{DK=PK(jK);OK=String.raw`
|
|
7
7
|
$ErrorActionPreference = 'Stop'
|
|
8
8
|
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
|
9
9
|
Add-Type @'
|
|
@@ -41,49 +41,49 @@ try {
|
|
|
41
41
|
if ($pointer -ne [IntPtr]::Zero) { [void][LodestarProxy]::GlobalFree($pointer) }
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
`;
|
|
45
|
-
`)}var
|
|
46
|
-
${Q}${V}`));else Z()})})}async function
|
|
47
|
-
${W}`),M=(S)=>{if(_||j||B)return;G??=Error(S),q=setTimeout(()=>
|
|
48
|
-
${W}`))}),z.once("close",async(S,b)=>{j=!0,clearTimeout(U),Z?.removeEventListener("abort",A);try{await B}catch(v){
|
|
49
|
-
${W}`));else
|
|
50
|
-
`,{mode:384}),await n$(()=>
|
|
51
|
-
`,{mode:384}),await(Z.install??
|
|
52
|
-
${L.green}>${L.reset} `)).trim();if(!Y&&Z.default!==void 0)return Z.default;if(!Y&&Z.required){console.log(`${L.red}必填,请重新输入${L.reset}`);continue}return Y}}function
|
|
44
|
+
`;ZY=NK()});import{Agent as TK}from"node:http";import{Agent as EK}from"node:https";import{Readable as YY}from"node:stream";import xK from"node-fetch";import{HttpProxyAgent as SK}from"http-proxy-agent";import{HttpsProxyAgent as bK}from"https-proxy-agent";function yK($,Z){if(!Z)return $.protocol==="https:"?kK:CK;return $.protocol==="https:"?new bK(Z):new SK(Z)}async function wK($,Z,J){if(typeof Bun<"u"){let H=$.protocol==="https:"?"HTTPS_PROXY":"HTTP_PROXY";if(!J&&(process.env[H.toLowerCase()]||process.env[H])){let X=await import("undici");return QY??=new X.Agent,await X.fetch($,{...Z,redirect:"manual",dispatcher:QY})}return globalThis.fetch($.href,{...Z,redirect:"manual",...J?{proxy:J}:{}})}let Y=new Request($,{...Z,redirect:"manual",duplex:"half"}),Q=await xK($,{method:Y.method,headers:Object.fromEntries(Y.headers),body:Y.body?YY.fromWeb(Y.body):void 0,signal:Y.signal,agent:yK($,J),redirect:"manual"}),V=Y.method==="HEAD"||[204,205,304].includes(Q.status)||!Q.body?null:YY.toWeb(Q.body);return new Response(V,{status:Q.status,statusText:Q.statusText,headers:[...Q.headers]})}async function VY($,Z,J,Y=ZY){let Q=new URL($),V={...Z};for(let H=0;;H++){if(!["http:","https:"].includes(Q.protocol))throw Error(`network: unsupported URL protocol ${Q.protocol}`);if(J&&!m9(Q))throw Error("network: local request must remain on loopback");V.signal?.throwIfAborted();let X=J?void 0:await Y(Q),z=await wK(Q,V,X),W=z.headers.get("location");if(![301,302,303,307,308].includes(z.status)||!W||Z.redirect==="manual")return z;if(await z.body?.cancel(),Z.redirect==="error")throw Error("network: redirect rejected");if(H>=20)throw Error("network: too many redirects");let G=new URL(W,Q),B=new Headers(V.headers);if(G.origin!==Q.origin)for(let j of["authorization","proxy-authorization","cookie","host"])B.delete(j);let _=(V.method??"GET").toUpperCase();if(z.status===303&&_!=="HEAD"||[301,302].includes(z.status)&&_==="POST"){V={...V,method:"GET",body:void 0};for(let j of["content-type","content-length","content-encoding"])B.delete(j)}else if(V.body instanceof ReadableStream)throw Error("network: cannot replay a streamed body after redirect");V.headers=B,Q=G}}function $0($,Z={}){return VY($,Z,!1)}function HY($,Z={}){return VY($,Z,!0)}var CK,kK,QY;var h0=R(()=>{JY();CK=new TK({keepAlive:!0}),kK=new EK({keepAlive:!0})});import{chmodSync as vK,closeSync as L7,fsyncSync as XY,mkdirSync as fK,openSync as zY,renameSync as hK,unlinkSync as IK,writeFileSync as gK}from"node:fs";import{randomUUID as mK}from"node:crypto";import{dirname as WY}from"node:path";function lK($){let Z=WY($);fK(Z,{recursive:!0,mode:uK})}function GY($,Z,J){lK($);let Y=`${$}.${process.pid}.${mK()}.tmp`,Q=null;try{Q=zY(Y,"wx",J),gK(Q,Z),XY(Q),L7(Q),Q=null,hK(Y,$);try{vK($,J)}catch{}if(process.platform!=="win32"){let V=null;try{V=zY(WY($),"r"),XY(V)}catch{}finally{if(V!==null)try{L7(V)}catch{}}}}catch(V){if(Q!==null)try{L7(Q)}catch{}try{IK(Y)}catch{}throw V}}function I0($,Z){GY($,Z,pK)}function KY($,Z){GY($,Z,cK)}function s($,Z){I0($,JSON.stringify(Z,null,2)+`
|
|
45
|
+
`)}var pK=384,cK=448,uK=448;var T0=()=>{};import{execFile as dK}from"node:child_process";import{spawn as iK}from"cross-spawn";function aK($){if(!Number.isSafeInteger($)||$<=0)return Promise.reject(Error(`Invalid npm installer PID: ${$}`));return new Promise((Z,J)=>{dK("taskkill",["/PID",String($),"/T","/F"],{windowsHide:!0,timeout:1e4},(Y,Q,V)=>{if(Y)J(Error(`taskkill npm installer PID ${$} failed: ${Y.message}
|
|
46
|
+
${Q}${V}`));else Z()})})}async function q7($,Z,J={}){Z?.throwIfAborted();let Y=J.platform??process.platform,Q=J.timeoutMs??300000,V=J.terminationTimeoutMs??1e4;return await new Promise((H,X)=>{let z=(J.spawn??iK)("npm",["install","--prefix",$,"--include=optional","--no-fund","--no-audit",`--registry=${nK}`],{cwd:$,stdio:["ignore","pipe","pipe"],shell:!1,windowsHide:!0}),W="",G,B,_=!1,j=!1,q,P=(S)=>{W=(W+S.toString()).slice(-16384)};z.stdout.on("data",P),z.stderr.on("data",P);let D=(S)=>{if(_)return;if(_=!0,clearTimeout(U),q)clearTimeout(q);if(Z?.removeEventListener("abort",A),S)X(S);else H()},T=(S)=>new p9(`${G?.message??"Agent runtime install failed"}; npm installer PID ${z.pid??"MISS"} termination unconfirmed: ${S}; partial directory retained: ${$}
|
|
47
|
+
${W}`),M=(S)=>{if(_||j||B)return;G??=Error(S),q=setTimeout(()=>D(T(`stdio did not close within ${V}ms`)),V),B=Promise.resolve().then(async()=>{if(j)throw Error("installer closed before process-tree termination started");if(!z.pid)throw Error("installer PID unavailable");if(Y==="win32")await(J.terminateWindows??aK)(z.pid);else if(!z.kill("SIGTERM"))throw Error("npm installer rejected SIGTERM")}),B.catch((b)=>D(T(b instanceof Error?b.message:String(b))))},A=()=>M("Agent runtime install aborted"),U=setTimeout(()=>M(`Agent runtime install timed out after ${Q}ms`),Q);if(Z?.addEventListener("abort",A,{once:!0}),z.on("error",(S)=>{if(G??=S,!z.pid)D(Error(`${S.message}
|
|
48
|
+
${W}`))}),z.once("close",async(S,b)=>{j=!0,clearTimeout(U),Z?.removeEventListener("abort",A);try{await B}catch(v){D(T(v instanceof Error?v.message:String(v)));return}if(G||S!==0)D(Error(`${G?.message??`npm install exited code=${S} signal=${b}`}
|
|
49
|
+
${W}`));else D()}),Z?.aborted)A()})}var nK="https://registry.npmjs.org",p9;var P7=R(()=>{p9=class p9 extends Error{}});import{createHash as oK,randomUUID as rK}from"node:crypto";import{createRequire as sK}from"node:module";import{existsSync as D7,readFileSync as _Y}from"node:fs";import{mkdir as jY,mkdtemp as tK,readFile as LY,rename as qY,rm as G4,writeFile as PY}from"node:fs/promises";import{join as g0,isAbsolute as eK}from"node:path";import{fileURLToPath as $B,pathToFileURL as ZB}from"node:url";function DY($,Z=W7){let J=g0(Z,$,"current.json");if(!D7(J))return null;let Y=JSON.parse(_Y(J,"utf8"));if(!Number.isFinite(Y.checkedAt)||Y.directory!==void 0&&!eK(Y.directory))throw Error(`Invalid ${$} runtime state: ${J}`);return Y}function c9($){let Z=DY($);if(Z?.error)throw Error(`${$} 更新失败: ${Z.error}`);if(!Z?.directory)throw Error(`${$} runtime 未安装,请运行 lodestar-update --agents-only`);return Z.directory}function F7($,Z){return sK(g0(c9($),"package.json")).resolve(Z)}function B4($,Z){let J=g0(c9($),"node_modules",".bin",`${Z}${process.platform==="win32"?".cmd":""}`);if(!D7(J))throw Error(`${$} executable missing: ${J}`);return J}async function FY(){return import(ZB(F7("claude","@anthropic-ai/claude-agent-sdk")).href)}async function VB($,Z,J){let Y=new AbortController,Q=()=>Y.abort(J?.reason);if(J?.addEventListener("abort",Q,{once:!0}),J?.aborted)Q();let V=setTimeout(()=>Y.abort(Error("npm registry request timed out")),30000);try{let H=await $0(`${QB}/${encodeURIComponent($)}/${encodeURIComponent(Z)}`,{signal:Y.signal});if(!H.ok)throw Error(`${$}@${Z}: npm HTTP ${H.status}`);let X=await H.json();if(X.name!==$||typeof X.version!=="string"||!X.version)throw Error(`Invalid npm manifest: ${$}@${Z}`);return X}finally{clearTimeout(V),J?.removeEventListener("abort",Q)}}async function HB($,Z){let J={};if($!=="dsh"){let H=await Promise.all(K4[$].map((X)=>Z(X,"latest")));for(let X of H)J[X.name]=X.version;return J}let Y=await Z("@deepseek-ai/dsh","latest"),Q=new Set(K4.dsh),V=new Set;while(Q.size){let H=[...Q].slice(0,12);for(let z of H)Q.delete(z),V.add(z);let X=await Promise.all(H.map((z)=>z===Y.name?Y:Z(z,Y.version)));for(let z of X){if(z.version!==Y.version)throw Error(`DSH release package mismatch: ${z.name}@${z.version}, expected ${Y.version}`);J[z.name]=z.version;for(let W of Object.keys({...z.dependencies,...z.peerDependencies,...z.optionalDependencies}))if(W.startsWith("@deepseek-ai/dsh")&&!V.has(W))Q.add(W)}}return J}async function n$($,Z=process.platform){for(let J=0;;J++)try{return await $()}catch(Y){let Q=Y.code;if(Z!=="win32"||!["EPERM","EACCES","EBUSY","ENOTEMPTY"].includes(Q??"")||J>=5)throw Y;await new Promise((V)=>setTimeout(V,100*(J+1)))}}async function BY($,Z){let J=g0($,`current-${rK()}.json`),Y;try{await PY(J,JSON.stringify(Z)+`
|
|
50
|
+
`,{mode:384}),await n$(()=>qY(J,g0($,"current.json")))}catch(Q){throw Y=Q,Q}finally{try{await n$(()=>G4(J,{force:!0}))}catch(Q){if(Y)throw AggregateError([Y,Q],`${x$(Y)}; state temporary file cleanup failed: ${x$(Q)}`);throw Q}}}async function XB($,Z){let J=g0($,"update.lock"),Y=Date.now()+360000;for(;;){Z?.throwIfAborted();try{await jY(J);try{await n$(async()=>I0(g0(J,"pid"),String(process.pid)))}catch(Q){try{await n$(()=>G4(J,{recursive:!0}))}catch(V){throw AggregateError([Q,V],`${x$(Q)}; runtime update lock cleanup failed: ${x$(V)}`)}throw Q}return()=>n$(()=>G4(J,{recursive:!0}))}catch(Q){if(Q.code!=="EEXIST")throw Q;try{let V=Number(await LY(g0(J,"pid"),"utf8"));if(!Number.isSafeInteger(V)||V<=0)throw Error(`Invalid runtime update lock: ${J}`);try{process.kill(V,0)}catch(H){if(H.code!=="ESRCH")throw H;await n$(()=>G4(J,{recursive:!0}));continue}}catch(V){if(V.code!=="ENOENT")throw V}if(Date.now()>=Y)throw Error(`Timed out waiting for runtime update lock: ${J}`);await new Promise((V)=>setTimeout(V,200))}}}async function u9($,Z={}){let J=Z.root??W7,Y=g0(J,$);await jY(Y,{recursive:!0,mode:448});let Q=await XB(Y,Z.signal),V,H,X=!1;try{Z.report?.(`${$}: 检查 upstream latest`);let z=DY($,J),W=await HB($,Z.metadata??((q,P)=>VB(q,P,Z.signal)));Z.signal?.throwIfAborted();let G=JSON.parse(_Y($B(new URL("../package.json",import.meta.url)),"utf8")).overrides??{},B=oK("sha256").update(JSON.stringify({installFormat:2,versions:Object.entries(W).sort(),security:G,platform:process.platform,arch:process.arch})).digest("hex").slice(0,20),_=g0(Y,B);if(!D7(_)){V=await tK(g0(Y,".install-")),await PY(g0(V,"package.json"),JSON.stringify({name:`lodestar-runtime-${$}`,version:W[K4[$][0]],private:!0,type:"module",dependencies:W,overrides:{...G,...$==="dsh"?W:{}}})+`
|
|
51
|
+
`,{mode:384}),await(Z.install??q7)(V,Z.signal);for(let[P,D]of Object.entries(W)){let T=JSON.parse(await LY(g0(V,"node_modules",P,"package.json"),"utf8"));if(T.version!==D)throw Error(`npm installed ${P}@${T.version}, expected ${D}`)}Z.signal?.throwIfAborted();let q=V;await n$(()=>qY(q,_)),V=void 0}let j={directory:_,versions:W,checkedAt:Date.now()};return await BY(Y,j),Z.report?.(`${$}: ${K4[$][0]}@${W[K4[$][0]]}${z?.directory===_?" 已是 latest":" 已更新,新进程使用新版"}`),j}catch(z){H=z,X=z instanceof p9;try{await BY(Y,{checkedAt:Date.now(),error:x$(z)})}catch(W){throw H=AggregateError([z,W],`${x$(z)}; recording update failure also failed: ${x$(W)}`),H}throw z}finally{let z=[];if(V&&!X){let W=V;try{await n$(()=>G4(W,{recursive:!0}))}catch(G){z.push(G)}}try{await Q()}catch(W){z.push(W)}if(z.length){let W=H?[H,...z]:z;throw AggregateError(W,W.map(x$).join("; "))}}}function MY($,Z={}){let J=JB.filter((Y)=>Z.enabled?.[Y]===!0).map((Y)=>{let Q=new AbortController,V,H=setInterval(()=>{if(V)return;V=(Z.update??u9)(Y,{report:$,signal:Q.signal}).catch((X)=>$(`${Y} 自动更新未完成: ${x$(X)}`)).finally(()=>{V=void 0})},YB);return H.unref(),()=>{clearInterval(H),Q.abort()}});return()=>{for(let Y of J)Y()}}var JB,YB=21600000,QB="https://registry.npmjs.org",K4,x$=($)=>$ instanceof Error?$.message:String($);var V2=R(()=>{h0();Q0();P7();T0();P7();JB=["codex","claude","dsh"],K4={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 AY;var UY=R(()=>{AY={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 NY={};E$(NY,{runSetup:()=>RB});import{execFileSync as WB,spawn as d9}from"node:child_process";import{spawn as GB}from"cross-spawn";import{existsSync as U7,mkdirSync as RY,readFileSync as KB}from"node:fs";import{createInterface as BB}from"node:readline/promises";import{dirname as _B,join as A7}from"node:path";import{homedir as jB}from"node:os";import{fileURLToPath as LB}from"node:url";async function M1($,Z={}){while(!0){let J=Z.default?`${L.dim} [${Z.default}]${L.reset}`:"",Y=(await _4.question(`${L.cyan}? ${L.reset}${$}${J}
|
|
52
|
+
${L.green}>${L.reset} `)).trim();if(!Y&&Z.default!==void 0)return Z.default;if(!Y&&Z.required){console.log(`${L.red}必填,请重新输入${L.reset}`);continue}return Y}}function qB($){let Z="═".repeat(58);console.log(`
|
|
53
53
|
${L.bold}${L.cyan}╔${Z}╗${L.reset}`),console.log(`${L.bold}${L.cyan}║ ${$.padEnd(54)} ║${L.reset}`),console.log(`${L.bold}${L.cyan}╚${Z}╝${L.reset}
|
|
54
|
-
`)}function
|
|
54
|
+
`)}function l9($,Z,J){console.log(`
|
|
55
55
|
${L.bold}${L.yellow}[${$}/${Z}] ${J}${L.reset}
|
|
56
|
-
`)}function
|
|
57
|
-
`),{path:J}}catch(Z){return{error:Z?.message??String(Z)}}}function
|
|
56
|
+
`)}function M7($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function OY($){try{let Z=WB($,["login","status"],{timeout:1e4,shell:process.platform==="win32"}).toString();return/Logged in using ChatGPT/i.test(Z)}catch{return!1}}async function PB($){return new Promise((Z)=>{let J=GB($,["login"],{stdio:"inherit",shell:!1});J.on("exit",(Y)=>Z(Y===0)),J.on("error",()=>Z(!1))})}function DB(){return process.env.CLAUDE_CONFIG_DIR||A7(jB(),".claude")}async function FB($){try{let Z=await $0("https://open.bigmodel.cn/api/anthropic/v1/models",{headers:{Authorization:`Bearer ${$}`},signal:AbortSignal.timeout(1e4)});if(!Z.ok)return null;let J=await Z.json(),Y=(Array.isArray(J?.data)?J.data:[]).map((B)=>typeof B?.display_name==="string"&&B.display_name?B.display_name:String(B?.id??"")).filter(Boolean);if(!Y.length)return null;let Q=(B)=>{let _=B.match(/(\d+(?:\.\d+)?)/);return _?Number(_[1]):-1},V=(B)=>B.replace(/-Turbo|-Air$/i,""),X=[...Y.filter((B)=>!/-Turbo|-Air/i.test(B))].sort((B,_)=>Q(_)-Q(B)),z=X[0],W=X[X.length-1],G={};if(z)G.ANTHROPIC_DEFAULT_OPUS_MODEL=`${z}[1m]`,G.ANTHROPIC_DEFAULT_SONNET_MODEL=`${z}[1m]`;if(W&&V(W)!==V(z))G.ANTHROPIC_DEFAULT_HAIKU_MODEL=W;return Object.keys(G).length?G:null}catch{return null}}async function MB($){try{let Z=DB();RY(Z,{recursive:!0});let J=A7(Z,"settings.json"),Y={};if(U7(J)){let X=KB(J,"utf8");try{let z=JSON.parse(X);if(!z||typeof z!=="object"||Array.isArray(z))return{error:`${J} 内容不是 JSON 对象, 拒绝覆盖, 请手动检查`};Y=z}catch{return{error:`${J} 解析失败 (JSON 语法错), 拒绝覆盖, 请手动修复后重跑`}}}let Q=Y.env&&typeof Y.env==="object"&&!Array.isArray(Y.env)?Y.env:{},V={ANTHROPIC_AUTH_TOKEN:$,ANTHROPIC_BASE_URL:"https://open.bigmodel.cn/api/anthropic",API_TIMEOUT_MS:"3000000",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"},H=await FB($);if(H)Object.assign(V,H);return Y.env={...Q,...V},I0(J,JSON.stringify(Y,null,2)+`
|
|
57
|
+
`),{path:J}}catch(Z){return{error:Z?.message??String(Z)}}}function UB($){try{if(process.platform==="win32")d9(process.env.ComSpec??"cmd.exe",["/c","start",'""',$],{detached:!0,stdio:"ignore",windowsHide:!0}).unref();else if(process.platform==="darwin")d9("open",[$],{detached:!0,stdio:"ignore"}).unref();else d9("xdg-open",[$],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function AB($,Z){try{let Y=await(await $0("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)})).json();if(Y.tenant_access_token)return{ok:!0};return{ok:!1,error:`飞书拒绝: code=${Y.code} msg=${Y.msg??"(no msg)"}`}}catch(J){return{ok:!1,error:`网络错误: ${J?.message??String(J)}`}}}function OB(){try{let $=_B(LB(import.meta.url)),Z=A7($,"lodestar.js");if(!U7(Z))return{error:`找不到 daemon bundle: ${Z}`};let J=d9(process.execPath,[Z],{detached:!0,stdio:"ignore",windowsHide:!0});return J.unref(),{pid:J.pid}}catch($){return{error:$?.message??String($)}}}async function RB(){if(!process.stdin.isTTY)console.error(`${L.red}lodestar-setup: stdin 不是 TTY,无法交互式输入。${L.reset}`),console.error("请直接在 cmd / PowerShell / Terminal 里跑,不要 pipe 或重定向 stdin。"),process.exit(1);if(U7(N0)){if(console.log(`${L.yellow}发现已有配置: ${N0}${L.reset}`),(await M1("覆盖? (y/N)",{default:"n"})).toLowerCase()!=="y"){console.log("已取消"),_4.close();return}}qB("Lodestar 安装向导"),console.log("Lodestar 把 Feishu (飞书) 群聊接到 AI agent。"),console.log("默认后端是 Claude Code; Codex 是可选第二后端, 群里发 model 一键切换。"),console.log("每个群对应一个项目目录, agent 在那里跑、能读写文件。"),console.log(),console.log(`${L.yellow}⚠ Claude 官方限制:${L.reset}`),console.log(` ${L.bold}Claude 订阅 (Pro/Max OAuth 登录) 不支持本项目${L.reset},`),console.log(" 必须走 API 方式 —— 推荐 GLM Coding Plan, 或自备 Anthropic API key。"),console.log(),console.log("本向导依次做 4 件事:"),console.log(` ${L.dim}1) 确保 Claude Code CLI 已装好${L.reset}`),console.log(` ${L.dim}2) GLM Coding Plan API key (推荐, 可选) + Codex (可选)${L.reset}`),console.log(` ${L.dim}3) Feishu 自建应用 (含权限 / 事件 / 发版 + 凭据测试)${L.reset}`),console.log(` ${L.dim}4) 工作目录, 自动启动 daemon${L.reset}`),console.log(),await _4.question(`${L.dim}按 Enter 开始 (Ctrl+C 退出)...${L.reset}`),l9(1,4,"准备 Claude Code CLI"),await u9("claude",{report:(B)=>console.log(B)}),console.log(`${L.green}✓ Claude Code / SDK 已更新${L.reset}: ${L.dim}${B4("claude","claude")}${L.reset}`),console.log(),console.log(`${L.dim}下一步可选配 GLM Coding Plan 自动写入路由; 不配则用本机 Claude Code 现有配置。${L.reset}`),console.log(`${L.dim}记住: 别用 \`claude\` 走订阅 OAuth 登录 —— 订阅不支持本项目, 要用 API key。${L.reset}`),l9(2,4,"GLM Coding Plan (推荐, 可选)"),console.log("GLM Coding Plan 给 Claude Code 接 GLM 系列模型 (支持 1M token 上下文, 中文友好)。"),console.log("订阅后在智谱开放平台拿一个 API key, 粘到下面 —— 向导自动写进 ~/.claude/settings.json。"),console.log(` ${L.dim}拿 key: https://open.bigmodel.cn → 控制台 → API Keys${L.reset}`),console.log(` ${L.dim}不给也行: 以本机 Claude Code 现有配置启动 (确保是 API key 方式, 非订阅)。${L.reset}`),console.log();let $=await M1("GLM API key (直接回车跳过)",{});if($){let B=await MB($);if("path"in B)console.log(`${L.green}✓ GLM 路由已写入${L.reset}: ${L.dim}${B.path}${L.reset}`),console.log(`${L.dim}模型 slots 按端点当前列表自动选取(最新一代 opus/sonnet, 1M ctx)${L.reset}`);else console.log(`${L.red}✗ 写入失败:${L.reset} ${B.error}`),console.log(`${L.dim}跳过 GLM 配置, 以本机 Claude Code 现有配置启动。${L.reset}`)}else console.log(`${L.dim}已跳过 GLM, 以本机 Claude Code 现有配置启动。${L.reset}`);if(console.log(),console.log(`${L.bold}Codex (可选第二后端)${L.reset}`),console.log(` ${L.dim}想用 Codex 的话, 登录 ChatGPT 订阅即可, 模型/effort 走 ~/.codex/config.toml, 群里发 model 切换。${L.reset}`),(await M1("现在顺便配置 Codex 后端吗?",{default:"n"})).toLowerCase()==="y"){await u9("codex",{report:(_)=>console.log(_)});let B=B4("codex","codex");if(OY(B))console.log(`${L.green}✓ Codex 已登录 ChatGPT${L.reset}`);else if(console.log(`${L.dim}启动 \`codex login\`...${L.reset}`),await PB(B)&&OY(B))console.log(`${L.green}✓ Codex 已登录 ChatGPT${L.reset}`);else console.log(`${L.yellow}Codex 登录未完成 — 不影响默认 Claude 后端; 需要时随时跑 codex login。${L.reset}`)}else console.log(`${L.dim}已跳过 Codex (需要时随时跑 codex login, 群里发 model 切)。${L.reset}`);l9(3,4,"Feishu 自建应用");let J="https://open.feishu.cn/app";console.log("打开飞书开放平台 (浏览器):"),console.log(` ${L.cyan}${J}${L.reset}`),UB(J),console.log(`${L.dim}(如果浏览器没自动开, 复制上面 URL 粘到浏览器)${L.reset}`),console.log(),console.log(`${L.bold}详细操作步骤:${L.reset}`),console.log(),console.log(` ${L.bold}① 创建应用${L.reset}`),console.log(` 点 "创建企业自建应用", 填名字 (如 ${L.dim}Lodestar${L.reset}), logo 随意。`),console.log(),console.log(` ${L.bold}② 添加机器人能力${L.reset}`),console.log(` 左侧菜单 "${L.cyan}添加应用能力${L.reset}" → 找到 "机器人" → 点 "${L.bold}添加${L.reset}" 按钮。`),console.log(),console.log(` ${L.bold}③ 申请权限 (左侧 "${L.cyan}权限管理${L.reset}" → "${L.bold}批量导入/导出权限${L.reset}")${L.reset}`),console.log(` ${L.yellow}选择应用身份权限,复制下方完整 JSON 批量导入,一次开齐账号信息、消息、卡片和云空间能力。${L.reset}`),console.log(JSON.stringify(AY,null,2)),console.log(` ${L.dim}无需用户身份权限或飞书 CLI 登录。权限申请后须完成审批,并在步骤 ⑤ 发布飞书应用版本。${L.reset}`),console.log(` ${L.dim}清单包含以下用途;也可按名称逐项开通:${L.reset}`),console.log(` ${L.dim}账号与认证信息 (排障):${L.reset}`),console.log(` • ${L.bold}verification:verification_information:readonly${L.reset} ${L.dim}# 查看账号主体认证状态${L.reset}`),console.log(` • ${L.bold}tenant:tenant:readonly${L.reset} ${L.dim}# 查看租户基本信息${L.reset}`),console.log(` ${L.dim}消息类:${L.reset}`),console.log(` • ${L.bold}im:message:send_as_bot${L.reset} ${L.dim}# 以机器人身份发消息${L.reset}`),console.log(` • ${L.bold}im:message${L.reset} ${L.dim}# 接收/操作消息 (核心)${L.reset}`),console.log(` • ${L.bold}im:chat${L.reset} ${L.dim}# 读/写群信息 (匹配群名 ↔ 项目目录)${L.reset}`),console.log(` • ${L.bold}im:chat:create${L.reset} ${L.dim}# wt: 自动创建 worktree 群${L.reset}`),console.log(` • ${L.bold}im:chat:delete${L.reset} ${L.dim}# wt: 解散 worktree 群${L.reset}`),console.log(` • ${L.bold}im:chat.members:read${L.reset} ${L.dim}# wt: 判断发起人是否已在群内${L.reset}`),console.log(` • ${L.bold}im:chat.members:write_only${L.reset} ${L.dim}# wt: 把发起人拉进已有 worktree 群${L.reset}`),console.log(` • ${L.bold}im:resource${L.reset} ${L.dim}# 上传/下载附件 (图文双向)${L.reset}`),console.log(` • ${L.bold}im:message.urgent${L.reset} ${L.dim}# 加急推送 (锁屏通知 / Ask)${L.reset}`),console.log(` • ${L.bold}im:message.group_msg${L.reset} ${L.dim}# 敏感: 接收群里所有消息${L.reset}`),console.log(` ${L.dim}└ 关键: 没它机器人只收 @ 自己的消息, 拿不到群里其他对话, 一定要开${L.reset}`),console.log(` ${L.dim}└ 敏感权限要走审批: 申请时填用途, 个人开发者通常秒过${L.reset}`),console.log(` • ${L.bold}im:message.group_at_msg:readonly${L.reset} ${L.dim}# 读 @ 机器人消息 (兜底)${L.reset}`),console.log(` ${L.dim}卡片类 (Card Kit):${L.reset}`),console.log(` • ${L.bold}cardkit:card:read${L.reset} ${L.dim}# 读卡片状态${L.reset}`),console.log(` • ${L.bold}cardkit:card:write${L.reset} ${L.dim}# 创建/更新卡片 (流式渲染核心)${L.reset}`),console.log(` ${L.dim}云空间交付 (权限预先开通,功能仍按群开启):${L.reset}`),console.log(` • ${L.bold}drive:drive${L.reset} ${L.dim}# 上传、创建目录、协作者授权、关闭并核对文件链接分享${L.reset}`),console.log(` • ${L.bold}drive:file:upload${L.reset} ${L.dim}# 文件夹改名接口单独要求此权限${L.reset}`),console.log(` ${L.dim}默认仍直接发聊天附件;在指定群发送 files on 开启云空间,files off 恢复附件。${L.reset}`),console.log(` ${L.yellow}只取得 tenant_access_token 不代表以上权限已生效;缺少权限时群内命令会明确报错。${L.reset}`),console.log(),console.log(` ${L.bold}④ 订阅事件 (左侧 "${L.cyan}事件与回调${L.reset}", 拆两个子页:)${L.reset}`),console.log(` ${L.dim}a)${L.reset} ${L.bold}事件配置${L.reset} 页:`),console.log(` ${L.yellow}• "订阅方式" → 选 "长连接" → 点保存${L.reset}`),console.log(` • 添加事件: ${L.bold}im.message.receive_v1${L.reset} ${L.dim}# 收群消息${L.reset}`),console.log(` ${L.dim}b)${L.reset} ${L.bold}回调配置${L.reset} 页:`),console.log(` ${L.yellow}• "订阅方式" → 选 "长连接" → 点保存${L.reset}`),console.log(` • 添加事件: ${L.bold}card.action.trigger${L.reset} ${L.dim}# 卡片按钮点击回调${L.reset}`),console.log(),console.log(` ${L.bold}⑤ 发布版本${L.reset}`),console.log(` 页面顶部 "${L.bold}创建版本${L.reset}" → 滚到底点 "${L.bold}保存${L.reset}" → 弹框点 "${L.bold}发布${L.reset}"。`),console.log(` ${L.yellow}没发版的应用收不到任何事件 — 这步九成新手会忘!${L.reset}`),console.log(),console.log(` ${L.bold}⑥ 拿凭据${L.reset}`),console.log(` 左侧 "凭证与基础信息" → 顶部 ${L.bold}App ID${L.reset} (${L.dim}cli_...${L.reset}) 和 ${L.bold}App Secret${L.reset}, 待会粘到下面。`),console.log(),console.log(` ${L.bold}⑦ 把机器人拉进群${L.reset}`),console.log(" 想用的飞书群 → 群设置 → 群机器人 → 添加机器人 → 选你的应用。"),console.log(` ${L.yellow}群名要等于 projects_root 下的项目目录名${L.reset} (下一步设, 默认是用户主目录)。`),console.log();let Y="",Q="";while(!0){Y=await M1("App ID (以 cli_ 开头)",{required:!0}),Q=await M1("App Secret",{required:!0}),console.log(`${L.dim}测试中... (调 tenant_access_token endpoint)${L.reset}`);let B=await AB(Y,Q);if(B.ok){console.log(`${L.green}✓ Feishu 凭据测试通过${L.reset}`);break}if(console.log(`${L.red}✗ 测试失败:${L.reset} ${B.error}`),console.log(`${L.dim}最常见原因: app_id / app_secret 抄错, 或应用还没 "发布上线" (步骤 ⑤)。${L.reset}`),console.log(),(await M1("重新填? (Y/n)",{default:"y"})).toLowerCase()==="n")console.log(`${L.yellow}已取消, 配置未写盘。${L.reset}`),_4.close(),process.exit(1)}l9(4,4,"工作目录 + 启动"),console.log("每个 Feishu 群对应 projects_root 下同名的目录。"),console.log();let V=process.platform==="win32"?process.env.USERPROFILE??"C:\\Users\\Default":process.env.HOME??"/root",H=await M1("projects_root",{default:V});RY(Y7,{recursive:!0});let X=["# Lodestar config — generated by `lodestar-setup`","# Edit by hand or re-run setup to overwrite.","","[feishu]",`app_id = "${M7(Y)}"`,`app_secret = "${M7(Q)}"`,"","[runtime]",`projects_root = "${M7(H)}"`,"","[runtime.agent_auto_update]","codex = false","claude = false","dsh = false",""];I0(N0,X.join(`
|
|
58
58
|
`)),console.log(`
|
|
59
59
|
${L.green}${L.bold}✓ 配置已写入${L.reset}`),console.log(` ${L.cyan}${N0}${L.reset}`),console.log(`
|
|
60
|
-
${L.bold}启动 daemon...${L.reset}`);let z=
|
|
61
|
-
`;if(process.stderr.write(J),!
|
|
62
|
-
${this.stderr}`);this.rejectPending(h),
|
|
60
|
+
${L.bold}启动 daemon...${L.reset}`);let z=OB(),W=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(z.pid)console.log(`${L.green}✓ daemon 已在后台启动${L.reset} (pid ${z.pid})`),console.log(),console.log(`${L.bold}最后一步: 在 Feishu 验证${L.reset}`),console.log(" ① 把机器人拉进任意飞书群"),console.log(` ② 群名 = ${L.cyan}${H}${W}<群名>${L.reset} 下的目录名 (新群第一条消息会自动建)`),console.log(" ③ 在群里发任意一条消息, 默认由 Claude 接管"),console.log(` ${L.dim}(群里发 model 可选择已配置账号、动态模型和 effort)${L.reset}`),console.log(),console.log("日志 (按日滚动, 保留近 7 天):"),console.log(` ${L.cyan}${G}${L.reset}`),console.log(),console.log(`${L.dim}若长期跑后台, Linux 配 systemd --user,macOS 配 launchd,Windows 配任务计划程序。${L.reset}`);else console.log(`${L.yellow}启动失败: ${z.error}${L.reset}`),console.log(`手动运行: ${L.cyan}lodestar-daemon${L.reset}`);console.log(),_4.close()}var L,_4;var TY=R(()=>{h0();Q0();T0();V2();UY();L={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m"},_4=BB({input:process.stdin,output:process.stdout})});import{existsSync as NB,readFileSync as TB}from"node:fs";function EY($,Z){return`${$}:${Z}`}function EB(){if(!NB(k9))return;try{let $=JSON.parse(TB(k9,"utf8"));if($?.version!==1||!Array.isArray($.ids)||$.ids.some((Z)=>typeof Z!=="string"||!Z))throw Error("invalid delegated-agent session registry");j4=new Set($.ids)}catch($){O7=$ instanceof Error?$:Error(String($))}}function xY(){if(O7)throw Error(`delegated-agent session registry is unavailable: ${O7.message}`)}function SY($,Z){xY();let J=Z.trim();if(!J)throw Error("delegated-agent session id is empty");let Y=EY($,J);if(j4.has(Y))return;let Q=new Set(j4);Q.add(Y),s(k9,{version:1,ids:[...Q].sort()}),j4=Q}function H2($,Z){return xY(),j4.has(EY($,Z))}var j4,O7=null;var L4=R(()=>{Q0();T0();j4=new Set;EB()});var bY=1;import{appendFileSync as yY,mkdirSync as xB,readdirSync as SB,unlinkSync as wY,existsSync as CY,statSync as bB,renameSync as CB,readFileSync as kB}from"node:fs";import{join as vY}from"node:path";function T7($="development"){return $!=="test"}function fY($){let Z=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),Y=String($.getDate()).padStart(2,"0");return`${Z}-${J}-${Y}`}function hY($,Z=r){return vY(Z,`${R7}${fY($)}${N7}`)}function wB($){if(!$.startsWith(R7)||!$.endsWith(N7))return null;let Z=$.slice(R7.length,$.length-N7.length),J=/^(\d{4})-(\d{2})-(\d{2})$/.exec(Z);if(!J)return null;let Y=new Date(Number(J[1]),Number(J[2])-1,Number(J[3]));return Number.isNaN(Y.getTime())?null:Y}function IY($,Z=new Date,J=yB){let Y;try{Y=SB($)}catch{return 0}let Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),V=0;for(let H of Y){let X=wB(H);if(!X)continue;if(Math.round((Q.getTime()-X.getTime())/86400000)<J)continue;try{wY(vY($,H)),V++}catch{}}return V}function vB(){try{if(!CY(J2))return;let $=bB(J2);if(!$.isFile()||$.size===0)return;let Z=hY($.mtime);if(CY(Z)){yY(Z,kB(J2)),wY(J2);return}CB(J2,Z)}catch{}}function K($){let Z=new Date,J=`[${Z.toISOString()}] ${$}
|
|
61
|
+
`;if(process.stderr.write(J),!T7())return;try{let Y=fY(Z);if(kY!==Y)kY=Y,IY(r,Z);yY(hY(Z),J)}catch{}}var yB=7,R7="daemon-",N7=".log",kY=null;var I=R(()=>{Q0();if(T7())try{xB(r,{recursive:!0})}catch{}if(T7()){vB();try{IY(r)}catch{}}});import{EventEmitter as fB}from"node:events";import{createRequire as hB}from"node:module";import{createHash as IB,randomUUID as gB}from"node:crypto";import{createInterface as mB}from"node:readline";import{dirname as pB,join as S$,isAbsolute as cB}from"node:path";import{fileURLToPath as E7}from"node:url";import{tmpdir as uB}from"node:os";import{existsSync as gY,mkdirSync as mY,mkdtempSync as lB,readFileSync as q4,renameSync as dB,writeFileSync as pY,rmSync as x7}from"node:fs";import iB from"cross-spawn";function nB($){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((Y)=>typeof Y==="string"&&Y)))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((Y)=>({id:Y,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 aB($,Z){if(Z?.loadProjectMcp===!1)return[];let J;try{J=q4(S$($,".mcp.json"),"utf8")}catch(Q){if(Q?.code==="ENOENT")return[];throw Q}let Y=JSON.parse(J);if(!Y.mcpServers||typeof Y.mcpServers!=="object"||Array.isArray(Y.mcpServers))throw Error("DSH project .mcp.json must contain an mcpServers object");return Object.entries(Y.mcpServers).map(([Q,V])=>{if(!/^[A-Za-z0-9_-]{1,32}$/.test(Q)||!V||typeof V!=="object")throw Error(`invalid DSH MCP server: ${Q}`);let H=V,X=H.type==="http"?{transport:"streamable-http",serverName:Q,url:H.url,headers:H.headers??{}}:H.type===void 0||H.type==="stdio"?{transport:"stdio",serverName:Q,command:H.command,args:H.args??[],env:H.env??{},cwd:$}:null;if(!X)throw Error(`DSH does not support MCP transport ${H.type} for ${Q}`);return{id:`lodestar-mcp-${Q}`,name:"@deepseek-ai/dsh-mcp-client",config:{...X,failOnStartupError:!0}}})}async function X2($,Z,J={}){let Y=new i9($);Y.on("failure",(H)=>K(`dsh catalog: ${H}`));let Q,V;try{await Y.initialize(),V=await Y.request(Z,J)}catch(H){Q=H}try{await Y.close()}catch(H){if(Q)throw AggregateError([Q,H],"DSH query and cleanup both failed");throw H}if(Q)throw Q;return V}var i9;var P4=R(()=>{Q0();V2();I();i9=class i9 extends fB{child;pending=new Map;nextId=0;exited=!1;closing=!1;stderr="";initialized=!1;initTask;closeTask;exitTask;launchDir;constructor($){super();if(!cB($.cwd))throw Error("DSH requires an absolute workspace");let Z=c9("dsh"),Y=hB(S$(Z,"package.json")).resolve("@deepseek-ai/dsh/package.json"),Q=JSON.parse(q4(Y,"utf8"));K(`dsh runtime: ${Q.version} (${Z})`);let V=nB($.env),H=$.home??Y2;mY(H,{recursive:!0,mode:448});let X=aB($.cwd,$.profile);this.launchDir=lB(S$(uB(),"lodestar-dsh-"));let z=import.meta.url.endsWith(".ts"),W=z?"dsh-bridge.ts":"dsh-bridge.js",G=q4(E7(new URL(`./${W}`,import.meta.url))),B=z?q4(E7(new URL("./dsh-protocol.ts",import.meta.url))):Buffer.alloc(0),_=JSON.parse(q4(E7(new URL("../package.json",import.meta.url)),"utf8")),j=Buffer.from(JSON.stringify({name:_.name,version:_.version,type:"module",private:!0})),q=IB("sha256").update(G).update(B).update(j).digest("hex").slice(0,20),P=S$(Z,".lodestar-bridges",q);mY(P,{recursive:!0});let D=S$(P,W),T=(y,g)=>{if(gY(y))return;let x=`${y}.${gB()}.tmp`;try{pY(x,g),dB(x,y)}finally{if(gY(x))x7(x)}};if(T(S$(P,"package.json"),j),z)T(S$(P,"dsh-protocol.ts"),B);T(D,G);let M=[...["sdk-jsonrpc-server","session-title-llm","session-telemetry-otel","settings","credentials","llm-pi-ai"].map((y)=>({id:y,disabled:!0})),{id:"approval",config:{policy:"ask"}},{id:"permission",config:{defaultPreset:"lodestar",presets:{lodestar:{sandbox:"danger-full-access",approval:"ask"}}}},{id:"system-prompt",config:{personaPrefix:"You are a coding agent powered by {{model}}.",personaSuffix:"Your working directory is {{cwd}}."}},{id:"skill-filesystem",config:{includeDefaultRoots:!0,...$.managedSkillDir?{customSkillDirs:[$.managedSkillDir]}:{}}},{insert:[{id:"lodestar-bridge",name:D},{id:"lodestar-ask-user",name:"@deepseek-ai/dsh-tool-ask-user"},...X]},...V],A=S$(this.launchDir,"bridge.patch.yml");pY(A,JSON.stringify(M),{mode:384});let U=$.env.LODESTAR_DSH_NODE||"node",S=[S$(pB(Y),Q.bin.dsh),"--profile","sdk","--patch",A,...($.patches??[]).flatMap((y)=>["--patch",y])],b={...$.env};if(b.LODESTAR_AGENT_CAPABILITY&&b.LODESTAR_AGENT_URL)b.DSH_LODESTAR_AGENT_CONTEXT=JSON.stringify({baseUrl:b.LODESTAR_AGENT_URL,capability:b.LODESTAR_AGENT_CAPABILITY});for(let y of Object.keys(b))if(y.startsWith("LODESTAR_AGENT_"))delete b[y];try{this.child=iB(U,S,{cwd:$.cwd,stdio:["pipe","pipe","pipe"],shell:!1,env:{...b,DSH_HOME:H,DSH_PERMISSION_MODE:"danger-full-access"}})}catch(y){throw x7(this.launchDir,{recursive:!0,force:!0}),y}this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",(y)=>{this.stderr=(this.stderr+y).slice(-16384),K(`dsh stderr: ${y.trimEnd()}`)}),this.child.stdin.on("error",(y)=>this.transportFailure(y));let v=mB({input:this.child.stdout,crlfDelay:1/0});v.on("line",(y)=>this.receive(y)),this.exitTask=new Promise((y)=>{this.child.once("error",(g)=>this.transportFailure(g)),this.child.once("close",(g,x)=>{this.exited=!0,v.close();let h=Error(`DSH exited code=${g} signal=${x}
|
|
62
|
+
${this.stderr}`);this.rejectPending(h),x7(this.launchDir,{recursive:!0,force:!0}),y(),this.emit("exit",{code:g,signal:x,expected:this.closing})})})}get pid(){return this.child.pid}isAlive(){return!this.exited}initialize(){return this.initTask??=this.request("initialize",{},30000).then(($)=>{if($.protocolVersion!==bY||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 Y=++this.nextId;return new Promise((Q,V)=>{let H=J===null?void 0:setTimeout(()=>{this.pending.delete(Y),V(Error(`DSH ${$} timed out after ${J}ms
|
|
63
63
|
${this.stderr}`))},J);this.pending.set(Y,{resolve:Q,reject:V,timer:H}),this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",id:Y,method:$,params:Z})+`
|
|
64
|
-
`,(X)=>{if(X)this.transportFailure(X)})})}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){K(`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){K(`dsh shutdown: ${J}`)}this.child.stdin.end();let Z=async(J)=>{let Y;return await Promise.race([this.exitTask,new Promise((Q)=>{Y=setTimeout(Q,J)})]),clearTimeout(Y),this.exited};if(await Z($))return;if(K(`dsh: terminate owned child pid=${this.pid}`),this.child.kill("SIGTERM"),await Z($))return;if(K(`dsh: kill unresponsive owned child pid=${this.pid}`),this.child.kill("SIGKILL"),!await Z($))throw Error(`DSH child exit not confirmed: pid=${this.pid}`)}}});function B$($){return typeof $==="string"&&
|
|
65
|
-
`)){let Q=
|
|
64
|
+
`,(X)=>{if(X)this.transportFailure(X)})})}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){K(`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){K(`dsh shutdown: ${J}`)}this.child.stdin.end();let Z=async(J)=>{let Y;return await Promise.race([this.exitTask,new Promise((Q)=>{Y=setTimeout(Q,J)})]),clearTimeout(Y),this.exited};if(await Z($))return;if(K(`dsh: terminate owned child pid=${this.pid}`),this.child.kill("SIGTERM"),await Z($))return;if(K(`dsh: kill unresponsive owned child pid=${this.pid}`),this.child.kill("SIGKILL"),!await Z($))throw Error(`DSH child exit not confirmed: pid=${this.pid}`)}}});function B$($){return typeof $==="string"&&S7.includes($)}function B0($){return typeof $==="string"&&["off","minimal","low","medium","high","xhigh","max"].includes($)}function E0($){return typeof $==="string"&&b7.includes($)}function z2($){if($?.startsWith("dsh:"))return"dsh";return $?.startsWith("claude:")?"claude":"codex"}function _$($){return{claude:"Claude",codex:"Codex",dsh:"DeepSeek Harness"}[$]}var S7,b7,a$="max",U1;var D0=R(()=>{S7=["codex","claude","dsh"];b7=["low","medium","high","xhigh","max","default"];U1=class U1 extends Error{constructor($="上下文窗口充足,无需压缩"){super($);this.name="NothingToCompactError"}}});import{readFileSync as oB}from"node:fs";import{homedir as uY}from"node:os";function cY($){return $.replace(/^~(?=\/|$)/,uY())}function rB($){let Z={_:{}},J="_";for(let Y of $.split(`
|
|
65
|
+
`)){let Q=sB(Y).trim();if(!Q)continue;let V=Q.match(/^\[([^\]]+)\]$/);if(V){J=V[1].trim(),Z[J]??={};continue}let H=Q.match(/^([\w.-]+)\s*=\s*(.+)$/);if(H){let X=H[2].trim(),z=X.startsWith('"')&&X.endsWith('"'),W=X.startsWith("'")&&X.endsWith("'");if(z||W){if(X=X.slice(1,-1),z)X=X.replace(/\\([\\"])/g,"$1")}Z[J][H[1]]=X}}return Z}function sB($){let Z=null,J=!1;for(let Y=0;Y<$.length;Y++){let Q=$[Y];if(Z==="double"){if(J){J=!1;continue}if(Q==="\\"){J=!0;continue}if(Q==='"')Z=null;continue}if(Z==="single"){if(Q==="'")Z=null;continue}if(Q==='"')Z="double";else if(Q==="'")Z="single";else if(Q==="#")return $.slice(0,Y)}return $}function n9(){let $;try{$=oB(N0,"utf8")}catch(U){throw process.stderr.write(`lodestar: cannot read config at ${N0}
|
|
66
66
|
`+" → 运行 `lodestar-setup` 走交互式向导生成 (Feishu / Codex / 工作目录)\n"+` → 或手写: 设 LODESTAR_CONFIG=/path/to/config.toml 覆盖默认路径
|
|
67
67
|
`+` [feishu]
|
|
68
68
|
app_id = "cli_xxx"
|
|
69
69
|
app_secret = "xxx"
|
|
70
70
|
|
|
71
|
-
`),U}let Z=
|
|
72
|
-
`)}else if(H)for(let[U,S]of Object.entries(H)){if(U!=="codex"&&U!=="claude"&&U!=="dsh")throw Error(`lodestar: unknown [runtime.agent_auto_update] Agent "${U}"`);if(S!=="true"&&S!=="false")throw Error(`lodestar: [runtime.agent_auto_update].${U} must be true or false, got "${S}"`);V[U]=S==="true"}let z=(Z.runtime?.live_elapsed??"bucket").trim().toLowerCase();if(z!=="bucket"&&z!=="second")throw Error(`lodestar: [runtime].live_elapsed must be "bucket" or "second", got "${Z.runtime?.live_elapsed}"`);let W=z,G=Z.notify?.bind??"127.0.0.1",B=Z.notify?.port??"9876";if(!/^\d+$/.test(B.trim()))throw Error(`lodestar: [notify].port must be an integer, got "${B}"`);let _=Number.parseInt(B,10);if(!Number.isFinite(_)||_<=0||_>65535)throw Error(`lodestar: [notify].port must be 1..65535, got "${B}"`);let j=(U)=>{let S=Z[U]??{},b={};for(let[v,y]of Object.entries(S))if(typeof y==="string"&&y.length>0)b[v]=y;return b},q=()=>{let U={};for(let[S,b]of Object.entries(Z)){if(!S.startsWith("claude.models."))continue;let y=S.slice(14).trim();if(!y)continue;let g={};for(let[x,h]of Object.entries(b)){if(typeof h!=="string"||h.length===0)continue;if(x.trim()==="model")g.model=h}U[y]=g}return U},P=()=>{let U={},S="projects.";for(let[b,v]of Object.entries(Z)){if(!b.startsWith("projects."))continue;let y=b.slice(9).trim();if(!y)continue;let g={};for(let[x,h]of Object.entries(v)){if(typeof h!=="string"||h.length===0)continue;switch(x.trim()){case"cwd":g.cwd=h;break;case"setting_sources":g.settingSources=h;break;case"strict_mcp":g.strictMcp=h==="true";break;case"tools":g.tools=h;break;case"load_project_mcp":g.loadProjectMcp=h==="true";break}}U[y]=g}return U},
|
|
71
|
+
`),U}let Z=rB($),J=Z.feishu?.app_id,Y=Z.feishu?.app_secret;if(!J||!Y)throw Error(`lodestar: ${N0} is missing [feishu].app_id / [feishu].app_secret`);let Q=cY(Z.runtime?.projects_root??uY()),V={codex:!1,claude:!1,dsh:!1},H=Z["runtime.agent_auto_update"],X=Z.runtime?.agent_auto_update;if(X!==void 0){if(H)throw Error("lodestar: legacy [runtime].agent_auto_update cannot be combined with [runtime.agent_auto_update]");if(X!=="true"&&X!=="false")throw Error(`lodestar: [runtime].agent_auto_update must be true or false, got "${X}"`);for(let U of["codex","claude","dsh"])V[U]=X==="true";process.stderr.write(`lodestar: 旧 agent_auto_update 总开关已按原值映射为三个开关;请改用 [runtime.agent_auto_update] 的 codex、claude、dsh 配置。
|
|
72
|
+
`)}else if(H)for(let[U,S]of Object.entries(H)){if(U!=="codex"&&U!=="claude"&&U!=="dsh")throw Error(`lodestar: unknown [runtime.agent_auto_update] Agent "${U}"`);if(S!=="true"&&S!=="false")throw Error(`lodestar: [runtime.agent_auto_update].${U} must be true or false, got "${S}"`);V[U]=S==="true"}let z=(Z.runtime?.live_elapsed??"bucket").trim().toLowerCase();if(z!=="bucket"&&z!=="second")throw Error(`lodestar: [runtime].live_elapsed must be "bucket" or "second", got "${Z.runtime?.live_elapsed}"`);let W=z,G=Z.notify?.bind??"127.0.0.1",B=Z.notify?.port??"9876";if(!/^\d+$/.test(B.trim()))throw Error(`lodestar: [notify].port must be an integer, got "${B}"`);let _=Number.parseInt(B,10);if(!Number.isFinite(_)||_<=0||_>65535)throw Error(`lodestar: [notify].port must be 1..65535, got "${B}"`);let j=(U)=>{let S=Z[U]??{},b={};for(let[v,y]of Object.entries(S))if(typeof y==="string"&&y.length>0)b[v]=y;return b},q=()=>{let U={};for(let[S,b]of Object.entries(Z)){if(!S.startsWith("claude.models."))continue;let y=S.slice(14).trim();if(!y)continue;let g={};for(let[x,h]of Object.entries(b)){if(typeof h!=="string"||h.length===0)continue;if(x.trim()==="model")g.model=h}U[y]=g}return U},P=()=>{let U={},S="projects.";for(let[b,v]of Object.entries(Z)){if(!b.startsWith("projects."))continue;let y=b.slice(9).trim();if(!y)continue;let g={};for(let[x,h]of Object.entries(v)){if(typeof h!=="string"||h.length===0)continue;switch(x.trim()){case"cwd":g.cwd=h;break;case"setting_sources":g.settingSources=h;break;case"strict_mcp":g.strictMcp=h==="true";break;case"tools":g.tools=h;break;case"load_project_mcp":g.loadProjectMcp=h==="true";break}}U[y]=g}return U},D=()=>{let U={},S="token_source.";for(let[b,v]of Object.entries(Z)){if(!b.startsWith("token_source."))continue;let y=b.slice(13).trim();if(!y)continue;let g={};for(let[x,h]of Object.entries(v)){if(typeof h!=="string")continue;let p=x.trim();if(p==="default")g.default=h==="true";else if(p==="agent"||p==="display"||p==="auth"||p==="base_url"||p==="auth_token"||p==="api_key"||p==="bin"||p==="model"||p==="effort"||p==="models"||p==="hidden_models"||p==="custom_models"||p==="slots"||p==="usage")g[p]=h}U[y]=g}return U},T=j("codex.env"),M=j("claude.env"),A=Z.claude?.bin?cY(Z.claude.bin):void 0;return{feishu:{app_id:J,app_secret:Y},runtime:{projects_root:Q,live_elapsed:W,agent_auto_update:V},notify:{bind:G,port:_},codex:{env:T},claude:{bin:A,env:M,models:q()},projects:P(),token_sources:D()}}function lY(){f.token_sources=n9().token_sources}var f;var y0=R(()=>{Q0();f=n9()});function W0($){return typeof $==="string"&&$?$:void 0}function a($){return $!=null&&typeof $==="object"?$:null}function b$($){if($==null||$==="")return"-";return String($).replace(/\s+/g," ").slice(0,300)}function a9($){if(!$)return"[]";let Z=Object.keys($),J=Z.slice(0,80),Y=Z.length>J.length?`,...+${Z.length-J.length}`:"";return`[${J.join(",")}${Y}]`}function eB($){let Z=$.slice(0,y7),J=$.length>Z.length?`,...+${$.length-Z.length}`:"";return`[${Z.join(",")}${J}]`}function $_($){let Z=a($);if(!Z)return null;let J=a(Z.event),Y=a(Z.payload);return a(Z.item)??a(Z.responseItem)??a(Z.rawItem)??a(J?.item)??a(J?.responseItem)??a(J?.rawItem)??a(Y?.item)??a(Y?.responseItem)??a(Y?.rawItem)??(D4(Z.type)?Z:null)??(J&&D4(J.type)?J:null)??(Y&&D4(Y.type)?Y:null)}function Z_($){let Z=[],J=new WeakSet,Y=(Q,V,H)=>{if(Z.length>=y7||H>6)return;if(Array.isArray(Q)){if(V)Z.push(`${V}[]`);if(Q.length>0)Y(Q[0],V?`${V}[]`:"[]",H+1);return}if(Q==null||typeof Q!=="object")return;if(J.has(Q))return;J.add(Q);for(let X of Object.keys(Q)){if(Z.length>=y7)return;let z=V?`${V}.${X}`:X;Z.push(z),Y(Q[X],z,H+1)}};return Y($,"",0),Z}function w7($){let Z=new WeakSet,J;try{J=JSON.stringify($,(Y,Q)=>{if(typeof Q==="bigint")return`${Q.toString()}n`;if(typeof Q==="string"&&Q.length>k7)return`${Q.slice(0,k7)}...<truncated ${Q.length-k7} chars>`;if(Q!=null&&typeof Q==="object"){if(Z.has(Q))return"[Circular]";Z.add(Q)}return Q})??String($)}catch(Y){J=`<unserializable: ${Y}>`}if(J.length>C7)return`${J.slice(0,C7)}...<truncated ${J.length-C7} chars>`;return J}function m0($,Z){let J=a(Z),Y=J?a(J.params):null,Q=J?a(J.item)??a(Y?.item):null,V=J?W0(J.method)??"-":"-";K([`codex-process: APP_SERVER_UNHANDLED_${$}`,`method=${b$(V)}`,`rootKeys=${a9(J)}`,`itemKeys=${a9(Q)}`,`payload=${w7(Z)}`].join(" "))}function v7($,Z,J){let Y=a(Z),Q=$_(Z),V=[`phase=${b$(J.phase??"event")}`,`method=${b$($)}`,`sourceMethod=${b$(J.sourceMethod)}`,`sourceType=${b$(J.sourceType)}`,`sessionId=${b$(J.sessionId)}`,`threadId=${b$(J.threadId)}`,`turnId=${b$(J.turnId)}`,`itemId=${b$(J.itemId)}`].join(" ");if(K(`codex-process: CONTEXT_COMPACTION_EVENT ${V} rootKeys=${a9(Y)} itemKeys=${a9(Q)}`),K(`codex-process: CONTEXT_COMPACTION_PATHS ${V} paths=${eB(Z_(Z))}`),Q)K(`codex-process: CONTEXT_COMPACTION_ITEM ${V} item=${w7(Q)}`);K(`codex-process: CONTEXT_COMPACTION_PAYLOAD ${V} payload=${w7(Z)}`)}function D4($){if(typeof $!=="string")return null;return tB.has($)?$:null}function J_($,Z){if(Z==="item/started")return"start";if(Z==="item/completed"||Z==="rawResponseItem/completed")return"end";if($==="compacted")return"start";if($==="context_compacted"||dY.has(Z))return"end";return"event"}function f7($,Z){return iY($,a(Z)??{})}function h7($){let Z=a($);if(!Z)return null;let J=W0(Z.method)??W0(Z.type)??"raw_message";return iY(J,Z)}function iY($,Z){let J=a(Z.payload),Y=[Z,a(Z.event),J,a(Z.item),a(Z.responseItem),a(Z.rawItem)].filter((z)=>z!=null),Q=null;for(let z of Y)if(Q=D4(z.type),Q)break;if(!dY.has($)&&!Q)return null;let V=a(Z.item)??a(Z.responseItem)??a(Z.rawItem),H=Q==="compacted"&&J?J:V&&D4(V.type)?V:Z,X=a(H.item)??a(H.responseItem)??a(H.rawItem)??V??{};return{...H,threadId:W0(H.threadId)??W0(H.thread_id)??W0(Z.threadId)??W0(Z.thread_id),turnId:W0(H.turnId)??W0(H.turn_id)??W0(Z.turnId)??W0(Z.turn_id),itemId:W0(H.itemId)??W0(H.item_id)??W0(X.id)??W0(X.itemId)??W0(X.item_id),timestamp:W0(Z.timestamp)??W0(H.timestamp),recordType:W0(Z.type),phase:J_(Q,$),sourceMethod:$,sourceType:Q??$}}var dY,tB,C7=200000,k7=50000,y7=400;var I7=R(()=>{I();dY=new Set(["thread/compacted","context/compacted","context_compacted","contextCompacted"]),tB=new Set(["compacted","compaction","compaction_trigger","context_compacted","context_compaction","contextCompaction","ContextCompaction"])});function F4($){return $!=null&&typeof $==="object"?$:null}function C$($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function nY($){return Object.values($).some((Z)=>typeof Z==="number"&&Number.isFinite(Z))}function o9($,Z){return $?C$($[Z]):void 0}function W2($){let Z=F4($);if(!Z)return null;let J=F4(Z.inputTokensDetails)??F4(Z.input_tokens_details),Y=F4(Z.outputTokensDetails)??F4(Z.output_tokens_details),Q={total_tokens:C$(Z.totalTokens??Z.total_tokens),input_tokens:C$(Z.inputTokens??Z.input_tokens),output_tokens:C$(Z.outputTokens??Z.output_tokens),reasoning_output_tokens:C$(Z.reasoningOutputTokens??Z.reasoning_output_tokens??o9(Y,"reasoningTokens")??o9(Y,"reasoning_tokens")),cache_creation_input_tokens:C$(Z.cacheCreationInputTokens??Z.cache_creation_input_tokens),cache_read_input_tokens:C$(Z.cachedInputTokens??Z.cached_input_tokens??Z.cacheReadInputTokens??Z.cache_read_input_tokens??o9(J,"cachedTokens")??o9(J,"cached_tokens"))};return nY(Q)?Q:null}function g7($,Z){let J=(Q)=>{let V=C$($?.[Q]),H=C$(Z?.[Q]);if(V===void 0&&H===void 0)return;return Math.max(0,(V??0)-(H??0))},Y={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 nY(Y)?Y:null}function m7($){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 aY($){let Z=$.trim();if(Z.length<2)return Z;let J=r9[Z[0]];if(!J||!Z.endsWith(J))return Z;let Y=Z.slice(1,-1);if(Z[0]==="'")return Y.replace(/''/g,"'");if(Z[0]==='"')return Y.replace(/\\"/g,'"');return Y}function c7($){let Z=Q_(String($??"")),J=Z.split(`
|
|
73
73
|
`,1)[0]?.trim()??"",Q=(J.startsWith("#")&&!J.startsWith("#!")?J.replace(/^#\s*/,"").trim():"").replace(/^(?:desc|dec|description|说明|目的|用途)\s*[::]\s*/i,"").trim(),V=Q?Z.split(`
|
|
74
74
|
`).slice(1).join(`
|
|
75
|
-
`).trimStart():Z;return{description:Q,command:V||Z}}function G2($,Z=60){let{description:J,command:Y}=
|
|
76
|
-
`).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 Q=
|
|
77
|
-
`)}function
|
|
78
|
-
`).replace(/\s*"\s*'\$\(([^)]*)\)'/g,(H,X)=>` $(${X})`)}function H_($,Z){let J=s9[Z];for(let Y=0;Y<$.length;Y++){let Q=$[Y];if(Z==='"'&&Q==="\\"&&Y+1<$.length){Y++;continue}if(Q===J)return/^[\s]*$/.test($.slice(Y+1))}return!1}var s9;var t9=R(()=>{s9={'"':'"',"'":"'","“":"”"}});function O($){return $ instanceof Error?$.message:String($)}function U0($){return $.length<=16?$:`${$.slice(0,8)}…${$.slice(-4)}`}async function rY($,Z,J){let Y=null;try{return await Promise.race([$,new Promise((Q,V)=>{Y=setTimeout(()=>V(Error(`${J} timed out after ${Z/1000}s`)),Z)})])}finally{if(Y)clearTimeout(Y)}}import{isAbsolute as sY}from"node:path";function X_($){return $.kind==="fresh"?null:$.source.provider}function _0($,Z,J){let Y=X_($);if(Y&&Y!==Z)throw Error(`conversation launch provider mismatch: source=${Y} 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"||!sY($.source.cwd)))throw Error(`conversation launch source cwd is not absolute: ${String($.source.cwd)}`);if($.kind!=="fresh"&&J!==void 0){if(!sY(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 A1=()=>{};import{createHash as z_,randomUUID as tY}from"node:crypto";import{existsSync as e9,lstatSync as $8,mkdirSync as l7,readFileSync as eY,readdirSync as W_,realpathSync as K2,rmSync as G_,symlinkSync as K_,writeFileSync as B_}from"node:fs";import{homedir as __}from"node:os";import{isAbsolute as j_,join as k$,relative as L_,resolve as q_,sep as P_}from"node:path";class $Q{defaultHome;root;stateFile;constructor($=q_(process.env.CODEX_HOME||k$(__(),".codex")),Z=lJ,J=dJ){this.defaultHome=$;this.root=Z;this.stateFile=J}read(){if(!e9(this.stateFile))return{version:1,accounts:[],selections:{}};let $=JSON.parse(eY(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 Y of $.accounts){if(!Y||!/^[a-f0-9-]{36}$/.test(Y.id)||typeof Y.name!=="string"||Z.has(Y.id)||J.has(this.nameKey(Y.name)))throw Error("Codex 账号记录重复或无效");this.validateName(Y.name),Z.add(Y.id),J.add(this.nameKey(Y.name))}for(let Y of Object.values($.selections))if(Y!==u&&!Z.has(Y))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:u,name:"默认"},...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(u);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(u);this.validateName($);let Z=this.read(),J=Z.accounts.find((Q)=>this.nameKey(Q.name)===this.nameKey($));if(J)return{...J};let Y={id:tY(),name:$.normalize("NFC").trim()};return Z.accounts.push(Y),s(this.stateFile,Z),Y}remove($){let Z=this.get($);if($===u)throw Error("默认账号由设备原生 Codex 管理,不能用此命令删除");if(J8($))throw Error(`账号正在登录;先发送 codex-login-cancel ${Z.name}`);if(Y8($,!0))throw Error("账号正在使用中;请先结束使用该账号的会话或委派任务,额度及模型查询结束后重试");let J=this.read(),Y=this.home($),Q;try{Q=$8(Y)}catch(H){if(H.code!=="ENOENT")throw H}if(Q){if(Q.isSymbolicLink()||!Q.isDirectory())throw Error("额外账号目录不是独立目录,拒绝删除");if(e9(this.defaultHome)){let H=L_(K2(Y),K2(this.defaultHome));if(!H||!j_(H)&&H!==".."&&!H.startsWith(`..${P_}`))throw Error("额外账号目录包含默认认证目录,拒绝删除")}try{G_(Y,{recursive:!0})}catch(H){throw Error(`账号文件删除失败,账号记录已保留;${H}`)}}J.accounts=J.accounts.filter((H)=>H.id!==$);let V=0;for(let[H,X]of Object.entries(J.selections)){if(X!==$)continue;delete J.selections[H],V++}try{s(this.stateFile,J)}catch(H){throw Error(`账号文件已移除,但账号记录保存失败;请重试 codex-account-delete ${Z.name};${H}`)}return{account:Z,clearedSelections:V}}selected($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:u}preferred($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:null}selectAuto($){let Z=this.read();delete Z.selections[$],s(this.stateFile,Z)}select($,Z){this.get(Z);let J=this.read();Object.defineProperty(J.selections,$,{value:Z,enumerable:!0,writable:!0,configurable:!0}),s(this.stateFile,J)}recordLogin($,Z){let J=this.read();if($!==u){let Y=J.accounts.find((Q)=>Q.id===$);if(!Y)throw Error("登录完成时账号记录已不存在");Object.assign(Y,{email:Z.email,planType:Z.planType,revision:tY()}),s(this.stateFile,J)}}home($=u){return $===u?this.defaultHome:k$(this.root,this.get($).id)}revision($){let Z=this.get($);return JSON.stringify([this.home($),Z.revision??null])}prepareHome($){let Z=this.home($);if($===u)return Z;let J;try{J=$8(Z)}catch(V){if(V.code!=="ENOENT")throw V}if(J?.isSymbolicLink())throw Error("额外账号目录不能是软链接");if(l7(Z,{recursive:!0,mode:448}),l7(this.defaultHome,{recursive:!0,mode:448}),K2(Z)===K2(this.defaultHome))throw Error("额外账号不能使用默认认证目录");let Y;try{Y=$8(k$(Z,"auth.json"))}catch(V){if(V.code!=="ENOENT")throw V}if(Y?.isSymbolicLink()||Y&&!Y.isFile())throw Error("额外账号的 auth.json 必须为独立文件");try{B_(k$(this.defaultHome,"config.toml"),"",{flag:"wx",mode:384})}catch(V){if(V.code!=="EEXIST")throw V}for(let V of F_){let H=k$(this.defaultHome,V);l7(H,{recursive:!0,mode:448}),this.link(H,k$(Z,V),!0)}let Q=new Set([...D_,...W_(this.defaultHome).filter((V)=>V.endsWith(".config.toml"))]);for(let V of Q){let H=k$(this.defaultHome,V);if(e9(H))this.link(H,k$(Z,V),!1)}return Z}link($,Z,J){let Y;try{Y=$8(Z)}catch(Q){if(Q.code!=="ENOENT")throw Q}if(Y){if(!Y.isSymbolicLink()||K2(Z)!==K2($))throw Error(`Codex 共享路径已被替换或指向其他位置:${Z}`);return}K_($,Z,J&&process.platform==="win32"?"junction":J?"dir":"file")}env($,Z,J=!0,Y=!1){if(!Y&&J8($))throw Error("该 Codex 账号正在登录,请等待授权完成");let Q=J?this.prepareHome($):this.home($),V={...Z,CODEX_HOME:Q};if($!==u){V.CODEX_SQLITE_HOME=Z.CODEX_SQLITE_HOME||this.defaultHome;for(let H of["CODEX_API_KEY","OPENAI_API_KEY","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete V[H]}return V}cliArgs($){return this.get($),$===u?[]:["-c",'cli_auth_credentials_store="file"',"-c",'forced_login_method="chatgpt"']}fingerprint($){let Z=k$(this.home($),"auth.json");if(!e9(Z))return null;let Y=JSON.parse(eY(Z,"utf8"))?.tokens;if(!Y?.account_id||typeof Y.id_token!=="string")return null;let Q=Y.id_token.split(".")[1];if(!Q)throw Error("Codex 身份 Token 格式无效");let V=JSON.parse(Buffer.from(Q,"base64url").toString("utf8"));if(typeof V.sub!=="string"||!V.sub)return null;return z_("sha256").update(JSON.stringify([Y.account_id,V.sub])).digest("hex")}}function o$($,Z,J=!0){if(ZQ.set($,Z),!Z8.has($))$.once("exit",()=>Z8.delete($));Z8.set($,{id:Z,ownsNativeProcess:J})}function Y8($,Z=!1){return[...Z8].some(([J,Y])=>Y.id===$&&(Y.ownsNativeProcess||Z)&&J.isAlive())}function J8($){return M4.has($)}function JQ($){if(M4.has($))throw Error("该账号已有登录任务");if(Y8($))throw Error("该 Codex 账号正在使用中");let Z=Symbol($);return M4.set($,Z),()=>{if(M4.get($)===Z)M4.delete($)}}function r0($){return $?ZQ.get($)??u:u}var u="default",F_,D_,k,ZQ,Z8,M4;var p0=R(()=>{Q0();T0();F_=["sessions","archived_sessions","skills","rules","prompts","plugins","memories","generated_images","thread-writer-locks"],D_=["config.toml","AGENTS.md","AGENTS.override.md","hooks.json","history.jsonl","session_index.jsonl","installation_id"];k=new $Q,ZQ=new WeakMap,Z8=new Map;M4=new Map});function d7($,Z){return $==="plus"&&Z===null?{percent:0,resetsAt:null,durationMins:300,unreportedFull:!0}:Z}function M_($){switch($){case"plus":return 1;case"prolite":return 5;case"pro":return 20;default:return null}}function U4($,Z){let J=$.buckets?.find((Y)=>Y.limitName?.toLowerCase()===Z.toLowerCase()||Y.normalModelSlug===Z)??$;return{...J,fiveHour:d7($.subscriptionType,J.fiveHour)}}function i7($,Z){if($.state!=="ok")throw Error("额度计量桶 MISS");let J=U4($,Z);return"limitId"in J?J.limitId:$.defaultLimitId??"codex"}function n7($,Z,J=Date.now(),Y){let Q={state:"miss",score:null,shares:null,remaining:null,hours:null};if($.state!=="ok")return{...Q,reason:$.state==="network"?$.reason??"额度读取失败":$.state};let V=M_($.subscriptionType);if(V===null)return{...Q,reason:`未知周额度套餐:${$.subscriptionType??"MISS"}`};if(Q.shares=V,Y==="ultra"&&$.subscriptionType==="plus")return{...Q,state:"excluded",reason:"Ultra 自动选择不使用 Plus"};let H=U4($,Z),X=[H.fiveHour,H.weekly].filter((q)=>q!==null),z=X.filter((q)=>q.percent!==null&&q.percent>=100);if(z.length||$.ordinaryUsageAllowed===!1||H.rateLimitReachedType||H.spendControlReached===!0){let q=z.map((P)=>P.resetsAt?.getTime()).filter((P)=>P!=null&&Number.isFinite(P)&&P>J);return{...Q,state:"exhausted",reason:"额度耗尽",...q.length===z.length&&q.length?{retryAt:Math.max(...q)}:{}}}if(X.some((q)=>q.percent===null||!Number.isFinite(q.percent)||q.percent<0))return{...Q,reason:"额度百分比 MISS"};let W=H.weekly;if(!W||W.percent===null)return{...Q,reason:"周额度 MISS"};let G=W.resetsAt?.getTime();if(G==null||!Number.isFinite(G)||G<=J)return{...Q,reason:"周重置时间 MISS 或已过期"};let B=V*(100-W.percent)/100,_=(G-J)/3600000,j=B/_;if(Y==="ultra"&&B<0.5)return{...Q,state:"waiting",remaining:B,hours:_,weeklyScore:j,reason:`Ultra 至少需要 ${0.5} 份周余量`,retryAt:G};if($.subscriptionType==="plus"){let q=H.fiveHour,P=0.15*(100-q.percent)/100,F=q.unreportedFull?5:((q.resetsAt?.getTime()??NaN)-J)/3600000;if(!Number.isFinite(F)||F<=0)return{...Q,reason:"5h 重置时间 MISS 或已过期"};return{state:"ready",shares:V,remaining:B,hours:_,weeklyScore:j,fiveHourRemaining:P,fiveHourHours:F,availableNow:Math.min(B,P),score:Math.min(j,P/F)}}return{state:"ready",shares:V,remaining:B,hours:_,weeklyScore:j,availableNow:B,score:j}}function Q8($){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)}import{closeSync as U_,existsSync as A_,mkdirSync as O_,openSync as R_,readdirSync as N_,readSync as T_,statSync as H8,writeFileSync as E_}from"node:fs";import{homedir as a7}from"node:os";import{delimiter as YQ,isAbsolute as QQ,join as r$}from"node:path";import{EventEmitter as x_}from"node:events";import{StringDecoder as VQ}from"node:string_decoder";import{spawn as S_}from"cross-spawn";function A4(){return B4("codex","codex")}function b_(){if(process.platform==="win32")return process.env.PATH??"";return[...new Set([r$(a7(),".local","npm-global","bin"),r$(a7(),".local","bin"),r$(a7(),".bun","bin"),...(process.env.PATH??"").split(YQ),"/usr/local/bin","/usr/bin","/bin"].filter(Boolean))].join(YQ)}function XQ($){return typeof $==="string"&&/\bselected\s+model\s+is\s+at\s+capacity\b/i.test($)}function h_($=!0){return["app-server","--listen","stdio://",...$?[]:["--disable","multi_agent"]]}function I_($,Z){return{cwd:$,stdio:["pipe","pipe","pipe"],shell:!1,env:Z}}function s0($){return typeof $==="string"&&s7.includes($)}function g_($){if(!Array.isArray($))return[];let Z=new Set,J=[];for(let Y of $){let Q=typeof Y==="string"?Y:typeof Y==="object"&&Y?Y.reasoningEffort:null;if(!s0(Q)||Z.has(Q))continue;Z.add(Q);let V=typeof Y==="object"&&Y&&typeof Y.description==="string"?Y.description:"";J.push({reasoningEffort:Q,description:V})}return J}function o7($,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:r7($)}}return null}function m_($){let Z=$?.revisedPrompt??$?.revised_prompt;return typeof Z==="string"&&Z?Z:void 0}function r7($){return{status:$.status,revisedPrompt:m_($),...typeof $?.prompt==="string"&&$.prompt?{prompt:$.prompt}:{}}}function zQ($){if(!$||!A_(HQ))return null;let Z=null,J=[HQ];while(J.length){let Y=J.pop(),Q;try{Q=N_(Y,{withFileTypes:!0})}catch(V){K(`codex-process: cannot scan Codex session dir ${Y}: ${V instanceof Error?V.message:V}`);continue}for(let V of Q){let H=r$(Y,V.name);if(V.isDirectory()){J.push(H);continue}if(!V.isFile())continue;if(!V.name.startsWith("rollout-")||!V.name.endsWith(`${$}.jsonl`))continue;try{let X=H8(H).mtimeMs;if(!Z||X>Z.mtimeMs)Z={path:H,mtimeMs:X}}catch(X){K(`codex-process: cannot stat Codex rollout ${H}: ${X instanceof Error?X.message:X}`)}}}return Z?.path??null}function BQ($,Z,J=C_){let Y=$?.savedPath??$?.saved_path;if(typeof Y==="string"&&Y)return Y;let Q=$?.result;if(typeof Q==="string"){let V=p_($,Z,J);if(V)return V;if(Q.length>2048){let H=_Q($);return K(`codex-process: image generation inline result could not be decoded id=${H} length=${Q.length}`),`Image generation returned ${Q.length} chars of inline data, but Lodestar could not materialize it as an image file.`}return Q}if(Q&&typeof Q==="object"){let V=Q.savedPath??Q.saved_path??Q.path;if(typeof V==="string"&&V)return V;return JSON.stringify(Q,null,2)}return""}function p_($,Z,J){let Y=$?.result;if(typeof Y!=="string")return null;let Q=c_(Y);if(!Q)return null;let V=WQ(Z??"unknown-thread"),H=WQ(_Q($)),X=r$(J,V),z=r$(X,`${H}.${Q.ext}`);try{return O_(X,{recursive:!0}),E_(z,Q.buffer),z}catch(W){return K(`codex-process: failed to write image generation result ${z}: ${W instanceof Error?W.message:W}`),null}}function _Q($){let Z=$?.callId??$?.call_id??$?.id;return typeof Z==="string"&&Z?Z:`image-${Date.now()}`}function WQ($){let Z=$.trim().replace(/[^a-zA-Z0-9_.-]/g,"_").replace(/^_+|_+$/g,"");return Z?Z.slice(0,140):"unknown"}function c_($){let Z=$.trim(),J=Z,Y=null,Q=Z.match(/^data:image\/([a-zA-Z0-9.+-]+);base64,(.*)$/s);if(Q)Y=l_(Q[1]),J=Q[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,"="),H;try{H=Buffer.from(V,"base64")}catch{return null}if(H.length<12)return null;let X=u_(H)??Y;if(!X)return null;return{buffer:H,ext:X}}function u_($){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 l_($){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 GQ($,Z,J){let Y=o7($,Z);if(!Y)return null;switch($.type){case"commandExecution":return{...Y,output:$.aggregatedOutput??"",isError:$.exitCode!=null&&$.exitCode!==0};case"fileChange":return{...Y,output:JSON.stringify($.changes??[],null,2),isError:$.status==="failed"};case"mcpToolCall":return{...Y,output:$.error?JSON.stringify($.error,null,2):JSON.stringify($.result??null,null,2),isError:!!$.error};case"dynamicToolCall":return{...Y,output:JSON.stringify($.contentItems??[],null,2),isError:$.success===!1};case"webSearch":return{...Y,output:JSON.stringify($.action??{},null,2),isError:!1};case"imageGeneration":return{...Y,output:BQ($,J),isError:$.status==="failed"}}return null}function V8($,Z){if(typeof $==="string"&&$){let J=$.split("/").filter(Boolean).pop();if(J)return J}return U0(Z)}function KQ($){if(typeof $!=="string"||!$)return;if($.startsWith("gAAAA")&&!/[一-鿿]/.test($))return"(继承主线程历史的密文任务书)";return $}function d_($,Z,J){let Y=(Q)=>typeof Q==="string"?Q:"";switch($){case"Bash":{if(J!=null){let Q=J.replace(/\s+/g," ").trim();return Q?`→ ${Q.slice(0,60)}`:""}return G2(Y(Z?.command))||"(空命令)"}case"FileChange":{let Q=Array.isArray(Z?.changes)?Z.changes.length:0;if(J!=null)return"";return Q>0?`改 ${Q} 个文件`:"文件变更"}case"MCP":return`${Y(Z?.server)}/${Y(Z?.tool)}`.slice(0,60);case"WebSearch":return`"${Y(Z?.query).slice(0,50)}"`;default:{if(J!=null){let Q=J.replace(/\s+/g," ").trim();return Q?`→ ${Q.slice(0,60)}`:""}return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}}function jQ($){return(Array.isArray($.receiverThreadIds)?$.receiverThreadIds:[]).filter((J)=>typeof J==="string"&&!!J)}function i_($){let Z=jQ($);return Z.length>0?`派生 ${Z.length} 个子 agent`:"派生子 agent"}function n_($){let Z=$.agentsStates;if(!Z||typeof Z!=="object")return"";let J=[];for(let[Y,Q]of Object.entries(Z)){let V=Q,H=typeof V?.status==="string"?V.status:"unknown";J.push(`${U0(Y)}: ${H}`)}return J.join(`
|
|
79
|
-
`)}var
|
|
75
|
+
`).trimStart():Z;return{description:Q,command:V||Z}}function G2($,Z=60){let{description:J,command:Y}=c7($);if(J)return J;return Y_(Y).replace(/\s+/g," ").trim().slice(0,Z)}function Y_($){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 Q_($){let Z=$.replace(/\r\n/g,`
|
|
76
|
+
`).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 Q=H_(J[1]);return p7(Q||Z)}let Y=V_(Z);if(Y)return Y;return p7(Z)}function V_($){let Z=$.match(/^("[^"]*"|'[^']*'|“[^”]*”|\S+)\s+([\s\S]*)$/);if(!Z)return null;let J=aY(Z[1]).replace(/\.exe$/i,"");if(!/(?:^|[\\/])(?:powershell|pwsh)$/i.test(J))return null;let Y=Z[2];for(;;){let Q=Y.match(/^(-[A-Za-z][\w-]*)\s+([\s\S]*)$/);if(!Q)break;let V=Q[1].toLowerCase();if(V==="-command"||V==="-c")return p7(aY(Q[2]));if(Y=Q[2],V==="-executionpolicy"||V==="-inputformat"||V==="-outputformat")Y=Y.replace(/^(?:"[^"]*"|'[^']*'|\S+)\s+/,"")}return null}function H_($){let Z=$.trim();if(Z.length<2)return Z;let J=r9[Z[0]];if(!J||!Z.endsWith(J))return Z;let Y=Z.slice(1,-1);if(Z[0]==="'")return Y.replace(/'\\''/g,"'");return Y.replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
|
|
77
|
+
`)}function p7($){let Z=$.trim(),J=Z[0];if(!r9[J])return Z;let Y=Z.slice(1);if(!/^#\s*(?:desc|dec|description|说明|目的|用途)\s*[::]/i.test(Y)&&!X_(Y,J))return Z;if(J!=='"')return Y.replace(/'\s*$/,"");return Y.replace(/\s*[”"]\s*$/,"").replace(/\\(["\\$`])/g,"$1").replace(/\\n/g,`
|
|
78
|
+
`).replace(/\s*"\s*'\$\(([^)]*)\)'/g,(H,X)=>` $(${X})`)}function X_($,Z){let J=r9[Z];for(let Y=0;Y<$.length;Y++){let Q=$[Y];if(Z==='"'&&Q==="\\"&&Y+1<$.length){Y++;continue}if(Q===J)return/^[\s]*$/.test($.slice(Y+1))}return!1}var r9;var s9=R(()=>{r9={'"':'"',"'":"'","“":"”"}});function O($){return $ instanceof Error?$.message:String($)}function U0($){return $.length<=16?$:`${$.slice(0,8)}…${$.slice(-4)}`}async function oY($,Z,J){let Y=null;try{return await Promise.race([$,new Promise((Q,V)=>{Y=setTimeout(()=>V(Error(`${J} timed out after ${Z/1000}s`)),Z)})])}finally{if(Y)clearTimeout(Y)}}import{isAbsolute as rY}from"node:path";function z_($){return $.kind==="fresh"?null:$.source.provider}function _0($,Z,J){let Y=z_($);if(Y&&Y!==Z)throw Error(`conversation launch provider mismatch: source=${Y} 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"||!rY($.source.cwd)))throw Error(`conversation launch source cwd is not absolute: ${String($.source.cwd)}`);if($.kind!=="fresh"&&J!==void 0){if(!rY(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 A1=()=>{};import{createHash as W_,randomUUID as sY}from"node:crypto";import{existsSync as t9,lstatSync as e9,mkdirSync as u7,readFileSync as tY,readdirSync as G_,realpathSync as K2,rmSync as K_,symlinkSync as B_,writeFileSync as __}from"node:fs";import{homedir as j_}from"node:os";import{isAbsolute as L_,join as k$,relative as q_,resolve as P_,sep as D_}from"node:path";class eY{defaultHome;root;stateFile;constructor($=P_(process.env.CODEX_HOME||k$(j_(),".codex")),Z=uJ,J=lJ){this.defaultHome=$;this.root=Z;this.stateFile=J}read(){if(!t9(this.stateFile))return{version:1,accounts:[],selections:{}};let $=JSON.parse(tY(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 Y of $.accounts){if(!Y||!/^[a-f0-9-]{36}$/.test(Y.id)||typeof Y.name!=="string"||Z.has(Y.id)||J.has(this.nameKey(Y.name)))throw Error("Codex 账号记录重复或无效");this.validateName(Y.name),Z.add(Y.id),J.add(this.nameKey(Y.name))}for(let Y of Object.values($.selections))if(Y!==u&&!Z.has(Y))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:u,name:"默认"},...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(u);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(u);this.validateName($);let Z=this.read(),J=Z.accounts.find((Q)=>this.nameKey(Q.name)===this.nameKey($));if(J)return{...J};let Y={id:sY(),name:$.normalize("NFC").trim()};return Z.accounts.push(Y),s(this.stateFile,Z),Y}remove($){let Z=this.get($);if($===u)throw Error("默认账号由设备原生 Codex 管理,不能用此命令删除");if(Z8($))throw Error(`账号正在登录;先发送 codex-login-cancel ${Z.name}`);if(J8($,!0))throw Error("账号正在使用中;请先结束使用该账号的会话或委派任务,额度及模型查询结束后重试");let J=this.read(),Y=this.home($),Q;try{Q=e9(Y)}catch(H){if(H.code!=="ENOENT")throw H}if(Q){if(Q.isSymbolicLink()||!Q.isDirectory())throw Error("额外账号目录不是独立目录,拒绝删除");if(t9(this.defaultHome)){let H=q_(K2(Y),K2(this.defaultHome));if(!H||!L_(H)&&H!==".."&&!H.startsWith(`..${D_}`))throw Error("额外账号目录包含默认认证目录,拒绝删除")}try{K_(Y,{recursive:!0})}catch(H){throw Error(`账号文件删除失败,账号记录已保留;${H}`)}}J.accounts=J.accounts.filter((H)=>H.id!==$);let V=0;for(let[H,X]of Object.entries(J.selections)){if(X!==$)continue;delete J.selections[H],V++}try{s(this.stateFile,J)}catch(H){throw Error(`账号文件已移除,但账号记录保存失败;请重试 codex-account-delete ${Z.name};${H}`)}return{account:Z,clearedSelections:V}}selected($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:u}preferred($){let Z=this.read().selections;return Object.prototype.hasOwnProperty.call(Z,$)?Z[$]:null}selectAuto($){let Z=this.read();delete Z.selections[$],s(this.stateFile,Z)}select($,Z){this.get(Z);let J=this.read();Object.defineProperty(J.selections,$,{value:Z,enumerable:!0,writable:!0,configurable:!0}),s(this.stateFile,J)}recordLogin($,Z){let J=this.read();if($!==u){let Y=J.accounts.find((Q)=>Q.id===$);if(!Y)throw Error("登录完成时账号记录已不存在");Object.assign(Y,{email:Z.email,planType:Z.planType,revision:sY()}),s(this.stateFile,J)}}home($=u){return $===u?this.defaultHome:k$(this.root,this.get($).id)}revision($){let Z=this.get($);return JSON.stringify([this.home($),Z.revision??null])}prepareHome($){let Z=this.home($);if($===u)return Z;let J;try{J=e9(Z)}catch(V){if(V.code!=="ENOENT")throw V}if(J?.isSymbolicLink())throw Error("额外账号目录不能是软链接");if(u7(Z,{recursive:!0,mode:448}),u7(this.defaultHome,{recursive:!0,mode:448}),K2(Z)===K2(this.defaultHome))throw Error("额外账号不能使用默认认证目录");let Y;try{Y=e9(k$(Z,"auth.json"))}catch(V){if(V.code!=="ENOENT")throw V}if(Y?.isSymbolicLink()||Y&&!Y.isFile())throw Error("额外账号的 auth.json 必须为独立文件");try{__(k$(this.defaultHome,"config.toml"),"",{flag:"wx",mode:384})}catch(V){if(V.code!=="EEXIST")throw V}for(let V of F_){let H=k$(this.defaultHome,V);u7(H,{recursive:!0,mode:448}),this.link(H,k$(Z,V),!0)}let Q=new Set([...M_,...G_(this.defaultHome).filter((V)=>V.endsWith(".config.toml"))]);for(let V of Q){let H=k$(this.defaultHome,V);if(t9(H))this.link(H,k$(Z,V),!1)}return Z}link($,Z,J){let Y;try{Y=e9(Z)}catch(Q){if(Q.code!=="ENOENT")throw Q}if(Y){if(!Y.isSymbolicLink()||K2(Z)!==K2($))throw Error(`Codex 共享路径已被替换或指向其他位置:${Z}`);return}B_($,Z,J&&process.platform==="win32"?"junction":J?"dir":"file")}env($,Z,J=!0,Y=!1){if(!Y&&Z8($))throw Error("该 Codex 账号正在登录,请等待授权完成");let Q=J?this.prepareHome($):this.home($),V={...Z,CODEX_HOME:Q};if($!==u){V.CODEX_SQLITE_HOME=Z.CODEX_SQLITE_HOME||this.defaultHome;for(let H of["CODEX_API_KEY","OPENAI_API_KEY","CODEX_ACCESS_TOKEN","OPENAI_FEDERATION_RULE_ID","OPENAI_IDENTITY_TOKEN_FILE","OPENAI_WORKLOAD_IDENTITY_CONTEXT"])delete V[H]}return V}cliArgs($){return this.get($),$===u?[]:["-c",'cli_auth_credentials_store="file"',"-c",'forced_login_method="chatgpt"']}fingerprint($){let Z=k$(this.home($),"auth.json");if(!t9(Z))return null;let Y=JSON.parse(tY(Z,"utf8"))?.tokens;if(!Y?.account_id||typeof Y.id_token!=="string")return null;let Q=Y.id_token.split(".")[1];if(!Q)throw Error("Codex 身份 Token 格式无效");let V=JSON.parse(Buffer.from(Q,"base64url").toString("utf8"));if(typeof V.sub!=="string"||!V.sub)return null;return W_("sha256").update(JSON.stringify([Y.account_id,V.sub])).digest("hex")}}function o$($,Z,J=!0){if($Q.set($,Z),!$8.has($))$.once("exit",()=>$8.delete($));$8.set($,{id:Z,ownsNativeProcess:J})}function J8($,Z=!1){return[...$8].some(([J,Y])=>Y.id===$&&(Y.ownsNativeProcess||Z)&&J.isAlive())}function Z8($){return M4.has($)}function ZQ($){if(M4.has($))throw Error("该账号已有登录任务");if(J8($))throw Error("该 Codex 账号正在使用中");let Z=Symbol($);return M4.set($,Z),()=>{if(M4.get($)===Z)M4.delete($)}}function r0($){return $?$Q.get($)??u:u}var u="default",F_,M_,k,$Q,$8,M4;var p0=R(()=>{Q0();T0();F_=["sessions","archived_sessions","skills","rules","prompts","plugins","memories","generated_images","thread-writer-locks"],M_=["config.toml","AGENTS.md","AGENTS.override.md","hooks.json","history.jsonl","session_index.jsonl","installation_id"];k=new eY,$Q=new WeakMap,$8=new Map;M4=new Map});function l7($,Z){return $==="plus"&&Z===null?{percent:0,resetsAt:null,durationMins:300,unreportedFull:!0}:Z}function U_($){switch($){case"plus":return 1;case"prolite":return 5;case"pro":return 20;default:return null}}function U4($,Z){let J=$.buckets?.find((Y)=>Y.limitName?.toLowerCase()===Z.toLowerCase()||Y.normalModelSlug===Z)??$;return{...J,fiveHour:l7($.subscriptionType,J.fiveHour)}}function d7($,Z){if($.state!=="ok")throw Error("额度计量桶 MISS");let J=U4($,Z);return"limitId"in J?J.limitId:$.defaultLimitId??"codex"}function i7($,Z,J=Date.now(),Y){let Q={state:"miss",score:null,shares:null,remaining:null,hours:null};if($.state!=="ok")return{...Q,reason:$.state==="network"?$.reason??"额度读取失败":$.state};let V=U_($.subscriptionType);if(V===null)return{...Q,reason:`未知周额度套餐:${$.subscriptionType??"MISS"}`};if(Q.shares=V,Y==="ultra"&&$.subscriptionType==="plus")return{...Q,state:"excluded",reason:"Ultra 自动选择不使用 Plus"};let H=U4($,Z),X=[H.fiveHour,H.weekly].filter((q)=>q!==null),z=X.filter((q)=>q.percent!==null&&q.percent>=100);if(z.length||$.ordinaryUsageAllowed===!1||H.rateLimitReachedType||H.spendControlReached===!0){let q=z.map((P)=>P.resetsAt?.getTime()).filter((P)=>P!=null&&Number.isFinite(P)&&P>J);return{...Q,state:"exhausted",reason:"额度耗尽",...q.length===z.length&&q.length?{retryAt:Math.max(...q)}:{}}}if(X.some((q)=>q.percent===null||!Number.isFinite(q.percent)||q.percent<0))return{...Q,reason:"额度百分比 MISS"};let W=H.weekly;if(!W||W.percent===null)return{...Q,reason:"周额度 MISS"};let G=W.resetsAt?.getTime();if(G==null||!Number.isFinite(G)||G<=J)return{...Q,reason:"周重置时间 MISS 或已过期"};let B=V*(100-W.percent)/100,_=(G-J)/3600000,j=B/_;if(Y==="ultra"&&B<0.5)return{...Q,state:"waiting",remaining:B,hours:_,weeklyScore:j,reason:`Ultra 至少需要 ${0.5} 份周余量`,retryAt:G};if($.subscriptionType==="plus"){let q=H.fiveHour,P=0.15*(100-q.percent)/100,D=q.unreportedFull?5:((q.resetsAt?.getTime()??NaN)-J)/3600000;if(!Number.isFinite(D)||D<=0)return{...Q,reason:"5h 重置时间 MISS 或已过期"};return{state:"ready",shares:V,remaining:B,hours:_,weeklyScore:j,fiveHourRemaining:P,fiveHourHours:D,availableNow:Math.min(B,P),score:Math.min(j,P/D)}}return{state:"ready",shares:V,remaining:B,hours:_,weeklyScore:j,availableNow:B,score:j}}function Y8($){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)}import{closeSync as A_,existsSync as O_,mkdirSync as R_,openSync as N_,readdirSync as T_,readSync as E_,statSync as V8,writeFileSync as x_}from"node:fs";import{homedir as n7}from"node:os";import{delimiter as JQ,isAbsolute as YQ,join as r$}from"node:path";import{EventEmitter as S_}from"node:events";import{StringDecoder as QQ}from"node:string_decoder";import{spawn as b_}from"cross-spawn";function A4(){return B4("codex","codex")}function C_(){if(process.platform==="win32")return process.env.PATH??"";return[...new Set([r$(n7(),".local","npm-global","bin"),r$(n7(),".local","bin"),r$(n7(),".bun","bin"),...(process.env.PATH??"").split(JQ),"/usr/local/bin","/usr/bin","/bin"].filter(Boolean))].join(JQ)}function HQ($){return typeof $==="string"&&/\bselected\s+model\s+is\s+at\s+capacity\b/i.test($)}function I_($=!0){return["app-server","--listen","stdio://",...$?[]:["--disable","multi_agent"]]}function g_($,Z){return{cwd:$,stdio:["pipe","pipe","pipe"],shell:!1,env:Z}}function s0($){return typeof $==="string"&&r7.includes($)}function m_($){if(!Array.isArray($))return[];let Z=new Set,J=[];for(let Y of $){let Q=typeof Y==="string"?Y:typeof Y==="object"&&Y?Y.reasoningEffort:null;if(!s0(Q)||Z.has(Q))continue;Z.add(Q);let V=typeof Y==="object"&&Y&&typeof Y.description==="string"?Y.description:"";J.push({reasoningEffort:Q,description:V})}return J}function a7($,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:o7($)}}return null}function p_($){let Z=$?.revisedPrompt??$?.revised_prompt;return typeof Z==="string"&&Z?Z:void 0}function o7($){return{status:$.status,revisedPrompt:p_($),...typeof $?.prompt==="string"&&$.prompt?{prompt:$.prompt}:{}}}function XQ($){if(!$||!O_(VQ))return null;let Z=null,J=[VQ];while(J.length){let Y=J.pop(),Q;try{Q=T_(Y,{withFileTypes:!0})}catch(V){K(`codex-process: cannot scan Codex session dir ${Y}: ${V instanceof Error?V.message:V}`);continue}for(let V of Q){let H=r$(Y,V.name);if(V.isDirectory()){J.push(H);continue}if(!V.isFile())continue;if(!V.name.startsWith("rollout-")||!V.name.endsWith(`${$}.jsonl`))continue;try{let X=V8(H).mtimeMs;if(!Z||X>Z.mtimeMs)Z={path:H,mtimeMs:X}}catch(X){K(`codex-process: cannot stat Codex rollout ${H}: ${X instanceof Error?X.message:X}`)}}}return Z?.path??null}function KQ($,Z,J=k_){let Y=$?.savedPath??$?.saved_path;if(typeof Y==="string"&&Y)return Y;let Q=$?.result;if(typeof Q==="string"){let V=c_($,Z,J);if(V)return V;if(Q.length>2048){let H=BQ($);return K(`codex-process: image generation inline result could not be decoded id=${H} length=${Q.length}`),`Image generation returned ${Q.length} chars of inline data, but Lodestar could not materialize it as an image file.`}return Q}if(Q&&typeof Q==="object"){let V=Q.savedPath??Q.saved_path??Q.path;if(typeof V==="string"&&V)return V;return JSON.stringify(Q,null,2)}return""}function c_($,Z,J){let Y=$?.result;if(typeof Y!=="string")return null;let Q=u_(Y);if(!Q)return null;let V=zQ(Z??"unknown-thread"),H=zQ(BQ($)),X=r$(J,V),z=r$(X,`${H}.${Q.ext}`);try{return R_(X,{recursive:!0}),x_(z,Q.buffer),z}catch(W){return K(`codex-process: failed to write image generation result ${z}: ${W instanceof Error?W.message:W}`),null}}function BQ($){let Z=$?.callId??$?.call_id??$?.id;return typeof Z==="string"&&Z?Z:`image-${Date.now()}`}function zQ($){let Z=$.trim().replace(/[^a-zA-Z0-9_.-]/g,"_").replace(/^_+|_+$/g,"");return Z?Z.slice(0,140):"unknown"}function u_($){let Z=$.trim(),J=Z,Y=null,Q=Z.match(/^data:image\/([a-zA-Z0-9.+-]+);base64,(.*)$/s);if(Q)Y=d_(Q[1]),J=Q[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,"="),H;try{H=Buffer.from(V,"base64")}catch{return null}if(H.length<12)return null;let X=l_(H)??Y;if(!X)return null;return{buffer:H,ext:X}}function l_($){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 d_($){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 WQ($,Z,J){let Y=a7($,Z);if(!Y)return null;switch($.type){case"commandExecution":return{...Y,output:$.aggregatedOutput??"",isError:$.exitCode!=null&&$.exitCode!==0};case"fileChange":return{...Y,output:JSON.stringify($.changes??[],null,2),isError:$.status==="failed"};case"mcpToolCall":return{...Y,output:$.error?JSON.stringify($.error,null,2):JSON.stringify($.result??null,null,2),isError:!!$.error};case"dynamicToolCall":return{...Y,output:JSON.stringify($.contentItems??[],null,2),isError:$.success===!1};case"webSearch":return{...Y,output:JSON.stringify($.action??{},null,2),isError:!1};case"imageGeneration":return{...Y,output:KQ($,J),isError:$.status==="failed"}}return null}function Q8($,Z){if(typeof $==="string"&&$){let J=$.split("/").filter(Boolean).pop();if(J)return J}return U0(Z)}function GQ($){if(typeof $!=="string"||!$)return;if($.startsWith("gAAAA")&&!/[一-鿿]/.test($))return"(继承主线程历史的密文任务书)";return $}function i_($,Z,J){let Y=(Q)=>typeof Q==="string"?Q:"";switch($){case"Bash":{if(J!=null){let Q=J.replace(/\s+/g," ").trim();return Q?`→ ${Q.slice(0,60)}`:""}return G2(Y(Z?.command))||"(空命令)"}case"FileChange":{let Q=Array.isArray(Z?.changes)?Z.changes.length:0;if(J!=null)return"";return Q>0?`改 ${Q} 个文件`:"文件变更"}case"MCP":return`${Y(Z?.server)}/${Y(Z?.tool)}`.slice(0,60);case"WebSearch":return`"${Y(Z?.query).slice(0,50)}"`;default:{if(J!=null){let Q=J.replace(/\s+/g," ").trim();return Q?`→ ${Q.slice(0,60)}`:""}return JSON.stringify(Z??{}).replace(/\s+/g," ").slice(0,60)}}}function _Q($){return(Array.isArray($.receiverThreadIds)?$.receiverThreadIds:[]).filter((J)=>typeof J==="string"&&!!J)}function n_($){let Z=_Q($);return Z.length>0?`派生 ${Z.length} 个子 agent`:"派生子 agent"}function a_($){let Z=$.agentsStates;if(!Z||typeof Z!=="object")return"";let J=[];for(let[Y,Q]of Object.entries(Z)){let V=Q,H=typeof V?.status==="string"?V.status:"unknown";J.push(`${U0(Y)}: ${H}`)}return J.join(`
|
|
79
|
+
`)}var VQ,k_,y_=30000,w_=600000,v_=5000,f_=60000,h_="上一轮因模型暂时满载而中断。请基于当前会话继续完成用户尚未完成的任务,沿用已有进度;执行操作前先确认结果,避免重复已完成的操作。",r7,O4="xhigh",B2,_2;var O1=R(()=>{y0();I();V2();I7();s9();A1();L4();p0();I7();VQ=r$(k.defaultHome,"sessions"),k_=r$(k.defaultHome,"generated_images");r7=["none","minimal","low","medium","high","xhigh","max","ultra"];B2=class B2 extends Error{method;requestId;serverCode;serverMessage;serverData;constructor($,Z,J,Y,Q){super(`codex app-server ${$} failed (id=${Z}, code=${J??"MISS"}): ${Y}`);this.method=$;this.requestId=Z;this.serverCode=J;this.serverMessage=Y;this.serverData=Q;this.name="CodexRpcResponseError"}};_2=class _2 extends S_{provider="codex";tokenSourceId;launchKind;proc;stdoutBuf="";stderrBuf="";requestCounter=0;pending=new Map;serverRequests=new Map;alive=!0;expectedExit=!1;exitEventEmitted=!1;childExitCode=null;childExitSignal=null;exitPromise;resolveExit;opts;readyPromise=null;initializePromise=null;conversationResumable=!1;conversationRolloutPath=null;conversationMaterializationVerification=null;conversationMaterializationRetrySource=null;lastConversationMaterializationFailure=null;currentTurnId=null;turnStartGeneration=0;turnStartOwner=null;turnStartOwnersByTurnId=new Map;finishedTurnIds=new Set;capacityRetryTimer=null;capacityRetryCount=0;capacityRetryHasStarted=!1;capacityRetryEnabled=!0;turnError=null;rolloutFilePath=null;rolloutReadOffset=0;rolloutLineRemainder="";rolloutDecoder=new QQ("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((V)=>{this.resolveExit=V}),this.opts=$,this.tokenSourceId=$.tokenSourceId??null,this.launchKind=($.launch??{kind:"fresh"}).kind;let Z=A4(),J=[...I_($.allowDelegation!==!1),...k.cliArgs($.codexAccountId??u)];K(`codex-process: spawn ${Z} app-server (cwd=${$.workDir})`);let Y={...process.env,NPM_CONFIG_LOGLEVEL:"error",PATH:C_(),...f.codex.env,...$.hostEnv??{}},Q=k.env($.codexAccountId??u,$.transformEnv?$.transformEnv(Y):Y);this.proc=b_(Z,J,g_($.workDir,Q)),this.proc.stdout.on("data",(V)=>this.onStdout(V)),this.proc.stderr.on("data",(V)=>this.onStderr(V)),this.proc.stdin.on("error",(V)=>this.handleStdinError(V)),this.proc.on("exit",(V,H)=>this.handleChildExit(V,H)),this.proc.on("close",(V,H)=>this.handleChildClose(V,H)),this.proc.on("error",(V)=>this.handleChildProcessError(V)),o$(this,$.codexAccountId??u)}handleStdinError($){let Z=$ instanceof Error?$:Error(String($));if(K(`codex-process: stdin failed: ${Z.message}`),!this.expectedExit)this.emit("error",Z)}handleChildExit($,Z){if(!this.alive){K(`codex-process: duplicate exit ignored code=${$} signal=${Z}`);return}this.alive=!1,this.cancelCapacityRetry(),this.childExitCode=$,this.childExitSignal=Z,K(`codex-process: OS exit code=${$} signal=${Z}; awaiting stdio close`)}handleChildClose($,Z){this.alive=!1,this.cancelCapacityRetry(),this.flushStdoutTail(),this.flushStderrTail(),this.rejectPendingRequests((V,H)=>Error(`codex app-server closed before ${H.method} response (id=${V})`)),this.serverRequests.clear();let J=$??this.childExitCode,Y=Z??this.childExitSignal,Q=this.conversationMaterializationBarrier();if(Q){Q.then(()=>this.emitProcessExit(J,Y),()=>this.emitProcessExit(J,Y));return}this.emitProcessExit(J,Y)}handleChildProcessError($){K(`codex-process: child process error: ${$}`),this.rejectPendingRequests((Y,Q)=>Error(`codex app-server process failed before ${Q.method} response (id=${Y}): ${$.message}`,{cause:$}));let Z=typeof this.proc.pid!=="number",J=!1;if(Z&&this.alive)this.alive=!1,this.cancelCapacityRetry(),this.serverRequests.clear(),J=!0;if(this.emit("error",$),J)K(`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(),K(`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(`
|
|
80
80
|
`))>=0){let J=this.stdoutBuf.slice(0,Z).trim();if(this.stdoutBuf=this.stdoutBuf.slice(Z+1),!J)continue;let Y;try{Y=JSON.parse(J)}catch(Q){K(`codex-process: bad json: ${J.slice(0,200)} (${Q})`);continue}try{this.handleMessage(Y)}catch(Q){K(`codex-process: dispatch error: ${JSON.stringify(Y).slice(0,200)} (${Q})`)}}}flushStdoutTail(){if(!this.stdoutBuf)return;this.onStdout(Buffer.from(`
|
|
81
81
|
`))}onStderr($){this.stderrBuf+=$.toString();let Z;while((Z=this.stderrBuf.indexOf(`
|
|
82
|
-
`))>=0){let J=this.stderrBuf.slice(0,Z);if(this.stderrBuf=this.stderrBuf.slice(Z+1),J.trim())K(`codex-process[stderr]: ${J}`)}}flushStderrTail(){let $=this.stderrBuf;if(this.stderrBuf="",$.trim())K(`codex-process[stderr]: ${$}`)}handleMessage($){if(Object.prototype.hasOwnProperty.call($,"id")&&!$.method){let J=this.pending.get($.id);if(!J){K(`codex-process: response for unknown id=${$.id}`);return}if(this.pending.delete($.id),clearTimeout(J.timeout),$.error){let Y=typeof $.error?.code==="number"?$.error.code:null,Q=typeof $.error==="string"?$.error:typeof $.error?.message==="string"?$.error.message:JSON.stringify($.error);J.reject(new B2(J.method,$.id,Y,Q,$.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=I7($);if(Z){let J=this.withSessionId(Z);f7(Z.sourceMethod??"raw_message",$,J),this.emit("context_compacted",J);return}m0("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=h7($,Z);if(J){let Y=this.withSessionId(J);f7($,Z,Y),this.emit("context_compacted",Y);return}switch($){case"thread/started":{let Y=Z.thread;if(Y?.id)this.sessionId=Y.id;return}case"thread/settings/updated":{let Y=Z.threadSettings;if(typeof Y?.model==="string")this.lastModel=Y.model;if(s0(Y?.effort))this.lastEffort=Y.effort;return}case"thread/tokenUsage/updated":{let Y=W2(Z.tokenUsage?.last);if(Y)this.lastUsage=Y,this.lastResult.usage=this.lastUsage;else K("codex-process: tokenUsage notification missing last breakdown");this.lastTotalUsage=W2(Z.tokenUsage?.total);let Q=Z.tokenUsage?.modelContextWindow;if(typeof Q==="number"&&Q>0)this.lastContextWindow=Q;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){m0("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){m0("TURN_COMPLETED_THREAD_MISMATCH",{method:$,params:Z});return}let Y=Z.turn??{},Q=typeof Y.id==="string"&&Y.id?Y.id:null;if(Q){if(this.finishedTurnIds?.has(Q)){K(`codex-process: duplicate turn/completed ignored turn=${Q}`);return}if(this.currentTurnId&&this.currentTurnId!==Q){this.markTurnStartTerminal(Q),this.rememberFinishedTurn(Q),K(`codex-process: stale turn/completed ignored turn=${Q} current=${this.currentTurnId}`);return}this.flushRolloutImageGenerations(),this.markConversationMaterialized("turn/completed notification"),this.markTurnStartTerminal(Q),this.rememberFinishedTurn(Q)}else m0("TURN_COMPLETED_MISSING_ID",{method:$,params:Z});let V=Y.status,H=Y.error??(V==="failed"&&this.turnError&&this.turnError.turnId===Q?this.turnError.error:null);this.turnError=null;let X=V==="failed"||!!H,z=V==="completed"&&!X&&!!Q;if(this.lastCompletedTurnId=z?Q:null,this.currentTurnId=null,V==="failed"&&Q&&XQ(H?.message)&&this.scheduleCapacityRetry(H.message,f_))return;this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!1;let W=X?H?.type??H?.message??"failed":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof Y.durationMs==="number"?Y.durationMs:null,num_turns:1,usage:this.lastUsage,subtype:W,is_error:X},this.emit("result",{subtype:W,is_error:X,...X&&typeof H?.message==="string"?{error:H.message}:{},...V==="failed"&&Q&&Q8(H)?{codexQuotaFailure:{accepted:!0}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,turn_id:Q,checkpoint:z&&this.sessionId?{provider:"codex",kind:"turn",id:Q,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 K("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 m0("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":{K(`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":{K(`codex-process: ${$}: ${Z.summary??Z.message??JSON.stringify(Z).slice(0,200)}`);return}case"error":{K(`codex-process: server error: ${JSON.stringify(Z).slice(0,500)}`);let Y=Z.error??Z;if(typeof Z.turnId==="string"&&Z.threadId===this.sessionId&&!this.finishedTurnIds?.has(Z.turnId)&&(!this.currentTurnId||this.currentTurnId===Z.turnId))this.turnError={turnId:Z.turnId,error:Y};this.emit("error",Error(Y.message??Y.summary??"codex app-server error"));return}}m0("NOTIFICATION",{method:$,params:Z}),this.emit("raw",{method:$,params:Z})}handleItemStarted($){let Z=$?.item;if(!Z?.id){m0("ITEM_STARTED_MISSING_ID",{method:"item/started",params:$});return}if(this.feedCollabItem(Z,"started"))return;let J=o7(Z,this.opts.workDir);if(!J){m0("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 Y=typeof $?.threadId==="string"?$.threadId:"";this.collabAgentSummaries.set(Y,J)}return}if(this.feedCollabItem(Z,"completed"))return;this.emitSubagentStep(Z,"completed",$)}handleItemCompleted($){let Z=$?.item;if(!Z?.id){m0("ITEM_COMPLETED_MISSING_ID",{method:"item/completed",params:$});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=GQ(Z,this.opts.workDir,this.sessionId??void 0);if(!J){m0("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:r7(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)??U0(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 Y=typeof J?.threadId==="string"?J.threadId:"",Q=Z==="started"?o7($,this.opts.workDir):GQ($,this.opts.workDir,this.sessionId??void 0);if(!Q)return;let V="output"in Q&&typeof Q.output==="string"?Q.output:void 0;this.emit("subagent_step",{thread_id:Y,item_id:$.id,tool:Q.name,phase:Z,brief:d_(Q.name,Q.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 Y=V8($.agentPath,J);this.collabAgentNames.set(J,Y),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Y}),this.emit("bg_task_updated",{task_id:J,patch:{is_backgrounded:!0}})}else if($.kind==="started"){let Y=this.collabAgentNames.get(J),Q=V8($.agentPath,J);if(Y!==Q&&!this.collabAgentSettled.has(J))this.collabAgentNames.set(J,Q),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Q})}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[Y,Q]of Object.entries(J))this.translateAgentState(Y,Q,$);if($.tool==="closeAgent"&&Z==="completed"&&$.status!=="failed"){let Y=jQ($);for(let Q of Y){if(this.collabAgentSettled.has(Q))continue;if(this.collabAgentSettled.add(Q),!this.collabAgentNames.has(Q))this.collabAgentNames.set(Q,V8(null,Q));this.emit("bg_task_settled",{task_id:Q,status:"stopped"})}}if($.tool==="spawnAgent"){if(Z==="started")this.emit("tool_use",{id:$.id,name:"Agent",input:{tool:"spawnAgent",prompt:KQ($.prompt),description:i_($),model:typeof $.model==="string"?$.model:void 0}});else if($.status!=="inProgress")this.emit("tool_result",{tool_use_id:$.id,content:n_($),is_error:$.status==="failed"})}return!0}return!1}translateAgentState($,Z,J){let Y=Z?.status;if(typeof Y!=="string")return;if(this.collabAgentSettled.has($)){if(Y!=="running"&&Y!=="pendingInit"){if(Y==="errored"||Y==="shutdown"||Y==="notFound"||Y==="interrupted")this.emit("bg_task_updated",{task_id:$,patch:{status:Y==="errored"?"failed":"killed",error:typeof Z?.message==="string"&&Z.message?Z.message:void 0}});return}this.collabAgentSettled.delete($);let V=this.collabAgentNames.get($)??V8(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 H={task_id:$,task_type:"local_agent",description:"子 agent",prompt:KQ(J.prompt)};this.emit("bg_task_started",H);let X={task_id:$,patch:{is_backgrounded:!0}};this.emit("bg_task_updated",X)}if(Y==="running"||Y==="pendingInit"||Y==="interrupted"){let V={task_id:$,patch:{status:Y==="pendingInit"?"pending":Y==="interrupted"?"paused":"running"}};this.emit("bg_task_updated",V);return}if(this.collabAgentSettled.size>=5000)this.collabAgentSettled.clear();this.collabAgentSettled.add($);let Q={task_id:$,status:Y==="completed"?"completed":Y==="errored"?"failed":"stopped",summary:typeof Z?.message==="string"&&Z.message?Z.message:void 0};this.emit("bg_task_settled",Q)}primeRolloutImageGenerationScan(){if(this.rolloutFilePath=null,this.rolloutReadOffset=0,this.rolloutLineRemainder="",this.rolloutDecoder=new VQ("utf8"),this.emittedImageGenerationIds.clear(),!this.sessionId)return;let $=zQ(this.sessionId);if(!$)return;this.rolloutFilePath=$;try{this.rolloutReadOffset=H8($).size,K(`codex-process: image generation rollout scan primed ${$} offset=${this.rolloutReadOffset}`)}catch(Z){K(`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??zQ(this.sessionId);if(!$){K(`codex-process: image generation rollout file not found for thread=${this.sessionId}`);return}this.rolloutFilePath=$;let Z;try{let Q=H8($).size;if(Q<=this.rolloutReadOffset)return;let V=Q-this.rolloutReadOffset;Z=Buffer.allocUnsafe(V);let H=R_($,"r"),X=0;try{while(X<V){let z=T_(H,Z,X,V-X,this.rolloutReadOffset+X);if(z===0)break;X+=z}}finally{U_(H)}Z=Z.subarray(0,X),this.rolloutReadOffset+=X}catch(Q){K(`codex-process: image generation rollout read failed ${$}: ${Q instanceof Error?Q.message:Q}`);return}let J=this.rolloutLineRemainder+this.rolloutDecoder.write(Z),Y=J.split(/\r?\n/);this.rolloutLineRemainder=J.endsWith(`
|
|
83
|
-
`)?"":Y.pop()??"";for(let Q of Y){if(!Q.trim())continue;let V;try{V=JSON.parse(Q)}catch(z){K(`codex-process: image generation rollout JSON parse failed ${$}: ${z instanceof Error?z.message:z}`);continue}let H=V?.payload,X=H?.type;if(X!=="image_generation_end"&&X!=="image_generation_call")continue;this.emitRolloutImageGeneration(H)}}emitRolloutImageGeneration($){let Z=typeof $?.call_id==="string"?$.call_id:typeof $?.id==="string"?$.id:"";if(!Z||this.emittedImageGenerationIds.has(Z))return;let J=
|
|
84
|
-
`,(Y)=>{if(Y)J(Y)}),!0}catch(Y){return J(Y)}}request($,Z,J=
|
|
82
|
+
`))>=0){let J=this.stderrBuf.slice(0,Z);if(this.stderrBuf=this.stderrBuf.slice(Z+1),J.trim())K(`codex-process[stderr]: ${J}`)}}flushStderrTail(){let $=this.stderrBuf;if(this.stderrBuf="",$.trim())K(`codex-process[stderr]: ${$}`)}handleMessage($){if(Object.prototype.hasOwnProperty.call($,"id")&&!$.method){let J=this.pending.get($.id);if(!J){K(`codex-process: response for unknown id=${$.id}`);return}if(this.pending.delete($.id),clearTimeout(J.timeout),$.error){let Y=typeof $.error?.code==="number"?$.error.code:null,Q=typeof $.error==="string"?$.error:typeof $.error?.message==="string"?$.error.message:JSON.stringify($.error);J.reject(new B2(J.method,$.id,Y,Q,$.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=h7($);if(Z){let J=this.withSessionId(Z);v7(Z.sourceMethod??"raw_message",$,J),this.emit("context_compacted",J);return}m0("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=f7($,Z);if(J){let Y=this.withSessionId(J);v7($,Z,Y),this.emit("context_compacted",Y);return}switch($){case"thread/started":{let Y=Z.thread;if(Y?.id)this.sessionId=Y.id;return}case"thread/settings/updated":{let Y=Z.threadSettings;if(typeof Y?.model==="string")this.lastModel=Y.model;if(s0(Y?.effort))this.lastEffort=Y.effort;return}case"thread/tokenUsage/updated":{let Y=W2(Z.tokenUsage?.last);if(Y)this.lastUsage=Y,this.lastResult.usage=this.lastUsage;else K("codex-process: tokenUsage notification missing last breakdown");this.lastTotalUsage=W2(Z.tokenUsage?.total);let Q=Z.tokenUsage?.modelContextWindow;if(typeof Q==="number"&&Q>0)this.lastContextWindow=Q;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){m0("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){m0("TURN_COMPLETED_THREAD_MISMATCH",{method:$,params:Z});return}let Y=Z.turn??{},Q=typeof Y.id==="string"&&Y.id?Y.id:null;if(Q){if(this.finishedTurnIds?.has(Q)){K(`codex-process: duplicate turn/completed ignored turn=${Q}`);return}if(this.currentTurnId&&this.currentTurnId!==Q){this.markTurnStartTerminal(Q),this.rememberFinishedTurn(Q),K(`codex-process: stale turn/completed ignored turn=${Q} current=${this.currentTurnId}`);return}this.flushRolloutImageGenerations(),this.markConversationMaterialized("turn/completed notification"),this.markTurnStartTerminal(Q),this.rememberFinishedTurn(Q)}else m0("TURN_COMPLETED_MISSING_ID",{method:$,params:Z});let V=Y.status,H=Y.error??(V==="failed"&&this.turnError&&this.turnError.turnId===Q?this.turnError.error:null);this.turnError=null;let X=V==="failed"||!!H,z=V==="completed"&&!X&&!!Q;if(this.lastCompletedTurnId=z?Q:null,this.currentTurnId=null,V==="failed"&&Q&&HQ(H?.message)&&this.scheduleCapacityRetry(H.message,h_))return;this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!1;let W=X?H?.type??H?.message??"failed":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof Y.durationMs==="number"?Y.durationMs:null,num_turns:1,usage:this.lastUsage,subtype:W,is_error:X},this.emit("result",{subtype:W,is_error:X,...X&&typeof H?.message==="string"?{error:H.message}:{},...V==="failed"&&Q&&Y8(H)?{codexQuotaFailure:{accepted:!0}}:{},duration_ms:this.lastResult.duration_ms,usage:this.lastUsage,turn_id:Q,checkpoint:z&&this.sessionId?{provider:"codex",kind:"turn",id:Q,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 K("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 m0("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":{K(`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":{K(`codex-process: ${$}: ${Z.summary??Z.message??JSON.stringify(Z).slice(0,200)}`);return}case"error":{K(`codex-process: server error: ${JSON.stringify(Z).slice(0,500)}`);let Y=Z.error??Z;if(typeof Z.turnId==="string"&&Z.threadId===this.sessionId&&!this.finishedTurnIds?.has(Z.turnId)&&(!this.currentTurnId||this.currentTurnId===Z.turnId))this.turnError={turnId:Z.turnId,error:Y};this.emit("error",Error(Y.message??Y.summary??"codex app-server error"));return}}m0("NOTIFICATION",{method:$,params:Z}),this.emit("raw",{method:$,params:Z})}handleItemStarted($){let Z=$?.item;if(!Z?.id){m0("ITEM_STARTED_MISSING_ID",{method:"item/started",params:$});return}if(this.feedCollabItem(Z,"started"))return;let J=a7(Z,this.opts.workDir);if(!J){m0("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 Y=typeof $?.threadId==="string"?$.threadId:"";this.collabAgentSummaries.set(Y,J)}return}if(this.feedCollabItem(Z,"completed"))return;this.emitSubagentStep(Z,"completed",$)}handleItemCompleted($){let Z=$?.item;if(!Z?.id){m0("ITEM_COMPLETED_MISSING_ID",{method:"item/completed",params:$});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=WQ(Z,this.opts.workDir,this.sessionId??void 0);if(!J){m0("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:o7(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)??U0(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 Y=typeof J?.threadId==="string"?J.threadId:"",Q=Z==="started"?a7($,this.opts.workDir):WQ($,this.opts.workDir,this.sessionId??void 0);if(!Q)return;let V="output"in Q&&typeof Q.output==="string"?Q.output:void 0;this.emit("subagent_step",{thread_id:Y,item_id:$.id,tool:Q.name,phase:Z,brief:i_(Q.name,Q.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 Y=Q8($.agentPath,J);this.collabAgentNames.set(J,Y),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Y}),this.emit("bg_task_updated",{task_id:J,patch:{is_backgrounded:!0}})}else if($.kind==="started"){let Y=this.collabAgentNames.get(J),Q=Q8($.agentPath,J);if(Y!==Q&&!this.collabAgentSettled.has(J))this.collabAgentNames.set(J,Q),this.emit("bg_task_started",{task_id:J,task_type:"local_agent",description:Q})}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[Y,Q]of Object.entries(J))this.translateAgentState(Y,Q,$);if($.tool==="closeAgent"&&Z==="completed"&&$.status!=="failed"){let Y=_Q($);for(let Q of Y){if(this.collabAgentSettled.has(Q))continue;if(this.collabAgentSettled.add(Q),!this.collabAgentNames.has(Q))this.collabAgentNames.set(Q,Q8(null,Q));this.emit("bg_task_settled",{task_id:Q,status:"stopped"})}}if($.tool==="spawnAgent"){if(Z==="started")this.emit("tool_use",{id:$.id,name:"Agent",input:{tool:"spawnAgent",prompt:GQ($.prompt),description:n_($),model:typeof $.model==="string"?$.model:void 0}});else if($.status!=="inProgress")this.emit("tool_result",{tool_use_id:$.id,content:a_($),is_error:$.status==="failed"})}return!0}return!1}translateAgentState($,Z,J){let Y=Z?.status;if(typeof Y!=="string")return;if(this.collabAgentSettled.has($)){if(Y!=="running"&&Y!=="pendingInit"){if(Y==="errored"||Y==="shutdown"||Y==="notFound"||Y==="interrupted")this.emit("bg_task_updated",{task_id:$,patch:{status:Y==="errored"?"failed":"killed",error:typeof Z?.message==="string"&&Z.message?Z.message:void 0}});return}this.collabAgentSettled.delete($);let V=this.collabAgentNames.get($)??Q8(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 H={task_id:$,task_type:"local_agent",description:"子 agent",prompt:GQ(J.prompt)};this.emit("bg_task_started",H);let X={task_id:$,patch:{is_backgrounded:!0}};this.emit("bg_task_updated",X)}if(Y==="running"||Y==="pendingInit"||Y==="interrupted"){let V={task_id:$,patch:{status:Y==="pendingInit"?"pending":Y==="interrupted"?"paused":"running"}};this.emit("bg_task_updated",V);return}if(this.collabAgentSettled.size>=5000)this.collabAgentSettled.clear();this.collabAgentSettled.add($);let Q={task_id:$,status:Y==="completed"?"completed":Y==="errored"?"failed":"stopped",summary:typeof Z?.message==="string"&&Z.message?Z.message:void 0};this.emit("bg_task_settled",Q)}primeRolloutImageGenerationScan(){if(this.rolloutFilePath=null,this.rolloutReadOffset=0,this.rolloutLineRemainder="",this.rolloutDecoder=new QQ("utf8"),this.emittedImageGenerationIds.clear(),!this.sessionId)return;let $=XQ(this.sessionId);if(!$)return;this.rolloutFilePath=$;try{this.rolloutReadOffset=V8($).size,K(`codex-process: image generation rollout scan primed ${$} offset=${this.rolloutReadOffset}`)}catch(Z){K(`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??XQ(this.sessionId);if(!$){K(`codex-process: image generation rollout file not found for thread=${this.sessionId}`);return}this.rolloutFilePath=$;let Z;try{let Q=V8($).size;if(Q<=this.rolloutReadOffset)return;let V=Q-this.rolloutReadOffset;Z=Buffer.allocUnsafe(V);let H=N_($,"r"),X=0;try{while(X<V){let z=E_(H,Z,X,V-X,this.rolloutReadOffset+X);if(z===0)break;X+=z}}finally{A_(H)}Z=Z.subarray(0,X),this.rolloutReadOffset+=X}catch(Q){K(`codex-process: image generation rollout read failed ${$}: ${Q instanceof Error?Q.message:Q}`);return}let J=this.rolloutLineRemainder+this.rolloutDecoder.write(Z),Y=J.split(/\r?\n/);this.rolloutLineRemainder=J.endsWith(`
|
|
83
|
+
`)?"":Y.pop()??"";for(let Q of Y){if(!Q.trim())continue;let V;try{V=JSON.parse(Q)}catch(z){K(`codex-process: image generation rollout JSON parse failed ${$}: ${z instanceof Error?z.message:z}`);continue}let H=V?.payload,X=H?.type;if(X!=="image_generation_end"&&X!=="image_generation_call")continue;this.emitRolloutImageGeneration(H)}}emitRolloutImageGeneration($){let Z=typeof $?.call_id==="string"?$.call_id:typeof $?.id==="string"?$.id:"";if(!Z||this.emittedImageGenerationIds.has(Z))return;let J=KQ($,this.sessionId??void 0);if(!J)return;let Y=$?.status==="failed",Q=$?.status==="generating"&&YQ(J)?"completed":$?.status;this.emittedImageGenerationIds.add(Z),this.emit("tool_use",{id:Z,name:"ImageGeneration",input:o7({...$,status:Q})}),this.emit("tool_result",{tool_use_id:Z,content:J,is_error:Y})}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??{},Y={questions:(J.questions??[]).map((Q)=>({id:Q.id,header:Q.header,question:Q.question,options:Array.isArray(Q.options)&&Q.options.length?Q.options.map((V)=>({label:V.label,description:V.description})):[{label:"自定义回答",description:Q.isSecret?"请直接在群里回复":"可直接在群里回复"}]}))};this.emit("tool_use",{id:J.itemId,name:"AskUserQuestion",input:Y}),this.emit("can_use_tool",{request_id:Z,tool_name:"AskUserQuestion",input:Y,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:m0("SERVER_REQUEST_UNSUPPORTED",$),this.respondError(Z,`unsupported server request: ${$.method}`)}}write($,Z){let J=(Y)=>{let Q=Y instanceof Error?Y:Error(String(Y));return K(`codex-process: stdin write failed: ${Q.message}`),Z?.(Q),!1};if(!this.alive)return J(Error(`write to dead process: ${JSON.stringify($).slice(0,200)}`));if(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($)+`
|
|
84
|
+
`,(Y)=>{if(Y)J(Y)}),!0}catch(Y){return J(Y)}}request($,Z,J=y_){let Y=++this.requestCounter;return new Promise((Q,V)=>{let H=setTimeout(()=>{let z=this.pending.get(Y);if(!z)return;this.pending.delete(Y),z.reject(Error(`codex app-server ${$} request timed out after ${J}ms (id=${Y})`))},Math.max(0,J)),X={resolve:Q,reject:V,method:$,timeout:H};this.pending.set(Y,X),this.write({id:Y,method:$,params:Z},(z)=>{if(this.pending.get(Y)!==X)return;this.pending.delete(Y),clearTimeout(H),V(Error(`codex app-server ${$} request write failed (id=${Y}): ${z.message}`,{cause:z}))})})}rejectPendingRequests($){for(let[Z,J]of this.pending)clearTimeout(J.timeout),J.reject($(Z,J));this.pending.clear()}respond($,Z){let J=String($),Y=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Y?.id??$,result:Z})}respondError($,Z){let J=String($),Y=this.serverRequests.get(J);this.serverRequests.delete(J),this.write({id:Y?.id??$,error:{code:-32601,message:Z}})}sendInitialize(){if(!this.readyPromise)this.readyPromise=this.initializeAndStartThread(),this.readyPromise.catch(($)=>{K(`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.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,Y;if($.kind==="resume")J="thread/resume",Y=await this.request(J,{threadId:$.source.sessionId,...Z,excludeTurns:!0,persistExtendedHistory:!1});else if($.kind==="fork")J="thread/fork",Y=await this.request(J,{threadId:$.source.sessionId,...$.through?{lastTurnId:$.through.id}:{},...Z,excludeTurns:!0});else J="thread/start",Y=await this.request(J,{...Z,experimentalRawEvents:!1,persistExtendedHistory:!1});let Q=Y?.thread;if(typeof Q?.id!=="string"||!Q.id)throw Error(`codex app-server ${J} returned no thread.id`);let V=typeof Q.cwd==="string"?Q.cwd:typeof Y?.cwd==="string"?Y.cwd:null;if(V!==this.opts.workDir)throw Error(`codex app-server ${J} returned cwd=${V??"MISS"}, expected ${this.opts.workDir}`);if($.kind==="fork"&&Q.id===$.source.sessionId)throw Error(`codex app-server thread/fork returned source thread id ${Q.id}`);if($.kind==="resume"&&Q.id!==$.source.sessionId)throw Error(`codex app-server thread/resume returned thread id ${Q.id}, expected ${$.source.sessionId}`);let H=typeof Q.path==="string"&&Q.path?Q.path:null;if(!H||!YQ(H)||!H.endsWith(`${Q.id}.jsonl`))throw Error(`codex app-server ${J} returned invalid thread.path=${H??"MISS"}`);if(this.sessionId=Q.id,this.conversationRolloutPath=H,this.conversationResumable=!1,$.kind!=="fresh")await this.verifyConversationMaterialized(`${J} response`),this.conversationResumable=!0;if(Y?.model)this.lastModel=Y.model;if(s0(Y?.reasoningEffort))this.lastEffort=Y.reasoningEffort;else this.lastEffort=this.opts.effort??null;K(`codex-process: thread=${this.sessionId}`),this.primeRolloutImageGenerationScan(),this.emit("init",{session_id:this.sessionId,thread:Q})}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,K(`codex-process: conversation materialized thread=${Z} source=${$}`),this.emit("conversation_materialized",{session_id:Z,source:$})},(Y)=>{let Q=Y instanceof Error?Y:Error(String(Y));this.lastConversationMaterializationFailure=Q,K(`codex-process: conversation materialization check failed thread=${Z} source=${$}: ${Q.message}`),this.emit("conversation_materialization_failed",{session_id:Z,path:this.conversationRolloutPath,source:$,error:Q})}).finally(()=>{if(this.conversationMaterializationVerification===J)this.conversationMaterializationVerification=null;let Y=this.conversationMaterializationRetrySource;if(this.conversationMaterializationRetrySource=null,!this.conversationResumable&&Y)this.markConversationMaterialized(Y)})}async verifyConversationMaterialized($){let Z=this.sessionId,J=this.conversationRolloutPath;if(!Z||!J)throw Error(`codex ${$} has no initialized rollout identity`);let Q=(await this.request("thread/read",{threadId:Z,includeTurns:!0},w_))?.thread;if(Q?.id!==Z||Q.cwd!==this.opts.workDir||Q.path!==J||!Array.isArray(Q.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=V8(Z)}catch(Y){throw Error(`codex ${$} rollout is not readable at ${Z}: ${Y instanceof Error?Y.message:Y}`,{cause:Y})}if(!J.isFile())throw Error(`codex ${$} rollout path is not a file: ${Z}`)}conversationLaunch(){let $=this.opts.launch??{kind:"fresh"};if(_0($,"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:{"features.default_mode_request_user_input":!0,...this.opts.allowDelegation===!1?{"features.multi_agent":!1}:{},...this.opts.effort?{model_reasoning_effort:this.opts.effort}:{}},...this.opts.model?{model:this.opts.model}:{},...this.opts.appendSystemPrompt?{developerInstructions:this.opts.appendSystemPrompt}:{},serviceName:this.opts.serviceName??"lodestar"}}sendUserText($,Z=[]){let J=Z.length?Z.map((Q)=>`[file: ${Q}]`).join(" ")+`
|
|
85
85
|
|
|
86
|
-
`:"";this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!1,this.capacityRetryEnabled=!0,this.turnError=null;let Y=this.beginTurnStart(J+$);this.startTurn(J+$,Y).catch((Q)=>this.failTurnStart(Q,Y))}async listModels(){await this.ensureInitialized();let $=[],Z=null;do{let J=await this.request("model/list",{cursor:Z,limit:100,includeHidden:!1});if(!Array.isArray(J?.data))throw Error("model/list returned no data array");for(let Y of J.data){if(typeof Y?.model!=="string"||!Y.model)continue;$.push({id:typeof Y.id==="string"&&Y.id?Y.id:Y.model,model:Y.model,displayName:typeof Y.displayName==="string"&&Y.displayName?Y.displayName:Y.model,description:typeof Y.description==="string"?Y.description:"",hidden:Y.hidden===!0,isDefault:Y.isDefault===!0,supportedReasoningEfforts:g_(Y.supportedReasoningEfforts),defaultReasoningEffort:s0(Y.defaultReasoningEffort)?Y.defaultReasoningEffort:null})}Z=typeof J?.nextCursor==="string"&&J.nextCursor?J.nextCursor:null}while(Z);return $}async listConversations(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Y=await this.request("thread/list",{cursor:J,limit:100,sortKey:"updated_at",sortDirection:"desc",cwd:this.opts.workDir});if(!Array.isArray(Y?.data))throw Error("thread/list returned no data array");for(let V of Y.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 H=typeof V.status==="string"?V.status:typeof V.status?.type==="string"?V.status.type:void 0;if(H2("codex",V.id))continue;$.push({provider:"codex",sessionId:V.id,cwd:V.cwd,preview:V.preview,ts:V.updatedAt*1000,...H?{status:H}:{}})}let Q=Y?.nextCursor;if(Q!==null&&typeof Q!=="string")throw Error("thread/list returned an invalid nextCursor");if(Q&&Z.has(Q))throw Error(`thread/list repeated pagination cursor ${Q}`);if(Q)Z.add(Q);J=Q}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){K("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");await this.request("thread/compact/start",{threadId:this.sessionId})}failTurnStart($,Z){if(!this.ownsTurnStartFailure(Z)){K(`codex-process: ignored stale turn/start failure generation=${Z.generation}`);return}this.turnStartOwner=null,Z.terminal=!0;let J=$ instanceof Error?$.message:String($);if(K(`codex-process: turn/start failed: ${J}`),$ instanceof B2&&$.method==="turn/start"&&XQ($.serverMessage)&&Z.inputText!==void 0&&this.scheduleCapacityRetry($.serverMessage,Z.inputText))return;this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!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 B2&&$.method==="turn/start"&&Z.inputText!==void 0&&(Q8($.serverData)||Q8({message:$.serverMessage}))?{codexQuotaFailure:{accepted:!1,rejectedInput:Z.inputText}}:{}})}recordTurnStarted($,Z,J,Y){let Q=typeof $?.id==="string"&&$.id?$.id:null;if(!Q)throw Error(`codex app-server ${J} returned no turn.id`);if(this.finishedTurnIds?.has(Q))return;let V=Y??this.turnStartOwner;if(V?.interrupted){if(this.rememberFinishedTurn(Q),this.turnStartOwner===V)this.turnStartOwner=null;this.interruptTurn(Q);return}this.confirmTurnStart(Q,Y);let H=this.currentTurnId!==Q;if(this.currentTurnId=Q,!H)return;let X=this.capacityRetryHasStarted&&(this.capacityRetryCount??0)>0;if(this.capacityRetryHasStarted=!0,this.capacityRetryTimer&&this.turnRetry){let z={...this.turnRetry,phase:"retrying",delayMs:0};this.cancelCapacityRetry(),this.emit("turn_retry",z)}this.turnRetry=null,this.lastCompletedTurnId=null,this.emit("turn_started",{turn_id:Q,thread_id:typeof Z==="string"&&Z?Z:this.sessionId,...X?{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 Y=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"}});this.recordTurnStarted(Y?.turn,this.sessionId,"turn/start response",J)}catch(Y){if(!this.ownsTurnStartFailure(J)){K(`codex-process: ignored stale turn/start rejection generation=${J.generation}`);return}throw Y}}sendInterrupt(){this.capacityRetryEnabled=!1;let $=!!this.turnRetry&&!this.currentTurnId;this.cancelCapacityRetry();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)=>K(`codex-process: interrupt failed: ${Z}`))}cancelCapacityRetry(){if(this.capacityRetryTimer)clearTimeout(this.capacityRetryTimer);this.capacityRetryTimer=null,this.turnRetry=null}scheduleCapacityRetry($,Z){if(!this.alive||this.expectedExit||!this.capacityRetryEnabled)return!1;if(this.capacityRetryTimer)return!0;let J=(this.capacityRetryCount??0)+1;this.capacityRetryCount=J;let Y=Math.min(w_*2**Math.min(J-1,4),v_),Q=this.turnStartGeneration??0,V={phase:"waiting",attempt:J,delayMs:Y,message:$};this.turnRetry=V,K(`codex-process: model capacity retry #${J} in ${Y}ms: ${$}`);let H=setTimeout(()=>{if(this.capacityRetryTimer!==H)return;if(this.capacityRetryTimer=null,!this.alive||this.expectedExit||!this.capacityRetryEnabled||this.currentTurnId||Q!==(this.turnStartGeneration??0))return;if(this.turnRetry={...V,phase:"retrying",delayMs:0},this.emit("turn_retry",this.turnRetry),!this.alive||this.expectedExit||!this.capacityRetryEnabled||Q!==(this.turnStartGeneration??0))return;let X=this.beginTurnStart(Z);this.startTurn(Z,X).catch((z)=>this.failTurnStart(z,X))},Y);return this.capacityRetryTimer=H,this.emit("turn_retry",V),!0}sendPermissionResponse($,Z,J){let Y=this.serverRequests.get(String($));if(!Y){K(`codex-process: permission response for unknown request ${$}`);return}let Q=Z==="allow";switch(Y.method){case"item/commandExecution/requestApproval":this.respond($,{decision:Q?"accept":"decline"});return;case"item/fileChange/requestApproval":this.respond($,{decision:Q?"accept":"decline"});return;case"item/permissions/requestApproval":if(Q)this.respond($,{permissions:Y.params?.permissions??{},scope:"session"});else this.respondError($,J?.denyMessage??"denied by user");return;case"item/tool/requestUserInput":{if(!Q){this.respondError($,J?.denyMessage??"denied by user");return}let V=J?.updatedInput?.answers??{},H={};for(let X of Y.params?.questions??[]){let z=V[X.question]??V[X.id];if(z!==void 0)H[X.id]={answers:[String(z)]}}this.respond($,{answers:H});return}default:m0("APPROVAL_RESPONSE_UNSUPPORTED",{requestId:$,method:Y.method,params:Y.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.capacityRetryEnabled=!1,this.cancelCapacityRetry(),!this.alive){if(await this.waitForExit($))return;throw Error(`codex app-server exited but stdio did not close within ${$}ms`)}this.expectedExit=!0,K(`codex-process: SIGTERM (timeout=${$}ms)`);let Z=[];if(this.sendSignal("SIGTERM",Z),await this.waitForExit($))return;if(K(`codex-process: SIGKILL (lifecycle not closed after ${$}ms)`),this.alive)this.sendSignal("SIGKILL",Z);if(await this.waitForExit($))return;let J=Z.length?`; ${Z.join("; ")}`:"",Y=Error(`codex app-server did not exit after SIGTERM and SIGKILL (${$}ms each)${J}`);throw K(`codex-process: kill failed: ${Y.message}`),Y}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,Y=(V)=>{if(J)return;J=!0,clearTimeout(Q),Z(V)},Q=setTimeout(()=>Y(!1),Math.max(0,$));this.exitPromise.then(()=>Y(!0))})}}});function a_($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t7($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Y=0;while(Y<$.length){J.lastIndex=Y;let X=J.exec($);if(!X)break;let z=X[1],W=new RegExp(`^(?: {0,3})${a_(z[0])}{${z.length},}[ \\t]*(?:\\n|$)`,"gm");W.lastIndex=X.index+X[0].length;let G=W.exec($),B=G?G.index+G[0].length:$.length;Z.push({start:X.index,end:B}),Y=B}let Q=[...Z],V=[],H=0;for(let X of Z){if(H<X.start)V.push({start:H,end:X.start});H=X.end}if(H<$.length)V.push({start:H,end:$.length});for(let X of V){let z=$.slice(X.start,X.end),W=/(`+)[^\n]*?\1/g,G;while((G=W.exec(z))!==null)Q.push({start:X.start+G.index,end:X.start+G.index+G[0].length})}return Q.sort((X,z)=>X.start-z.start)}function e7($,Z){if(!$)return $;let J=t7($);if(!J.length)return Z($);let Y="",Q=0;for(let V of J){if(V.start>Q)Y+=Z($.slice(Q,V.start));Y+=$.slice(V.start,V.end),Q=Math.max(Q,V.end)}if(Q<$.length)Y+=Z($.slice(Q));return Y}function o_($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function LQ($){return $.replace(/!\[([^\]]*)\]\(([^)]*)\)/g,(J,Y,Q)=>{let V=Q.trim();return Y.trim()?`\uD83D\uDDBC️ ${Y.trim()} (${V})`:`\uD83D\uDDBC️ ${V}`}).replace(/!\[/g,"\uD83D\uDDBC️ [")}function s$($){if(Array.isArray($))return $.map((Y)=>s$(Y));if($==null||typeof $!=="object")return $;let Z=$,J={};for(let[Y,Q]of Object.entries(Z))J[Y]=s$(Q);if(Z.tag==="markdown"&&typeof Z.content==="string")J.content=$3(Z.content);return J}function Z0($){return e7($,(Z)=>r_(LQ(o_(Z))))}function r_($){return $.replace(/\\\[([\s\S]*?)\\\]/g,(Z,J)=>`
|
|
86
|
+
`:"";this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!1,this.capacityRetryEnabled=!0,this.turnError=null;let Y=this.beginTurnStart(J+$);this.startTurn(J+$,Y).catch((Q)=>this.failTurnStart(Q,Y))}async listModels(){await this.ensureInitialized();let $=[],Z=null;do{let J=await this.request("model/list",{cursor:Z,limit:100,includeHidden:!1});if(!Array.isArray(J?.data))throw Error("model/list returned no data array");for(let Y of J.data){if(typeof Y?.model!=="string"||!Y.model)continue;$.push({id:typeof Y.id==="string"&&Y.id?Y.id:Y.model,model:Y.model,displayName:typeof Y.displayName==="string"&&Y.displayName?Y.displayName:Y.model,description:typeof Y.description==="string"?Y.description:"",hidden:Y.hidden===!0,isDefault:Y.isDefault===!0,supportedReasoningEfforts:m_(Y.supportedReasoningEfforts),defaultReasoningEffort:s0(Y.defaultReasoningEffort)?Y.defaultReasoningEffort:null})}Z=typeof J?.nextCursor==="string"&&J.nextCursor?J.nextCursor:null}while(Z);return $}async listConversations(){await this.ensureInitialized();let $=[],Z=new Set,J=null;do{let Y=await this.request("thread/list",{cursor:J,limit:100,sortKey:"updated_at",sortDirection:"desc",cwd:this.opts.workDir});if(!Array.isArray(Y?.data))throw Error("thread/list returned no data array");for(let V of Y.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 H=typeof V.status==="string"?V.status:typeof V.status?.type==="string"?V.status.type:void 0;if(H2("codex",V.id))continue;$.push({provider:"codex",sessionId:V.id,cwd:V.cwd,preview:V.preview,ts:V.updatedAt*1000,...H?{status:H}:{}})}let Q=Y?.nextCursor;if(Q!==null&&typeof Q!=="string")throw Error("thread/list returned an invalid nextCursor");if(Q&&Z.has(Q))throw Error(`thread/list repeated pagination cursor ${Q}`);if(Q)Z.add(Q);J=Q}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){K("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");await this.request("thread/compact/start",{threadId:this.sessionId})}failTurnStart($,Z){if(!this.ownsTurnStartFailure(Z)){K(`codex-process: ignored stale turn/start failure generation=${Z.generation}`);return}this.turnStartOwner=null,Z.terminal=!0;let J=$ instanceof Error?$.message:String($);if(K(`codex-process: turn/start failed: ${J}`),$ instanceof B2&&$.method==="turn/start"&&HQ($.serverMessage)&&Z.inputText!==void 0&&this.scheduleCapacityRetry($.serverMessage,Z.inputText))return;this.cancelCapacityRetry(),this.capacityRetryCount=0,this.capacityRetryHasStarted=!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 B2&&$.method==="turn/start"&&Z.inputText!==void 0&&(Y8($.serverData)||Y8({message:$.serverMessage}))?{codexQuotaFailure:{accepted:!1,rejectedInput:Z.inputText}}:{}})}recordTurnStarted($,Z,J,Y){let Q=typeof $?.id==="string"&&$.id?$.id:null;if(!Q)throw Error(`codex app-server ${J} returned no turn.id`);if(this.finishedTurnIds?.has(Q))return;let V=Y??this.turnStartOwner;if(V?.interrupted){if(this.rememberFinishedTurn(Q),this.turnStartOwner===V)this.turnStartOwner=null;this.interruptTurn(Q);return}this.confirmTurnStart(Q,Y);let H=this.currentTurnId!==Q;if(this.currentTurnId=Q,!H)return;let X=this.capacityRetryHasStarted&&(this.capacityRetryCount??0)>0;if(this.capacityRetryHasStarted=!0,this.capacityRetryTimer&&this.turnRetry){let z={...this.turnRetry,phase:"retrying",delayMs:0};this.cancelCapacityRetry(),this.emit("turn_retry",z)}this.turnRetry=null,this.lastCompletedTurnId=null,this.emit("turn_started",{turn_id:Q,thread_id:typeof Z==="string"&&Z?Z:this.sessionId,...X?{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 Y=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"}});this.recordTurnStarted(Y?.turn,this.sessionId,"turn/start response",J)}catch(Y){if(!this.ownsTurnStartFailure(J)){K(`codex-process: ignored stale turn/start rejection generation=${J.generation}`);return}throw Y}}sendInterrupt(){this.capacityRetryEnabled=!1;let $=!!this.turnRetry&&!this.currentTurnId;this.cancelCapacityRetry();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)=>K(`codex-process: interrupt failed: ${Z}`))}cancelCapacityRetry(){if(this.capacityRetryTimer)clearTimeout(this.capacityRetryTimer);this.capacityRetryTimer=null,this.turnRetry=null}scheduleCapacityRetry($,Z){if(!this.alive||this.expectedExit||!this.capacityRetryEnabled)return!1;if(this.capacityRetryTimer)return!0;let J=(this.capacityRetryCount??0)+1;this.capacityRetryCount=J;let Y=Math.min(v_*2**Math.min(J-1,4),f_),Q=this.turnStartGeneration??0,V={phase:"waiting",attempt:J,delayMs:Y,message:$};this.turnRetry=V,K(`codex-process: model capacity retry #${J} in ${Y}ms: ${$}`);let H=setTimeout(()=>{if(this.capacityRetryTimer!==H)return;if(this.capacityRetryTimer=null,!this.alive||this.expectedExit||!this.capacityRetryEnabled||this.currentTurnId||Q!==(this.turnStartGeneration??0))return;if(this.turnRetry={...V,phase:"retrying",delayMs:0},this.emit("turn_retry",this.turnRetry),!this.alive||this.expectedExit||!this.capacityRetryEnabled||Q!==(this.turnStartGeneration??0))return;let X=this.beginTurnStart(Z);this.startTurn(Z,X).catch((z)=>this.failTurnStart(z,X))},Y);return this.capacityRetryTimer=H,this.emit("turn_retry",V),!0}sendPermissionResponse($,Z,J){let Y=this.serverRequests.get(String($));if(!Y){K(`codex-process: permission response for unknown request ${$}`);return}let Q=Z==="allow";switch(Y.method){case"item/commandExecution/requestApproval":this.respond($,{decision:Q?"accept":"decline"});return;case"item/fileChange/requestApproval":this.respond($,{decision:Q?"accept":"decline"});return;case"item/permissions/requestApproval":if(Q)this.respond($,{permissions:Y.params?.permissions??{},scope:"session"});else this.respondError($,J?.denyMessage??"denied by user");return;case"item/tool/requestUserInput":{if(!Q){this.respondError($,J?.denyMessage??"denied by user");return}let V=J?.updatedInput?.answers??{},H={};for(let X of Y.params?.questions??[]){let z=V[X.question]??V[X.id];if(z!==void 0)H[X.id]={answers:[String(z)]}}this.respond($,{answers:H});return}default:m0("APPROVAL_RESPONSE_UNSUPPORTED",{requestId:$,method:Y.method,params:Y.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.capacityRetryEnabled=!1,this.cancelCapacityRetry(),!this.alive){if(await this.waitForExit($))return;throw Error(`codex app-server exited but stdio did not close within ${$}ms`)}this.expectedExit=!0,K(`codex-process: SIGTERM (timeout=${$}ms)`);let Z=[];if(this.sendSignal("SIGTERM",Z),await this.waitForExit($))return;if(K(`codex-process: SIGKILL (lifecycle not closed after ${$}ms)`),this.alive)this.sendSignal("SIGKILL",Z);if(await this.waitForExit($))return;let J=Z.length?`; ${Z.join("; ")}`:"",Y=Error(`codex app-server did not exit after SIGTERM and SIGKILL (${$}ms each)${J}`);throw K(`codex-process: kill failed: ${Y.message}`),Y}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,Y=(V)=>{if(J)return;J=!0,clearTimeout(Q),Z(V)},Q=setTimeout(()=>Y(!1),Math.max(0,$));this.exitPromise.then(()=>Y(!0))})}}});function o_($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s7($){let Z=[],J=/^(?: {0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/gm,Y=0;while(Y<$.length){J.lastIndex=Y;let X=J.exec($);if(!X)break;let z=X[1],W=new RegExp(`^(?: {0,3})${o_(z[0])}{${z.length},}[ \\t]*(?:\\n|$)`,"gm");W.lastIndex=X.index+X[0].length;let G=W.exec($),B=G?G.index+G[0].length:$.length;Z.push({start:X.index,end:B}),Y=B}let Q=[...Z],V=[],H=0;for(let X of Z){if(H<X.start)V.push({start:H,end:X.start});H=X.end}if(H<$.length)V.push({start:H,end:$.length});for(let X of V){let z=$.slice(X.start,X.end),W=/(`+)[^\n]*?\1/g,G;while((G=W.exec(z))!==null)Q.push({start:X.start+G.index,end:X.start+G.index+G[0].length})}return Q.sort((X,z)=>X.start-z.start)}function t7($,Z){if(!$)return $;let J=s7($);if(!J.length)return Z($);let Y="",Q=0;for(let V of J){if(V.start>Q)Y+=Z($.slice(Q,V.start));Y+=$.slice(V.start,V.end),Q=Math.max(Q,V.end)}if(Q<$.length)Y+=Z($.slice(Q));return Y}function r_($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function jQ($){return $.replace(/!\[([^\]]*)\]\(([^)]*)\)/g,(J,Y,Q)=>{let V=Q.trim();return Y.trim()?`\uD83D\uDDBC️ ${Y.trim()} (${V})`:`\uD83D\uDDBC️ ${V}`}).replace(/!\[/g,"\uD83D\uDDBC️ [")}function s$($){if(Array.isArray($))return $.map((Y)=>s$(Y));if($==null||typeof $!=="object")return $;let Z=$,J={};for(let[Y,Q]of Object.entries(Z))J[Y]=s$(Q);if(Z.tag==="markdown"&&typeof Z.content==="string")J.content=e7(Z.content);return J}function Z0($){return t7($,(Z)=>s_(jQ(r_(Z))))}function s_($){return $.replace(/\\\[([\s\S]*?)\\\]/g,(Z,J)=>`
|
|
87
87
|
\`\`\`
|
|
88
88
|
${J.trim()}
|
|
89
89
|
\`\`\`
|
|
@@ -91,194 +91,194 @@ ${J.trim()}
|
|
|
91
91
|
\`\`\`
|
|
92
92
|
${J.trim()}
|
|
93
93
|
\`\`\`
|
|
94
|
-
`).replace(/\\\(([\s\S]*?)\\\)/g,(Z,J)=>`\`${J.trim()}\``).replace(/\$([^$\n]+)\$/g,(Z,J)=>/\\|\^|_|=/.test(J)?`\`${J.trim()}\``:Z)}function
|
|
95
|
-
`):JSON.stringify($))??"MISS").replace(/\s+/g," ").trim();return Z?`❌ ${Y.slice(0,80)}`:Y.slice(0,80)}function
|
|
96
|
-
`):"_(暂无执行记录)_")}function j2($,Z=Date.now(),J="bucket"){return{tag:"collapsible_panel",element_id:R4.panel($.id),header:{title:{tag:"plain_text",content:`${
|
|
97
|
-
`)}],Y=new Set([...Z,...Array.from($.matchAll(/\[file: ([^\]\r\n]+)\]/g),(V)=>V[1])]),Q=new Set([".png",".jpg",".jpeg",".webp",".gif"]);for(let V of Y){if(!Q.has(
|
|
98
|
-
|
|
99
|
-
${Q.detail}`:Q.question}))};this.questionInputs.set(Z.id,Y.questions),this.emit("tool_use",{id:Z.id,name:"AskUserQuestion",input:Y,parentToolUseId:null}),this.emit("can_use_tool",{request_id:Z.id,tool_use_id:Z.id,tool_name:"AskUserQuestion",input:Y});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 Y=Z.frame,Q=`${Z.sessionId}:${Y.attemptId}`;if(Y.type==="start"){this.frames.set(Q,{revision:Y.revision,nextIndex:0});return}let V=this.frames.get(Q);if(!V||V.revision+1!==Y.revision||V.nextIndex!==Y.index)throw Error("DSH assistant stream sequence mismatch");if(V.revision=Y.revision,Y.type==="end"){if(this.frames.delete(Q),!J)this.emit("assistant_block_stop",{parentToolUseId:null});return}if(Y.type!=="chunk")throw Error(`unknown DSH assistant frame: ${Y.type}`);V.nextIndex++;let H=Y.chunk;if(H.type==="text-delta"){if(J)this.childText.set(Z.sessionId,(this.childText.get(Z.sessionId)??"")+H.text);this.emit("assistant_text",{text:H.text,parentToolUseId:J?Z.sessionId:null})}else if(H.type==="block-end"&&H.block.type==="text"&&!J)this.emit("assistant_block_stop",{parentToolUseId:null});else if(H.type==="usage"&&!J)this.observeUsage(H.usage);return}case"session.event":{let Y=Z.event,Q=Y.data;if(!Y||!Q||typeof Y.type!=="string")throw Error("invalid DSH session event");if(Y.type==="turn/start"&&!J)this.busy=!0,this.startedAt=Date.now(),this.lastUsage=null,this.lastResult=
|
|
100
|
-
`);for(let Y=J.length-1;Y>=0;Y--){let Q=J[Y].trim();if(!Q)continue;try{let V=JSON.parse(Q);if(V?.type==="assistant"&&V?.message?.usage){let H=V.message.usage;if((H.input_tokens??0)+(H.cache_read_input_tokens??0)+(H.cache_creation_input_tokens??0)+(H.output_tokens??0)>0)return H}}catch{}}return null}function
|
|
101
|
-
`);return $==null?"":JSON.stringify($,null,2)}function
|
|
102
|
-
`)}}catch{}return Z}function
|
|
103
|
-
|
|
104
|
-
`:"";try{this.input.push({type:"user",session_id:this.sessionId??"",message:{role:"user",content:[{type:"text",text:J+$}]},parent_tool_use_id:null,priority:"now"})}catch(Y){let Q=Y instanceof Error?Y:Error(String(Y));K(`claude-agent-process: sendUserText failed: ${Q.message}`),this.failTurnStart(Q)}}sendInterrupt(){this.query?.interrupt().catch(($)=>K(`claude-agent-process: interrupt failed: ${$}`))}sendPermissionResponse($,Z,J){let Y=this.pendingPermissions.get(String($));if(!Y){K(`claude-agent-process: permission response for unknown request ${$}`);return}if(this.pendingPermissions.delete(String($)),Y.cleanup?.(),Z==="allow")Y.resolve({behavior:"allow",updatedInput:J?.updatedInput??{}});else Y.resolve({behavior:"deny",message:J?.denyMessage??""})}sendHookResponse($,Z={}){K("claude-agent-process: sendHookResponse ignored; hooks are handled by SDK callbacks")}isAlive(){return this.alive}async kill($=5000){if(!this.alive)return;if(this.expectedExit=!0,this.denyPendingPermissions("claude process is stopping"),this.input.abort(),!this.started||!this.query){this.finishExit(null,null);return}let Z=null;try{this.query.close()}catch(J){Z=J instanceof Error?J:Error(String(J))}if(!this.abortController.signal.aborted)this.abortController.abort(Z??Error("claude process shutdown requested"));if(!await this.waitForExit($)){let J=Error(`claude Agent SDK query did not exit within ${$}ms after close/abort`,Z?{cause:Z}:void 0);throw K(`claude-agent-process: kill failed: ${J.message}`),J}if(Z){let J=Error(`claude Agent SDK close failed: ${Z.message}`,{cause:Z});throw K(`claude-agent-process: kill failed: ${J.message}`),J}}async listModels(){if(!this.started)this.sendInitialize();if(await this.queryStart,!this.query)throw Error("claude-agent-process: SDK query not initialized (sendInitialize failed or not called)");return(await this.query.supportedModels()).map(bj)}async setModelSettings($,Z){let J=q3($);if(!E0(Z))throw Error(`invalid Claude effort: ${String(Z)}`);if(this.opts.effort==="default"!==(Z==="default"))throw Error("effort 参数模式改变,需要使用新的启动环境恢复会话");if(!this.started)this.sendInitialize();if(await this.queryStart,!this.query)throw Error("claude-agent-process: SDK query not initialized (sendInitialize failed or not called)");if(J)await this.query.setModel(J);await this.query.applyFlagSettings({effortLevel:Z==="default"?null:Z,ultracode:null}),this.opts.model=$,this.opts.effort=Z,this.lastModel=J?e$($):"claude:default",this.lastEffort=Z}async compactThread(){if(!this.input)throw Error("claude thread not initialized");return this.input.push({type:"user",session_id:this.sessionId??"",message:{role:"user",content:[{type:"text",text:"/compact"}]},parent_tool_use_id:null,priority:"now"}),new Promise(($,Z)=>{let J=!1,Y=()=>{this.off("context_compacted",Q),this.off("assistant_text",V),this.off("exit",H),this.off("error",X)},Q=()=>{if(J)return;J=!0,Y(),$()},V=(z)=>{if(J)return;if((z?.text??"").includes("Not enough messages to compact"))J=!0,Y(),Z(new U1)},H=()=>{if(J)return;J=!0,Y(),Z(Error("claude thread exited during /compact"))},X=(z)=>{if(J)return;J=!0,Y(),Z(z instanceof Error?z:Error(String(z)))};this.on("context_compacted",Q),this.on("assistant_text",V),this.once("exit",H),this.once("error",X)})}canUseTool($,Z,J){if($!=="AskUserQuestion")return Promise.resolve({behavior:"allow",updatedInput:Z});let Y=Cj(Z);if(Y.length===0)return K("claude-agent-process: AskUserQuestion 无有效 questions — allow 原样"),Promise.resolve({behavior:"allow",updatedInput:Z});let Q={...Z,questions:Y},V=`claude_perm_${++this.requestCounter}`,H=J.toolUseID||V,X={request_id:V,tool_name:"AskUserQuestion",input:Q,tool_use_id:H},z=new Promise((W)=>{let G=(_)=>{J.signal.removeEventListener("abort",B),W(_)},B=()=>{if(!this.pendingPermissions.delete(V))return;G({behavior:"deny",message:"aborted"})};J.signal.addEventListener("abort",B,{once:!0}),this.pendingPermissions.set(V,{kind:"dialog",resolve:G,request:X})});return this.emitToolUseOnce(H,"AskUserQuestion",Q,null),this.emit("can_use_tool",X),z}async readLoop($){try{for await(let Z of $)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){K(`claude-agent-process: read loop stopped after requested shutdown: ${J.message}`),this.finishExit(null,null);return}K(`claude-agent-process: read loop failed: ${J.message}`),this.emit("error",J),this.finishExit(1,null)}}finishExit($,Z){if(!this.alive)return;this.alive=!1,this.turnActive=!1,this.denyPendingPermissions("claude process exited"),this.resolveExit(),K(`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,Y=(V)=>{if(J)return;J=!0,clearTimeout(Q),Z(V)},Q=setTimeout(()=>Y(!this.alive),Math.max(0,$));this.exitPromise.then(()=>Y(!0))})}handleMessage($){let Z=$;if(typeof Z.session_id==="string"&&Z.session_id)this.sessionId=Z.session_id;switch(Z.type){case"system":this.handleSystemMessage(Z);return;case"assistant":this.handleAssistantMessage(Z);return;case"user":this.handleUserMessage(Z);return;case"result":this.handleResultMessage(Z);return;case"rate_limit_event":this.emit("rate_limits_updated",Z.rate_limit_info);return;case"stream_event":return;default:K(`claude-agent-process: unhandled message type=${Z.type??"unknown"} subtype=${Z.subtype??""}`)}}handleSystemMessage($){switch($.subtype){case"init":if(typeof $.model==="string"&&$.model)this.lastModel=e$($.model);this.lastEffort=this.opts.effort,this.emit("init",{session_id:this.sessionId,raw:$});return;case"session_state_changed":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});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":K(`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){K("claude-agent-process: invalid thinking_tokens estimate");return}this.lastThinkingTokens=$.estimated_tokens,this.emit("thinking_progress",{estimatedTokens:$.estimated_tokens});return;case"permission_denied":K(`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});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});return;case"task_updated":this.emit("bg_task_updated",{task_id:String($.task_id??""),patch:$.patch&&typeof $.patch==="object"?$.patch:{}});return;case"task_notification":if(typeof $.task_id!=="string"||!$.task_id){K("claude-agent-process: task_notification missing task_id");return}if($.status!=="completed"&&$.status!=="failed"&&$.status!=="stopped"){K(`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});return;default:K(`claude-agent-process: unhandled system subtype=${String($.subtype??"unknown")}`);return}}handleAssistantMessage($){if(!$.parent_tool_use_id)this.lastThinkingTokens=null;let Z=$.message,J=typeof $.parent_tool_use_id==="string"&&$.parent_tool_use_id?$.parent_tool_use_id:null;if(!J&&typeof $.uuid==="string")this.lastAssistantUuid=$.uuid;if(typeof Z?.model==="string"&&Z.model)this.lastModel=e$(Z.model);let Y=Array.isArray(Z?.content)?Z.content:[];for(let Q of Y){if(!Q||typeof Q!=="object")continue;if(Q.type==="text"&&typeof Q.text==="string"&&Q.text.length>0){let V=xj(Q.text);if(V){if(this.pendingServerToolInputs.push(V),this.pendingServerToolInputs.length>20)this.pendingServerToolInputs.shift()}if(Sj(Q.text))continue;let H=$.uuid??Z?.id;this.emit("assistant_text",{uuid:H,text:Q.text,parentToolUseId:J}),this.emit("assistant_block_stop",{index:H,parentToolUseId:J})}else if(Q.type==="tool_use"&&typeof Q.id==="string"&&typeof Q.name==="string")this.emitToolUseOnce(Q.id,Q.name,Q.input??{},J);else if(Q.type==="server_tool_use"&&typeof Q.id==="string"&&typeof Q.name==="string")this.emitToolUseOnce(Q.id,Ej(Q.name),{tool:Q.name,input:this.serverToolInput(Q.name,Q.input??{})},J);else if(Q.type==="tool_result"&&typeof Q.tool_use_id==="string")this.emitToolResultOnce(Q.tool_use_id,Tj(Q.content),Q.is_error===!0,J)}}emitToolUseOnce($,Z,J,Y){if(this.emittedToolUseIds.has($))return;if(this.emittedToolUseIds.add($),!Z.trim())K(`claude-agent-process: tool_use ${$} has an empty name`),Z="MISS";this.emit("tool_use",{id:$,name:Z,input:J,parentToolUseId:Y})}serverToolInput($,Z){let J=Z;if(J&&typeof J==="object"&&!Array.isArray(J)&&Object.keys(J).length>0)return J;let Y=this.pendingServerToolInputs.findIndex((Q)=>Q.name===$);if(Y>=0){let[Q]=this.pendingServerToolInputs.splice(Y,1);return Q.input}return J}emitToolResultOnce($,Z,J,Y){if(this.emittedToolResultIds.has($))return;this.emittedToolResultIds.add($),this.emit("tool_result",{tool_use_id:$,content:Z,is_error:J,parentToolUseId:Y})}handleUserMessage($){let Z=$.message?.content;if($.isMeta===!0&&$.promptSource==="sdk"&&typeof Z==="string"&&Z.trim())this.emit("scheduled_turn_input",{text:Z,promptId:typeof $.promptId==="string"&&$.promptId?$.promptId:null});let J=Array.isArray(Z)?Z:[];for(let Y of J){if(!Y||typeof Y!=="object")continue;if(Y.type!=="tool_result"||typeof Y.tool_use_id!=="string")continue;let Q=$.tool_use_result,V=vQ(Y.content),H=Q&&typeof Q==="object"?[typeof Q.stdout==="string"?Q.stdout:"",typeof Q.stderr==="string"?Q.stderr:""].filter(Boolean).join(`
|
|
105
|
-
`):"",X=V||H;this.emitToolResultOnce(Y.tool_use_id,X,Y.is_error===!0||Q?.interrupted===!0,$.parent_tool_use_id??null)}}handleResultMessage($){if(typeof $.session_id==="string"&&$.session_id)this.sessionId=$.session_id;this.turnActive=!1;let Z=
|
|
106
|
-
`):String($.result??$.error??$.api_error_message??H)}:{},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})}failTurnStart($){this.turnActive=!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})}}});var lQ={};E$(lQ,{waitForTokenSourceModelRefresh:()=>A2,tokenSourceRuntimeModels:()=>F2,tokenSourceRuntimeModel:()=>L$,tokenSourceProcessRevision:()=>D2,tokenSourceFactories:()=>M2,setDefaultTokenSource:()=>N3,scrubDshEnv:()=>S4,scrubAnthropicEnv:()=>j$,resetTokenSourceRegistry:()=>T3,registerTokenSourceFactory:()=>S0,registerTokenSource:()=>R3,refreshAllTokenSourceModels:()=>C4,pendingTokenSourceModelRefresh:()=>U2,listTokenSourcesByAgent:()=>uQ,listTokenSources:()=>y$,listEnabledTokenSourcesByAgent:()=>F8,getTokenSourceForAccount:()=>H0,getTokenSource:()=>q$});function j$($){let Z={...$};for(let J of wj)delete Z[J];return Z}function S4($){let Z=j$($);for(let J of Object.keys(Z))if(/^(DSH_|DEEPSEEK_|LODESTAR_DSH_|ZAI_|ZHIPU_)/.test(J))delete Z[J];return Z}function F2($){return $.modelSelection?[...$.models,...$.modelSelection.availableModels.filter((Z)=>!$.models.some((J)=>J.model===Z.model))]:$.models}function L$($,Z){let J=(Y)=>$.agent==="claude"?Y?.replace(/\[1m\]$/,""):Y;return F2($).find((Y)=>J(Y.model)===J(Z))}function D2($,Z){let J=$?.spawnRevision??null,Y=$?.modelEnvironmentRevision?.(Z??$.defaultModel);return Y===void 0?J:JSON.stringify([J,Y])}function S0($){pQ.set($.kind,$)}function M2(){return[...pQ.values()]}function R3($,Z){if(b4.set($.id,$),Z?.default||P8===null)P8=$.id}function q$($){return $?b4.get($):void 0}function H0($,Z="default"){let J=q$($);return J?.forAccount?J.forAccount(Z):J}function y$(){return[...b4.values()]}function uQ($){return y$().filter((Z)=>Z.agent===$)}function F8($){return uQ($).filter((Z)=>Z.enabled)}function N3($){if(b4.has($))P8=$}function T3(){b4.clear(),P8=null,cQ++}function C4(){let $=cQ;if(P2?.generation===$)return P2.promise;let Z=Promise.allSettled(y$().map(async(J)=>{await J.refreshModels(),K(`token-source ${J.id}: ${J.models.length} models loaded`)})).then(()=>{}).finally(()=>{if(P2?.promise===Z)P2=null});return P2={generation:$,promise:Z},Z}function U2(){return P2?.promise??null}async function A2(){let $;while($=U2())await $}var wj,pQ,b4,P8=null,cQ=0,P2=null;var V0=R(()=>{I();wj=["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"];pQ=new Map;b4=new Map});import{spawn as vj}from"cross-spawn";import{EventEmitter as fj}from"node:events";import{StringDecoder as hj}from"node:string_decoder";import{createHash as Ij}from"node:crypto";function x3($,Z){if(w4.set($,Z),Z.state==="ok")M8.set($,Z);else if(Z.state==="no_credentials"||Z.state==="auth_failed")M8.delete($)}function iQ($,Z,J=(Y)=>new T1({accountId:Y})){if(!$||!Z.trim())return Promise.reject(Error("重置卡请求缺少账号或幂等标识"));let Y=D8.get($);if(Y)return Y.key===Z?Y.promise:Promise.reject(Error("该账号正在使用重置卡,请等待结果后再操作"));let Q=Promise.resolve().then(async()=>{let V=J($),H,X;try{await V.initialize("lodestar-codex-reset");let z=(await V.request("account/read",{}))?.account;if(!z||z.type!=="chatgpt")throw Error("该账号未登录 ChatGPT 订阅,不能使用重置卡");O2($);let W;try{W=await A8(()=>V.request("account/rateLimitResetCredit/consume",{idempotencyKey:Z}),"重置卡请求")}catch(_){throw Error(`重置卡请求未确认结果:${_ instanceof Error?_.message:String(_)};请用 codex-accounts 核对额度与重置卡次数`,{cause:_})}finally{O2($)}if(!["reset","alreadyRedeemed","nothingToReset","noCredit"].includes(W?.outcome))throw Error(`Codex 重置卡返回未知结果:${JSON.stringify(W)};请用 codex-accounts 核对后再操作`);let G=P$.get($),B;try{B=S3(await A8(()=>V.request("account/rateLimits/read",{})),z.planType)}catch(_){B={state:"network",reason:_ instanceof Error?_.message:String(_)}}if(P$.get($)!==G)B={state:"auth_failed"};else x3($,B);if(B.state!=="ok")K(`codex-reset: ${$} quota refresh failed: ${B.state==="network"?B.reason:B.state}`);H={outcome:W.outcome,usage:B}}catch(z){X=z,K(`codex-reset: ${$}: ${z}`)}try{await V.close()}catch(z){let W=`控制连接关闭失败:${z instanceof Error?z.message:String(z)}`;if(K(`codex-reset: ${$}: ${W}`),H)H.cleanupError=W;else throw AggregateError([X,z],`${String(X)};${W}`)}if(!H)throw X;return H}).finally(()=>{if(D8.get($)?.promise===Q)D8.delete($)});return D8.set($,{key:Z,promise:Q}),Q}function nQ($,Z){return new Promise((J,Y)=>{let Q=setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Q),J(V)},(V)=>{clearTimeout(Q),Y(V)})})}function gj($){return typeof $==="number"&&isFinite($)?Math.max(0,Math.min(100,$)):null}function U8($){if(!$)return null;return{percent:gj($.usedPercent),resetsAt:typeof $.resetsAt==="number"?new Date($.resetsAt*1000):null,durationMins:typeof $.windowDurationMins==="number"?$.windowDurationMins:null}}function mj($){let Z=U8($?.primary),J=U8($?.secondary),Y=(V)=>V?.durationMins!=null&&V.durationMins>0&&V.durationMins<=720,Q=(V)=>V?.durationMins!=null&&V.durationMins>720;if(Y(Z)&&Q(J))return{fiveHour:Z,weekly:J};if(Y(J)&&Q(Z))return{fiveHour:J,weekly:Z};if(Q(Z)&&!J)return{fiveHour:null,weekly:Z};if(Q(J)&&!Z)return{fiveHour:null,weekly:J};return{fiveHour:Z,weekly:J}}function pj($){let Z=$?.rateLimitsByLimitId,J=Z&&typeof Z==="object"?Object.entries(Z):$?.rateLimits?[[$.rateLimits.limitId??"codex",$.rateLimits]]:[],Y=[];for(let[Q,V]of J){let{fiveHour:H,weekly:X}=mj(V);if(!H&&!X)continue;Y.push({limitId:Q,limitName:V?.limitName??null,fiveHour:H,weekly:X,normalModelSlug:V?.normalModelSlug??null,rateLimitReachedType:V?.rateLimitReachedType??null,spendControlReached:V?.spendControlReached??null})}return{buckets:Y,defaultLimitId:$?.rateLimits?.limitId??void 0}}function cj($){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 aQ($,Z=u){let J=cj($),Y=w4.get(Z),Q=Y?.state==="ok"?Y.buckets??[]:[],V=Q.filter((H)=>dQ(H.fiveHour,U8($?.primary))&&dQ(H.weekly,U8($?.secondary)));if(Q.length>0&&V.length===0)K(`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)K(`usage: rate-limit notification labeled limitId=${$.limitId} but content matches bucket ${V[0].limitId} (known codex parser fallback relabels; ignoring notification payload)`)}function dQ($,Z){if(!$||!Z)return!$&&!Z;return $.percent===Z.percent&&$.durationMins===Z.durationMins&&$.resetsAt?.getTime()===Z.resetsAt?.getTime()}async function uj($){let Z=new T1({accountId:$});try{await Z.initialize("lodestar-usage");let Y=(await nQ(Z.request("account/read",{}),E3))?.account;if(!Y)return{state:"no_credentials"};if(Y.type!=="chatgpt")return{state:"auth_failed"};let Q=await A8(()=>Z.request("account/rateLimits/read",{}));return S3(Q,Y.planType)}catch(J){return K(`usage: codex app-server usage failed: ${J?.message??J}`),{state:"network",reason:J?.message??String(J)}}finally{await Z.close()}}function S3($,Z){let{buckets:J,defaultLimitId:Y}=pj($),Q=J.find((H)=>H.limitId===Y)??J[0];if(!Q)return{state:"network",reason:"empty rate limit response"};let V=Z??$?.rateLimits?.planType??void 0;return Q.fiveHour=d7(V,Q.fiveHour),{state:"ok",subscriptionType:V,...typeof $?.accountId==="string"&&$.accountId?{accountFingerprint:Ij("sha256").update($.accountId).digest("hex")}:{},...typeof $?.ordinaryUsageAllowed==="boolean"?{ordinaryUsageAllowed:$.ordinaryUsageAllowed}:{},rateLimitReachedType:Q.rateLimitReachedType,spendControlReached:Q.spendControlReached,fiveHour:Q.fiveHour,weekly:Q.weekly,buckets:J,defaultLimitId:Q.limitId,resetCredits:Number.isInteger($?.rateLimitResetCredits?.availableCount)&&$.rateLimitResetCredits.availableCount>=0?$.rateLimitResetCredits.availableCount:null,fetchedAt:Date.now()}}function oQ($=u){return w4.get($)??null}function rQ($=u){return M8.get($)??null}function E1($=u){let Z=k4.get($);if(Z)return Z;let J=P$.get($)??0,Y=Promise.resolve().then(()=>uj($)).catch((Q)=>{return K(`usage: ${$} fetch failed: ${Q}`),{state:"network",reason:String(Q)}}).then((Q)=>{if((P$.get($)??0)!==J)return{state:"auth_failed"};return x3($,Q),Q}).finally(()=>{if(k4.get($)===Y)k4.delete($)});return k4.set($,Y),Y}function O8($,Z=u){let J=y4.get(Z);if(J)return J;let Y=P$.get(Z)??0,Q=A8(()=>$("account/rateLimits/read",{})).then((V)=>{if((P$.get(Z)??0)!==Y)return null;let H=S3(V);if((P$.get(Z)??0)===Y)x3(Z,H);if(H.state!=="ok")K(`usage: refresh from connection: ${H.state==="network"?H.reason:H.state}`);return H}).catch((V)=>{if(K(`usage: refresh from connection failed: ${V?.message??V}`),(P$.get(Z)??0)===Y)w4.delete(Z);return null}).finally(()=>{if(y4.get(Z)===Q)y4.delete(Z)});return y4.set(Z,Q),Q}function O2($){P$.set($,(P$.get($)??0)+1),w4.delete($),M8.delete($),k4.delete($),y4.delete($)}async function A8($,Z="额度查询"){let J=[1000,4000];for(let Y=0;;Y++)try{return await nQ($(),E3)}catch(Q){let V=Q instanceof Error?Q.message:String(Q);if(!/error sending request|timed? ?out|timeout|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:429|502|503|504)\b/i.test(V))throw Q;if(Y>=J.length)throw Error(`Codex ${Z}失败(已尝试 ${Y+1} 次):${V}`,{cause:Q});K(`usage: ${Z} retry ${Y+1}/${J.length} in ${J[Y]}ms: ${V}`),await new Promise((X)=>setTimeout(X,J[Y]))}}var E3=1e4,w4,M8,k4,D8,T1,y4,P$;var w$=R(()=>{O1();I();y0();p0();w4=new Map,M8=new Map,k4=new Map;D8=new Map;T1=class T1 extends fj{proc;buf="";decoder=new hj("utf8");nextId=1;alive=!0;exitPromise;resolveExit;pending=new Map;constructor($={}){super();let Z=$.accountId??u;this.proc=vj($.bin??A4(),["app-server","--listen","stdio://",...$.args??k.cliArgs(Z)],{stdio:["pipe","pipe","pipe"],shell:!1,cwd:$.cwd,env:$.env??k.env(Z,{...process.env,...f.codex.env},!0,$.login)}),this.exitPromise=new Promise((Y)=>{this.resolveExit=Y}),this.proc.stdout.on("data",(Y)=>this.onStdout(Y)),this.proc.stderr.on("data",(Y)=>{let Q=Y.toString().trim();if(Q)K(`usage[codex stderr]: ${Q}`)});let J=(Y)=>{if(!this.alive)return;this.alive=!1;for(let[Q,V]of this.pending)clearTimeout(V.timer),V.reject(Error(`${Y.message}; pending ${V.method} id=${Q}`));this.pending.clear(),this.resolveExit(),this.emit("exit"),this.emit("closed",Y)};this.proc.on("error",(Y)=>J(Error(`codex app-server spawn failed: ${Y.message}`))),this.proc.stdin.on("error",(Y)=>{K(`usage: codex stdin failed: ${Y.message}`),this.emit("protocolError",Y)}),this.proc.on("close",(Y,Q)=>{J(Error(`codex app-server exited code=${Y} signal=${Q}`))}),o$(this,Z)}onStdout($){this.buf+=this.decoder.write($);let Z;while((Z=this.buf.indexOf(`
|
|
94
|
+
`).replace(/\\\(([\s\S]*?)\\\)/g,(Z,J)=>`\`${J.trim()}\``).replace(/\$([^$\n]+)\$/g,(Z,J)=>/\\|\^|_|=/.test(J)?`\`${J.trim()}\``:Z)}function e7($){return t7($,jQ)}var N;var x0=R(()=>{N={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"}});function G0($,Z="nearest"){if(!Number.isFinite($)||$<0)return"MISS";let[J,Y]=$>=3600?[$/3600,"h"]:$>=60?[$/60,"m"]:[$,"s"];return`${Z==="down"?Math.floor(J*10)/10:Number(J.toFixed(1))}${Y}`}function LQ($){let Z=2166136261;for(let J=0;J<$.length;J++)Z^=$.charCodeAt(J),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}function t_($,Z){let J=$??"";if(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 qQ($){return $==="workflow"||$==="monitor"}function t0($){return $.status==="completed"||$.status==="failed"||$.status==="killed"}function R1($){return $.some((Z)=>!t0(Z))}function J3($,Z,J=Date.now()){let Y=t_(Z.task_type,Z.subagent_type),Q=$.active.some((X)=>X.id===Z.task_id),V=$.pending.some((X)=>X.id===Z.task_id);if(Q||V){let X=(z)=>({...z,type:Y,toolUseId:Z.tool_use_id??z.toolUseId,description:Z.description||z.description,subagentType:Z.subagent_type??z.subagentType,workflowName:Z.workflow_name??z.workflowName,prompt:Z.prompt??z.prompt});return{active:Q?$.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}}let H={id:Z.task_id,toolUseId:Z.tool_use_id,type:Y,description:Z.description,subagentType:Z.subagent_type,workflowName:Z.workflow_name,prompt:Z.prompt,status:"running",startedAt:J,steps:[],...qQ(Y)?{isBackgrounded:!0}:{}};return qQ(Y)?{active:[...$.active,H],pending:$.pending}:{active:$.active,pending:[...$.pending,H]}}function Y3($,Z){let J=$.active.some((V)=>V.id===Z.task_id),Y=$.pending.some((V)=>V.id===Z.task_id);if(!J&&!Y)return $;let Q=(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?Q(V):V):$.active,pending:Y?$.pending.map((V)=>V.id===Z.task_id?Q(V):V):$.pending}}function Q3($,Z){let J=$.pending.findIndex((H)=>H.id===Z.task_id),Y=Z.patch;if(Y.is_backgrounded===!0&&J>=0){let H=$.pending[J],X={...H,isBackgrounded:!0,status:Y.status??H.status,description:Y.description??H.description,error:Y.error??H.error,endTime:Y.end_time??H.endTime};return{active:[...$.active,X],pending:$.pending.filter((z)=>z.id!==Z.task_id)}}let Q=$.active.some((H)=>H.id===Z.task_id),V=J>=0;if(Q||V){let H=(X)=>({...X,status:Y.status??X.status,description:Y.description??X.description,error:Y.error??X.error,isBackgrounded:Y.is_backgrounded??X.isBackgrounded,endTime:Y.end_time??X.endTime});return{active:Q?$.active.map((X)=>X.id===Z.task_id?H(X):X):$.active,pending:V?$.pending.map((X)=>X.id===Z.task_id?H(X):X):$.pending}}return $}function V3($){if($.pending.length===0)return $;return{active:[...$.active,...$.pending.map((Z)=>({...Z,isBackgrounded:!0}))],pending:[]}}function H3($,Z,J=Date.now()){let Y=Z.status==="completed"?"completed":Z.status==="failed"?"failed":"killed";if($.pending.some((Q)=>Q.id===Z.task_id))return{active:$.active,pending:$.pending.filter((Q)=>Q.id!==Z.task_id)};if($.active.some((Q)=>Q.id===Z.task_id))return{active:$.active.map((Q)=>Q.id===Z.task_id?{...Q,status:Y,usage:Z.usage??Q.usage,summary:Z.summary??Q.summary,endTime:Q.endTime??J}:Q),pending:$.pending};return $}function H8($){let Z=0,J=0;for(let Y=$.length-1;Y>=0;Y--)if(Z+=$[Y].brief.length+5,Z>e_){J=Y+1;break}return J===0?$:$.slice(J)}function $j($,Z){let J=(Y)=>typeof Y==="string"?Y:"";switch($){case"Bash":return G2(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 Zj($,Z){let Y=((typeof $==="string"?$:Array.isArray($)?$.map((Q)=>typeof Q?.text==="string"?Q.text:JSON.stringify(Q)).join(`
|
|
95
|
+
`):JSON.stringify($))??"MISS").replace(/\s+/g," ").trim();return Z?`❌ ${Y.slice(0,80)}`:Y.slice(0,80)}function X3($,Z,J,Y,Q){if(!Z)return $;let V=$.active.some((z)=>z.toolUseId===Z),H=$.pending.some((z)=>z.toolUseId===Z);if(!V&&!H)return $;let X=(z)=>z.map((W)=>W.toolUseId===Z?{...W,steps:H8([...W.steps,{toolUseId:J,tool:Y,brief:`${Y} ${$j(Y,Q)}`.trim()}])}:W);return{active:V?X($.active):$.active,pending:H?X($.pending):$.pending}}function z3($,Z,J,Y,Q,V){let H=$.active.some((W)=>W.id===Z),X=$.pending.some((W)=>W.id===Z);if(!H&&!X)return $;let z=(W)=>W.map((G)=>{if(G.id!==Z)return G;if(Q==="started")return{...G,steps:H8([...G.steps,{toolUseId:J,tool:Y,brief:`${Y} ${V}`.trim()}])};let B=!1,_=G.steps.map((j)=>{if(B||j.toolUseId!==J)return j;return B=!0,{...j,brief:V?`${j.brief} ${V}`:j.brief}});if(!B&&V)_.push({toolUseId:J,tool:Y,brief:`${Y} ${V}`.trim()});return{...G,steps:H8(_)}});return{active:H?z($.active):$.active,pending:X?z($.pending):$.pending}}function W3($,Z,J,Y,Q){if(!Z)return $;let V=$.active.some((z)=>z.toolUseId===Z),H=$.pending.some((z)=>z.toolUseId===Z);if(!V&&!H)return $;let X=(z)=>z.map((W)=>{if(W.toolUseId!==Z)return W;let G=!1,B=W.steps.map((_)=>{if(G||_.toolUseId!==J)return _;return G=!0,{..._,brief:`${_.brief} → ${Zj(Y,Q)}`}});return{...W,steps:H8(B)}});return{active:V?X($.active):$.active,pending:H?X($.pending):$.pending}}function FQ($){let Z=Number.isFinite($)?Math.max(0,$):0;for(let V of Qj)if(Z<V.limit)return{label:V.label,nextDelayMs:V.limit-Z};let J=600000,Y=Math.floor((Z-600000)/J),Q=600000+(Y+1)*J;return{label:`${G0((Y+1)*600,"down")}+`,nextDelayMs:Q-Z}}function t$($,Z="bucket"){if(Z==="second"){let J=Number.isFinite($)?Math.max(0,$):0;if(J>=$3){let Y=Math.floor((J-$3)/PQ),Q=$3+(Y+1)*PQ;return{label:`${G0((10+Y*5)*60,"down")}+`,nextDelayMs:Q-J}}return{label:G0(Math.floor(J/1000)),nextDelayMs:DQ}}return FQ($)}function Vj($){return $.subagentType??$.workflowName??Yj[$.type]}function Z3($){if($.usage?.duration_ms)return $.usage.duration_ms;if($.endTime&&$.endTime>$.startedAt)return $.endTime-$.startedAt;return 0}function Hj($,Z,J="bucket"){let Y=(Q)=>t$(Q,J).label;switch($.status){case"running":return`\uD83D\uDFE1 运行中 (${Y(Z-$.startedAt)})`;case"paused":return`⏸️ 已暂停 (${Y(Z-$.startedAt)})`;case"pending":return"⚪ 等待中";case"completed":return`✅ 用时 ${G0(Z3($)/1000)}`;case"failed":return`❌ 失败 ${G0(Z3($)/1000)}`;case"killed":return`\uD83D\uDC80 已终止 ${G0(Z3($)/1000)}`}}function MQ($){let Z=$.filter((Y)=>!t0(Y)).length,J=$.length-Z;if(Z>0)return`${Z} 进行中${J?` · ${J} 已结束`:""}`;return J?`${J} 已结束`:"空"}function X8($){return`\uD83E\uDDED 后台任务 · ${MQ($)}`}function Xj($){let Z=[];if($.error)Z.push(`⚠ ${$.error}`);if(t0($)&&$.summary)Z.push(`\uD83D\uDCDD ${$.summary.slice(0,400)}`,"");for(let J=0;J<$.steps.length;J++)Z.push(`${J+1}. ${$.steps[J].brief}`);return Z0(Z.length>0?Z.join(`
|
|
96
|
+
`):"_(暂无执行记录)_")}function j2($,Z=Date.now(),J="bucket"){return{tag:"collapsible_panel",element_id:R4.panel($.id),header:{title:{tag:"plain_text",content:`${Jj[$.type]} ${Vj($)} · ${$.description||"(无描述)"} — ${Hj($,Z,J)}`}},expanded:!1,elements:[{tag:"markdown",element_id:R4.body($.id),content:Xj($)}]}}function G3($,Z=Date.now(),J="bucket"){return{schema:"2.0",config:{streaming_mode:!0,summary:{content:X8($)}},body:{elements:$.map((Y)=>j2(Y,Z,J))}}}function z8($,Z=Date.now(),J="bucket"){let Y=$.filter(t0);return{schema:"2.0",config:{streaming_mode:!1,summary:{content:`\uD83E\uDDED 后台任务(历史) · ${Y.length} 已结束`}},body:{elements:Y.map((Q)=>j2(Q,Z,J))}}}function K3(){return{schema:"2.0",config:{streaming_mode:!1,summary:{content:"↪ 后台任务进行中"}},body:{elements:[{tag:"markdown",element_id:"bg_marker",content:"↪ 本轮后台任务仍在进行,进度已迁至最新卡片"}]}}}var R4,e_=1000,Jj,Yj,Qj,DQ=1000,$3=600000,PQ=300000;var B3=R(()=>{x0();s9();R4={panel:($)=>`bg_${LQ($)}`,body:($)=>`bgb_${LQ($)}`};Jj={subagent:"\uD83D\uDFE2",shell:"⚙️",monitor:"\uD83D\uDCE1",workflow:"\uD83D\uDD01",unknown:"\uD83D\uDD39"},Yj={subagent:"子agent",shell:"shell",monitor:"监控",workflow:"工作流",unknown:"任务"},Qj=[{limit:30000,label:"<30s"},{limit:60000,label:"<1m"},{limit:180000,label:"<3m"},{limit:300000,label:"<5m"},{limit:600000,label:"<10m"}]});import{EventEmitter as zj}from"node:events";import{join as Wj,isAbsolute as Gj,extname as Kj,basename as Bj}from"node:path";import{readFile as _j}from"node:fs/promises";function jj($){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 W8=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),_3,j3;var UQ=R(()=>{D0();A1();P4();I();_3={bash:"Bash",read:"Read",write:"Write",edit:"Edit",glob:"Glob",grep:"Grep"};j3=class j3 extends zj{opts;provider="dsh";tokenSourceId;launchKind;sessionId=null;lastAssistantUuid=null;lastCompletedTurnId=null;lastModel;lastEffort;lastUsage=null;lastTotalUsage=null;lastResult=W8();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"};_0(Z,"dsh",$.workDir),this.launchKind=Z.kind;let J={...process.env,...$.hostEnv};this.runtime=new i9({cwd:$.workDir,env:$.transformEnv?$.transformEnv(J):J,profile:$.profile,...$.managedSkillPluginPath?{managedSkillDir:Wj($.managedSkillPluginPath,"skills")}:{},...$.runtimeOptions}),this.runtime.on("notification",(Y)=>{if(!this.sessionId&&Y.method!=="failure"){this.earlyNotifications.push(Y);return}if(this.terminalError)return;try{this.onNotification(Y)}catch(Q){this.fail(Q)}}),this.runtime.on("failure",(Y)=>this.fail(Y)),this.runtime.on("exit",(Y)=>this.emit("exit",{...Y,expected:Y.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??"",allowDelegation:this.opts.allowDelegation!==!1,...this.opts.profile?.tools?{allowedTools:this.opts.profile.tools.split(",").map((Z)=>{let J=Z.trim();return Object.keys(_3).find((Y)=>_3[Y]===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)=>!Gj(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(`
|
|
97
|
+
`)}],Y=new Set([...Z,...Array.from($.matchAll(/\[file: ([^\]\r\n]+)\]/g),(V)=>V[1])]),Q=new Set([".png",".jpg",".jpeg",".webp",".gif"]);for(let V of Y){if(!Q.has(Kj(V).toLowerCase()))continue;let H=await _j(V);J.push({type:"image",mediaType:jj(H),name:Bj(V),data:H.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 Y=String($),Q=this.questionInputs.get(Y);if(!Q)throw Error(`unknown DSH question: ${Y}`);let V=J?.updatedInput?.answers,H=Z==="allow"?Q.map((X)=>{let z=V?.[X.question];if(typeof z!=="string")throw Error(`missing answer to DSH question: ${X.question}`);let W=X.options?.find((G)=>G.label===z);return{id:X.id,selected:W?[z]:[],...W?{}:{custom:z}}}):void 0;this.runtime.request("question/answer",{id:Y,answers:H,...Z==="deny"?{error:J?.denyMessage??"User declined the question"}:{}}).then(()=>{this.questionInputs.delete(Y),this.emit("tool_result",{tool_use_id:Y,content:JSON.stringify({answers:H}),is_error:Z==="deny",parentToolUseId:null})}).catch((X)=>this.fail(X))}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(!B0(Z))throw Error(`invalid DSH effort: ${Z}`);if(await this.initializationPromise(),await this.runtime.request("session/model",{model:$,effort:Z}),!this.busy)this.lastModel=$,this.lastEffort=Z}async compactThread(){if(await this.initializationPromise(),await this.runtime.request("session/compact",{},null)===null)throw new U1}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={...W8(),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 Y of this.frames.keys())if(Y.startsWith(`${Z.sessionId}:`))this.frames.delete(Y);return;case"session.status":return;case"question":{this.questionInputs.set(Z.id,Z.questions);let Y={questions:Z.questions.map((Q)=>({...Q,question:Q.detail?`${Q.question}
|
|
98
|
+
|
|
99
|
+
${Q.detail}`:Q.question}))};this.questionInputs.set(Z.id,Y.questions),this.emit("tool_use",{id:Z.id,name:"AskUserQuestion",input:Y,parentToolUseId:null}),this.emit("can_use_tool",{request_id:Z.id,tool_use_id:Z.id,tool_name:"AskUserQuestion",input:Y});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 Y=Z.frame,Q=`${Z.sessionId}:${Y.attemptId}`;if(Y.type==="start"){this.frames.set(Q,{revision:Y.revision,nextIndex:0});return}let V=this.frames.get(Q);if(!V||V.revision+1!==Y.revision||V.nextIndex!==Y.index)throw Error("DSH assistant stream sequence mismatch");if(V.revision=Y.revision,Y.type==="end"){if(this.frames.delete(Q),!J)this.emit("assistant_block_stop",{parentToolUseId:null});return}if(Y.type!=="chunk")throw Error(`unknown DSH assistant frame: ${Y.type}`);V.nextIndex++;let H=Y.chunk;if(H.type==="text-delta"){if(J)this.childText.set(Z.sessionId,(this.childText.get(Z.sessionId)??"")+H.text);this.emit("assistant_text",{text:H.text,parentToolUseId:J?Z.sessionId:null})}else if(H.type==="block-end"&&H.block.type==="text"&&!J)this.emit("assistant_block_stop",{parentToolUseId:null});else if(H.type==="usage"&&!J)this.observeUsage(H.usage);return}case"session.event":{let Y=Z.event,Q=Y.data;if(!Y||!Q||typeof Y.type!=="string")throw Error("invalid DSH session event");if(Y.type==="turn/start"&&!J)this.busy=!0,this.startedAt=Date.now(),this.lastUsage=null,this.lastResult=W8(),this.emit("scheduled_turn_input",{text:"DeepSeek Harness 继续执行",promptId:`dsh-turn-${Q.turn}`}),this.emit("turn_started",{turn_id:String(Q.turn),thread_id:this.sessionId});else if(Y.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(Y.type==="request/header"&&!J&&Q.header?.config)this.lastModel=Q.header.config.model,this.lastEffort=Q.header.config.reasoningEffort,this.lastContextWindow=this.models.find((V)=>V.model===this.lastModel)?.contextWindow??null;else if(Y.type==="tool/call"){let V=JSON.parse(Q.arguments),H=_3[Q.name]??Q.name;if(["read","write","edit"].includes(Q.name)&&V.path)V.file_path=V.path;this.toolInputs.set(Q.callId,{name:H,input:V}),this.emit("tool_use",{id:Q.callId,name:H,input:V,parentToolUseId:J?Z.sessionId:null})}else if(Y.type==="tool/result"){let V=Q.message?.content?.[0];if(V?.type!=="tool-result"||typeof V.toolCallId!=="string")throw Error("invalid DSH tool result");this.emit("tool_result",{tool_use_id:V.toolCallId,content:V.content,is_error:V.isError===!0,parentToolUseId:J?Z.sessionId:null}),this.toolInputs.delete(V.toolCallId)}else if(Y.type==="todo/write"&&!J)this.emit("turn_plan_updated",{threadId:this.sessionId,explanation:null,plan:Q.todos.map((V)=>({step:V.content,status:V.status==="in_progress"?"inProgress":V.status}))});else if(Y.type==="compaction/start"&&!J)this.emit("context_compacted",{threadId:this.sessionId,phase:"start",sourceType:"dsh"});else if(Y.type==="compaction/end"&&!J)if(Q.error)this.emit("error",Error(`DSH compaction: ${Q.error}`));else this.emit("context_compacted",{threadId:this.sessionId,phase:"end",sourceType:"dsh"});else if(Y.type==="goal/change"&&!J)if(Q.operation==="clear")this.emit("thread_goal_cleared",{threadId:this.sessionId});else this.emit("thread_goal_updated",{threadId:this.sessionId,objective:Q.goal.objective,status:Q.goal.phase,tokenBudget:null,tokensUsed:Number.NaN,timeUsedSeconds:Number.NaN});else if(Y.type==="turn/end"&&J&&this.children.has(Z.sessionId))this.settledChildren.add(Z.sessionId),this.emit("bg_task_settled",{task_id:Z.sessionId,status:Q.reason.kind==="completed"?"completed":Q.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 Y=Z.event,Q=Y.data.reason;this.lastCompletedTurnId=String(Y.seq),this.lastResult={...W8(),duration_ms:Date.now()-this.startedAt,num_turns:1,usage:this.lastUsage,subtype:Q.kind,is_error:Q.kind!=="completed"},this.emit("result",{...this.lastResult,...Q.kind!=="completed"?{error:Q.error?.message??`DSH turn ended: ${Q.kind}`,errors:[Q.error?.message??`DSH turn ended: ${Q.kind}`]}:{},checkpoint:{provider:"dsh",kind:"event",id:String(Y.seq),source:{provider:"dsh",sessionId:this.sessionId,cwd:this.opts.workDir}}});return}default:K(`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[Y,Q]of Object.entries(Z))if(Q!==void 0){let V=Y;J[V]=(J[V]??0)+Q}this.lastTotalUsage=J,this.lastContextTokens=$.inputTokens+($.cacheReadTokens??0)+($.cacheWriteTokens??0),this.emit("token_usage",{usage:Z,totalUsage:J,contextWindow:this.lastContextWindow,threadId:this.sessionId})}}});function e$($){return $.startsWith("claude:")?$:`claude:${$}`}function L3($){if(!$||$==="default"||$==="claude:default")return"opus";if(!$.startsWith("claude:"))return $;let Z=$.slice(7);if(Z==="glm"||Object.hasOwn(f.claude.models,Z))return f.claude.models[Z]?.model?.trim()||"opus";return Z}var AQ=R(()=>{y0()});import{existsSync as Lj,readFileSync as qj}from"node:fs";function q3(){return process.env.LODESTAR_DATA_DIR?`${process.env.LODESTAR_DATA_DIR.replace(/\/+$/,"")}/context-window-cache.json`:iJ}function T4(){if(N4!==null)return N4;try{N4=Lj(q3())?JSON.parse(qj(q3(),"utf8")):{}}catch($){K(`context-window-observe: cache read MISS (${$?.message??$}), starting fresh`),N4={}}return N4??{}}function Dj(){try{s(q3(),T4())}catch($){K(`context-window-observe: cache write MISS (${$?.message??$})`)}}function P3($,Z){return`${$}:${Z.replace(/\[1m\]$/,"")}`}function OQ($,Z,J){if(!Number.isFinite(J)||J<=0)return;let Y=P3($,Z),Q=T4()[Y];if(Q===J)return;T4()[Y]=J,Dj(),K(`context-window-observe: ${Y} → ${J} (prev ${Q??"-"})`)}function G8($,Z){if(!Z)return;if(Z.endsWith("[1m]"))return Z;let J=T4()[P3($,Z)];return J!=null&&J<Pj?Z:`${Z}[1m]`}function L2($,Z){return T4()[P3($,Z)]}var Pj=1e6,N4=null;var E4=R(()=>{Q0();I();T0()});var gQ={};E$(gQ,{toolsFromProfile:()=>hQ,settingSourcesFromProfile:()=>fQ,resolveClaudeExecutableConfig:()=>A3,resetClaudeContextWindowCache:()=>Rj,readProjectMcpServers:()=>IQ,readLastCallUsageFromTranscript:()=>yQ,claudeTranscriptPath:()=>j8,claudeTranscriptDir:()=>_8,claudeManagedSkillOptions:()=>CQ,buildClaudeSpawnPath:()=>kQ,assertClaudeCodeAvailable:()=>U3,ClaudeAgentProcess:()=>L8,CLAUDE_PERMISSION_MODE:()=>vQ});import{existsSync as xQ,readFileSync as SQ}from"node:fs";import{homedir as B8}from"node:os";import{spawn as Fj}from"cross-spawn";import{delimiter as RQ,join as N1}from"node:path";import{EventEmitter as Mj}from"node:events";function CQ($,Z){if(!Z||$.includes("user"))return{};return{plugins:[{type:"local",path:Z,skipMcpDiscovery:!0}],skills:"all"}}function Uj($){let Z=$.toLowerCase();return Z.endsWith(".cmd")||Z.endsWith(".bat")}function Aj($){let Z=Fj($.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 U3(){A3(),F7("claude","@anthropic-ai/claude-agent-sdk")}function A3($={}){let Z=$.platform??process.platform,J=$.configuredBin===void 0?f.claude.bin:$.configuredBin;if(J){if(!($.exists??xQ)(J))throw Error(`lodestar: [claude].bin not found: ${J} (config.toml)`);if(Z==="win32"&&Uj(J))return{pathToClaudeCodeExecutable:J,spawnClaudeCodeProcess:Aj,description:`windows-shell-shim:${J}`};return{pathToClaudeCodeExecutable:J,description:`config:${J}`}}return{description:"sdk-default"}}function kQ(){if(process.platform==="win32")return process.env.PATH??"";let $=[N1(B8(),".local","npm-global","bin"),N1(B8(),".local","bin"),N1(B8(),".bun","bin"),...(process.env.PATH??"").split(RQ),"/usr/local/bin","/usr/bin","/bin"];return[...new Set($.filter(Boolean))].join(RQ)}function Oj($){let Z=W2($);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 NQ($){if(!$)return null;let Z=($.input_tokens??0)+($.cache_read_input_tokens??0)+($.cache_creation_input_tokens??0);return Z>0?Z:null}function _8($){let Z=$.replace(/[^a-zA-Z0-9]/g,"-"),J=process.env.CLAUDE_CONFIG_DIR||N1(B8(),".claude");return N1(J,"projects",Z)}function j8($,Z){return N1(_8($),`${Z}.jsonl`)}function yQ($){let Z;try{Z=SQ($,"utf8")}catch{return null}let J=Z.split(`
|
|
100
|
+
`);for(let Y=J.length-1;Y>=0;Y--){let Q=J[Y].trim();if(!Q)continue;try{let V=JSON.parse(Q);if(V?.type==="assistant"&&V?.message?.usage){let H=V.message.usage;if((H.input_tokens??0)+(H.cache_read_input_tokens??0)+(H.cache_creation_input_tokens??0)+(H.output_tokens??0)>0)return H}}catch{}}return null}function TQ($,Z){let J=Z?.trim()||"no-source",Y=$&&$.trim()?$:"claude:default";return`${J}:${Y}`}function Rj(){F3.clear()}function Nj($){if(!$||typeof $!=="object")return{usage:null,contextWindow:null};let Z={},J=null;for(let Q of Object.values($)){if(!Q||typeof Q!=="object")continue;let V=Q;Z.input_tokens=(Z.input_tokens??0)+q2(V.inputTokens??V.input_tokens),Z.output_tokens=(Z.output_tokens??0)+q2(V.outputTokens??V.output_tokens),Z.reasoning_output_tokens=(Z.reasoning_output_tokens??0)+q2(V.reasoningOutputTokens??V.reasoning_output_tokens),Z.cache_read_input_tokens=(Z.cache_read_input_tokens??0)+q2(V.cacheReadInputTokens??V.cache_read_input_tokens),Z.cache_creation_input_tokens=(Z.cache_creation_input_tokens??0)+q2(V.cacheCreationInputTokens??V.cache_creation_input_tokens);let H=q2(V.contextWindow??V.context_window);if(H>0)J=Math.max(J??0,H)}let Y=(Z.input_tokens??0)+(Z.output_tokens??0)+(Z.cache_creation_input_tokens??0)+(Z.cache_read_input_tokens??0);if(Y<=0)return{usage:null,contextWindow:J};return Z.total_tokens=Y,{usage:Z,contextWindow:J}}function K8($){return{...$}}function D3($){if(!$||typeof $!=="object")return[];return Object.keys($).slice(0,20)}function Tj($,Z){let J=$?{...$}:{},Y=(Q)=>{let V=Z[Q];if(typeof V!=="number"||!Number.isFinite(V))return;J[Q]=(J[Q]??0)+V};return Y("total_tokens"),Y("input_tokens"),Y("output_tokens"),Y("reasoning_output_tokens"),Y("cache_creation_input_tokens"),Y("cache_read_input_tokens"),J}function q2($){return typeof $==="number"&&Number.isFinite($)?$:0}function wQ($){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(`
|
|
101
|
+
`);return $==null?"":JSON.stringify($,null,2)}function Ej($){let Z=wQ($);try{let J=JSON.parse(Z);if(Array.isArray(J)){let Y=J.map((Q)=>{if(typeof Q==="string")return Q;if(Q&&typeof Q==="object"&&typeof Q.text==="string")return Q.text;return JSON.stringify(Q)}).filter(Boolean);if(Y.length>0)return Y.join(`
|
|
102
|
+
`)}}catch{}return Z}function xj($){return`server_tool:${$}`}function Sj($){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 bj($){let Z=$.trim();return Z.includes("Built-in Tool:")||Z.startsWith("**Output:**")&&Z.includes("_result")}function Cj($){let Z=$.supportedEffortLevels&&$.supportedEffortLevels.length>0?$.supportedEffortLevels:[a$];return{id:e$($.value),model:e$($.value),displayName:$.displayName||e$($.value),description:$.description||"Claude Agent SDK backend",hidden:!1,isDefault:!1,supportedReasoningEfforts:Z.map((J)=>({reasoningEffort:J,description:""})),defaultReasoningEffort:Z.includes(a$)?a$:Z[0]}}function fQ($){if(!$?.settingSources)return[...EQ];let Z=$.settingSources.split(",").map((J)=>J.trim()).filter(Boolean);return Z.length?Z:[...EQ]}function hQ($){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 IQ($){let Z=N1($,".mcp.json"),J;try{J=SQ(Z,"utf8")}catch(Y){if(Y.code!=="ENOENT")K(`claude-agent-process: project .mcp.json not readable at ${Z}: ${Y}`);return}try{let Y=JSON.parse(J);if(Y&&typeof Y==="object"&&Y.mcpServers&&typeof Y.mcpServers==="object")return Y.mcpServers;K(`claude-agent-process: project .mcp.json has no mcpServers object at ${Z}`);return}catch(Y){K(`claude-agent-process: project .mcp.json parse failed at ${Z}: ${Y}`);return}}function kj($){let Z=$.questions;return(Array.isArray(Z)?Z:Z&&typeof Z==="object"?[Z]:[$]).map((Y)=>yj(Y)).filter((Y)=>Y!==null)}function yj($){let Z=$&&typeof $==="object"?$:{question:$},J=M3(Z.question,Z.prompt,Z.title,Z.message,Z.text,Z.label);if(!J)return null;if(!J.trim())return null;let Y=wj(Z.options??Z.choices??Z.suggestions);return{...Z,question:J,options:Y,...typeof Z.header==="string"?{header:Z.header}:{},...typeof Z.multiSelect==="boolean"?{multiSelect:Z.multiSelect}:{}}}function wj($){if(!Array.isArray($))return[];let Z=[];for(let J of $){if(typeof J==="string"){Z.push({label:J});continue}if(!J||typeof J!=="object")continue;let Y=J,Q=M3(Y.label,Y.value,Y.text,Y.title);if(!Q?.trim())continue;let V=M3(Y.description,Y.detail,Y.preview);Z.push(V?{label:Q,description:V}:{label:Q})}return Z}function M3(...$){for(let Z of $)if(typeof Z==="string")return Z;return}var bQ,F3,vQ="default",EQ,L8;var x4=R(()=>{V2();y0();I();D0();AQ();E4();bQ=class bQ{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.items=[],this.close()}[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($))}};F3=new Map;EQ=["project","local"];L8=class L8 extends Mj{provider="claude";tokenSourceId;opts;input=new bQ;query=null;abortController=new AbortController;alive=!0;expectedExit=!1;exitPromise;resolveExit;started=!1;queryStart;pendingPermissions=new Map;requestCounter=0;cumulativeUsageFromResults=null;turnActive=!1;emittedToolUseIds=new Set;emittedToolResultIds=new Set;pendingServerToolInputs=[];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.tokenSourceId=$.tokenSourceId??null,this.lastEffort=$.effort,this.lastModel=$.model?e$($.model):null}sendInitialize(){if(this.started)return;this.started=!0,this.queryStart=this.initializeQuery().catch(($)=>{this.emit("error",$ instanceof Error?$:Error(String($))),this.finishExit(1,null)})}async initializeQuery(){let $=L3(this.opts.model),Z=this.opts.profile;if(Z)K(`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??fQ(Z),Y=CQ(J,this.opts.managedSkillPluginPath),Q=hQ(Z),V=Z?.strictMcp===!0,H=Z?.loadProjectMcp!==!1?IQ(this.opts.workDir):void 0;try{let X=A3(),{query:z}=await FY();if(!this.alive||this.abortController.signal.aborted)return;let W={...process.env,PATH:kQ(),...f.claude.env,...this.opts.hostEnv??{}},G=this.opts.transformEnv?this.opts.transformEnv(W):W;if(this.opts.effort==="default")G.CLAUDE_CODE_EFFORT_LEVEL="unset";K(`claude-agent-process: spawn SDK query model=${$??"default"} effort=${this.opts.effort} cwd=${this.opts.workDir} executable=${X.description}`),this.query=z({prompt: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}:{},...X.pathToClaudeCodeExecutable?{pathToClaudeCodeExecutable:X.pathToClaudeCodeExecutable}:{},...X.spawnClaudeCodeProcess?{spawnClaudeCodeProcess:X.spawnClaudeCodeProcess}:{},permissionMode:vQ,env:G,settingSources:[...J],...Y,tools:Q,...this.opts.allowDelegation===!1?{disallowedTools:["Agent","Task"]}:{},...V?{strictMcpConfig:!0}:{},...H?{mcpServers:H}:{},toolConfig:{askUserQuestion:{previewFormat:"markdown"}},canUseTool:(B,_,j)=>this.canUseTool(B,_,j),includePartialMessages:!1,systemPrompt:{type:"preset",preset:"claude_code",...this.opts.appendSystemPrompt?{append:this.opts.appendSystemPrompt}:{}},stderr:(B)=>{let _=B.trim();if(_)K(`claude-agent-process[stderr]: ${_}`)}}})}catch(X){let z=X instanceof Error?X:Error(String(X));this.emit("error",z),this.finishExit(1,null);return}this.readLoop(this.query)}sendUserText($,Z=[]){if(!this.alive){K("claude-agent-process: sendUserText ignored on dead process");return}if(!this.started)this.sendInitialize();let J=Z.length?Z.map((Y)=>`[file: ${Y}]`).join(" ")+`
|
|
103
|
+
|
|
104
|
+
`:"";try{this.input.push({type:"user",session_id:this.sessionId??"",message:{role:"user",content:[{type:"text",text:J+$}]},parent_tool_use_id:null,priority:"now"})}catch(Y){let Q=Y instanceof Error?Y:Error(String(Y));K(`claude-agent-process: sendUserText failed: ${Q.message}`),this.failTurnStart(Q)}}sendInterrupt(){this.query?.interrupt().catch(($)=>K(`claude-agent-process: interrupt failed: ${$}`))}sendPermissionResponse($,Z,J){let Y=this.pendingPermissions.get(String($));if(!Y){K(`claude-agent-process: permission response for unknown request ${$}`);return}if(this.pendingPermissions.delete(String($)),Y.cleanup?.(),Z==="allow")Y.resolve({behavior:"allow",updatedInput:J?.updatedInput??{}});else Y.resolve({behavior:"deny",message:J?.denyMessage??""})}sendHookResponse($,Z={}){K("claude-agent-process: sendHookResponse ignored; hooks are handled by SDK callbacks")}isAlive(){return this.alive}async kill($=5000){if(!this.alive)return;if(this.expectedExit=!0,this.denyPendingPermissions("claude process is stopping"),this.input.abort(),!this.started||!this.query){this.finishExit(null,null);return}let Z=null;try{this.query.close()}catch(J){Z=J instanceof Error?J:Error(String(J))}if(!this.abortController.signal.aborted)this.abortController.abort(Z??Error("claude process shutdown requested"));if(!await this.waitForExit($)){let J=Error(`claude Agent SDK query did not exit within ${$}ms after close/abort`,Z?{cause:Z}:void 0);throw K(`claude-agent-process: kill failed: ${J.message}`),J}if(Z){let J=Error(`claude Agent SDK close failed: ${Z.message}`,{cause:Z});throw K(`claude-agent-process: kill failed: ${J.message}`),J}}async listModels(){if(!this.started)this.sendInitialize();if(await this.queryStart,!this.query)throw Error("claude-agent-process: SDK query not initialized (sendInitialize failed or not called)");return(await this.query.supportedModels()).map(Cj)}async setModelSettings($,Z){let J=L3($);if(!E0(Z))throw Error(`invalid Claude effort: ${String(Z)}`);if(this.opts.effort==="default"!==(Z==="default"))throw Error("effort 参数模式改变,需要使用新的启动环境恢复会话");if(!this.started)this.sendInitialize();if(await this.queryStart,!this.query)throw Error("claude-agent-process: SDK query not initialized (sendInitialize failed or not called)");if(J)await this.query.setModel(J);await this.query.applyFlagSettings({effortLevel:Z==="default"?null:Z,ultracode:null}),this.opts.model=$,this.opts.effort=Z,this.lastModel=J?e$($):"claude:default",this.lastEffort=Z}async compactThread(){if(!this.input)throw Error("claude thread not initialized");return this.input.push({type:"user",session_id:this.sessionId??"",message:{role:"user",content:[{type:"text",text:"/compact"}]},parent_tool_use_id:null,priority:"now"}),new Promise(($,Z)=>{let J=!1,Y=()=>{this.off("context_compacted",Q),this.off("assistant_text",V),this.off("exit",H),this.off("error",X)},Q=()=>{if(J)return;J=!0,Y(),$()},V=(z)=>{if(J)return;if((z?.text??"").includes("Not enough messages to compact"))J=!0,Y(),Z(new U1)},H=()=>{if(J)return;J=!0,Y(),Z(Error("claude thread exited during /compact"))},X=(z)=>{if(J)return;J=!0,Y(),Z(z instanceof Error?z:Error(String(z)))};this.on("context_compacted",Q),this.on("assistant_text",V),this.once("exit",H),this.once("error",X)})}canUseTool($,Z,J){if($!=="AskUserQuestion")return Promise.resolve({behavior:"allow",updatedInput:Z});let Y=kj(Z);if(Y.length===0)return K("claude-agent-process: AskUserQuestion 无有效 questions — allow 原样"),Promise.resolve({behavior:"allow",updatedInput:Z});let Q={...Z,questions:Y},V=`claude_perm_${++this.requestCounter}`,H=J.toolUseID||V,X={request_id:V,tool_name:"AskUserQuestion",input:Q,tool_use_id:H},z=new Promise((W)=>{let G=(_)=>{J.signal.removeEventListener("abort",B),W(_)},B=()=>{if(!this.pendingPermissions.delete(V))return;G({behavior:"deny",message:"aborted"})};J.signal.addEventListener("abort",B,{once:!0}),this.pendingPermissions.set(V,{kind:"dialog",resolve:G,request:X})});return this.emitToolUseOnce(H,"AskUserQuestion",Q,null),this.emit("can_use_tool",X),z}async readLoop($){try{for await(let Z of $)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){K(`claude-agent-process: read loop stopped after requested shutdown: ${J.message}`),this.finishExit(null,null);return}K(`claude-agent-process: read loop failed: ${J.message}`),this.emit("error",J),this.finishExit(1,null)}}finishExit($,Z){if(!this.alive)return;this.alive=!1,this.turnActive=!1,this.denyPendingPermissions("claude process exited"),this.resolveExit(),K(`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,Y=(V)=>{if(J)return;J=!0,clearTimeout(Q),Z(V)},Q=setTimeout(()=>Y(!this.alive),Math.max(0,$));this.exitPromise.then(()=>Y(!0))})}handleMessage($){let Z=$;if(typeof Z.session_id==="string"&&Z.session_id)this.sessionId=Z.session_id;switch(Z.type){case"system":this.handleSystemMessage(Z);return;case"assistant":this.handleAssistantMessage(Z);return;case"user":this.handleUserMessage(Z);return;case"result":this.handleResultMessage(Z);return;case"rate_limit_event":this.emit("rate_limits_updated",Z.rate_limit_info);return;case"stream_event":return;default:K(`claude-agent-process: unhandled message type=${Z.type??"unknown"} subtype=${Z.subtype??""}`)}}handleSystemMessage($){switch($.subtype){case"init":if(typeof $.model==="string"&&$.model)this.lastModel=e$($.model);this.lastEffort=this.opts.effort,this.emit("init",{session_id:this.sessionId,raw:$});return;case"session_state_changed":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});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":K(`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){K("claude-agent-process: invalid thinking_tokens estimate");return}this.lastThinkingTokens=$.estimated_tokens,this.emit("thinking_progress",{estimatedTokens:$.estimated_tokens});return;case"permission_denied":K(`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});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});return;case"task_updated":this.emit("bg_task_updated",{task_id:String($.task_id??""),patch:$.patch&&typeof $.patch==="object"?$.patch:{}});return;case"task_notification":if(typeof $.task_id!=="string"||!$.task_id){K("claude-agent-process: task_notification missing task_id");return}if($.status!=="completed"&&$.status!=="failed"&&$.status!=="stopped"){K(`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});return;default:K(`claude-agent-process: unhandled system subtype=${String($.subtype??"unknown")}`);return}}handleAssistantMessage($){if(!$.parent_tool_use_id)this.lastThinkingTokens=null;let Z=$.message,J=typeof $.parent_tool_use_id==="string"&&$.parent_tool_use_id?$.parent_tool_use_id:null;if(!J&&typeof $.uuid==="string")this.lastAssistantUuid=$.uuid;if(typeof Z?.model==="string"&&Z.model)this.lastModel=e$(Z.model);let Y=Array.isArray(Z?.content)?Z.content:[];for(let Q of Y){if(!Q||typeof Q!=="object")continue;if(Q.type==="text"&&typeof Q.text==="string"&&Q.text.length>0){let V=Sj(Q.text);if(V){if(this.pendingServerToolInputs.push(V),this.pendingServerToolInputs.length>20)this.pendingServerToolInputs.shift()}if(bj(Q.text))continue;let H=$.uuid??Z?.id;this.emit("assistant_text",{uuid:H,text:Q.text,parentToolUseId:J}),this.emit("assistant_block_stop",{index:H,parentToolUseId:J})}else if(Q.type==="tool_use"&&typeof Q.id==="string"&&typeof Q.name==="string")this.emitToolUseOnce(Q.id,Q.name,Q.input??{},J);else if(Q.type==="server_tool_use"&&typeof Q.id==="string"&&typeof Q.name==="string")this.emitToolUseOnce(Q.id,xj(Q.name),{tool:Q.name,input:this.serverToolInput(Q.name,Q.input??{})},J);else if(Q.type==="tool_result"&&typeof Q.tool_use_id==="string")this.emitToolResultOnce(Q.tool_use_id,Ej(Q.content),Q.is_error===!0,J)}}emitToolUseOnce($,Z,J,Y){if(this.emittedToolUseIds.has($))return;if(this.emittedToolUseIds.add($),!Z.trim())K(`claude-agent-process: tool_use ${$} has an empty name`),Z="MISS";this.emit("tool_use",{id:$,name:Z,input:J,parentToolUseId:Y})}serverToolInput($,Z){let J=Z;if(J&&typeof J==="object"&&!Array.isArray(J)&&Object.keys(J).length>0)return J;let Y=this.pendingServerToolInputs.findIndex((Q)=>Q.name===$);if(Y>=0){let[Q]=this.pendingServerToolInputs.splice(Y,1);return Q.input}return J}emitToolResultOnce($,Z,J,Y){if(this.emittedToolResultIds.has($))return;this.emittedToolResultIds.add($),this.emit("tool_result",{tool_use_id:$,content:Z,is_error:J,parentToolUseId:Y})}handleUserMessage($){let Z=$.message?.content;if($.isMeta===!0&&$.promptSource==="sdk"&&typeof Z==="string"&&Z.trim())this.emit("scheduled_turn_input",{text:Z,promptId:typeof $.promptId==="string"&&$.promptId?$.promptId:null});let J=Array.isArray(Z)?Z:[];for(let Y of J){if(!Y||typeof Y!=="object")continue;if(Y.type!=="tool_result"||typeof Y.tool_use_id!=="string")continue;let Q=$.tool_use_result,V=wQ(Y.content),H=Q&&typeof Q==="object"?[typeof Q.stdout==="string"?Q.stdout:"",typeof Q.stderr==="string"?Q.stderr:""].filter(Boolean).join(`
|
|
105
|
+
`):"",X=V||H;this.emitToolResultOnce(Y.tool_use_id,X,Y.is_error===!0||Q?.interrupted===!0,$.parent_tool_use_id??null)}}handleResultMessage($){if(typeof $.session_id==="string"&&$.session_id)this.sessionId=$.session_id;this.turnActive=!1;let Z=Oj($.usage),J=$.modelUsage??$.model_usage,Y=Nj(J);if(!Z&&!Y.usage)K(`claude-agent-process: result usage missing rootKeys=${D3($).join(",")||"-"} usageKeys=${D3($.usage).join(",")||"-"} modelUsageKeys=${D3(J).join(",")||"-"}`);if(this.lastUsage=Z,Y.usage)this.cumulativeUsageFromResults=K8(Y.usage),this.lastTotalUsage=K8(Y.usage);else if(Z)this.cumulativeUsageFromResults=Tj(this.cumulativeUsageFromResults,Z),this.lastTotalUsage=K8(this.cumulativeUsageFromResults);else this.lastTotalUsage=this.cumulativeUsageFromResults?K8(this.cumulativeUsageFromResults):null;if(Y.contextWindow!=null){let X=TQ(this.opts.model,this.tokenSourceId);if(F3.set(X,Y.contextWindow),this.tokenSourceId)for(let[z,W]of Object.entries(J??{})){let G=W?.contextWindow;if(typeof G==="number"&&G>0)OQ(this.tokenSourceId,z,G)}}this.lastContextWindow=F3.get(TQ(this.opts.model,this.tokenSourceId))??Y.contextWindow??null;let Q=j8(this.opts.workDir,this.sessionId??""),V=yQ(Q);if(this.lastContextTokens=NQ(V)??(xQ(Q)?NQ(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 H=typeof $.subtype==="string"?$.subtype:$.is_error?"error":"success";this.lastResult={cost_usd:null,cost_delta_usd:null,duration_ms:typeof $.duration_ms==="number"?$.duration_ms:null,num_turns:typeof $.num_turns==="number"?$.num_turns:1,usage:this.lastUsage,subtype:H,is_error:$.is_error===!0||H!=="success"},this.emit("result",{subtype:H,is_error:this.lastResult.is_error,...this.lastResult.is_error?{error:Array.isArray($.errors)&&$.errors.length?$.errors.map(String).join(`
|
|
106
|
+
`):String($.result??$.error??$.api_error_message??H)}:{},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})}failTurnStart($){this.turnActive=!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})}}});var uQ={};E$(uQ,{waitForTokenSourceModelRefresh:()=>A2,tokenSourceRuntimeModels:()=>D2,tokenSourceRuntimeModel:()=>L$,tokenSourceProcessRevision:()=>F2,tokenSourceFactories:()=>M2,setDefaultTokenSource:()=>R3,scrubDshEnv:()=>S4,scrubAnthropicEnv:()=>j$,resetTokenSourceRegistry:()=>N3,registerTokenSourceFactory:()=>S0,registerTokenSource:()=>O3,refreshAllTokenSourceModels:()=>C4,pendingTokenSourceModelRefresh:()=>U2,listTokenSourcesByAgent:()=>cQ,listTokenSources:()=>y$,listEnabledTokenSourcesByAgent:()=>P8,getTokenSourceForAccount:()=>H0,getTokenSource:()=>q$});function j$($){let Z={...$};for(let J of vj)delete Z[J];return Z}function S4($){let Z=j$($);for(let J of Object.keys(Z))if(/^(DSH_|DEEPSEEK_|LODESTAR_DSH_|ZAI_|ZHIPU_)/.test(J))delete Z[J];return Z}function D2($){return $.modelSelection?[...$.models,...$.modelSelection.availableModels.filter((Z)=>!$.models.some((J)=>J.model===Z.model))]:$.models}function L$($,Z){let J=(Y)=>$.agent==="claude"?Y?.replace(/\[1m\]$/,""):Y;return D2($).find((Y)=>J(Y.model)===J(Z))}function F2($,Z){let J=$?.spawnRevision??null,Y=$?.modelEnvironmentRevision?.(Z??$.defaultModel);return Y===void 0?J:JSON.stringify([J,Y])}function S0($){mQ.set($.kind,$)}function M2(){return[...mQ.values()]}function O3($,Z){if(b4.set($.id,$),Z?.default||q8===null)q8=$.id}function q$($){return $?b4.get($):void 0}function H0($,Z="default"){let J=q$($);return J?.forAccount?J.forAccount(Z):J}function y$(){return[...b4.values()]}function cQ($){return y$().filter((Z)=>Z.agent===$)}function P8($){return cQ($).filter((Z)=>Z.enabled)}function R3($){if(b4.has($))q8=$}function N3(){b4.clear(),q8=null,pQ++}function C4(){let $=pQ;if(P2?.generation===$)return P2.promise;let Z=Promise.allSettled(y$().map(async(J)=>{await J.refreshModels(),K(`token-source ${J.id}: ${J.models.length} models loaded`)})).then(()=>{}).finally(()=>{if(P2?.promise===Z)P2=null});return P2={generation:$,promise:Z},Z}function U2(){return P2?.promise??null}async function A2(){let $;while($=U2())await $}var vj,mQ,b4,q8=null,pQ=0,P2=null;var V0=R(()=>{I();vj=["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"];mQ=new Map;b4=new Map});import{spawn as fj}from"cross-spawn";import{EventEmitter as hj}from"node:events";import{StringDecoder as Ij}from"node:string_decoder";import{createHash as gj}from"node:crypto";function E3($,Z){if(w4.set($,Z),Z.state==="ok")F8.set($,Z);else if(Z.state==="no_credentials"||Z.state==="auth_failed")F8.delete($)}function dQ($,Z,J=(Y)=>new T1({accountId:Y})){if(!$||!Z.trim())return Promise.reject(Error("重置卡请求缺少账号或幂等标识"));let Y=D8.get($);if(Y)return Y.key===Z?Y.promise:Promise.reject(Error("该账号正在使用重置卡,请等待结果后再操作"));let Q=Promise.resolve().then(async()=>{let V=J($),H,X;try{await V.initialize("lodestar-codex-reset");let z=(await V.request("account/read",{}))?.account;if(!z||z.type!=="chatgpt")throw Error("该账号未登录 ChatGPT 订阅,不能使用重置卡");O2($);let W;try{W=await U8(()=>V.request("account/rateLimitResetCredit/consume",{idempotencyKey:Z}),"重置卡请求")}catch(_){throw Error(`重置卡请求未确认结果:${_ instanceof Error?_.message:String(_)};请用 codex-accounts 核对额度与重置卡次数`,{cause:_})}finally{O2($)}if(!["reset","alreadyRedeemed","nothingToReset","noCredit"].includes(W?.outcome))throw Error(`Codex 重置卡返回未知结果:${JSON.stringify(W)};请用 codex-accounts 核对后再操作`);let G=P$.get($),B;try{B=x3(await U8(()=>V.request("account/rateLimits/read",{})),z.planType)}catch(_){B={state:"network",reason:_ instanceof Error?_.message:String(_)}}if(P$.get($)!==G)B={state:"auth_failed"};else E3($,B);if(B.state!=="ok")K(`codex-reset: ${$} quota refresh failed: ${B.state==="network"?B.reason:B.state}`);H={outcome:W.outcome,usage:B}}catch(z){X=z,K(`codex-reset: ${$}: ${z}`)}try{await V.close()}catch(z){let W=`控制连接关闭失败:${z instanceof Error?z.message:String(z)}`;if(K(`codex-reset: ${$}: ${W}`),H)H.cleanupError=W;else throw AggregateError([X,z],`${String(X)};${W}`)}if(!H)throw X;return H}).finally(()=>{if(D8.get($)?.promise===Q)D8.delete($)});return D8.set($,{key:Z,promise:Q}),Q}function iQ($,Z){return new Promise((J,Y)=>{let Q=setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Q),J(V)},(V)=>{clearTimeout(Q),Y(V)})})}function mj($){return typeof $==="number"&&isFinite($)?Math.max(0,Math.min(100,$)):null}function M8($){if(!$)return null;return{percent:mj($.usedPercent),resetsAt:typeof $.resetsAt==="number"?new Date($.resetsAt*1000):null,durationMins:typeof $.windowDurationMins==="number"?$.windowDurationMins:null}}function pj($){let Z=M8($?.primary),J=M8($?.secondary),Y=(V)=>V?.durationMins!=null&&V.durationMins>0&&V.durationMins<=720,Q=(V)=>V?.durationMins!=null&&V.durationMins>720;if(Y(Z)&&Q(J))return{fiveHour:Z,weekly:J};if(Y(J)&&Q(Z))return{fiveHour:J,weekly:Z};if(Q(Z)&&!J)return{fiveHour:null,weekly:Z};if(Q(J)&&!Z)return{fiveHour:null,weekly:J};return{fiveHour:Z,weekly:J}}function cj($){let Z=$?.rateLimitsByLimitId,J=Z&&typeof Z==="object"?Object.entries(Z):$?.rateLimits?[[$.rateLimits.limitId??"codex",$.rateLimits]]:[],Y=[];for(let[Q,V]of J){let{fiveHour:H,weekly:X}=pj(V);if(!H&&!X)continue;Y.push({limitId:Q,limitName:V?.limitName??null,fiveHour:H,weekly:X,normalModelSlug:V?.normalModelSlug??null,rateLimitReachedType:V?.rateLimitReachedType??null,spendControlReached:V?.spendControlReached??null})}return{buckets:Y,defaultLimitId:$?.rateLimits?.limitId??void 0}}function uj($){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 nQ($,Z=u){let J=uj($),Y=w4.get(Z),Q=Y?.state==="ok"?Y.buckets??[]:[],V=Q.filter((H)=>lQ(H.fiveHour,M8($?.primary))&&lQ(H.weekly,M8($?.secondary)));if(Q.length>0&&V.length===0)K(`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)K(`usage: rate-limit notification labeled limitId=${$.limitId} but content matches bucket ${V[0].limitId} (known codex parser fallback relabels; ignoring notification payload)`)}function lQ($,Z){if(!$||!Z)return!$&&!Z;return $.percent===Z.percent&&$.durationMins===Z.durationMins&&$.resetsAt?.getTime()===Z.resetsAt?.getTime()}async function lj($){let Z=new T1({accountId:$});try{await Z.initialize("lodestar-usage");let Y=(await iQ(Z.request("account/read",{}),T3))?.account;if(!Y)return{state:"no_credentials"};if(Y.type!=="chatgpt")return{state:"auth_failed"};let Q=await U8(()=>Z.request("account/rateLimits/read",{}));return x3(Q,Y.planType)}catch(J){return K(`usage: codex app-server usage failed: ${J?.message??J}`),{state:"network",reason:J?.message??String(J)}}finally{await Z.close()}}function x3($,Z){let{buckets:J,defaultLimitId:Y}=cj($),Q=J.find((H)=>H.limitId===Y)??J[0];if(!Q)return{state:"network",reason:"empty rate limit response"};let V=Z??$?.rateLimits?.planType??void 0;return Q.fiveHour=l7(V,Q.fiveHour),{state:"ok",subscriptionType:V,...typeof $?.accountId==="string"&&$.accountId?{accountFingerprint:gj("sha256").update($.accountId).digest("hex")}:{},...typeof $?.ordinaryUsageAllowed==="boolean"?{ordinaryUsageAllowed:$.ordinaryUsageAllowed}:{},rateLimitReachedType:Q.rateLimitReachedType,spendControlReached:Q.spendControlReached,fiveHour:Q.fiveHour,weekly:Q.weekly,buckets:J,defaultLimitId:Q.limitId,resetCredits:Number.isInteger($?.rateLimitResetCredits?.availableCount)&&$.rateLimitResetCredits.availableCount>=0?$.rateLimitResetCredits.availableCount:null,fetchedAt:Date.now()}}function aQ($=u){return w4.get($)??null}function oQ($=u){return F8.get($)??null}function E1($=u){let Z=k4.get($);if(Z)return Z;let J=P$.get($)??0,Y=Promise.resolve().then(()=>lj($)).catch((Q)=>{return K(`usage: ${$} fetch failed: ${Q}`),{state:"network",reason:String(Q)}}).then((Q)=>{if((P$.get($)??0)!==J)return{state:"auth_failed"};return E3($,Q),Q}).finally(()=>{if(k4.get($)===Y)k4.delete($)});return k4.set($,Y),Y}function A8($,Z=u){let J=y4.get(Z);if(J)return J;let Y=P$.get(Z)??0,Q=U8(()=>$("account/rateLimits/read",{})).then((V)=>{if((P$.get(Z)??0)!==Y)return null;let H=x3(V);if((P$.get(Z)??0)===Y)E3(Z,H);if(H.state!=="ok")K(`usage: refresh from connection: ${H.state==="network"?H.reason:H.state}`);return H}).catch((V)=>{if(K(`usage: refresh from connection failed: ${V?.message??V}`),(P$.get(Z)??0)===Y)w4.delete(Z);return null}).finally(()=>{if(y4.get(Z)===Q)y4.delete(Z)});return y4.set(Z,Q),Q}function O2($){P$.set($,(P$.get($)??0)+1),w4.delete($),F8.delete($),k4.delete($),y4.delete($)}async function U8($,Z="额度查询"){let J=[1000,4000];for(let Y=0;;Y++)try{return await iQ($(),T3)}catch(Q){let V=Q instanceof Error?Q.message:String(Q);if(!/error sending request|timed? ?out|timeout|ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|\b(?:429|502|503|504)\b/i.test(V))throw Q;if(Y>=J.length)throw Error(`Codex ${Z}失败(已尝试 ${Y+1} 次):${V}`,{cause:Q});K(`usage: ${Z} retry ${Y+1}/${J.length} in ${J[Y]}ms: ${V}`),await new Promise((X)=>setTimeout(X,J[Y]))}}var T3=1e4,w4,F8,k4,D8,T1,y4,P$;var w$=R(()=>{O1();I();y0();p0();w4=new Map,F8=new Map,k4=new Map;D8=new Map;T1=class T1 extends hj{proc;buf="";decoder=new Ij("utf8");nextId=1;alive=!0;exitPromise;resolveExit;pending=new Map;constructor($={}){super();let Z=$.accountId??u;this.proc=fj($.bin??A4(),["app-server","--listen","stdio://",...$.args??k.cliArgs(Z)],{stdio:["pipe","pipe","pipe"],shell:!1,cwd:$.cwd,env:$.env??k.env(Z,{...process.env,...f.codex.env},!0,$.login)}),this.exitPromise=new Promise((Y)=>{this.resolveExit=Y}),this.proc.stdout.on("data",(Y)=>this.onStdout(Y)),this.proc.stderr.on("data",(Y)=>{let Q=Y.toString().trim();if(Q)K(`usage[codex stderr]: ${Q}`)});let J=(Y)=>{if(!this.alive)return;this.alive=!1;for(let[Q,V]of this.pending)clearTimeout(V.timer),V.reject(Error(`${Y.message}; pending ${V.method} id=${Q}`));this.pending.clear(),this.resolveExit(),this.emit("exit"),this.emit("closed",Y)};this.proc.on("error",(Y)=>J(Error(`codex app-server spawn failed: ${Y.message}`))),this.proc.stdin.on("error",(Y)=>{K(`usage: codex stdin failed: ${Y.message}`),this.emit("protocolError",Y)}),this.proc.on("close",(Y,Q)=>{J(Error(`codex app-server exited code=${Y} signal=${Q}`))}),o$(this,Z)}onStdout($){this.buf+=this.decoder.write($);let Z;while((Z=this.buf.indexOf(`
|
|
107
107
|
`))>=0){let J=this.buf.slice(0,Z).trim();if(this.buf=this.buf.slice(Z+1),!J)continue;let Y;try{Y=JSON.parse(J)}catch{this.emit("protocolError",Error("Codex app-server returned invalid JSON"));continue}if(!Y||typeof Y!=="object"||Array.isArray(Y)){this.emit("protocolError",Error("Codex app-server returned invalid RPC object"));continue}let Q=Object.prototype.hasOwnProperty.call(Y,"id");if(typeof Y.method==="string"){if(!Q)this.emit("notification",Y.method,Y.params);else K(`usage: unsupported Codex server request: ${Y.method}`),this.proc.stdin.write(JSON.stringify({id:Y.id,error:{code:-32601,message:`Unsupported server request: ${Y.method}`}})+`
|
|
108
108
|
`);continue}if(!Q||!Object.prototype.hasOwnProperty.call(Y,"result")&&!Object.prototype.hasOwnProperty.call(Y,"error")){this.emit("protocolError",Error("Codex app-server returned an incomplete RPC response"));continue}let V=this.pending.get(Y.id);if(!V)continue;if(this.pending.delete(Y.id),clearTimeout(V.timer),Y.error)V.reject(Error(JSON.stringify(Y.error)));else V.resolve(Y.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"})+`
|
|
109
|
-
`,(Y)=>Y?J(Y):Z())})}isAlive(){return this.alive}request($,Z,J=
|
|
110
|
-
`,(X)=>{if(!X)return;let z=this.pending.get(Y);if(!z)return;this.pending.delete(Y),clearTimeout(z.timer),z.reject(Error(`codex app-server write failed for ${$}: ${X.message}`))})}catch(X){this.pending.delete(Y),clearTimeout(H),V(X instanceof Error?X:Error(String(X)))}})}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)}}};y4=new Map,P$=new Map});import{existsSync as lj,readFileSync as dj}from"node:fs";class sQ{deps;constructor($){this.deps=$}blocks(){if(!lj(this.deps.stateFile))return[];let $=JSON.parse(dj(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.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"?U4($.usage,Z):null,Y=["fiveHour","weekly"].flatMap((X)=>{let z=J?.[X];return z?[{kind:X,percent:z.percent,reset:z.resetsAt?.getTime()??null}]:[]}),Q=i7($.usage,Z),V=JSON.stringify([$.identity,Q]),H=this.blocks().filter((X)=>X.key!==V);H.push({key:V,identity:$.identity,meter:Q,windows:Y}),s(this.deps.stateFile,{version:1,blocks:H})}async choose($){$.signal?.throwIfAborted();let Z=this.deps.accounts();if($.preferred){let J=Z.find((Y)=>Y.id===$.preferred);if(!J)throw Error(`指定 Codex 账号不存在:${$.preferred}`);return{selected:{account:J,identity:`record:${J.id}`,usage:null,state:"manual",score:null,shares:null,remaining:null,hours:null},candidates:[]}}if($.preferCachedUsage){let J=await this.chooseAutomatic(Z,$,!0);if(J.selected)return J}return this.chooseAutomatic(Z,$,!1)}async chooseAutomatic($,Z,J){Z.signal?.throwIfAborted();let Y=await Promise.all($.map(async(q)=>{let P,F=null,T=`record:${q.id}`;if(this.deps.pendingLogin(q.id))P={state:"network",reason:"正在登录"};else try{P=J?this.deps.cachedUsage(q.id):await this.deps.usage(q.id);let M=P?.state==="ok"?P.accountFingerprint??this.deps.identity(q.id):null;if(M)T=M;else if(P?.state==="ok")F="账号身份 MISS";if(P?.state==="ok"&&!F)F=await this.deps.compatible(q.id,Z.model,Z.effort)}catch(M){P={state:"network",reason:String(M)}}return{account:q,usage:P,identity:T,reason:F}}));Z.signal?.throwIfAborted();let Q=Z.failedAccountId&&Y.find((q)=>q.account.id===Z.failedAccountId);if(Q&&Q.usage?.state==="ok")this.block({account:Q.account,usage:Q.usage,identity:Q.identity,...n7(Q.usage,Z.model,this.deps.now(),Z.effort)},Z.model);let V=this.blocks(),H=this.deps.now(),X=new Set,z=new Map,W=Y.map(({account:q,usage:P,identity:F,reason:T})=>{let M=n7(P??{state:"network",reason:"尚无额度缓存"},Z.model,H,Z.effort);if(T)M={...M,state:"miss",score:null,reason:T};let A=z.get(F);if(z.set(F,A??q.name),A)M={...M,state:"miss",score:null,reason:`重复账号:${A}`};let U=P?.state==="ok"?i7(P,Z.model):null,S=V.find((b)=>(b.identity===F||b.identity===`record:${q.id}`)&&b.meter===U);if(S&&P?.state==="ok"&&M.state==="ready"){let b=U4(P,Z.model);if(!J&&S.windows.some((y)=>{let g=b[y.kind];return g&&g.percent!==null&&(y.percent!==null&&g.percent<y.percent||y.reset!==null&&y.reset<=H&&(g.resetsAt?.getTime()??0)>y.reset)}))X.add(S.key);else M={...M,state:"exhausted",score:null,reason:"上次请求已确认额度耗尽,等待接口确认恢复"}}return{account:q,usage:P,identity:F,...M,...A?{duplicateOf:A}:{}}});if(X.size)s(this.deps.stateFile,{version:1,blocks:V.filter((q)=>!X.has(q.key))});let G=W.filter((q)=>q.state==="ready");G.sort((q,P)=>P.score-q.score||(P.availableNow??0)-(q.availableNow??0)||q.account.id.localeCompare(P.account.id));let B=G[0]??null,_=W.filter((q)=>q.state==="exhausted"||q.state==="waiting"),j=_.length?Math.min(..._.map((q)=>q.retryAt??H+60000)):void 0;for(let q of W)K(`codex scheduler${J?" [cache]":""}: ${q.account.name} ${q.state} score=${q.score??"MISS"}${q.reason?` (${q.reason})`:""}`);return{selected:B,candidates:W,...j!==void 0?{retryAt:j}:{}}}}var R8;var b3=R(()=>{p0();w$();V0();Q0();T0();I();R8=new sQ({accounts:()=>k.list(),usage:E1,cachedUsage:rQ,identity:($)=>k.fingerprint($),pendingLogin:J8,now:Date.now,stateFile:iJ,compatible:async($,Z,J)=>{let Y=H0("codex-sub",$);if(!Y)return"订阅来源 MISS";if(Y.modelCatalogState?.status!=="ready")await Y.refreshModels();if(!Y.enabled||Y.modelCatalogState?.status!=="ready")return Y.modelCatalogState?.error??"模型目录 MISS";let Q=L$(Y,Z);return!Q||Q.unavailableReason||J&&!Q.efforts.includes(J)?`${Z}/${J??"default"} 不可用`:null}})});import{EventEmitter as ij}from"node:events";function oj($,Z){return Z.throwIfAborted(),new Promise((J,Y)=>{let Q=()=>{clearTimeout(H),Z.removeEventListener("abort",V)},V=()=>{Q(),Y(Z.reason)},H=setTimeout(()=>{Q(),J()},$);Z.addEventListener("abort",V,{once:!0})})}var nj="上一轮因当前账号额度耗尽而中断,现已切换账号。请基于本会话已有记录继续完成用户尚未完成的任务,保留已完成的修改和工具结果。执行有副作用的操作前先确认现状,不要重复已完成的操作。",aj,C3=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),k3;var tQ=R(()=>{p0();b3();w$();I();aj=["error","conversation_materialized","conversation_materialization_failed","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"];k3=class k3 extends ij{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??C3()}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??R8}notice($,Z=0){this.ownRetry={reason:"quota",phase:Z?"waiting":"retrying",attempt:this.retryCount,delayMs:Z,message:$},K(`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 Y=await this.scheduler().choose(J);if(delete J.failedAccountId,this.lifetime.signal.throwIfAborted(),Y.selected)return{...Y,selected:Y.selected};J.preferCachedUsage=!1;let Q=Y.candidates.map((X)=>`${X.account.name}:${X.reason??X.state}`).join(";");if(Y.retryAt===void 0){let z=Y.candidates.some((W)=>W.state==="miss"&&!W.duplicateOf)?"Codex 账号检查失败,无法自动选账号(MISS)":Y.candidates.length?"没有符合条件的 Codex 账号":"没有配置 Codex 账号";throw Error(`${z}${Q?`;${Q}`:""}`)}let V=Math.max(1000,Math.min(60000,Y.retryAt-Date.now())),H=Y.candidates.filter((X)=>X.state==="miss"&&!X.duplicateOf).length;K(`codex account: waiting for quota: ${Q}`),this.notice(`暂无可用账号 · 自动等待恢复${H?` · ${H} 个 MISS`:""}`,V),this.resolveQuotaWait(),await(this.opts.wait??oj)(V,this.lifetime.signal)}}async launch($,Z,J){this.starting=!0;let Y=await this.choose(Z,J);this.lifetime.signal.throwIfAborted();let Q=this.selected?.account.id??null,{process:V,sourceRevision:H}=this.opts.create(Y.selected.account.id,$,Y.selected.state==="manual",this.opts.model||this.lastModel||void 0,this.opts.effort??this.lastEffort??void 0);this.inner=V,this.selected=Y.selected,this.revision=H,o$(this,Y.selected.account.id,!1),this.wire(V),this.emit("codex_account_changed",{accountId:Y.selected.account.id,previousAccountId:Q,diagnostics:Y.candidates.filter((z)=>z.usage!==null&&z.state==="miss"&&!z.duplicateOf).map((z)=>`${z.account.name}:${z.reason}`)}),this.lifetime.signal.throwIfAborted(),V.sendInitialize();let X=V.initializationPromise?.();if(!X)throw Error("Codex 初始化未提供确认事务");if(await X,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($){for(let Z of aj)$.on(Z,(...J)=>{if(this.inner===$&&!this.closed){if(Z==="bg_task_started")this.backgroundTasks.add(J[0].task_id);if(Z==="bg_task_settled")this.backgroundTasks.delete(J[0].task_id);this.emit(Z,...J)}});$.on("turn_retry",(Z)=>{if(this.inner===$&&!this.closed)this.emit("turn_retry",Z)}),$.on("turn_started",(Z)=>{if(this.inner!==$||this.closed)return;this.result=null,this.ownRetry=null;let J=this.retryTurn||Z.retry;this.retryTurn=!1,this.emit("turn_started",{...Z,...J?{retry:!0}:{}})}),$.on("result",(Z)=>{if(this.inner!==$||this.closed||this.lifetime.signal.aborted)return;if(Z?.is_error&&Z.codexQuotaFailure&&!this.recovery){this.retryCount++;let J=Promise.resolve().then(()=>this.recover($,Z.codexQuotaFailure)).catch((Y)=>{if(!this.lifetime.signal.aborted)this.fail(Y)}).finally(()=>{if(this.recovery===J)this.recovery=null});this.recovery=J,this.notice(`「${this.selected?.account.name??"MISS"}」额度耗尽 · 正在换号续跑`);return}if(this.recovery)return;this.retryCount=0,this.result=null,this.emit("result",Z)}),$.on("exit",(Z)=>{if(this.inner!==$||this.closed)return;if((this.recovery||this.shutdown)&&Z.expected)return;this.lifetime.abort(Error("Codex 进程退出")),this.closed=!0,this.emit("exit",Z)})}async recover($,Z){if(this.lifetime.signal.throwIfAborted(),!this.selected)throw Error("额度耗尽时未记录运行账号");if($.readRateLimits){let X=await O8(()=>$.readRateLimits(),this.selected.account.id);if(this.lifetime.signal.throwIfAborted(),X?.state==="ok")this.selected={...this.selected,usage:X,identity:X.accountFingerprint??this.selected.identity};else this.notice("已确认额度耗尽 · 用量读取 MISS,正在换号")}let J=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 Q=$.isConversationResumable?.()===!0&&$.sessionId;if(Z.accepted&&!Q)throw Error("额度耗尽后未确认原会话落盘,不能重放已执行的任务");if(!Z.accepted&&typeof Z.rejectedInput!=="string")throw Error("额度耗尽的拒绝响应缺少原始输入");let V=Q?{kind:"resume",source:{provider:"codex",sessionId:$.sessionId,cwd:this.opts.workDir}}:this.opts.launch;if(await $.kill(),$.isAlive())throw Error("旧 Codex 进程退出未确认,不能启动下一账号");for(let X of this.backgroundTasks)this.emit("bg_task_settled",{task_id:X,status:"failed",summary:"账号额度耗尽,原进程已退出;主任务换号后继续"});this.backgroundTasks.clear(),this.lifetime.signal.throwIfAborted(),await this.launch(V,void 0,J),this.lifetime.signal.throwIfAborted(),this.retryTurn=!0,this.notice(`已切换「${this.selected.account.name}」· 继续原任务`),this.lifetime.signal.throwIfAborted();let H=Z.accepted?nj:Z.rejectedInput;this.recovery=null,this.inner.sendUserText(H),this.drainInputs()}fail($){let Z=$ instanceof Error?$:Error(String($));this.fault=Z,this.ownRetry=null,this.inputs.length=0,this.result={...C3(),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()}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={...C3(),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 v4($){if($.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexAccountPreference!==void 0){if(!$.model&&!$.codexAccountPreference)throw Error("Codex 自动选号需要明确模型");return{process:new k3({model:$.model??"",effort:$.effort,preferred:$.codexAccountPreference,workDir:$.workDir,launch:$.launch??{kind:"fresh"},create:(B,_,j,q,P)=>v4({...$,model:q,effort:P,codexAccountPreference:void 0,codexManualAccount:j,codexAccountId:B,launch:_})}),sourceRevision:null}}let Z=$.codexAccountId??u,J=H0($.tokenSourceId,Z),Y=$.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexManualAccount===!0;if($.tokenSourceId&&!J)throw Error(`token source not found: ${$.tokenSourceId}`);if(J&&!J.enabled&&!Y)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(!Y&&J?.modelCatalogState?.status==="failed")throw Error(`model catalog refresh failed for ${J.id}: ${J.modelCatalogState.error??"MISS"}`);if(!Y&&(J?.modelCatalogState?.status==="idle"||J?.modelCatalogState?.status==="loading"))throw Error(`model catalog is not ready for ${J.id}: ${J.modelCatalogState.status}`);let Q=$.model||J?.defaultModel||void 0,V=D2(J,Q),H=!Y&&J&&L$(J,Q);if(!Y&&J&&Q&&!H)throw Error(`model is not present in token source ${J.id}: ${Q}`);if(!Y&&H&&(H.unavailableReason||!H.efforts.length||$.effort!==void 0&&!H.efforts.includes($.effort)))throw Error(`model effort unavailable: ${J.id}/${Q}/${$.effort??"MISS"}`);let X=!Y&&J&&Q?J.resolveSpawnModel(Q):Q;if(Q&&!X)throw Error(`model did not resolve: ${$.tokenSourceId??"default"}/${Q}`);let z=J?(G)=>J.spawnEnv(G,X):void 0;if($.provider==="dsh"){if(!J||!X||!B0($.effort))throw Error("DSH requires a configured source, model and valid effort");return{process:new L3({...$,model:X,effort:$.effort,tokenSourceId:J.id,transformEnv:z}),sourceRevision:V}}if($.provider==="claude"){if(A3(),!E0($.effort))throw Error(`invalid Claude effort: ${$.effort??"MISS"}`);return{process:new q8({workDir:$.workDir,model:X,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}:{},...$.allowDelegation===!1?{allowDelegation:!1}:{},...$.profile?{profile:$.profile}:{},...J?{settingSources:J.settingSources??["project","local"]}:{},...$.managedSkillPluginPath?{managedSkillPluginPath:$.managedSkillPluginPath}:{},tokenSourceId:J?.id??null,transformEnv:z,hostEnv:$.hostEnv}),sourceRevision:V}}if($.effort!==void 0&&!s0($.effort))throw Error(`invalid Codex effort: ${$.effort}`);let W=new _2({workDir:$.workDir,model:X,effort:$.effort,launch:$.launch,...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowDelegation===!1?{allowDelegation:!1}:{},tokenSourceId:J?.id??null,transformEnv:z,hostEnv:$.hostEnv,serviceName:$.serviceName,codexAccountId:Z});return o$(W,Z),{process:W,sourceRevision:V}}var y3=R(()=>{F0();AQ();x4();O1();V0();p0();tQ()});function N8($,Z){return`http://${$==="0.0.0.0"?"127.0.0.1":$==="::"||$==="::1"?"[::1]":$}:${Z}`}function R2($){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 N2($,Z){let J=Z.replace(/[&<>\\`*_\[\]~]/g,(z)=>`&#${z.charCodeAt(0)};`),Y=typeof $.used==="number"&&typeof $.total==="number"?` · ${$.used}/${$.total}`:"",Q=$.percent;if(Q===null||!Number.isFinite(Q)||Q<0||Q>100)return[{tag:"markdown",content:`**${J} · MISS${Y}**`}];let V=Math.round(Q/100*6),H=Q>=100?"red":Q>=80?"orange":"green",X=$.unreportedFull?"满窗 · 0.15 份":$.resetsAt&&Number.isFinite($.resetsAt.getTime())?`${R2($.resetsAt)} 重置`:"重置时间 MISS";return[{tag:"markdown",content:`**${J} · ${Math.round(Q)}%${Y}**
|
|
111
|
-
<font color='${H}'>${"▰".repeat(V)}${"▱".repeat(6-V)}</font>`},{tag:"markdown",content:`<font color='grey'>${X}</font>`,text_size:"notation"}]}var
|
|
112
|
-
`)),c0("备注可用 default 指定设备默认账号;默认账号不可删除。")]});if($.hint)J.push(c0($.hint));if($.details)J.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查看详情"}},elements:[w0($1($.details))]});return{tag:"collapsible_panel",element_id:N.codexAccountPanel,expanded:!0,header:{title:{tag:"plain_text",content:f4($)},background_color:`${Z}-50`},border:{color:`${Z}-100`,corner_radius:"8px"},padding:"12px",elements:J}}function rj($){let Z=$.total,J=Math.max(1,Math.ceil(Z.entries.length/T8)),Y=$.page??1;if(!Number.isInteger(Y)||Y<1||Y>J)throw Error(`页码应为 1–${J}`);let Q=[c0(`${Z.entries.length} 个记录 · 可用 ${Z.available??"MISS"} 个账号${Z.complete?"":" · 汇总不完整"}`)],V=$.scheduling?.candidates.filter((H)=>H.state==="ready").sort((H,X)=>X.score-H.score||(X.availableNow??0)-(H.availableNow??0)||H.account.id.localeCompare(X.account.id));if($.scheduling)Q.push(c0(`${$.scheduling.ultra?"Ultra · Pro ≥ 0.5 份":"普通 · 周 / 5h 综合"} · 最高分优先 · 可调度 ${V.length}`));for(let H of Z.entries.slice((Y-1)*T8,Y*T8)){let X=[H.account.id===$.currentId?"使用中":"",H.account.id===$.selectedId&&$.selectedId!==$.currentId?"下次启动":""].filter(Boolean),z=H.usage,W=[];if(Q.push({tag:"collapsible_panel",expanded:!0,header:{title:{tag:"plain_text",content:`${H.account.name}${X.length?` · ${X.join(" · ")}`:""}`},background_color:H.account.id===$.currentId?"blue-50":"grey-50"},border:{color:"grey-100",corner_radius:"8px"},padding:"8px",vertical_spacing:"4px",elements:W}),H.duplicateOf){W.push(c0(`与「${H.duplicateOf}」同一账号,合计只计一次`));continue}let G=$.scheduling?.candidates.find((j)=>j.account.id===H.account.id);if(G){let j=V.findIndex((q)=>q.account.id===H.account.id);if(W.push(G.state==="ready"?w0(`**#${j+1} · ${G.score.toPrecision(3)} 份/h**`):c0(G.state==="exhausted"?"⏳ 耗尽 · 暂不参与":G.state==="excluded"?"Ultra 自动排除 Plus":G.state==="waiting"?`⏳ 周余量 ${G.remaining?.toPrecision(3)} 份 · 未达 0.5 份`:"MISS · 无法排序")),G.state==="ready"&&G.remaining!=null)W.push(c0(`周余量 ${G.remaining.toPrecision(3)} 份${G.fiveHourRemaining!=null?` · 5h ${G.fiveHourRemaining.toPrecision(3)} 份`:""}`));if(G.state==="miss"&&G.reason&&z.state==="ok")W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"未参与原因"}},elements:[w0($1(G.reason))]})}if(z.state!=="ok"){if(W.push(w0(z.state==="no_credentials"?"⚪ 未登录":"⚠️ 额度 MISS")),z.state==="network"&&z.reason)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查询错误"}},elements:[w0($1(z.reason))]});continue}let B=z.subscriptionType==="pro"?"Pro 20×":z.subscriptionType==="prolite"?"Pro 5×":z.subscriptionType==="plus"?"Plus 1×":z.subscriptionType??"套餐 MISS";W.push(c0(`${B} · 重置卡 ${z.resetCredits??"MISS"}`));let _=[[z.fiveHour,"5h"],[z.weekly,"周"]].flatMap(([j,q])=>j?[N2(j,q)]:[]);if(_.length)W.push(w3(_))}if(J>1)Q.push(c0(`${Y}/${J} 页 · ${Y<J?`下一页 codex-accounts ${Y+1}`:"首页 codex-accounts"}`));return Q}var T8=4,eQ,w0=($)=>({tag:"markdown",content:$}),c0=($)=>({tag:"markdown",content:`<font color='grey'>${$1($)}</font>`,text_size:"notation"});var T2=R(()=>{x0();eQ={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"]}});function ZV($){if(!$||typeof $!=="object")return!1;let Z=$.response?.status??$.status,J=$.response?.data?.code??$.code;if(J===99991400||J===230020||J===1061045||sj.has(Z))return!0;if(typeof Z==="number"&&Z>=400)return!1;if(tj.has(J)||$.name==="TimeoutError")return!0;return $.cause!==$&&ZV($.cause)}function ej($){let Z=$?.retryAfter??$?.response?.headers?.["retry-after"]??$?.response?.headers?.["x-ogw-ratelimit-reset"];if(typeof Z!=="string"||!Z.trim())return 0;let J=Number(Z),Y=Number.isFinite(J)?J*1000:Date.parse(Z)-Date.now();return Number.isFinite(Y)?Math.max(0,Y):0}async function x1($,Z){for(let J=0;;J++)try{return await Z()}catch(Y){let Q=Math.max(v3[J]??0,ej(Y)),V=ZV(Y)&&J<v3.length&&Q<=60000;if(K(`feishu: ${$} attempt ${J+1}/${v3.length+1} failed: ${Y}; ${V?`retry in ${Q}ms`:"FINAL"}`),!V)throw Y;await new Promise((H)=>setTimeout(H,Q))}}async function E2($,Z){let J=await $.text(),Y=$.headers.get("retry-after")??$.headers.get("x-ogw-ratelimit-reset"),Q;try{Q=JSON.parse(J)}catch{throw new F$(`${Z} HTTP ${$.status}: invalid JSON — ${J.slice(0,200)}`,$.status,void 0,Y)}if(!$.ok||Q?.code!==0)throw new F$(`${Z} HTTP ${$.status} code=${Q?.code??"MISS"} msg=${Q?.msg??"MISS"}`,$.status,Q?.code,Y);return Q}var v3,sj,tj,F$;var E8=R(()=>{I();v3=[1000,4000],sj=new Set([408,429,500,502,503,504]),tj=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"]);F$=class F$ extends Error{status;code;retryAfter;constructor($,Z,J,Y){super($);this.status=Z;this.code=J;this.retryAfter=Y;this.name="FeishuRequestError"}}});function ZL($){let Z=$?.action?.value??{},J=String(Z.kind??"");if(!J)return"无效操作";if(!$L.has(J))return`不支持的操作: ${J}`;let Y=J==="notify_callback"||J==="notify_reply"||J==="notify_reply_cancel";if(!Y&&!String($?.context?.open_chat_id??""))return"回调缺少 chat_id,操作未执行";if(!Y&&!String($?.context?.open_message_id??""))return"回调缺少原卡 message_id,操作未执行";if(J==="permission"&&!["allow","allow_always","deny"].includes(String(Z.decision??"")))return"无效的权限决定,操作未执行";return null}class g4{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 Q=(this.tails.get(J)??Promise.resolve()).then(Z),V;return V=Q.then(()=>{},()=>{}).finally(()=>{if(this.tails.get(J)===V)this.tails.delete(J)}),this.tails.set(J,V),{accepted:!0,completion:Q}}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 JV($){let Z=$.now??Date.now;return{accept(J){let Y=Z();return $.actor.tryEnqueue($.key(J),()=>$.execute(J,Y))}}}class h3{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 f3($){if(Array.isArray($))return`[${$.map(f3).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)}:${f3(J)}`).join(",")}}`}function JL($){let Z=$?.action?.value??{},J=String(Z?.kind??"unknown"),Y=String($?.context?.open_chat_id??""),Q=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`${Y}\x00${Q}\x00${J}\x00${f3(V)}`}function YL($){let Z=String($?.event_id??$?.header?.event_id??$?.event?.event_id??"");return{...Z?{deliveryKey:`event\x00${Z}`}:{},businessKey:`semantic\x00${JL($)}`,...["agent_identity_page","model_page","model_list_open","model_add","model_remove","model_custom_remove","notify_reply"].includes($?.action?.value?.kind)?{repeatable:!0}:{}}}function QL(){return new Promise(($)=>setTimeout($,0))}function I4($,Z,J){if(Z.deliveryKey)$.complete(Z.deliveryKey);if(J&&!Z.repeatable)$.complete(Z.businessKey);else $.fail(Z.businessKey)}function YV($){let Z=$.afterAck??QL,J=(Q)=>{try{$.onBackgroundError?.(Q)}catch{}},Y=async(Q)=>{try{await Q()}catch(V){J(V)}};return{accept(Q){if(!$.actor.isAccepting())return $.responses.closed(Q);let V=ZL(Q);if(V)return $.responses.invalid(Q,V);let H=YL(Q),X=H.deliveryKey?[H.deliveryKey,H.businessKey]:[H.businessKey],z=$.deduper.claimAll(X);if(z==="inflight")return $.responses.inflight(Q);if(z==="completed")return $.responses.completed(Q);let W=$.actor.tryEnqueue($.scope(Q),async()=>{try{await Z()}catch(_){$.deduper.failAll(X),J(_);return}let G;try{G=await $.execute(Q)}catch(_){I4($.deduper,H,!0),await Y(()=>$.presentExecutionFailure(Q,_));return}await Y(async()=>{try{await $.present(Q,G)}catch(_){await $.presentPresentationFailure(Q,_)}});let B;try{B=$.completion(Q,G)}catch(_){I4($.deduper,H,!1),J(_);return}if(B){let _=B.then((j)=>{I4($.deduper,H,j==="complete")},(j)=>{I4($.deduper,H,!1),J(j)});$.track(_);return}I4($.deduper,H,$.businessSucceeded(Q,G))});if(!W.accepted)return $.deduper.failAll(X),$.responses.closed(Q);return $.track(W.completion),W.completion.catch(J),$.responses.accepted(Q)}}}var $L;var I3=R(()=>{$L=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 VL}from"node:async_hooks";class QV{actor=new g4;context=new VL;run($,Z){let J=this.context.getStore();if(J?.active&&J.chatId===$)return Z();return this.actor.enqueue($,async()=>{let Y={chatId:$,active:!0};try{return await this.context.run(Y,Z)}finally{Y.active=!1}})}}function D$($,Z){return HL.run($,Z)}var HL;var g3=R(()=>{I3();HL=new QV});async function m3($){let Z=await u3("feishu chat.get",()=>X0.im.chat.get({path:{chat_id:$},params:{user_id_type:"open_id"}}));if(Z.code&&Z.code!==0)x8("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 p3($,Z){let J=await u3("feishu tasklist.create",()=>X0.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)x8("feishu tasklist.create",J);let Y=J.data?.tasklist,Q=Y?.guid;if(!Q)throw Error("feishu tasklist.create returned no guid");return{guid:Q,name:Y?.name||$,url:Y?.url??"",createdAt:Y?.created_at}}async function c3($){let Z=await u3("feishu tasklist.delete",()=>X0.task.v2.tasklist.delete({path:{tasklist_guid:$}}));if(Z.code&&Z.code!==0)x8("feishu tasklist.delete",Z)}function VV($,Z){let J=Z&&typeof Z==="object"?Z:{},Y=J.response?.data&&typeof J.response.data==="object"?J.response.data:J.data&&typeof J.data==="object"?J.data:J,Q=Y.code??J.code,V=Y.msg??Y.message??J.msg??J.message??"unknown error",H=Y.error?.permission_violations??Y.permission_violations??J.error?.permission_violations,X=Array.isArray(H)?H.map((z)=>z?.scope??z?.subject??z?.name??z).filter(Boolean).join(", "):"";return`${$} failed code=${Q??"unknown"} msg=${V}${X?` missing_scopes=${X}`:""}`}async function u3($,Z){try{return await Z()}catch(J){x8($,J)}}function x8($,Z){throw Error(VV($,Z))}var HV=R(()=>{t()});var Y0={};E$(Y0,{writeAliveMarker:()=>z5,urgentApp:()=>C1,uploadImageKey:()=>q5,uploadAndSend:()=>o4,updateCard:()=>A$,unbindSessionChat:()=>C8,tempProjectName:()=>U$,tempChatName:()=>Y5,setPendingConversationLaunchChecked:()=>J1,sendTextRaw:()=>w,sendText:()=>E,sendImage:()=>m8,sendFile:()=>SV,sendCard:()=>c,sanitizeSessionName:()=>F5,resolveProjectDir:()=>w8,replaceTurnAnchors:()=>e0,registerTempSessionLease:()=>r3,refreshChatList:()=>n4,readAliveMarker:()=>W5,provisionProject:()=>P5,projectProfile:()=>b2,preferredChatForSession:()=>L0,loadTempSessionLeases:()=>o3,loadSessionTurnsMap:()=>Z5,loadSessionResumeMap:()=>e3,loadSessionModelMap:()=>Q5,loadSessionChatMap:()=>t3,listNormalChatIdsByName:()=>f8,isOpenAIChatGPTAuthenticated:()=>r4,hasTempSessionLease:()=>s3,getTurnAnchors:()=>l4,getTenantToken:()=>M$,getSessionResumeRef:()=>Z1,getSessionModelSelection:()=>H5,getSessionBranchBase:()=>d4,getPendingConversationLaunch:()=>i4,getChatTailMessageId:()=>L5,formatFeishuApiError:()=>VV,findNormalChatIdByName:()=>h8,fetchChatOwnerOpenId:()=>m3,fetchChatName:()=>j5,ensureChatForSession:()=>G5,downloadAttachment:()=>a4,disbandChatForSessionExact:()=>_5,disbandChatForSession:()=>B5,deleteTasklistByGuid:()=>c3,deleteReaction:()=>C0,createTempChatForSession:()=>K5,createTasklistWithOwner:()=>p3,client:()=>X0,clearSessionResumeChecked:()=>C2,clearSessionConversationState:()=>X5,chatNameCache:()=>q0,chatIdForSession:()=>v8,bindSessionToChat:()=>S2,bindSessionResumeChecked:()=>u4,bindSessionModelChecked:()=>b1,bindSessionModel:()=>V5,appendTurnAnchorChecked:()=>J5,addReaction:()=>l0,PROJECTS_ROOT:()=>DV,MAX_UPLOAD_BYTES:()=>g8});import*as _V from"@larksuiteoapi/node-sdk";import{execSync as XL}from"node:child_process";import{randomUUID as a3}from"node:crypto";import{mkdirSync as d3,readFileSync as S1,statSync as jV,writeFileSync as LV}from"node:fs";import{readFile as zL}from"node:fs/promises";import{homedir as XV}from"node:os";import{basename as x2,extname as WL,isAbsolute as qV,join as b8}from"node:path";import{sync as GL}from"cross-spawn";function i3(){let $={};for(let[Z,J]of u0)$[Z]=J;s(W7,$)}function o3(){u0.clear();try{let $=JSON.parse(S1(W7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("lease file must contain an object");for(let[Z,J]of Object.entries($)){let Y=J;if(typeof Z!=="string"||!Z||Y.chatId!==Z||typeof Y.sessionName!=="string"||!U$(Y.sessionName)||typeof Y.createdAt!=="number"||!Number.isFinite(Y.createdAt)){K(`feishu: rejected malformed temp-session lease chat=${Z}`);continue}u0.set(Z,{chatId:Z,sessionName:Y.sessionName,createdAt:Y.createdAt})}K(`feishu: loaded ${u0.size} temporary-session leases`)}catch($){if($?.code!=="ENOENT")K(`feishu: load temp-session leases failed: ${$?.message??$}`)}}function r3($,Z){if(!U$($))throw Error(`refusing to lease non-temporary session name "${$}"`);if(!Z)throw Error("cannot lease a temporary session without chat_id");for(let Q of u0.values())if(Q.sessionName===$&&Q.chatId!==Z)throw Error(`temporary session name "${$}" is already leased to ${Q.chatId}`);let J=u0.get(Z),Y={sessionName:$,chatId:Z,createdAt:Date.now()};u0.set(Z,Y);try{i3()}catch(Q){if(J)u0.set(Z,J);else u0.delete(Z);throw Q}}function s3($,Z){let J=u0.get(Z);return J?.sessionName===$&&J.chatId===Z}function b2($){return f.projects[$]}function w8($){return b2($)?.cwd?.trim()||b8(DV,$)}function c4($,Z={}){return $0($,{...Z,signal:Z.signal??AbortSignal.timeout(MV)})}async function UV($,Z,J){let Y=Z.signal??AbortSignal.timeout(MV);try{return await E2(await c4($,{...Z,signal:Y}),J)}catch(Q){if(Y.aborted&&Y.reason?.name==="TimeoutError")throw Y.reason;throw Q}}async function M$(){if(S8&&Date.now()<zV)return S8;return l3??=(async()=>{let $=await UV("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:PV,app_secret:FV})},"tenant token");if(typeof $.tenant_access_token!=="string"||!$.tenant_access_token.trim())throw Error("feishu: tenant token MISS");return S8=$.tenant_access_token,zV=Date.now()+Math.max(0,($.expire??7200)-60)*1000,S8})().finally(()=>{l3=null}),l3}function t3(){try{let $=JSON.parse(S1(V7,"utf8"));for(let[Z,J]of Object.entries($))if(typeof J==="string")L0.set(Z,J);K(`feishu: loaded ${L0.size} session→chat bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-chat-map failed: ${$?.message??$}`)}}function AV(){try{n3()}catch($){K(`feishu: save session-chat-map failed: ${$}`)}}function n3(){let $={};for(let[Z,J]of L0)$[Z]=J;s(V7,$)}function S2($,Z){if(L0.get($)===Z)return;let J=L0.get($);L0.set($,Z),AV(),K(`feishu: bound session "${$}" → ${Z}${J?` (was ${J})`:""}`)}function C8($){let Z=L0.get($);if(!Z)return;L0.delete($),AV(),K(`feishu: unbound session "${$}" from ${Z}`)}function m4($,Z){let J=j0.get($)??{};J[Z.provider]=Z,j0.set($,J)}function WV($,Z){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$,Y=B$(J.provider)?J.provider:Z??null;if(!Y||Z&&Y!==Z)return null;let Q=typeof J.sessionId==="string"?J.sessionId.trim():typeof J.session_id==="string"?J.session_id.trim():"";if(!Q)return null;if(J.cwd===void 0||J.cwd===null)return{provider:Y,sessionId:Q,cwd:null};if(typeof J.cwd!=="string"||!qV(J.cwd))return null;return{provider:Y,sessionId:Q,cwd:J.cwd}}function GV($){let Z=$.sessionId.trim();if(!Z)throw Error("cannot bind an empty conversation session id");if(!B$($.provider))throw Error(`cannot bind an unknown conversation provider: ${String($.provider)}`);if(typeof $.cwd!=="string"||!qV($.cwd))throw Error(`cannot bind a conversation without an absolute cwd: ${String($.cwd)}`);return{provider:$.provider,sessionId:Z,cwd:$.cwd}}function KL($,Z,J){if(typeof $!=="string")return GV($);if(!Z)throw Error("cannot bind a conversation without a provider");return GV({provider:Z,sessionId:$,cwd:J??null})}function e3(){try{let $=JSON.parse(S1(H7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("resume map must contain an object");j0.clear();for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){m4(Z,{provider:"codex",sessionId:J.trim(),cwd:null});continue}if(!J||typeof J!=="object"||Array.isArray(J))continue;let Y=J,Q=WV(Y);if(Q){m4(Z,Q);continue}for(let V of b7){let H=Y[V];if(typeof H==="string"&&H.trim()){m4(Z,{provider:V,sessionId:H.trim(),cwd:null});continue}let X=WV(H,V);if(X)m4(Z,X)}}K(`feishu: loaded ${j0.size} session→resume bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-resume-map failed: ${$?.message??$}`)}}function k8(){let $={};for(let[Z,J]of j0){let Y={};if(J.codex)Y.codex={...J.codex};if(J.claude)Y.claude={...J.claude};if(J.dsh)Y.dsh={...J.dsh};$[Z]=Y}s(H7,$)}function u4($,Z,J,Y){let Q=KL(Z,J,Y),V=j0.get($),H=V?{...V}:void 0,X=V?.[Q.provider];if(X?.sessionId===Q.sessionId&&X.cwd===Q.cwd)return;m4($,Q);try{k8()}catch(z){if(H)j0.set($,H);else j0.delete($);throw z}}function Z1($,Z="codex"){let J=j0.get($)?.[Z];return J?{...J}:null}function C2($,Z){let J=j0.get($);if(!J||Z&&J[Z]===void 0)return;let Y={...J};if(!Z)j0.delete($);else{let Q={...J};if(delete Q[Z],!Q.codex&&!Q.claude)j0.delete($);else j0.set($,Q)}try{k8()}catch(Q){throw j0.set($,Y),Q}}function OV($){if(!$||typeof $!=="object")return null;let Z=$;if(!B$(Z.provider))return null;let J=typeof Z.sessionId==="string"?Z.sessionId.trim():"";if(!J)return null;let Y;if(Z.cwd===void 0||Z.cwd===null)Y=null;else if(typeof Z.cwd==="string"&&Z.cwd.trim())Y=Z.cwd;else return null;return{provider:Z.provider,sessionId:J,cwd:Y}}function RV($){if(!$||typeof $!=="object")return null;let Z=$,J=Z.source;if(!J||typeof J!=="object")return null;let Y=OV(J),Q=typeof Z.id==="string"?Z.id.trim():"";if(!Q||!Y)return null;if(Z.provider==="dsh"&&Z.kind==="event"&&Y.provider==="dsh"&&/^\d+$/.test(Q)&&Number.isSafeInteger(Number(Q)))return{provider:"dsh",kind:"event",id:Q,source:{...Y,provider:"dsh"}};if(Z.provider==="claude"&&Z.kind==="assistant-message"&&Y.provider==="claude")return{provider:"claude",kind:"assistant-message",id:Q,source:{...Y,provider:"claude"}};if(Z.provider==="codex"&&Z.kind==="turn"&&Y.provider==="codex")return{provider:"codex",kind:"turn",id:Q,source:{...Y,provider:"codex"}};return null}function NV($){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=OV(Z.source);if(!J)return null;let Y=Z.kind==="resume"?{kind:"resume",source:J}:(()=>{if(!Object.prototype.hasOwnProperty.call(Z,"through"))return{kind:"fork",source:J};let Q=RV(Z.through);return Q?{kind:"fork",source:J,through:Q}:null})();if(!Y)return null;try{_0(Y,J.provider)}catch{return null}return Y}function BL($){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 _L($,Z){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.ts!=="number"||!Number.isFinite(J.ts))return null;let Y=Object.prototype.hasOwnProperty.call(J,"checkpoint"),Q=RV(J.checkpoint);if(Y&&!Q)return null;if(!Q){if(Z!=="claude")return null;let V=typeof J.uuid==="string"?J.uuid.trim():"",H=typeof J.sid==="string"?J.sid.trim():"";if(!V||!H)return null;Q={provider:"claude",kind:"assistant-message",id:V,source:{provider:"claude",sessionId:H,cwd:null}}}return{checkpoint:Q,preview:String(J.preview??""),ts:J.ts,writes:BL(J.writes)}}function jL($){if(!$||typeof $!=="object")return null;let Z=$,J=NV(Z.launch);if(J?.kind!=="fork"||J.source.provider!=="claude"||J.source.cwd===null)return null;let Y=Z.previousSessionId,Q=Y===null?null:typeof Y==="string"&&Y.trim()?Y.trim():void 0;if(Q===void 0)return null;return{launch:{...J,source:{...J.source,provider:"claude"}},previousSessionId:Q}}function $5($){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 Z5(){try{let $=JSON.parse(S1(X7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("turns map must contain an object");e.clear();let Z=0,J=0;for(let[Y,Q]of Object.entries($)){let V,H,X=null;if(Array.isArray(Q))V=Q,H=null;else if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let B=Q;if(!Array.isArray(B.anchors)||!Object.prototype.hasOwnProperty.call(B,"base")){J++;continue}if(V=B.anchors,B.base===null)H=null;else{let _=NV(B.base);if(!_){J++;continue}H=_}if(Object.prototype.hasOwnProperty.call(B,"pendingLaunch")){let _=jL(B.pendingLaunch);if(!_){J++;continue}X=_}}else{J++;continue}let z=j0.get(Y),W=z?.claude!==void 0&&z.codex===void 0?"claude":null,G=[];for(let B of V){let _=_L(B,W);if(_)G.push(_);else J++}if(G.length||H!==null||X)e.set(Y,{base:H,anchors:G,...X?{pendingLaunch:X}:{}}),Z+=G.length}if(K(`feishu: loaded ${Z} turn anchors across ${e.size} sessions`),J>0)K(`feishu: rejected ${J} malformed turn anchors while loading`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-turns-map failed: ${$?.message??$}`)}}function p4(){let $={};for(let[Z,J]of e)$[Z]=J;s(X7,$)}function J5($,Z){let J=e.get($),Y=[...J?.anchors??[],Z],Q=J?.base??null;if(Y.length>KV){let V=Y.splice(0,Y.length-KV),H=V[V.length-1].checkpoint;Q={kind:"fork",source:H.source,through:H}}e.set($,{base:Q,anchors:Y,...J?.pendingLaunch?{pendingLaunch:J.pendingLaunch}:{}});try{p4()}catch(V){if(J)e.set($,J);else e.delete($);throw V}}function l4($){return e.get($)?.anchors??[]}function d4($){return e.get($)?.base??null}function i4($){let Z=e.get($)?.pendingLaunch;return Z?$5(Z):null}function J1($,Z){if(Z){if(Z.launch.source.cwd===null)throw Error("pending conversation launch source cwd is missing");_0(Z.launch,"claude",Z.launch.source.cwd)}let J=e.get($),Y=J?.base??null,Q=J?.anchors.slice()??[];if(!Z&&Q.length===0&&Y===null)e.delete($);else e.set($,{base:Y,anchors:Q,...Z?{pendingLaunch:$5(Z)}:{}});try{p4()}catch(V){if(J)e.set($,J);else e.delete($);throw V}}function e0($,Z,J,Y){let Q=e.get($),V=Y===void 0?Q?.pendingLaunch:Y??void 0,H=V?$5(V):void 0;if(Z.length===0&&J===null&&!H)e.delete($);else e.set($,{base:J,anchors:Z.slice(),...H?{pendingLaunch:H}:{}});try{p4()}catch(X){if(Q)e.set($,Q);else e.delete($);throw X}}function U$($){return BV.test($)?$.replace(BV,""):null}function Y5($,Z=[]){let J=new Date,Y=(X)=>String(X).padStart(2,"0"),Q=`${Y(J.getMonth()+1)}${Y(J.getDate())}-${Y(J.getHours())}${Y(J.getMinutes())}`,V=new Set([...q0.values(),...e.keys(),...Z]),H=`${$}*${Q}`;for(let X=2;V.has(H);X++)H=`${$}*${Q}-${X}`;return H}function Q5(){try{let $=JSON.parse(S1(z7,"utf8"));for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){b0.set(Z,{provider:z2(J),model:J,effort:null});continue}if(!J||typeof J!=="object")continue;let{model:Y,provider:Q}=J,V=B$(Q)?Q:typeof Y==="string"&&Y.trim()?z2(Y):"claude",H=typeof Y==="string"&&Y.trim()?Y:null;if(V==="claude"&&!H)continue;let{effort:X,tokenSourceId:z}=J,W=typeof z==="string"&&z.trim()?z.trim():null,G=V==="dsh"?B0(X)?X:null:V==="claude"?E0(X)?X:null:s0(X)?X:null;b0.set(Z,{provider:V,model:H,effort:G,...W?{tokenSourceId:W}:{}})}K(`feishu: loaded ${b0.size} session→model bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-model-map failed: ${$?.message??$}`)}}function LL(){try{y8()}catch($){K(`feishu: save session-model-map failed: ${$}`)}}function y8(){let $={};for(let[Z,J]of b0)$[Z]=J;s(z7,$)}function V5($,Z,J,Y,Q){let V=b0.get($);if(V?.provider===Z&&V.model===J&&V.effort===Y&&(V.tokenSourceId??null)===(Q??null))return;b0.set($,{provider:Z,model:J,effort:Y,...Q?{tokenSourceId:Q}:{}}),LL()}function b1($,Z,J,Y,Q){let V=b0.get($),H={provider:Z,model:J,effort:Y,...Q?{tokenSourceId:Q}:{}};if(V?.provider===Z&&V.model===J&&V.effort===Y&&(V.tokenSourceId??null)===(Q??null))return;b0.set($,H);try{y8()}catch(X){if(V)b0.set($,V);else b0.delete($);throw X}}function H5($){let Z=b0.get($);if(Z)return Z;let J=U$($);return J?b0.get(J)??null:null}function X5($){let Z=L0.get($),J=j0.get($),Y=b0.get($),Q=e.get($),V=[...u0.entries()].filter(([,H])=>H.sessionName===$);L0.delete($),j0.delete($),b0.delete($),e.delete($);for(let[H]of V)u0.delete(H);try{n3(),k8(),y8(),p4(),i3()}catch(H){if(Z)L0.set($,Z);if(J)j0.set($,J);if(Y)b0.set($,Y);if(Q)e.set($,Q);for(let[z,W]of V)u0.set(z,W);let X=[H];for(let z of[n3,k8,y8,p4,i3])try{z()}catch(W){X.push(W)}throw X.length===1?X[0]:AggregateError(X,`failed to clear and restore conversation state for ${$}`)}}function z5($){s(K7,$)}function W5(){let $;try{$=S1(K7,"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 v8($){let Z=L0.get($);if(Z){let Y=q0.get(Z);if(Y&&Y!==$)K(`feishu: chatIdForSession("${$}"): persisted binding ${Z} has cached name "${Y}", using persisted binding`);return Z}let J=[];for(let[Y,Q]of q0)if(Q===$)J.push(Y);if(J.length===1)return J[0];if(J.length>1)K(`feishu: chatIdForSession("${$}"): ${J.length} candidates with no binding — [${J.join(", ")}]`);return null}async function n4(){try{let $;do{let Z=await X0.im.chat.list({params:{page_size:100,...$?{page_token:$}:{}}});for(let J of Z.data?.items??[])if(J.chat_id&&J.name)q0.set(J.chat_id,J.name);$=Z.data?.page_token}while($);K(`feishu: refreshed chat list — ${q0.size} groups`)}catch($){K(`feishu: refresh chat list failed: ${$}`)}}async function f8(){let $=new Map,Z;do{let J=await X0.im.chat.list({params:{page_size:100,...Z?{page_token:Z}:{}}});if(J.code&&J.code!==0)throw Error(`feishu chat.list failed code=${J.code} msg=${J.msg}`);for(let Y of J.data?.items??[]){if(!Y.chat_id||!Y.name)continue;if(Y.chat_status&&Y.chat_status!=="normal")continue;q0.set(Y.chat_id,Y.name);let Q=$.get(Y.name)??[];Q.push(Y.chat_id),$.set(Y.name,Q)}Z=J.data?.page_token}while(Z);return $}async function h8($){let Z=L0.get($);if(Z&&q0.get(Z)===$){let V=await TV(Z);if(V.name===$&&EV(V.status))return Z;q0.delete(Z),C8($)}let Y=(await f8()).get($)??[];if(Y.length===0)return null;let Q=L0.get($);if(Q&&Y.includes(Q))return Q;if(Y.length===1)return Y[0];throw Error(`multiple Feishu groups named "${$}": ${Y.join(", ")}`)}async function G5($,Z){if(!Z)throw Error("missing sender open_id; cannot add user to worktree group");let J=await h8($);if(J){let V=await qL(J,Z);return S2($,J),{chatId:J,created:!1,joined:V}}let Y=await X0.im.chat.create({params:{user_id_type:"open_id",uuid:a3()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.create failed code=${Y.code} msg=${Y.msg}`);let Q=Y.data?.chat_id;if(!Q)throw Error("feishu chat.create returned no chat_id");return q0.set(Q,$),S2($,Q),{chatId:Q,created:!0,joined:!0}}async function K5($,Z){if(!Z)throw Error("missing sender open_id; cannot create temporary group");if(await h8($))throw Error(`temporary group name already exists: ${$}`);let Y=await X0.im.chat.create({params:{user_id_type:"open_id",uuid:a3()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.create failed code=${Y.code} msg=${Y.msg}`);let Q=Y.data?.chat_id;if(!Q)throw Error("feishu chat.create returned no chat_id");return q0.set(Q,$),S2($,Q),{chatId:Q,created:!0,joined:!0}}async function B5($){let Z=await h8($);if(!Z)return C8($),{chatId:null,disbanded:!1};let J=await X0.im.chat.delete({path:{chat_id:Z}});if(J.code&&J.code!==0)throw Error(`feishu chat.delete failed code=${J.code} msg=${J.msg}`);if(q0.delete(Z),L0.get($)===Z)C8($);return{chatId:Z,disbanded:!0}}async function _5($,Z){if(!Z)throw Error("cannot disband a temporary session without an exact chat_id");let J=await TV(Z);if(J.name!==$)throw Error(`refusing to delete chat ${Z}: expected name "${$}", got "${J.name??""}"`);if(!EV(J.status))throw Error(`refusing to delete chat ${Z}: status=${J.status??"unknown"}`);let Y=await X0.im.chat.delete({path:{chat_id:Z}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.delete failed code=${Y.code} msg=${Y.msg}`);return q0.delete(Z),{chatId:Z,disbanded:!0}}async function qL($,Z){let J;do{let Q=await X0.im.chatMembers.get({path:{chat_id:$},params:{member_id_type:"open_id",page_size:100,...J?{page_token:J}:{}}});if(Q.code&&Q.code!==0)throw Error(`feishu chatMembers.get failed code=${Q.code} msg=${Q.msg}`);for(let V of Q.data?.items??[])if(V.member_id===Z)return!1;J=Q.data?.page_token}while(J);let Y=await X0.im.chatMembers.create({path:{chat_id:$},params:{member_id_type:"open_id"},data:{id_list:[Z]}});if(Y.code&&Y.code!==0)throw Error(`feishu chatMembers.create failed code=${Y.code} msg=${Y.msg}`);return!0}async function j5($){try{let Z=await M$(),Y=await(await c4(`https://open.feishu.cn/open-apis/im/v1/chats/${encodeURIComponent($)}`,{headers:{Authorization:`Bearer ${Z}`}})).json();if(Y?.code!==0)return K(`feishu: fetchChatName ${$} code=${Y?.code} msg=${Y?.msg}`),null;let Q=Y.data?.name;if(typeof Q==="string"&&Q)return q0.set($,Q),K(`feishu: fetchChatName ${$} → "${Q}" (point lookup)`),Q;return K(`feishu: fetchChatName ${$} — chat has no name (unnamed group?)`),null}catch(Z){return K(`feishu: fetchChatName ${$} failed: ${Z}`),null}}async function I8($,Z,J,Y){let Q=a3();try{return await x1(`send${$} chat=${Z}`,async()=>{let V=await X0.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:Z,msg_type:J,content:Y,uuid:Q}});if(V?.code!==0)throw new F$(`send${$} code=${V?.code??"MISS"} msg=${V?.msg??"MISS"}`,void 0,V?.code);let H=V?.data?.message_id;if(typeof H!=="string"||!H.trim())throw Error(`send${$} message_id MISS`);return H})}catch{return null}}async function TV($){let Z=await X0.im.chat.get({path:{chat_id:$}});if(Z.code&&Z.code!==0)throw Error(`feishu chat.get failed code=${Z.code} msg=${Z.msg}`);return{name:Z.data?.name??null,status:Z.data?.chat_status??null}}function EV($){return $===null||$==="normal"}async function E($,Z){return D$($,()=>I8("Text",$,"text",JSON.stringify({text:Z})))}async function c($,Z){return D$($,()=>I8("Card",$,"interactive",JSON.stringify(s$(Z))))}async function L5($){let Z=await X0.im.message.list({params:{container_id_type:"chat",container_id:$,sort_type:"ByCreateTimeDesc",page_size:1}});if(Z.code!==0)throw Error(`feishu message.list failed code=${Z.code??"MISS"} msg=${Z.msg??"MISS"}`);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 A$($,Z){let J=await X0.im.v1.message.patch({path:{message_id:$},data:{content:JSON.stringify(s$(Z))}});if(J?.code&&J.code!==0)throw Error(`feishu message.patch failed code=${J.code} msg=${J.msg}`)}async function w($,Z){return D$($,()=>PL($,Z))}async function PL($,Z){try{let J=await M$(),Q=await(await c4("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})})})).json();if(Q?.code!==0)return K(`feishu: sendTextRaw rejected chat=${$} code=${Q?.code} msg=${Q?.msg}`),null;return Q.data?.message_id??null}catch(J){return K(`feishu: sendTextRaw chat=${$} failed: ${J}`),null}}async function l0($,Z){if(!$)return null;try{return(await X0.im.messageReaction.create({path:{message_id:$},data:{reaction_type:{emoji_type:Z}}}))?.data?.reaction_id??null}catch(J){return K(`feishu: addReaction ${Z} on ${$} failed: ${J}`),null}}async function C0($,Z){if(!$||!Z)return;try{await X0.im.messageReaction.delete({path:{message_id:$,reaction_id:Z}})}catch(J){K(`feishu: deleteReaction ${Z} on ${$} failed: ${J}`)}}async function C1($,Z){if(!$){K("feishu: urgentApp skip — missing messageId");return}if(Z.length===0){K(`feishu: urgentApp skip — empty openIds (msg=${$})`);return}let J=await M$(),Y=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/urgent_app?user_id_type=open_id`;try{let V=await(await c4(Y,{method:"PATCH",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({user_id_list:Z})})).json();if(V?.code!==0){K(`feishu: urgentApp ${$} code=${V?.code} msg=${V?.msg}`);return}let H=V.data?.invalid_user_id_list??[],X=Z.length-H.length;K(`feishu: urgentApp ${$} ok — delivered=${X}${H.length?` invalid=${H.length}`:""}`)}catch(Q){K(`feishu: urgentApp ${$} failed: ${Q}`)}}async function a4($,Z,J,Y){try{let Q=await M$(),V=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/resources/${Z}?type=${J}`,H=await c4(V,{headers:{Authorization:`Bearer ${Q}`}});if(!H.ok){K(`feishu: download ${J} HTTP ${H.status}: ${(await H.text()).slice(0,200)}`);return}let X=Buffer.from(await H.arrayBuffer());d3(B7,{recursive:!0});let z=Y?Y.replace(/[^a-zA-Z0-9._-]/g,"_"):`${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}.png`,W=b8(B7,`${Date.now()}-${z}`);return LV(W,X),K(`feishu: downloaded ${J} ${W} (${X.length}B)`),W}catch(Q){K(`feishu: download ${J} failed: ${Q instanceof Error?Q.message:Q}`);return}}function DL($){return FL.has(WL($).toLowerCase())}async function xV($,Z){let J=`upload${Z==="image"?"Image":"File"}`,Y;return x1(`${J} ${$}`,async()=>{if(Y??=new Blob([Uint8Array.from(await zL($))]),Y.size>g8)throw Error(`${x2($)} 超过 30 MB`);let Q=await M$(),V=new FormData;if(Z==="image")V.append("image_type","message");else V.append("file_type","stream"),V.append("file_name",x2($));V.append(Z,Y,x2($));let X=(await UV(`https://open.feishu.cn/open-apis/im/v1/${Z}s`,{method:"POST",headers:{Authorization:`Bearer ${Q}`},body:V},J)).data?.[`${Z}_key`];if(typeof X!=="string"||!X.trim())throw Error(`${J} ${Z}_key MISS`);return X})}async function q5($){try{let Z=jV($);if(!Z.isFile())return K(`feishu: uploadImageKey not a file — ${$}`),null;if(Z.size>g8)return K(`feishu: uploadImageKey oversize — ${$} (${(Z.size/1024/1024).toFixed(1)} MB)`),null}catch(Z){return K(`feishu: uploadImageKey stat failed — ${$}: ${Z}`),null}try{return await xV($,"image")}catch{return null}}async function m8($,Z){return D$($,()=>I8("Image",$,"image",JSON.stringify({image_key:Z})))}async function SV($,Z){return D$($,()=>I8("File",$,"file",JSON.stringify({file_key:Z})))}async function o4($,Z){try{let Q=jV(Z);if(!Q.isFile())return K(`feishu: uploadAndSend not a file — ${Z}`),await E($,`❌ 出站文件: 路径不是文件 — ${Z}`),!1;if(Q.size>g8)return K(`feishu: uploadAndSend oversize — ${Z} (${Q.size}B)`),await E($,`❌ 出站文件: ${x2(Z)} 超过 30 MB (${(Q.size/1024/1024).toFixed(1)} MB)`),!1}catch(Q){return K(`feishu: uploadAndSend stat failed — ${Z}: ${Q}`),await E($,`❌ 出站文件: 无法读取 ${Z} (${Q})`),!1}let J=DL(Z)?"image":"file",Y=J==="image"?"出站图片":"出站文件";try{let Q=await xV(Z,J),V=await(J==="image"?m8($,Q):SV($,Q));if(!V)return K(`feishu: uploadAndSend ${Z} send failed after upload`),await E($,`❌ ${Y}发送失败: ${x2(Z)}(上传已完成)`),!1;return K(`feishu: uploadAndSend ${Z} delivered msg=${V}`),!0}catch(Q){return K(`feishu: uploadAndSend ${Z} failed: ${Q}`),await E($,`❌ ${Y}上传失败: ${x2(Z)} — ${Q}`),!1}}function P5($){d3($,{recursive:!0}),K(`feishu: provisioned ${$}`);let Z=b8(XV(),".codex","config.toml");try{d3(b8(XV(),".codex"),{recursive:!0});let J="";try{J=S1(Z,"utf8")}catch{}let Y=`[projects.${JSON.stringify($)}]`;if(!J.includes(Y)){let Q=J.trimEnd();J=`${Q}${Q?`
|
|
109
|
+
`,(Y)=>Y?J(Y):Z())})}isAlive(){return this.alive}request($,Z,J=T3){let Y=this.nextId++;return new Promise((Q,V)=>{if(!this.alive){V(Error(`codex app-server is not alive; cannot request ${$}`));return}let H=setTimeout(()=>{if(!this.pending.delete(Y))return;V(Error(`codex app-server ${$} timed out after ${J}ms`))},J);this.pending.set(Y,{resolve:Q,reject:V,method:$,timer:H});try{this.proc.stdin.write(JSON.stringify({id:Y,method:$,params:Z})+`
|
|
110
|
+
`,(X)=>{if(!X)return;let z=this.pending.get(Y);if(!z)return;this.pending.delete(Y),clearTimeout(z.timer),z.reject(Error(`codex app-server write failed for ${$}: ${X.message}`))})}catch(X){this.pending.delete(Y),clearTimeout(H),V(X instanceof Error?X:Error(String(X)))}})}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)}}};y4=new Map,P$=new Map});import{existsSync as dj,readFileSync as ij}from"node:fs";class rQ{deps;constructor($){this.deps=$}blocks(){if(!dj(this.deps.stateFile))return[];let $=JSON.parse(ij(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.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"?U4($.usage,Z):null,Y=["fiveHour","weekly"].flatMap((X)=>{let z=J?.[X];return z?[{kind:X,percent:z.percent,reset:z.resetsAt?.getTime()??null}]:[]}),Q=d7($.usage,Z),V=JSON.stringify([$.identity,Q]),H=this.blocks().filter((X)=>X.key!==V);H.push({key:V,identity:$.identity,meter:Q,windows:Y}),s(this.deps.stateFile,{version:1,blocks:H})}async choose($){$.signal?.throwIfAborted();let Z=this.deps.accounts();if($.preferred){let J=Z.find((Y)=>Y.id===$.preferred);if(!J)throw Error(`指定 Codex 账号不存在:${$.preferred}`);return{selected:{account:J,identity:`record:${J.id}`,usage:null,state:"manual",score:null,shares:null,remaining:null,hours:null},candidates:[]}}if($.preferCachedUsage){let J=await this.chooseAutomatic(Z,$,!0);if(J.selected)return J}return this.chooseAutomatic(Z,$,!1)}async chooseAutomatic($,Z,J){Z.signal?.throwIfAborted();let Y=await Promise.all($.map(async(q)=>{let P,D=null,T=`record:${q.id}`;if(this.deps.pendingLogin(q.id))P={state:"network",reason:"正在登录"};else try{P=J?this.deps.cachedUsage(q.id):await this.deps.usage(q.id);let M=P?.state==="ok"?P.accountFingerprint??this.deps.identity(q.id):null;if(M)T=M;else if(P?.state==="ok")D="账号身份 MISS";if(P?.state==="ok"&&!D)D=await this.deps.compatible(q.id,Z.model,Z.effort)}catch(M){P={state:"network",reason:String(M)}}return{account:q,usage:P,identity:T,reason:D}}));Z.signal?.throwIfAborted();let Q=Z.failedAccountId&&Y.find((q)=>q.account.id===Z.failedAccountId);if(Q&&Q.usage?.state==="ok")this.block({account:Q.account,usage:Q.usage,identity:Q.identity,...i7(Q.usage,Z.model,this.deps.now(),Z.effort)},Z.model);let V=this.blocks(),H=this.deps.now(),X=new Set,z=new Map,W=Y.map(({account:q,usage:P,identity:D,reason:T})=>{let M=i7(P??{state:"network",reason:"尚无额度缓存"},Z.model,H,Z.effort);if(T)M={...M,state:"miss",score:null,reason:T};let A=z.get(D);if(z.set(D,A??q.name),A)M={...M,state:"miss",score:null,reason:`重复账号:${A}`};let U=P?.state==="ok"?d7(P,Z.model):null,S=V.find((b)=>(b.identity===D||b.identity===`record:${q.id}`)&&b.meter===U);if(S&&P?.state==="ok"&&M.state==="ready"){let b=U4(P,Z.model);if(!J&&S.windows.some((y)=>{let g=b[y.kind];return g&&g.percent!==null&&(y.percent!==null&&g.percent<y.percent||y.reset!==null&&y.reset<=H&&(g.resetsAt?.getTime()??0)>y.reset)}))X.add(S.key);else M={...M,state:"exhausted",score:null,reason:"上次请求已确认额度耗尽,等待接口确认恢复"}}return{account:q,usage:P,identity:D,...M,...A?{duplicateOf:A}:{}}});if(X.size)s(this.deps.stateFile,{version:1,blocks:V.filter((q)=>!X.has(q.key))});let G=W.filter((q)=>q.state==="ready");G.sort((q,P)=>P.score-q.score||(P.availableNow??0)-(q.availableNow??0)||q.account.id.localeCompare(P.account.id));let B=G[0]??null,_=W.filter((q)=>q.state==="exhausted"||q.state==="waiting"),j=_.length?Math.min(..._.map((q)=>q.retryAt??H+60000)):void 0;for(let q of W)K(`codex scheduler${J?" [cache]":""}: ${q.account.name} ${q.state} score=${q.score??"MISS"}${q.reason?` (${q.reason})`:""}`);return{selected:B,candidates:W,...j!==void 0?{retryAt:j}:{}}}}var O8;var S3=R(()=>{p0();w$();V0();Q0();T0();I();O8=new rQ({accounts:()=>k.list(),usage:E1,cachedUsage:oQ,identity:($)=>k.fingerprint($),pendingLogin:Z8,now:Date.now,stateFile:dJ,compatible:async($,Z,J)=>{let Y=H0("codex-sub",$);if(!Y)return"订阅来源 MISS";if(Y.modelCatalogState?.status!=="ready")await Y.refreshModels();if(!Y.enabled||Y.modelCatalogState?.status!=="ready")return Y.modelCatalogState?.error??"模型目录 MISS";let Q=L$(Y,Z);return!Q||Q.unavailableReason||J&&!Q.efforts.includes(J)?`${Z}/${J??"default"} 不可用`:null}})});import{EventEmitter as nj}from"node:events";function rj($,Z){return Z.throwIfAborted(),new Promise((J,Y)=>{let Q=()=>{clearTimeout(H),Z.removeEventListener("abort",V)},V=()=>{Q(),Y(Z.reason)},H=setTimeout(()=>{Q(),J()},$);Z.addEventListener("abort",V,{once:!0})})}var aj="上一轮因当前账号额度耗尽而中断,现已切换账号。请基于本会话已有记录继续完成用户尚未完成的任务,保留已完成的修改和工具结果。执行有副作用的操作前先确认现状,不要重复已完成的操作。",oj,b3=()=>({cost_usd:null,cost_delta_usd:null,duration_ms:null,num_turns:null,usage:null,subtype:null,is_error:!1}),C3;var sQ=R(()=>{p0();S3();w$();I();oj=["error","conversation_materialized","conversation_materialization_failed","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"];C3=class C3 extends nj{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??b3()}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??O8}notice($,Z=0){this.ownRetry={reason:"quota",phase:Z?"waiting":"retrying",attempt:this.retryCount,delayMs:Z,message:$},K(`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 Y=await this.scheduler().choose(J);if(delete J.failedAccountId,this.lifetime.signal.throwIfAborted(),Y.selected)return{...Y,selected:Y.selected};J.preferCachedUsage=!1;let Q=Y.candidates.map((X)=>`${X.account.name}:${X.reason??X.state}`).join(";");if(Y.retryAt===void 0){let z=Y.candidates.some((W)=>W.state==="miss"&&!W.duplicateOf)?"Codex 账号检查失败,无法自动选账号(MISS)":Y.candidates.length?"没有符合条件的 Codex 账号":"没有配置 Codex 账号";throw Error(`${z}${Q?`;${Q}`:""}`)}let V=Math.max(1000,Math.min(60000,Y.retryAt-Date.now())),H=Y.candidates.filter((X)=>X.state==="miss"&&!X.duplicateOf).length;K(`codex account: waiting for quota: ${Q}`),this.notice(`暂无可用账号 · 自动等待恢复${H?` · ${H} 个 MISS`:""}`,V),this.resolveQuotaWait(),await(this.opts.wait??rj)(V,this.lifetime.signal)}}async launch($,Z,J){this.starting=!0;let Y=await this.choose(Z,J);this.lifetime.signal.throwIfAborted();let Q=this.selected?.account.id??null,{process:V,sourceRevision:H}=this.opts.create(Y.selected.account.id,$,Y.selected.state==="manual",this.opts.model||this.lastModel||void 0,this.opts.effort??this.lastEffort??void 0);this.inner=V,this.selected=Y.selected,this.revision=H,o$(this,Y.selected.account.id,!1),this.wire(V),this.emit("codex_account_changed",{accountId:Y.selected.account.id,previousAccountId:Q,diagnostics:Y.candidates.filter((z)=>z.usage!==null&&z.state==="miss"&&!z.duplicateOf).map((z)=>`${z.account.name}:${z.reason}`)}),this.lifetime.signal.throwIfAborted(),V.sendInitialize();let X=V.initializationPromise?.();if(!X)throw Error("Codex 初始化未提供确认事务");if(await X,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($){for(let Z of oj)$.on(Z,(...J)=>{if(this.inner===$&&!this.closed){if(Z==="bg_task_started")this.backgroundTasks.add(J[0].task_id);if(Z==="bg_task_settled")this.backgroundTasks.delete(J[0].task_id);this.emit(Z,...J)}});$.on("turn_retry",(Z)=>{if(this.inner===$&&!this.closed)this.emit("turn_retry",Z)}),$.on("turn_started",(Z)=>{if(this.inner!==$||this.closed)return;this.result=null,this.ownRetry=null;let J=this.retryTurn||Z.retry;this.retryTurn=!1,this.emit("turn_started",{...Z,...J?{retry:!0}:{}})}),$.on("result",(Z)=>{if(this.inner!==$||this.closed||this.lifetime.signal.aborted)return;if(Z?.is_error&&Z.codexQuotaFailure&&!this.recovery){this.retryCount++;let J=Promise.resolve().then(()=>this.recover($,Z.codexQuotaFailure)).catch((Y)=>{if(!this.lifetime.signal.aborted)this.fail(Y)}).finally(()=>{if(this.recovery===J)this.recovery=null});this.recovery=J,this.notice(`「${this.selected?.account.name??"MISS"}」额度耗尽 · 正在换号续跑`);return}if(this.recovery)return;this.retryCount=0,this.result=null,this.emit("result",Z)}),$.on("exit",(Z)=>{if(this.inner!==$||this.closed)return;if((this.recovery||this.shutdown)&&Z.expected)return;this.lifetime.abort(Error("Codex 进程退出")),this.closed=!0,this.emit("exit",Z)})}async recover($,Z){if(this.lifetime.signal.throwIfAborted(),!this.selected)throw Error("额度耗尽时未记录运行账号");if($.readRateLimits){let X=await A8(()=>$.readRateLimits(),this.selected.account.id);if(this.lifetime.signal.throwIfAborted(),X?.state==="ok")this.selected={...this.selected,usage:X,identity:X.accountFingerprint??this.selected.identity};else this.notice("已确认额度耗尽 · 用量读取 MISS,正在换号")}let J=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 Q=$.isConversationResumable?.()===!0&&$.sessionId;if(Z.accepted&&!Q)throw Error("额度耗尽后未确认原会话落盘,不能重放已执行的任务");if(!Z.accepted&&typeof Z.rejectedInput!=="string")throw Error("额度耗尽的拒绝响应缺少原始输入");let V=Q?{kind:"resume",source:{provider:"codex",sessionId:$.sessionId,cwd:this.opts.workDir}}:this.opts.launch;if(await $.kill(),$.isAlive())throw Error("旧 Codex 进程退出未确认,不能启动下一账号");for(let X of this.backgroundTasks)this.emit("bg_task_settled",{task_id:X,status:"failed",summary:"账号额度耗尽,原进程已退出;主任务换号后继续"});this.backgroundTasks.clear(),this.lifetime.signal.throwIfAborted(),await this.launch(V,void 0,J),this.lifetime.signal.throwIfAborted(),this.retryTurn=!0,this.notice(`已切换「${this.selected.account.name}」· 继续原任务`),this.lifetime.signal.throwIfAborted();let H=Z.accepted?aj:Z.rejectedInput;this.recovery=null,this.inner.sendUserText(H),this.drainInputs()}fail($){let Z=$ instanceof Error?$:Error(String($));this.fault=Z,this.ownRetry=null,this.inputs.length=0,this.result={...b3(),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()}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={...b3(),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 v4($){if($.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexAccountPreference!==void 0){if(!$.model&&!$.codexAccountPreference)throw Error("Codex 自动选号需要明确模型");return{process:new C3({model:$.model??"",effort:$.effort,preferred:$.codexAccountPreference,workDir:$.workDir,launch:$.launch??{kind:"fresh"},create:(B,_,j,q,P)=>v4({...$,model:q,effort:P,codexAccountPreference:void 0,codexManualAccount:j,codexAccountId:B,launch:_})}),sourceRevision:null}}let Z=$.codexAccountId??u,J=H0($.tokenSourceId,Z),Y=$.provider==="codex"&&$.tokenSourceId==="codex-sub"&&$.codexManualAccount===!0;if($.tokenSourceId&&!J)throw Error(`token source not found: ${$.tokenSourceId}`);if(J&&!J.enabled&&!Y)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(!Y&&J?.modelCatalogState?.status==="failed")throw Error(`model catalog refresh failed for ${J.id}: ${J.modelCatalogState.error??"MISS"}`);if(!Y&&(J?.modelCatalogState?.status==="idle"||J?.modelCatalogState?.status==="loading"))throw Error(`model catalog is not ready for ${J.id}: ${J.modelCatalogState.status}`);let Q=$.model||J?.defaultModel||void 0,V=F2(J,Q),H=!Y&&J&&L$(J,Q);if(!Y&&J&&Q&&!H)throw Error(`model is not present in token source ${J.id}: ${Q}`);if(!Y&&H&&(H.unavailableReason||!H.efforts.length||$.effort!==void 0&&!H.efforts.includes($.effort)))throw Error(`model effort unavailable: ${J.id}/${Q}/${$.effort??"MISS"}`);let X=!Y&&J&&Q?J.resolveSpawnModel(Q):Q;if(Q&&!X)throw Error(`model did not resolve: ${$.tokenSourceId??"default"}/${Q}`);let z=J?(G)=>J.spawnEnv(G,X):void 0;if($.provider==="dsh"){if(!J||!X||!B0($.effort))throw Error("DSH requires a configured source, model and valid effort");return{process:new j3({...$,model:X,effort:$.effort,tokenSourceId:J.id,transformEnv:z}),sourceRevision:V}}if($.provider==="claude"){if(U3(),!E0($.effort))throw Error(`invalid Claude effort: ${$.effort??"MISS"}`);return{process:new L8({workDir:$.workDir,model:X,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}:{},...$.allowDelegation===!1?{allowDelegation:!1}:{},...$.profile?{profile:$.profile}:{},...J?{settingSources:J.settingSources??["project","local"]}:{},...$.managedSkillPluginPath?{managedSkillPluginPath:$.managedSkillPluginPath}:{},tokenSourceId:J?.id??null,transformEnv:z,hostEnv:$.hostEnv}),sourceRevision:V}}if($.effort!==void 0&&!s0($.effort))throw Error(`invalid Codex effort: ${$.effort}`);let W=new _2({workDir:$.workDir,model:X,effort:$.effort,launch:$.launch,...$.developerInstructions?{appendSystemPrompt:$.developerInstructions}:{},...$.allowDelegation===!1?{allowDelegation:!1}:{},tokenSourceId:J?.id??null,transformEnv:z,hostEnv:$.hostEnv,serviceName:$.serviceName,codexAccountId:Z});return o$(W,Z),{process:W,sourceRevision:V}}var k3=R(()=>{D0();UQ();x4();O1();V0();p0();sQ()});function R8($,Z){return`http://${$==="0.0.0.0"?"127.0.0.1":$==="::"||$==="::1"?"[::1]":$}:${Z}`}function R2($){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 N2($,Z){let J=Z.replace(/[&<>\\`*_\[\]~]/g,(z)=>`&#${z.charCodeAt(0)};`),Y=typeof $.used==="number"&&typeof $.total==="number"?` · ${$.used}/${$.total}`:"",Q=$.percent;if(Q===null||!Number.isFinite(Q)||Q<0||Q>100)return[{tag:"markdown",content:`**${J} · MISS${Y}**`}];let V=Math.round(Q/100*6),H=Q>=100?"red":Q>=80?"orange":"green",X=$.unreportedFull?"满窗 · 0.15 份":$.resetsAt&&Number.isFinite($.resetsAt.getTime())?`${R2($.resetsAt)} 重置`:"重置时间 MISS";return[{tag:"markdown",content:`**${J} · ${Math.round(Q)}%${Y}**
|
|
111
|
+
<font color='${H}'>${"▰".repeat(V)}${"▱".repeat(6-V)}</font>`},{tag:"markdown",content:`<font color='grey'>${X}</font>`,text_size:"notation"}]}var eQ={};E$(eQ,{codexAccountSummary:()=>f4,codexAccountPanel:()=>h4,codexAccountCard:()=>V$,CODEX_ACCOUNTS_PAGE_SIZE:()=>N8});function $1($){return $.replace(/[&<>\\`*_\[\]~]/g,(Z)=>`&#${Z.charCodeAt(0)};`)}function y3($){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 f4($){let[Z,J]=tQ[$.phase],Y=$.name&&$.name.length>40?$.name.slice(0,37)+"…":$.name;return`${Z} Codex · ${Y?`${Y} · `:""}${$.title??J}`}function V$($,Z=!1){return{schema:"2.0",config:{update_multi:!0,width_mode:"compact",streaming_mode:Z,summary:{content:f4($)}},body:{elements:[h4($)]}}}function h4($){let[,,Z]=tQ[$.phase],J=[];if($.flow==="login"&&["connecting","waiting","checking","success"].includes($.phase)){let Y=$.phase==="connecting"?0:$.phase==="waiting"?1:2;J.push(w0(["连接","授权","就绪"].map((Q,V)=>V===Y?`**${V+1} ${Q}**`:`${V<Y?"✓":V+1} ${Q}`).join(" → ")))}if($.phase==="waiting"&&$.verification){let Y=new URL($.verification.url);if(Y.protocol!=="https:"||/[\s<>]/.test($.verification.url))throw Error("授权链接无效");if(!/^[A-Za-z0-9-]{1,64}$/.test($.verification.code))throw Error("验证码格式无效");J.push(y3([[c0("验证码"),{tag:"markdown",content:`**${$.verification.code}**`,text_size:"heading-2"}],[w0(`[**打开授权页 ↗**](${Y.href.replace(/\(/g,"%28").replace(/\)/g,"%29")})`),c0("登录账号,输入左侧验证码")]]))}if($.current)J.push(y3([[c0("当前使用"),w0(`**${$1($.current)}**`)],...$.selected&&$.selected!==$.current?[[c0("下次启动"),w0(`**${$1($.selected)}**`)]]:[]]));if($.plan||$.email)J.push(w0([$.plan?.toUpperCase(),$.email].filter(Boolean).map((Y)=>$1(Y)).join(" · ")));if($.message)J.push(w0($1($.message)));if($.resetUsage){let Y=$.resetUsage;if(J.push(w0(`**重置卡** ${Y.state==="ok"&&Y.resetCredits!=null?`${Y.resetCredits} 次可用`:"MISS"}`)),Y.state==="ok"){for(let[Q,V]of[[Y.fiveHour,"5h"],[Y.weekly,"周"]])if(Q)J.push(...N2(Q,V))}else J.push(w0("⚠️ 额度 MISS · 查看详情中的查询错误"))}if($.total)J.push(...sj($));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:[w0(["`hi` · 打开控制台;未运行时启动","`hi 备注` · 本次指定账号;换号时重启并续跑","`codex-login [备注]` · 设备码登录;省略备注为默认账号","`codex-login-cancel [备注]` · 取消本人在本群的登录;仅一个任务时可省略备注","`codex-accounts [页码]` · 查看账号、额度与调度顺序","`codex-reset [备注]` · 使用一次重置卡;省略备注为当前使用账号","`codex-account` · 查看当前账号与下次启动策略","`codex-account 备注` · 持久指定账号,下次启动生效","`codex-auto` · 清除指定,下次启动自动选择","`codex-account-delete 备注` · 删除额外账号"].join(`
|
|
112
|
+
`)),c0("备注可用 default 指定设备默认账号;默认账号不可删除。")]});if($.hint)J.push(c0($.hint));if($.details)J.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查看详情"}},elements:[w0($1($.details))]});return{tag:"collapsible_panel",element_id:N.codexAccountPanel,expanded:!0,header:{title:{tag:"plain_text",content:f4($)},background_color:`${Z}-50`},border:{color:`${Z}-100`,corner_radius:"8px"},padding:"12px",elements:J}}function sj($){let Z=$.total,J=Math.max(1,Math.ceil(Z.entries.length/N8)),Y=$.page??1;if(!Number.isInteger(Y)||Y<1||Y>J)throw Error(`页码应为 1–${J}`);let Q=[c0(`${Z.entries.length} 个记录 · 可用 ${Z.available??"MISS"} 个账号${Z.complete?"":" · 汇总不完整"}`)],V=$.scheduling?.candidates.filter((H)=>H.state==="ready").sort((H,X)=>X.score-H.score||(X.availableNow??0)-(H.availableNow??0)||H.account.id.localeCompare(X.account.id));if($.scheduling)Q.push(c0(`${$.scheduling.ultra?"Ultra · Pro ≥ 0.5 份":"普通 · 周 / 5h 综合"} · 最高分优先 · 可调度 ${V.length}`));for(let H of Z.entries.slice((Y-1)*N8,Y*N8)){let X=[H.account.id===$.currentId?"使用中":"",H.account.id===$.selectedId&&$.selectedId!==$.currentId?"下次启动":""].filter(Boolean),z=H.usage,W=[];if(Q.push({tag:"collapsible_panel",expanded:!0,header:{title:{tag:"plain_text",content:`${H.account.name}${X.length?` · ${X.join(" · ")}`:""}`},background_color:H.account.id===$.currentId?"blue-50":"grey-50"},border:{color:"grey-100",corner_radius:"8px"},padding:"8px",vertical_spacing:"4px",elements:W}),H.duplicateOf){W.push(c0(`与「${H.duplicateOf}」同一账号,合计只计一次`));continue}let G=$.scheduling?.candidates.find((j)=>j.account.id===H.account.id);if(G){let j=V.findIndex((q)=>q.account.id===H.account.id);if(W.push(G.state==="ready"?w0(`**#${j+1} · ${G.score.toPrecision(3)} 份/h**`):c0(G.state==="exhausted"?"⏳ 耗尽 · 暂不参与":G.state==="excluded"?"Ultra 自动排除 Plus":G.state==="waiting"?`⏳ 周余量 ${G.remaining?.toPrecision(3)} 份 · 未达 0.5 份`:"MISS · 无法排序")),G.state==="ready"&&G.remaining!=null)W.push(c0(`周余量 ${G.remaining.toPrecision(3)} 份${G.fiveHourRemaining!=null?` · 5h ${G.fiveHourRemaining.toPrecision(3)} 份`:""}`));if(G.state==="miss"&&G.reason&&z.state==="ok")W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"未参与原因"}},elements:[w0($1(G.reason))]})}if(z.state!=="ok"){if(W.push(w0(z.state==="no_credentials"?"⚪ 未登录":"⚠️ 额度 MISS")),z.state==="network"&&z.reason)W.push({tag:"collapsible_panel",expanded:!1,header:{title:{tag:"plain_text",content:"查询错误"}},elements:[w0($1(z.reason))]});continue}let B=z.subscriptionType==="pro"?"Pro 20×":z.subscriptionType==="prolite"?"Pro 5×":z.subscriptionType==="plus"?"Plus 1×":z.subscriptionType??"套餐 MISS";W.push(c0(`${B} · 重置卡 ${z.resetCredits??"MISS"}`));let _=[[z.fiveHour,"5h"],[z.weekly,"周"]].flatMap(([j,q])=>j?[N2(j,q)]:[]);if(_.length)W.push(y3(_))}if(J>1)Q.push(c0(`${Y}/${J} 页 · ${Y<J?`下一页 codex-accounts ${Y+1}`:"首页 codex-accounts"}`));return Q}var N8=4,tQ,w0=($)=>({tag:"markdown",content:$}),c0=($)=>({tag:"markdown",content:`<font color='grey'>${$1($)}</font>`,text_size:"notation"});var T2=R(()=>{x0();tQ={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"]}});function $V($){if(!$||typeof $!=="object")return!1;let Z=$.response?.status??$.status,J=$.response?.data?.code??$.code;if(J===99991400||J===230020||J===1061045||tj.has(Z))return!0;if(typeof Z==="number"&&Z>=400)return!1;if(ej.has(J)||$.name==="TimeoutError")return!0;return $.cause!==$&&$V($.cause)}function $L($){let Z=$?.retryAfter??$?.response?.headers?.["retry-after"]??$?.response?.headers?.["x-ogw-ratelimit-reset"];if(typeof Z!=="string"||!Z.trim())return 0;let J=Number(Z),Y=Number.isFinite(J)?J*1000:Date.parse(Z)-Date.now();return Number.isFinite(Y)?Math.max(0,Y):0}async function x1($,Z){for(let J=0;;J++)try{return await Z()}catch(Y){let Q=Math.max(w3[J]??0,$L(Y)),V=$V(Y)&&J<w3.length&&Q<=60000;if(K(`feishu: ${$} attempt ${J+1}/${w3.length+1} failed: ${Y}; ${V?`retry in ${Q}ms`:"FINAL"}`),!V)throw Y;await new Promise((H)=>setTimeout(H,Q))}}async function E2($,Z){let J=await $.text(),Y=$.headers.get("retry-after")??$.headers.get("x-ogw-ratelimit-reset"),Q;try{Q=JSON.parse(J)}catch{throw new D$(`${Z} HTTP ${$.status}: invalid JSON — ${J.slice(0,200)}`,$.status,void 0,Y)}if(!$.ok||Q?.code!==0)throw new D$(`${Z} HTTP ${$.status} code=${Q?.code??"MISS"} msg=${Q?.msg??"MISS"}`,$.status,Q?.code,Y);return Q}var w3,tj,ej,D$;var T8=R(()=>{I();w3=[1000,4000],tj=new Set([408,429,500,502,503,504]),ej=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"]);D$=class D$ extends Error{status;code;retryAfter;constructor($,Z,J,Y){super($);this.status=Z;this.code=J;this.retryAfter=Y;this.name="FeishuRequestError"}}});function JL($){let Z=$?.action?.value??{},J=String(Z.kind??"");if(!J)return"无效操作";if(!ZL.has(J))return`不支持的操作: ${J}`;let Y=J==="notify_callback"||J==="notify_reply"||J==="notify_reply_cancel";if(!Y&&!String($?.context?.open_chat_id??""))return"回调缺少 chat_id,操作未执行";if(!Y&&!String($?.context?.open_message_id??""))return"回调缺少原卡 message_id,操作未执行";if(J==="permission"&&!["allow","allow_always","deny"].includes(String(Z.decision??"")))return"无效的权限决定,操作未执行";return null}class g4{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 Q=(this.tails.get(J)??Promise.resolve()).then(Z),V;return V=Q.then(()=>{},()=>{}).finally(()=>{if(this.tails.get(J)===V)this.tails.delete(J)}),this.tails.set(J,V),{accepted:!0,completion:Q}}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 ZV($){let Z=$.now??Date.now;return{accept(J){let Y=Z();return $.actor.tryEnqueue($.key(J),()=>$.execute(J,Y))}}}class f3{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 v3($){if(Array.isArray($))return`[${$.map(v3).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)}:${v3(J)}`).join(",")}}`}function YL($){let Z=$?.action?.value??{},J=String(Z?.kind??"unknown"),Y=String($?.context?.open_chat_id??""),Q=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`${Y}\x00${Q}\x00${J}\x00${v3(V)}`}function QL($){let Z=String($?.event_id??$?.header?.event_id??$?.event?.event_id??"");return{...Z?{deliveryKey:`event\x00${Z}`}:{},businessKey:`semantic\x00${YL($)}`,...["agent_identity_page","model_page","model_list_open","model_add","model_remove","model_custom_remove","notify_reply"].includes($?.action?.value?.kind)?{repeatable:!0}:{}}}function VL(){return new Promise(($)=>setTimeout($,0))}function I4($,Z,J){if(Z.deliveryKey)$.complete(Z.deliveryKey);if(J&&!Z.repeatable)$.complete(Z.businessKey);else $.fail(Z.businessKey)}function JV($){let Z=$.afterAck??VL,J=(Q)=>{try{$.onBackgroundError?.(Q)}catch{}},Y=async(Q)=>{try{await Q()}catch(V){J(V)}};return{accept(Q){if(!$.actor.isAccepting())return $.responses.closed(Q);let V=JL(Q);if(V)return $.responses.invalid(Q,V);let H=QL(Q),X=H.deliveryKey?[H.deliveryKey,H.businessKey]:[H.businessKey],z=$.deduper.claimAll(X);if(z==="inflight")return $.responses.inflight(Q);if(z==="completed")return $.responses.completed(Q);let W=$.actor.tryEnqueue($.scope(Q),async()=>{try{await Z()}catch(_){$.deduper.failAll(X),J(_);return}let G;try{G=await $.execute(Q)}catch(_){I4($.deduper,H,!0),await Y(()=>$.presentExecutionFailure(Q,_));return}await Y(async()=>{try{await $.present(Q,G)}catch(_){await $.presentPresentationFailure(Q,_)}});let B;try{B=$.completion(Q,G)}catch(_){I4($.deduper,H,!1),J(_);return}if(B){let _=B.then((j)=>{I4($.deduper,H,j==="complete")},(j)=>{I4($.deduper,H,!1),J(j)});$.track(_);return}I4($.deduper,H,$.businessSucceeded(Q,G))});if(!W.accepted)return $.deduper.failAll(X),$.responses.closed(Q);return $.track(W.completion),W.completion.catch(J),$.responses.accepted(Q)}}}var ZL;var h3=R(()=>{ZL=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 HL}from"node:async_hooks";class YV{actor=new g4;context=new HL;run($,Z){let J=this.context.getStore();if(J?.active&&J.chatId===$)return Z();return this.actor.enqueue($,async()=>{let Y={chatId:$,active:!0};try{return await this.context.run(Y,Z)}finally{Y.active=!1}})}}function F$($,Z){return XL.run($,Z)}var XL;var I3=R(()=>{h3();XL=new YV});async function g3($){let Z=await c3("feishu chat.get",()=>X0.im.chat.get({path:{chat_id:$},params:{user_id_type:"open_id"}}));if(Z.code&&Z.code!==0)E8("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 m3($,Z){let J=await c3("feishu tasklist.create",()=>X0.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)E8("feishu tasklist.create",J);let Y=J.data?.tasklist,Q=Y?.guid;if(!Q)throw Error("feishu tasklist.create returned no guid");return{guid:Q,name:Y?.name||$,url:Y?.url??"",createdAt:Y?.created_at}}async function p3($){let Z=await c3("feishu tasklist.delete",()=>X0.task.v2.tasklist.delete({path:{tasklist_guid:$}}));if(Z.code&&Z.code!==0)E8("feishu tasklist.delete",Z)}function QV($,Z){let J=Z&&typeof Z==="object"?Z:{},Y=J.response?.data&&typeof J.response.data==="object"?J.response.data:J.data&&typeof J.data==="object"?J.data:J,Q=Y.code??J.code,V=Y.msg??Y.message??J.msg??J.message??"unknown error",H=Y.error?.permission_violations??Y.permission_violations??J.error?.permission_violations,X=Array.isArray(H)?H.map((z)=>z?.scope??z?.subject??z?.name??z).filter(Boolean).join(", "):"";return`${$} failed code=${Q??"unknown"} msg=${V}${X?` missing_scopes=${X}`:""}`}async function c3($,Z){try{return await Z()}catch(J){E8($,J)}}function E8($,Z){throw Error(QV($,Z))}var VV=R(()=>{t()});var Y0={};E$(Y0,{writeAliveMarker:()=>X5,urgentApp:()=>C1,uploadImageKey:()=>L5,uploadAndSend:()=>o4,updateCard:()=>A$,unbindSessionChat:()=>b8,tempProjectName:()=>U$,tempChatName:()=>J5,setPendingConversationLaunchChecked:()=>J1,sendTextRaw:()=>w,sendText:()=>E,sendImage:()=>g8,sendFile:()=>xV,sendCard:()=>c,sanitizeSessionName:()=>P5,resolveProjectDir:()=>y8,replaceTurnAnchors:()=>e0,registerTempSessionLease:()=>o3,refreshChatList:()=>n4,readAliveMarker:()=>z5,provisionProject:()=>q5,projectProfile:()=>b2,preferredChatForSession:()=>L0,loadTempSessionLeases:()=>a3,loadSessionTurnsMap:()=>$5,loadSessionResumeMap:()=>t3,loadSessionModelMap:()=>Y5,loadSessionChatMap:()=>s3,listNormalChatIdsByName:()=>v8,isOpenAIChatGPTAuthenticated:()=>r4,hasTempSessionLease:()=>r3,getTurnAnchors:()=>l4,getTenantToken:()=>M$,getSessionResumeRef:()=>Z1,getSessionModelSelection:()=>V5,getSessionBranchBase:()=>d4,getPendingConversationLaunch:()=>i4,getChatTailMessageId:()=>j5,formatFeishuApiError:()=>QV,findNormalChatIdByName:()=>f8,fetchChatOwnerOpenId:()=>g3,fetchChatName:()=>_5,ensureChatForSession:()=>W5,downloadAttachment:()=>a4,disbandChatForSessionExact:()=>B5,disbandChatForSession:()=>K5,deleteTasklistByGuid:()=>p3,deleteReaction:()=>C0,createTempChatForSession:()=>G5,createTasklistWithOwner:()=>m3,client:()=>X0,clearSessionResumeChecked:()=>C2,clearSessionConversationState:()=>H5,chatNameCache:()=>q0,chatIdForSession:()=>w8,bindSessionToChat:()=>S2,bindSessionResumeChecked:()=>u4,bindSessionModelChecked:()=>b1,bindSessionModel:()=>Q5,appendTurnAnchorChecked:()=>Z5,addReaction:()=>l0,PROJECTS_ROOT:()=>DV,MAX_UPLOAD_BYTES:()=>I8});import*as BV from"@larksuiteoapi/node-sdk";import{execSync as zL}from"node:child_process";import{randomUUID as n3}from"node:crypto";import{mkdirSync as l3,readFileSync as S1,statSync as _V,writeFileSync as jV}from"node:fs";import{readFile as WL}from"node:fs/promises";import{homedir as HV}from"node:os";import{basename as x2,extname as GL,isAbsolute as LV,join as S8}from"node:path";import{sync as KL}from"cross-spawn";function d3(){let $={};for(let[Z,J]of u0)$[Z]=J;s(z7,$)}function a3(){u0.clear();try{let $=JSON.parse(S1(z7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("lease file must contain an object");for(let[Z,J]of Object.entries($)){let Y=J;if(typeof Z!=="string"||!Z||Y.chatId!==Z||typeof Y.sessionName!=="string"||!U$(Y.sessionName)||typeof Y.createdAt!=="number"||!Number.isFinite(Y.createdAt)){K(`feishu: rejected malformed temp-session lease chat=${Z}`);continue}u0.set(Z,{chatId:Z,sessionName:Y.sessionName,createdAt:Y.createdAt})}K(`feishu: loaded ${u0.size} temporary-session leases`)}catch($){if($?.code!=="ENOENT")K(`feishu: load temp-session leases failed: ${$?.message??$}`)}}function o3($,Z){if(!U$($))throw Error(`refusing to lease non-temporary session name "${$}"`);if(!Z)throw Error("cannot lease a temporary session without chat_id");for(let Q of u0.values())if(Q.sessionName===$&&Q.chatId!==Z)throw Error(`temporary session name "${$}" is already leased to ${Q.chatId}`);let J=u0.get(Z),Y={sessionName:$,chatId:Z,createdAt:Date.now()};u0.set(Z,Y);try{d3()}catch(Q){if(J)u0.set(Z,J);else u0.delete(Z);throw Q}}function r3($,Z){let J=u0.get(Z);return J?.sessionName===$&&J.chatId===Z}function b2($){return f.projects[$]}function y8($){return b2($)?.cwd?.trim()||S8(DV,$)}function c4($,Z={}){return $0($,{...Z,signal:Z.signal??AbortSignal.timeout(FV)})}async function MV($,Z,J){let Y=Z.signal??AbortSignal.timeout(FV);try{return await E2(await c4($,{...Z,signal:Y}),J)}catch(Q){if(Y.aborted&&Y.reason?.name==="TimeoutError")throw Y.reason;throw Q}}async function M$(){if(x8&&Date.now()<XV)return x8;return u3??=(async()=>{let $=await MV("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:qV,app_secret:PV})},"tenant token");if(typeof $.tenant_access_token!=="string"||!$.tenant_access_token.trim())throw Error("feishu: tenant token MISS");return x8=$.tenant_access_token,XV=Date.now()+Math.max(0,($.expire??7200)-60)*1000,x8})().finally(()=>{u3=null}),u3}function s3(){try{let $=JSON.parse(S1(Q7,"utf8"));for(let[Z,J]of Object.entries($))if(typeof J==="string")L0.set(Z,J);K(`feishu: loaded ${L0.size} session→chat bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-chat-map failed: ${$?.message??$}`)}}function UV(){try{i3()}catch($){K(`feishu: save session-chat-map failed: ${$}`)}}function i3(){let $={};for(let[Z,J]of L0)$[Z]=J;s(Q7,$)}function S2($,Z){if(L0.get($)===Z)return;let J=L0.get($);L0.set($,Z),UV(),K(`feishu: bound session "${$}" → ${Z}${J?` (was ${J})`:""}`)}function b8($){let Z=L0.get($);if(!Z)return;L0.delete($),UV(),K(`feishu: unbound session "${$}" from ${Z}`)}function m4($,Z){let J=j0.get($)??{};J[Z.provider]=Z,j0.set($,J)}function zV($,Z){if(!$||typeof $!=="object"||Array.isArray($))return null;let J=$,Y=B$(J.provider)?J.provider:Z??null;if(!Y||Z&&Y!==Z)return null;let Q=typeof J.sessionId==="string"?J.sessionId.trim():typeof J.session_id==="string"?J.session_id.trim():"";if(!Q)return null;if(J.cwd===void 0||J.cwd===null)return{provider:Y,sessionId:Q,cwd:null};if(typeof J.cwd!=="string"||!LV(J.cwd))return null;return{provider:Y,sessionId:Q,cwd:J.cwd}}function WV($){let Z=$.sessionId.trim();if(!Z)throw Error("cannot bind an empty conversation session id");if(!B$($.provider))throw Error(`cannot bind an unknown conversation provider: ${String($.provider)}`);if(typeof $.cwd!=="string"||!LV($.cwd))throw Error(`cannot bind a conversation without an absolute cwd: ${String($.cwd)}`);return{provider:$.provider,sessionId:Z,cwd:$.cwd}}function BL($,Z,J){if(typeof $!=="string")return WV($);if(!Z)throw Error("cannot bind a conversation without a provider");return WV({provider:Z,sessionId:$,cwd:J??null})}function t3(){try{let $=JSON.parse(S1(V7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("resume map must contain an object");j0.clear();for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){m4(Z,{provider:"codex",sessionId:J.trim(),cwd:null});continue}if(!J||typeof J!=="object"||Array.isArray(J))continue;let Y=J,Q=zV(Y);if(Q){m4(Z,Q);continue}for(let V of S7){let H=Y[V];if(typeof H==="string"&&H.trim()){m4(Z,{provider:V,sessionId:H.trim(),cwd:null});continue}let X=zV(H,V);if(X)m4(Z,X)}}K(`feishu: loaded ${j0.size} session→resume bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-resume-map failed: ${$?.message??$}`)}}function C8(){let $={};for(let[Z,J]of j0){let Y={};if(J.codex)Y.codex={...J.codex};if(J.claude)Y.claude={...J.claude};if(J.dsh)Y.dsh={...J.dsh};$[Z]=Y}s(V7,$)}function u4($,Z,J,Y){let Q=BL(Z,J,Y),V=j0.get($),H=V?{...V}:void 0,X=V?.[Q.provider];if(X?.sessionId===Q.sessionId&&X.cwd===Q.cwd)return;m4($,Q);try{C8()}catch(z){if(H)j0.set($,H);else j0.delete($);throw z}}function Z1($,Z="codex"){let J=j0.get($)?.[Z];return J?{...J}:null}function C2($,Z){let J=j0.get($);if(!J||Z&&J[Z]===void 0)return;let Y={...J};if(!Z)j0.delete($);else{let Q={...J};if(delete Q[Z],!Q.codex&&!Q.claude)j0.delete($);else j0.set($,Q)}try{C8()}catch(Q){throw j0.set($,Y),Q}}function AV($){if(!$||typeof $!=="object")return null;let Z=$;if(!B$(Z.provider))return null;let J=typeof Z.sessionId==="string"?Z.sessionId.trim():"";if(!J)return null;let Y;if(Z.cwd===void 0||Z.cwd===null)Y=null;else if(typeof Z.cwd==="string"&&Z.cwd.trim())Y=Z.cwd;else return null;return{provider:Z.provider,sessionId:J,cwd:Y}}function OV($){if(!$||typeof $!=="object")return null;let Z=$,J=Z.source;if(!J||typeof J!=="object")return null;let Y=AV(J),Q=typeof Z.id==="string"?Z.id.trim():"";if(!Q||!Y)return null;if(Z.provider==="dsh"&&Z.kind==="event"&&Y.provider==="dsh"&&/^\d+$/.test(Q)&&Number.isSafeInteger(Number(Q)))return{provider:"dsh",kind:"event",id:Q,source:{...Y,provider:"dsh"}};if(Z.provider==="claude"&&Z.kind==="assistant-message"&&Y.provider==="claude")return{provider:"claude",kind:"assistant-message",id:Q,source:{...Y,provider:"claude"}};if(Z.provider==="codex"&&Z.kind==="turn"&&Y.provider==="codex")return{provider:"codex",kind:"turn",id:Q,source:{...Y,provider:"codex"}};return null}function RV($){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=AV(Z.source);if(!J)return null;let Y=Z.kind==="resume"?{kind:"resume",source:J}:(()=>{if(!Object.prototype.hasOwnProperty.call(Z,"through"))return{kind:"fork",source:J};let Q=OV(Z.through);return Q?{kind:"fork",source:J,through:Q}:null})();if(!Y)return null;try{_0(Y,J.provider)}catch{return null}return Y}function _L($){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 jL($,Z){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.ts!=="number"||!Number.isFinite(J.ts))return null;let Y=Object.prototype.hasOwnProperty.call(J,"checkpoint"),Q=OV(J.checkpoint);if(Y&&!Q)return null;if(!Q){if(Z!=="claude")return null;let V=typeof J.uuid==="string"?J.uuid.trim():"",H=typeof J.sid==="string"?J.sid.trim():"";if(!V||!H)return null;Q={provider:"claude",kind:"assistant-message",id:V,source:{provider:"claude",sessionId:H,cwd:null}}}return{checkpoint:Q,preview:String(J.preview??""),ts:J.ts,writes:_L(J.writes)}}function LL($){if(!$||typeof $!=="object")return null;let Z=$,J=RV(Z.launch);if(J?.kind!=="fork"||J.source.provider!=="claude"||J.source.cwd===null)return null;let Y=Z.previousSessionId,Q=Y===null?null:typeof Y==="string"&&Y.trim()?Y.trim():void 0;if(Q===void 0)return null;return{launch:{...J,source:{...J.source,provider:"claude"}},previousSessionId:Q}}function e3($){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 $5(){try{let $=JSON.parse(S1(H7,"utf8"));if(!$||typeof $!=="object"||Array.isArray($))throw Error("turns map must contain an object");e.clear();let Z=0,J=0;for(let[Y,Q]of Object.entries($)){let V,H,X=null;if(Array.isArray(Q))V=Q,H=null;else if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let B=Q;if(!Array.isArray(B.anchors)||!Object.prototype.hasOwnProperty.call(B,"base")){J++;continue}if(V=B.anchors,B.base===null)H=null;else{let _=RV(B.base);if(!_){J++;continue}H=_}if(Object.prototype.hasOwnProperty.call(B,"pendingLaunch")){let _=LL(B.pendingLaunch);if(!_){J++;continue}X=_}}else{J++;continue}let z=j0.get(Y),W=z?.claude!==void 0&&z.codex===void 0?"claude":null,G=[];for(let B of V){let _=jL(B,W);if(_)G.push(_);else J++}if(G.length||H!==null||X)e.set(Y,{base:H,anchors:G,...X?{pendingLaunch:X}:{}}),Z+=G.length}if(K(`feishu: loaded ${Z} turn anchors across ${e.size} sessions`),J>0)K(`feishu: rejected ${J} malformed turn anchors while loading`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-turns-map failed: ${$?.message??$}`)}}function p4(){let $={};for(let[Z,J]of e)$[Z]=J;s(H7,$)}function Z5($,Z){let J=e.get($),Y=[...J?.anchors??[],Z],Q=J?.base??null;if(Y.length>GV){let V=Y.splice(0,Y.length-GV),H=V[V.length-1].checkpoint;Q={kind:"fork",source:H.source,through:H}}e.set($,{base:Q,anchors:Y,...J?.pendingLaunch?{pendingLaunch:J.pendingLaunch}:{}});try{p4()}catch(V){if(J)e.set($,J);else e.delete($);throw V}}function l4($){return e.get($)?.anchors??[]}function d4($){return e.get($)?.base??null}function i4($){let Z=e.get($)?.pendingLaunch;return Z?e3(Z):null}function J1($,Z){if(Z){if(Z.launch.source.cwd===null)throw Error("pending conversation launch source cwd is missing");_0(Z.launch,"claude",Z.launch.source.cwd)}let J=e.get($),Y=J?.base??null,Q=J?.anchors.slice()??[];if(!Z&&Q.length===0&&Y===null)e.delete($);else e.set($,{base:Y,anchors:Q,...Z?{pendingLaunch:e3(Z)}:{}});try{p4()}catch(V){if(J)e.set($,J);else e.delete($);throw V}}function e0($,Z,J,Y){let Q=e.get($),V=Y===void 0?Q?.pendingLaunch:Y??void 0,H=V?e3(V):void 0;if(Z.length===0&&J===null&&!H)e.delete($);else e.set($,{base:J,anchors:Z.slice(),...H?{pendingLaunch:H}:{}});try{p4()}catch(X){if(Q)e.set($,Q);else e.delete($);throw X}}function U$($){return KV.test($)?$.replace(KV,""):null}function J5($,Z=[]){let J=new Date,Y=(X)=>String(X).padStart(2,"0"),Q=`${Y(J.getMonth()+1)}${Y(J.getDate())}-${Y(J.getHours())}${Y(J.getMinutes())}`,V=new Set([...q0.values(),...e.keys(),...Z]),H=`${$}*${Q}`;for(let X=2;V.has(H);X++)H=`${$}*${Q}-${X}`;return H}function Y5(){try{let $=JSON.parse(S1(X7,"utf8"));for(let[Z,J]of Object.entries($)){if(typeof J==="string"&&J.trim()){b0.set(Z,{provider:z2(J),model:J,effort:null});continue}if(!J||typeof J!=="object")continue;let{model:Y,provider:Q}=J,V=B$(Q)?Q:typeof Y==="string"&&Y.trim()?z2(Y):"claude",H=typeof Y==="string"&&Y.trim()?Y:null;if(V==="claude"&&!H)continue;let{effort:X,tokenSourceId:z}=J,W=typeof z==="string"&&z.trim()?z.trim():null,G=V==="dsh"?B0(X)?X:null:V==="claude"?E0(X)?X:null:s0(X)?X:null;b0.set(Z,{provider:V,model:H,effort:G,...W?{tokenSourceId:W}:{}})}K(`feishu: loaded ${b0.size} session→model bindings`)}catch($){if($?.code!=="ENOENT")K(`feishu: load session-model-map failed: ${$?.message??$}`)}}function qL(){try{k8()}catch($){K(`feishu: save session-model-map failed: ${$}`)}}function k8(){let $={};for(let[Z,J]of b0)$[Z]=J;s(X7,$)}function Q5($,Z,J,Y,Q){let V=b0.get($);if(V?.provider===Z&&V.model===J&&V.effort===Y&&(V.tokenSourceId??null)===(Q??null))return;b0.set($,{provider:Z,model:J,effort:Y,...Q?{tokenSourceId:Q}:{}}),qL()}function b1($,Z,J,Y,Q){let V=b0.get($),H={provider:Z,model:J,effort:Y,...Q?{tokenSourceId:Q}:{}};if(V?.provider===Z&&V.model===J&&V.effort===Y&&(V.tokenSourceId??null)===(Q??null))return;b0.set($,H);try{k8()}catch(X){if(V)b0.set($,V);else b0.delete($);throw X}}function V5($){let Z=b0.get($);if(Z)return Z;let J=U$($);return J?b0.get(J)??null:null}function H5($){let Z=L0.get($),J=j0.get($),Y=b0.get($),Q=e.get($),V=[...u0.entries()].filter(([,H])=>H.sessionName===$);L0.delete($),j0.delete($),b0.delete($),e.delete($);for(let[H]of V)u0.delete(H);try{i3(),C8(),k8(),p4(),d3()}catch(H){if(Z)L0.set($,Z);if(J)j0.set($,J);if(Y)b0.set($,Y);if(Q)e.set($,Q);for(let[z,W]of V)u0.set(z,W);let X=[H];for(let z of[i3,C8,k8,p4,d3])try{z()}catch(W){X.push(W)}throw X.length===1?X[0]:AggregateError(X,`failed to clear and restore conversation state for ${$}`)}}function X5($){s(G7,$)}function z5(){let $;try{$=S1(G7,"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 w8($){let Z=L0.get($);if(Z){let Y=q0.get(Z);if(Y&&Y!==$)K(`feishu: chatIdForSession("${$}"): persisted binding ${Z} has cached name "${Y}", using persisted binding`);return Z}let J=[];for(let[Y,Q]of q0)if(Q===$)J.push(Y);if(J.length===1)return J[0];if(J.length>1)K(`feishu: chatIdForSession("${$}"): ${J.length} candidates with no binding — [${J.join(", ")}]`);return null}async function n4(){try{let $;do{let Z=await X0.im.chat.list({params:{page_size:100,...$?{page_token:$}:{}}});for(let J of Z.data?.items??[])if(J.chat_id&&J.name)q0.set(J.chat_id,J.name);$=Z.data?.page_token}while($);K(`feishu: refreshed chat list — ${q0.size} groups`)}catch($){K(`feishu: refresh chat list failed: ${$}`)}}async function v8(){let $=new Map,Z;do{let J=await X0.im.chat.list({params:{page_size:100,...Z?{page_token:Z}:{}}});if(J.code&&J.code!==0)throw Error(`feishu chat.list failed code=${J.code} msg=${J.msg}`);for(let Y of J.data?.items??[]){if(!Y.chat_id||!Y.name)continue;if(Y.chat_status&&Y.chat_status!=="normal")continue;q0.set(Y.chat_id,Y.name);let Q=$.get(Y.name)??[];Q.push(Y.chat_id),$.set(Y.name,Q)}Z=J.data?.page_token}while(Z);return $}async function f8($){let Z=L0.get($);if(Z&&q0.get(Z)===$){let V=await NV(Z);if(V.name===$&&TV(V.status))return Z;q0.delete(Z),b8($)}let Y=(await v8()).get($)??[];if(Y.length===0)return null;let Q=L0.get($);if(Q&&Y.includes(Q))return Q;if(Y.length===1)return Y[0];throw Error(`multiple Feishu groups named "${$}": ${Y.join(", ")}`)}async function W5($,Z){if(!Z)throw Error("missing sender open_id; cannot add user to worktree group");let J=await f8($);if(J){let V=await PL(J,Z);return S2($,J),{chatId:J,created:!1,joined:V}}let Y=await X0.im.chat.create({params:{user_id_type:"open_id",uuid:n3()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.create failed code=${Y.code} msg=${Y.msg}`);let Q=Y.data?.chat_id;if(!Q)throw Error("feishu chat.create returned no chat_id");return q0.set(Q,$),S2($,Q),{chatId:Q,created:!0,joined:!0}}async function G5($,Z){if(!Z)throw Error("missing sender open_id; cannot create temporary group");if(await f8($))throw Error(`temporary group name already exists: ${$}`);let Y=await X0.im.chat.create({params:{user_id_type:"open_id",uuid:n3()},data:{name:$,user_id_list:[Z],group_message_type:"chat"}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.create failed code=${Y.code} msg=${Y.msg}`);let Q=Y.data?.chat_id;if(!Q)throw Error("feishu chat.create returned no chat_id");return q0.set(Q,$),S2($,Q),{chatId:Q,created:!0,joined:!0}}async function K5($){let Z=await f8($);if(!Z)return b8($),{chatId:null,disbanded:!1};let J=await X0.im.chat.delete({path:{chat_id:Z}});if(J.code&&J.code!==0)throw Error(`feishu chat.delete failed code=${J.code} msg=${J.msg}`);if(q0.delete(Z),L0.get($)===Z)b8($);return{chatId:Z,disbanded:!0}}async function B5($,Z){if(!Z)throw Error("cannot disband a temporary session without an exact chat_id");let J=await NV(Z);if(J.name!==$)throw Error(`refusing to delete chat ${Z}: expected name "${$}", got "${J.name??""}"`);if(!TV(J.status))throw Error(`refusing to delete chat ${Z}: status=${J.status??"unknown"}`);let Y=await X0.im.chat.delete({path:{chat_id:Z}});if(Y.code&&Y.code!==0)throw Error(`feishu chat.delete failed code=${Y.code} msg=${Y.msg}`);return q0.delete(Z),{chatId:Z,disbanded:!0}}async function PL($,Z){let J;do{let Q=await X0.im.chatMembers.get({path:{chat_id:$},params:{member_id_type:"open_id",page_size:100,...J?{page_token:J}:{}}});if(Q.code&&Q.code!==0)throw Error(`feishu chatMembers.get failed code=${Q.code} msg=${Q.msg}`);for(let V of Q.data?.items??[])if(V.member_id===Z)return!1;J=Q.data?.page_token}while(J);let Y=await X0.im.chatMembers.create({path:{chat_id:$},params:{member_id_type:"open_id"},data:{id_list:[Z]}});if(Y.code&&Y.code!==0)throw Error(`feishu chatMembers.create failed code=${Y.code} msg=${Y.msg}`);return!0}async function _5($){try{let Z=await M$(),Y=await(await c4(`https://open.feishu.cn/open-apis/im/v1/chats/${encodeURIComponent($)}`,{headers:{Authorization:`Bearer ${Z}`}})).json();if(Y?.code!==0)return K(`feishu: fetchChatName ${$} code=${Y?.code} msg=${Y?.msg}`),null;let Q=Y.data?.name;if(typeof Q==="string"&&Q)return q0.set($,Q),K(`feishu: fetchChatName ${$} → "${Q}" (point lookup)`),Q;return K(`feishu: fetchChatName ${$} — chat has no name (unnamed group?)`),null}catch(Z){return K(`feishu: fetchChatName ${$} failed: ${Z}`),null}}async function h8($,Z,J,Y){let Q=n3();try{return await x1(`send${$} chat=${Z}`,async()=>{let V=await X0.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:Z,msg_type:J,content:Y,uuid:Q}});if(V?.code!==0)throw new D$(`send${$} code=${V?.code??"MISS"} msg=${V?.msg??"MISS"}`,void 0,V?.code);let H=V?.data?.message_id;if(typeof H!=="string"||!H.trim())throw Error(`send${$} message_id MISS`);return H})}catch{return null}}async function NV($){let Z=await X0.im.chat.get({path:{chat_id:$}});if(Z.code&&Z.code!==0)throw Error(`feishu chat.get failed code=${Z.code} msg=${Z.msg}`);return{name:Z.data?.name??null,status:Z.data?.chat_status??null}}function TV($){return $===null||$==="normal"}async function E($,Z){return F$($,()=>h8("Text",$,"text",JSON.stringify({text:Z})))}async function c($,Z){return F$($,()=>h8("Card",$,"interactive",JSON.stringify(s$(Z))))}async function j5($){let Z=await X0.im.message.list({params:{container_id_type:"chat",container_id:$,sort_type:"ByCreateTimeDesc",page_size:1}});if(Z.code!==0)throw Error(`feishu message.list failed code=${Z.code??"MISS"} msg=${Z.msg??"MISS"}`);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 A$($,Z){let J=await X0.im.v1.message.patch({path:{message_id:$},data:{content:JSON.stringify(s$(Z))}});if(J?.code&&J.code!==0)throw Error(`feishu message.patch failed code=${J.code} msg=${J.msg}`)}async function w($,Z){return F$($,()=>DL($,Z))}async function DL($,Z){try{let J=await M$(),Q=await(await c4("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})})})).json();if(Q?.code!==0)return K(`feishu: sendTextRaw rejected chat=${$} code=${Q?.code} msg=${Q?.msg}`),null;return Q.data?.message_id??null}catch(J){return K(`feishu: sendTextRaw chat=${$} failed: ${J}`),null}}async function l0($,Z){if(!$)return null;try{return(await X0.im.messageReaction.create({path:{message_id:$},data:{reaction_type:{emoji_type:Z}}}))?.data?.reaction_id??null}catch(J){return K(`feishu: addReaction ${Z} on ${$} failed: ${J}`),null}}async function C0($,Z){if(!$||!Z)return;try{await X0.im.messageReaction.delete({path:{message_id:$,reaction_id:Z}})}catch(J){K(`feishu: deleteReaction ${Z} on ${$} failed: ${J}`)}}async function C1($,Z){if(!$){K("feishu: urgentApp skip — missing messageId");return}if(Z.length===0){K(`feishu: urgentApp skip — empty openIds (msg=${$})`);return}let J=await M$(),Y=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/urgent_app?user_id_type=open_id`;try{let V=await(await c4(Y,{method:"PATCH",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"},body:JSON.stringify({user_id_list:Z})})).json();if(V?.code!==0){K(`feishu: urgentApp ${$} code=${V?.code} msg=${V?.msg}`);return}let H=V.data?.invalid_user_id_list??[],X=Z.length-H.length;K(`feishu: urgentApp ${$} ok — delivered=${X}${H.length?` invalid=${H.length}`:""}`)}catch(Q){K(`feishu: urgentApp ${$} failed: ${Q}`)}}async function a4($,Z,J,Y){try{let Q=await M$(),V=`https://open.feishu.cn/open-apis/im/v1/messages/${$}/resources/${Z}?type=${J}`,H=await c4(V,{headers:{Authorization:`Bearer ${Q}`}});if(!H.ok){K(`feishu: download ${J} HTTP ${H.status}: ${(await H.text()).slice(0,200)}`);return}let X=Buffer.from(await H.arrayBuffer());l3(K7,{recursive:!0});let z=Y?Y.replace(/[^a-zA-Z0-9._-]/g,"_"):`${Z.replace(/[^a-zA-Z0-9_-]/g,"_")}.png`,W=S8(K7,`${Date.now()}-${z}`);return jV(W,X),K(`feishu: downloaded ${J} ${W} (${X.length}B)`),W}catch(Q){K(`feishu: download ${J} failed: ${Q instanceof Error?Q.message:Q}`);return}}function ML($){return FL.has(GL($).toLowerCase())}async function EV($,Z){let J=`upload${Z==="image"?"Image":"File"}`,Y;return x1(`${J} ${$}`,async()=>{if(Y??=new Blob([Uint8Array.from(await WL($))]),Y.size>I8)throw Error(`${x2($)} 超过 30 MB`);let Q=await M$(),V=new FormData;if(Z==="image")V.append("image_type","message");else V.append("file_type","stream"),V.append("file_name",x2($));V.append(Z,Y,x2($));let X=(await MV(`https://open.feishu.cn/open-apis/im/v1/${Z}s`,{method:"POST",headers:{Authorization:`Bearer ${Q}`},body:V},J)).data?.[`${Z}_key`];if(typeof X!=="string"||!X.trim())throw Error(`${J} ${Z}_key MISS`);return X})}async function L5($){try{let Z=_V($);if(!Z.isFile())return K(`feishu: uploadImageKey not a file — ${$}`),null;if(Z.size>I8)return K(`feishu: uploadImageKey oversize — ${$} (${(Z.size/1024/1024).toFixed(1)} MB)`),null}catch(Z){return K(`feishu: uploadImageKey stat failed — ${$}: ${Z}`),null}try{return await EV($,"image")}catch{return null}}async function g8($,Z){return F$($,()=>h8("Image",$,"image",JSON.stringify({image_key:Z})))}async function xV($,Z){return F$($,()=>h8("File",$,"file",JSON.stringify({file_key:Z})))}async function o4($,Z){try{let Q=_V(Z);if(!Q.isFile())return K(`feishu: uploadAndSend not a file — ${Z}`),await E($,`❌ 出站文件: 路径不是文件 — ${Z}`),!1;if(Q.size>I8)return K(`feishu: uploadAndSend oversize — ${Z} (${Q.size}B)`),await E($,`❌ 出站文件: ${x2(Z)} 超过 30 MB (${(Q.size/1024/1024).toFixed(1)} MB)`),!1}catch(Q){return K(`feishu: uploadAndSend stat failed — ${Z}: ${Q}`),await E($,`❌ 出站文件: 无法读取 ${Z} (${Q})`),!1}let J=ML(Z)?"image":"file",Y=J==="image"?"出站图片":"出站文件";try{let Q=await EV(Z,J),V=await(J==="image"?g8($,Q):xV($,Q));if(!V)return K(`feishu: uploadAndSend ${Z} send failed after upload`),await E($,`❌ ${Y}发送失败: ${x2(Z)}(上传已完成)`),!1;return K(`feishu: uploadAndSend ${Z} delivered msg=${V}`),!0}catch(Q){return K(`feishu: uploadAndSend ${Z} failed: ${Q}`),await E($,`❌ ${Y}上传失败: ${x2(Z)} — ${Q}`),!1}}function q5($){l3($,{recursive:!0}),K(`feishu: provisioned ${$}`);let Z=S8(HV(),".codex","config.toml");try{l3(S8(HV(),".codex"),{recursive:!0});let J="";try{J=S1(Z,"utf8")}catch{}let Y=`[projects.${JSON.stringify($)}]`;if(!J.includes(Y)){let Q=J.trimEnd();J=`${Q}${Q?`
|
|
113
113
|
|
|
114
114
|
`:""}${Y}
|
|
115
115
|
trust_level = "trusted"
|
|
116
|
-
`,
|
|
117
|
-
${Z.stderr}`)}function
|
|
118
|
-
`)).digest("hex")}async function y1($,Z,J){let Y=J?JSON.stringify({...J,..."sequence"in J?{uuid:
|
|
119
|
-
${Y}`}]}]}}function
|
|
120
|
-
群:${w2($.settings?.folder?.name??$.groupName)}`},...$.notice?[{tag:"markdown",content:w2($.notice)}]:[],...$.error?[{tag:"markdown",content:`<font color='red'>${w2($.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?.folder?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:
|
|
121
|
-
`)}]}}function
|
|
122
|
-
`)}function
|
|
123
|
-
`)}]}}function
|
|
124
|
-
`)});continue}if(H===J){if(V.push({tag:"markdown",content:`**\uD83E\uDD14 ${z}**`}),X.options.length>0)V.push(...
|
|
125
|
-
*— 由 ${B} 回答*`})}else if(X!==void 0&&J[X])G=`${Y} 等你确认 · ${X+1}/${V}`,W.push(...
|
|
116
|
+
`,jV(Z,J)}}catch(J){K(`feishu: codex trust write failed for ${$}: ${J}`)}try{zL("git init -q",{cwd:$,stdio:"ignore"})}catch{}}function r4($=u){let Z=KL(A4(),["login","status",...k.cliArgs($)],{timeout:1e4,shell:!1,encoding:"utf8",env:k.env($,{...process.env,...f.codex.env})});if(Z.error)K(`codex login status failed: ${Z.error.message}`);return Z.status===0&&/Logged in using ChatGPT/i.test(`${Z.stdout}
|
|
117
|
+
${Z.stderr}`)}function P5($){return $.replace(/[^\w一-鿿\-\[\]\*]/g,"_").slice(0,64)}var qV,PV,DV,u0,X0,FV=15000,x8="",XV=0,u3=null,q0,L0,j0,e,GV=200,KV,b0,I8=31457280,FL;var t=R(()=>{h0();T8();I3();D0();y0();O1();D0();Q0();I();p0();T0();x0();A1();VV();qV=f.feishu.app_id,PV=f.feishu.app_secret,DV=f.runtime.projects_root,u0=new Map;X0=new BV.Client({appId:qV,appSecret:PV,disableTokenCache:!1});q0=new Map,L0=new Map;j0=new Map;e=new Map;KV=/\*[0-9]{4}-[0-9]{4}(-[0-9]+)?$/;b0=new Map;FL=new Set([".png",".jpg",".jpeg",".gif",".bmp",".webp"])});import{createHash as SV,randomUUID as UL}from"node:crypto";function s4($,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 bV($,Z){if($!==300315)return!1;return/(?:duplicate\s+(?:element\s*)?id|code\s*1001\s*:\s*duplicate id)/i.test(Z?.message??"")}function X$($){let Z=H$.get($);if(!Z)throw Error(`cardkit card is not registered: ${$}`);return Z}function $$($){return!H$.has($)}function d0($,Z,J){H$.set($,{sequence:0,queue:Promise.resolve(),elementCount:Z,contentFingerprints:new Map,deadElements:new Set,failedAdds:new Map,failedReplacements:new Set,onFailure:J,closing:!1})}function t4($){return H$.get($)?.elementCount??0}function CV($){let Z=H$.get($);return Z?[...Z.contentFingerprints.keys()].filter((J)=>!Z.deadElements.has(J)):[]}function k2($,Z){return H$.get($)?.deadElements.has(Z)??!1}function kV($,Z){let J=H$.get($);J?.deadElements.delete(Z),J?.failedAdds.delete(Z),J?.failedReplacements.delete(Z)}function e4($){let Z=X$($);return Z.sequence+=1,Z.sequence}function D5($,Z){$.deadElements.add(Z)}function yV($){return SV("sha256").update(JSON.stringify($,(Z,J)=>Z==="element_id"?void 0:J)).digest("hex")}function TL($,Z,J){let Y=[...$.contentFingerprints].filter(([Q])=>Q!==Z).map(([,Q])=>Q);if(J&&Z!==N.footer)Y.push(J);return SV("sha256").update(Y.sort().join(`
|
|
118
|
+
`)).digest("hex")}async function y1($,Z,J){let Y=J?JSON.stringify({...J,..."sequence"in J?{uuid:UL()}:{}}):void 0,Q=`cardkit ${$} ${Z}`;return x1(Q,async()=>{let V=await M$(),H=AbortSignal.timeout(OL),X;try{return X=await $0(`${AL}${Z}`,{method:$,headers:{Authorization:`Bearer ${V}`,"Content-Type":"application/json"},...Y!==void 0?{body:Y}:{},signal:H}),(await E2(X,Q))?.data}catch(z){if(H.aborted&&H.reason?.name==="TimeoutError")throw H.reason;if(X&&z instanceof D$){let W=X.headers.get("x-tt-logid")??X.headers.get("x-request-id")??X.headers.get("request-id")??void 0;if(Object.assign(z,{httpStatus:X.status,logId:W}),W)z.message+=` log_id=${W}`}throw z}})}function EL($){return new Promise((Z)=>setTimeout(Z,$))}function xL($){if(typeof $!=="object"||$===null)return!1;let Z=$.code;return Z===300309||Z===200850}async function SL($){let Z=e4($);await y1("PATCH",`/cards/${$}/settings`,{settings:JSON.stringify({config:{streaming_mode:!0}}),sequence:Z})}async function m8($,Z,J,Y,Q=!1,V={}){let H=(X)=>{let z=typeof X==="object"&&X!==null?X:null,W={cardId:$,operation:Z,elementId:V.elementId,targetElementId:V.targetElementId,code:z?.code,httpStatus:z?.httpStatus,logId:z?.logId,message:X instanceof Error?X.message:String(X)};if(s4(W.code,W))W.capacityFingerprint=TL(X$($),V.elementId,V.contentFingerprint);try{if(!Q)X$($).onFailure?.(W.code,W)}catch(G){K(`cardkit failure callback ${$}: ${G}`)}try{Y?.(W)}catch(G){K(`cardkit per-call failure callback ${$}: ${G}`)}};try{await J();return}catch(X){if(!xL(X)){K(`cardkit ${Z} ${$}: ${X}`),H(X);return}K(`cardkit ${Z} ${$}: streaming closed (code=${X.code}) — reopening`)}try{await SL($)}catch(X){K(`cardkit STREAMING_REOPEN_FAILED ${$}: ${X}`),H(X);return}try{await J()}catch(X){K(`cardkit ${Z} ${$} retry-after-reopen: ${X}`),H(X)}}function bL($){return typeof $==="object"&&$!==null&&$.code===200740}async function Z$($,Z={}){let J=Z.retryDelaysMs?.length?Z.retryDelaysMs:RL,Y=null;for(let Q=0;Q<J.length;Q++){let V=J[Q]??0;if(V>0)await EL(V);try{let H=await y1("POST","/cards/id_convert",{message_id:$});if(typeof H?.card_id!=="string"||!H.card_id)throw Error("cardkit POST /cards/id_convert: missing card_id");return H.card_id}catch(H){if(Y=H,!bL(H)||Q===J.length-1)throw H;let X=J[Q+1]??0;K(`cardkit id_convert ${$}: empty result, retry ${Q+2}/${J.length} in ${X}ms`)}}throw Y}async function O$($){let Z=H$.get($);if(!Z)return;await Z.queue}function F0($,Z,J={},Y){if($$($))return Promise.resolve();let Q=X$($);if(Q.closing)return Promise.resolve();let V=s$(Z),H=V.element_id,X=yV(V),z=()=>{if(!H)return;D5(Q,H),Q.failedAdds.set(H,J)};return Q.queue=Q.queue.then(()=>m8($,"addElement",async()=>{let W=e4($);if(await y1("POST",`/cards/${$}/elements`,{type:J.type??"append",...J.targetElementId?{target_element_id:J.targetElementId}:{},elements:JSON.stringify([V]),sequence:W}),Q.elementCount+=1,H!==N.footer)Q.contentFingerprints.set(H??`#${W}`,X);if(H)Q.deadElements.delete(H),Q.failedAdds.delete(H),Q.failedReplacements.delete(H)},(W)=>{z(),Y?.(W.code,W)},!1,{elementId:H,targetElementId:J.targetElementId,contentFingerprint:X})),Q.queue}function J0($,Z,J,Y,Q=!0){if($$($))return Promise.resolve();let V=X$($);if(V.closing)return Promise.resolve();let H=s$(J),X=yV(H),z=()=>{D5(V,Z),V.failedReplacements.add(Z)};return V.queue=V.queue.then(()=>m8($,`replaceElement ${Z}`,async()=>{let W=V.failedAdds.get(Z);if(V.deadElements.has(Z)&&!W&&!V.failedReplacements.has(Z))return;let G=e4($);if(W)await y1("POST",`/cards/${$}/elements`,{type:W.type??"append",...W.targetElementId?{target_element_id:W.targetElementId}:{},elements:JSON.stringify([H]),sequence:G}),V.elementCount++;else await y1("PUT",`/cards/${$}/elements/${Z}`,{element:JSON.stringify(H),sequence:G});if(V.deadElements.delete(Z),V.failedAdds.delete(Z),V.failedReplacements.delete(Z),Z!==N.footer)V.contentFingerprints.set(Z,X)},(W)=>{if(Q)z();Y?.(W.code,W)},!Q,{elementId:Z,contentFingerprint:X})),V.queue}async function M0($,Z,J,Y={}){if($$($))return!1;let Q=X$($);if(Q.closing)return!1;let V=!1;return await J0($,Z,J,()=>{V=!0},Y.notifyCardFailure!==!1),!V&&!Q.deadElements.has(Z)}async function wV($,Z,J){if($$($))return{landed:!1};let Y=X$($);if(Y.closing)return{landed:!1};let Q;return await J0($,Z,J,(V,H)=>{Q=H}),{landed:!Q&&!Y.deadElements.has(Z),...Q?{failure:Q}:{}}}async function Y1($,Z,J={}){return(await y2($,Z,J)).landed}async function y2($,Z,J={}){if($$($))return{landed:!1};let Y=X$($);if(Y.closing)return{landed:!1};let Q=Z.element_id,V;return await F0($,Z,J,(H,X)=>{V=X}),{landed:!V&&!(Q&&Y.deadElements.has(Q)),...V?{failure:V}:{}}}function CL($,Z,J){if($$($))return Promise.resolve();let Y=X$($);if(Y.closing)return Promise.resolve();let Q=()=>Y.deadElements.has(Z)&&!Y.failedAdds.has(Z)&&!Y.failedReplacements.has(Z);if(Q())return Promise.resolve();return Y.queue=Y.queue.then(()=>m8($,`deleteElement ${Z}`,async()=>{if(Q())return;let V=e4($);await y1("DELETE",`/cards/${$}/elements/${Z}`,{sequence:V}),Y.elementCount=Math.max(0,Y.elementCount-1),Y.contentFingerprints.delete(Z),Y.failedAdds.delete(Z),Y.failedReplacements.delete(Z),D5(Y,Z)},(V)=>J?.(V.code,V),!0,{elementId:Z})),Y.queue}async function vV($,Z){if($$($))return!1;let J=X$($);if(J.closing)return!1;if(J.deadElements.has(Z)&&!J.failedAdds.has(Z)&&!J.failedReplacements.has(Z))return!0;let Y=!1;return await CL($,Z,()=>{Y=!0}),!Y&&J.deadElements.has(Z)}function w1($,Z){if($$($)||H$.get($)?.closing)return;let J=(Z??"").replace(/\s+/g," ").trim();if(!J)return;let Y=k1.get($);if(!Y)Y={latest:J,lastSent:"",timer:null},k1.set($,Y);else Y.latest=J;if(Y.timer)return;Y.timer=setTimeout(()=>{let Q=k1.get($);if(!Q)return;if($$($)){k1.delete($);return}if(Q.timer=null,Q.latest===Q.lastSent)return;let V=Q.latest;P0($,{config:{summary:{content:V}}}).then((H)=>{let X=k1.get($);if(H&&X===Q)X.lastSent=V})},NL)}function A0($){let Z=k1.get($);if(!Z)return;if(Z.timer)clearTimeout(Z.timer),Z.timer=null;k1.delete($)}function p8($,Z){return P0($,Z).then(()=>{})}async function P0($,Z){if($$($))return!1;let J=X$($);if(J.closing)return!1;let Y=!1,Q=!1;return J.queue=J.queue.then(()=>m8($,"patchSettings",async()=>{if($$($))return;let V=e4($);await y1("PATCH",`/cards/${$}/settings`,{settings:JSON.stringify(Z),sequence:V}),Y=!0},()=>{Q=!0},!0)),await J.queue,Y&&!Q&&!$$($)}async function v0($){let Z=H$.get($);if(!Z){A0($);return}if(Z.closing){await Z.queue;return}Z.closing=!0,A0($),await Z.queue,H$.delete($)}var AL="https://open.feishu.cn/open-apis/cardkit/v1",OL=15000,RL,H$,k1,NL=1500;var v$=R(()=>{h0();t();T8();I();x0();RL=[0,250,750,1500];H$=new Map,k1=new Map});function fV($){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 w2($){return $.replace(/[&<>\[\]()*_`!\\#|~]/g,(Z)=>`&#${Z.charCodeAt(0)};`).replace(/[\r\n]+/g," ")}function F5($){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 yL($){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 wL($){let Z=w2($.name),J=$.status==="ready"&&$.file?.url?`[${Z}](${F5($.file.url)})`:Z,Y=$.status==="failed"?`<font color='red'>${w2($.error??"交付失败")}</font>`:`<font color='grey'>${fV($.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:yL($.name)}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[{tag:"markdown",content:`${J}
|
|
119
|
+
${Y}`}]}]}}function M5($){let Z=$.files.filter((z)=>z.status==="ready").length,J=$.files.filter((z)=>z.status==="failed").length,Y=`${Z} 个文件${J?` · ${J} 个未完成`:""}`,Q=$.folderAccessReady&&$.folder?F5($.folder.url):void 0,V=[...$.files.filter((z)=>z.status==="failed"),...$.files.filter((z)=>z.status!=="failed")],H=V.slice(0,kL),X=V.slice(H.length).filter((z)=>z.status==="failed").length;return{schema:"2.0",config:{update_multi:!0,width_mode:"default",summary:{content:`交付文件 · ${Y}`}},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:`**本次交付 · ${Y}**`},{tag:"column_set",element_id:N.fileDeliveryList,flex_mode:"none",background_style:"grey-50",columns:[{tag:"column",width:"weighted",weight:1,padding:"12px",vertical_spacing:"12px",elements:[...H.map(wL),...$.files.length>H.length?[{tag:"markdown",content:`<font color='grey'>其余 ${$.files.length-H.length} 个文件${X?`中有 ${X} 个未完成,原因已单独提示;已上传文件`:""}请打开文件夹查看</font>`}]:[]]}]},...$.error?[{tag:"markdown",content:`<font color='red'>${w2($.error)}</font>`}]:[],...Q?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:Q}]},{tag:"markdown",content:"<font color='grey'>卡片仅列本轮文件;管理入口查看本群全部云空间交付文件,可重命名、移动或删除。</font>",text_size:"notation"}]:[]]}}}function U5($){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}**
|
|
120
|
+
群:${w2($.settings?.folder?.name??$.groupName)}`},...$.notice?[{tag:"markdown",content:w2($.notice)}]:[],...$.error?[{tag:"markdown",content:`<font color='red'>${w2($.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?.folder?[{tag:"button",text:{tag:"plain_text",content:"管理群文件"},type:"primary_filled",width:"fill",behaviors:[{type:"open_url",default_url:F5($.settings.folder.url)}]}]:[]]}}}var kL=12;var c8=R(()=>{x0()});function u8($){if(!$)return null;return typeof $.total_tokens==="number"&&Number.isFinite($.total_tokens)?$.total_tokens:null}function l8($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:null}function vL($,Z,J=12000){if(Z==null||Z<=0)return null;if(Z<=J)return 0;let Y=Z-J,Q=Math.max(0,$-J),V=Math.max(0,Y-Q);return Math.round(Math.min(100,Math.max(0,V/Y*100)))}function IV($,Z,J){let Y=vL($,Z,J??12000);if(Y==null)return null;return{used:Math.min(100,Math.max(0,100-Y)),remaining:Y}}function hV($){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 d8($,Z){let J=hV($);return Z!=null&&Z>0?`${J}/${hV(Z)}`:`${J}/--`}function gV($,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 O5($,Z,J){let Y=Z?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"");return`${$} · ${Y||"MISS"}/${J||"MISS"}`}function n8($){return JSON.stringify({objective:$.objective,status:$.status,tokenBudget:$.tokenBudget})}function fL($){switch($){case"pending":return"☐";case"inProgress":return"\uD83D\uDD04";case"completed":return"✅";default:return"·"}}function hL($,Z){return $.length>Z?$.slice(0,Z)+"…":$}function i8($){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 mV($){switch($){case"active":return"进行中";case"paused":return"已暂停";case"blocked":return"受阻";case"usageLimited":return"额度受限";case"budgetLimited":return"预算受限";case"complete":return"已完成";default:return $}}function cV($){let Z=$.filter((V)=>V.status==="completed").length,J=$.filter((V)=>V.status==="inProgress").length,Y=$.filter((V)=>V.status==="pending").length,Q=[`${$.length} 项`];if(J)Q.push(`${J} 进行中`);if(Z)Q.push(`${Z} 完成`);if(Y)Q.push(`${Y} 待办`);return Q.join(" · ")}function IL($,Z=""){let J=Z.trim();if($.length===0)return J?"\uD83D\uDCCB 计划草稿":"\uD83D\uDCCB 计划更新";return`\uD83D\uDCCB 计划更新 · ${cV($)}`}function A5($){return typeof $==="number"&&Number.isFinite($)?$:null}function gL($){let Z=A5($.startedAtMs),J=A5($.completedAtMs);if(Z==null||J==null||J<Z)return"";return` · 耗时 ${G0((J-Z)/1000)}`}function mL($){let Z=A5($);return Z==null?null:i8(Z)}function pL($,Z){if(!Z)return["压缩中..."];let J=[],Y=typeof $.trigger==="string"&&$.trigger.trim()?$.trigger.trim():"",Q=mL($.preTokens),V=typeof $.sourceType==="string"&&$.sourceType.trim()?$.sourceType.trim():"";if(Y)J.push(`**触发**: ${Y}`);if(Q)J.push(`**压缩前**: ${Q} tokens`);if(V)J.push(`**来源**: ${V}`);return J.length>0?J:["压缩完成,无摘要内容"]}function R5($,Z,J){if($==null||!Number.isFinite($))return null;let Y=IV($,Z,J);return Y?`${Y.used}% · ${d8($,Z)}`:"--"}function N5($){let Z=i8($?.input_tokens??Number.NaN),J=i8($?.cache_read_input_tokens??Number.NaN),Y=i8($?.output_tokens??Number.NaN);return`└ 入 ${Z} | 缓 ${J} | 出 ${Y}`}function $9($,Z,J){let Y=Z&&typeof Z==="object"?Z:{},Q=Y.phase==="end"||Y.phase==="event",V=Q?"✅":"⏳",H=Q?gL(Y):"",X=`${V} \uD83D\uDEA8 上下文压缩 #${$+1}${H}`,z=pL(Y,Q);return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:X}},expanded:!1,elements:[{tag:"markdown",content:z.join(`
|
|
121
|
+
`)}]}}function uV($,Z,J=""){let Y=["**\uD83D\uDCCB 当前计划**"],Q=Z?.trim();if(Q)Y.push(""),Y.push(Q);if($.length>0){Y.push("");for(let V of $)Y.push(`- ${fL(V.status)} ${V.step}`)}else{let V=J.trim();if(Y.push(""),V)Y.push("正在生成计划草稿..."),Y.push(""),Y.push(V);else Y.push("--")}return Y.join(`
|
|
122
|
+
`)}function T5($,Z,J="",Y){return{tag:"collapsible_panel",element_id:Y,header:{title:{tag:"plain_text",content:IL($,J)}},expanded:!1,elements:[{tag:"markdown",content:uV($,Z,J)}]}}function Z9($,Z,J){let Y=$.length>0?`\uD83D\uDCCB 当前计划 · ${cV($)}`:"\uD83D\uDCCB 当前计划";return{tag:"collapsible_panel",element_id:J,header:{title:{tag:"plain_text",content:Y}},expanded:!0,elements:[{tag:"markdown",content:uV($,Z)}]}}function E5($,Z){let J=Number.isFinite($.tokensUsed)?String($.tokensUsed):"MISS",Y=$.tokenBudget==null?"":Number.isFinite($.tokenBudget)?` / ${$.tokenBudget}`:" / MISS",Q=[`**\uD83C\uDFAF 当前目标** · ${mV($.status)}`,"",$.objective,"",`- 用量: ${J}${Y} tokens`,`- 用时: ${G0($.timeUsedSeconds)}`];return{tag:"collapsible_panel",element_id:Z,header:{title:{tag:"plain_text",content:`\uD83C\uDFAF 目标更新 · ${mV($.status)}: ${hL($.objective,48)}`}},expanded:!1,elements:[{tag:"markdown",content:Q.join(`
|
|
123
|
+
`)}]}}function a8($){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}`}]:[],Y=$.userInputs??[],Q=`\uD83D\uDCE5 收到 (${Y.length}) ${$.directStart?"\uD83D\uDE80":`#${$.turn}`}`,V=Y.length>0?[{tag:"collapsible_panel",element_id:N.userInput,header:{title:{tag:"plain_text",content:Q}},expanded:!1,elements:Y.map((H)=>({tag:"markdown",content:Z0(H)}))}]:[];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:N.footer,content:$.initialFooter??"Waiting...(0s)"}]}}}function lV($,Z,J){let Y=$.question.trim()||`问题 ${Z+1}`;return`${Z+1}/${J} · ${Y}`}function cL($,Z){if(!Z)return"?";return Z.customText??(Z.optionIdx!==void 0?$.options[Z.optionIdx]?.label:void 0)??"?"}function uL($,Z,J){let Y=[];for(let Q=0;Q<$.options.length;Q++){let V=$.options[Q],H=V.description?` · ${Z0(V.description)}`:"";Y.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:Q}}],elements:[{tag:"markdown",content:`**${Z0(V.label)}**${H}`}]})}return Y}function pV($,Z,J,Y){if($.length===0)return null;let Q=$.length,V=[];for(let H=0;H<$.length;H++){let X=$[H];if(!X)continue;let z=lV(X,H,Q),W=Y.get(H);if(W){let G=cL(X,W),B=[`**✅ ${z}**`,`**回答**:${G}`];V.push({tag:"markdown",content:B.join(`
|
|
124
|
+
`)});continue}if(H===J){if(V.push({tag:"markdown",content:`**\uD83E\uDD14 ${z}**`}),X.options.length>0)V.push(...uL(X,Z,H));V.push({tag:"markdown",content:"_\uD83D\uDCAC 也可以直接在群里回复你的答案(裸词命令 `hi`/`stop`/`kill`/`restart`/`clear`/`model` 仍然优先)_"});continue}V.push({tag:"markdown",content:`**⏳ ${z}**`})}return V}function v2($,Z,J,Y="\uD83E\uDD14",Q){let V=J.length,H=Q?.answered??new Map,X=Q?.currentIdx,z=X===void 0&&H.size>0,W=[],G;if(Q?.waitingFor)G=Q.waitingFor==="notification"?"⏳ 等待通知回复完成":"⏳ 提问排队中",W.push({tag:"markdown",content:Q.waitingFor==="notification"?"请先完成或取消通知回复,再回答这个问题。":"先回答当前问题,再显示这个提问。"});else if(z){G=`${Y} 已回答 · ${V}/${V}`,W.push(...pV(J,Z,X,H)??[]);let B=[...H.values()].reverse().find((_)=>_.user)?.user;if(B)W.push({tag:"markdown",content:`
|
|
125
|
+
*— 由 ${B} 回答*`})}else if(X!==void 0&&J[X])G=`${Y} 等你确认 · ${X+1}/${V}`,W.push(...pV(J,Z,X,H)??[]);else if(G=`${Y} 等你确认`,J[0])W.push({tag:"markdown",content:`**${lV(J[0],0,V||1)}**`});return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:G}},expanded:!z&&!Q?.waitingFor,elements:W}}var dV=R(()=>{x0()});import{isAbsolute as x5,relative as lL}from"node:path";function r8($){return $==="Bash"||$==="exec_command"||$.endsWith(".exec_command")}function s8($){return $==="write_stdin"||$.endsWith(".write_stdin")}function iL($){return r8($)||s8($)}function t8($){return $==="FileChange"||$==="fileChange"}function Y9($){return $==="WebSearch"||$==="webSearch"}function e8($){return $==="WebFetch"||$==="webFetch"}function w5($){return $==="MCP"}function Q9($){return $==="ImageGeneration"||$==="imageGeneration"}function v5($){return $==="Agent"||$==="Task"}function $6($){return $==="Read"}function Z6($){return $==="Write"}function J6($){return $==="Edit"||$==="NotebookEdit"}function Y6($){return $==="MultiEdit"}function f5($){return $==="Glob"||$==="Grep"||$==="LS"}function Q6($){return $==="TodoWrite"}function V6($){return $==="ExitPlanMode"}function H6($){return $.startsWith(nV)}function aV($){return H6($)?$.slice(nV.length):$}function f1($){if(H6($))return"服务端工具";if(t8($))return"文件变更";if(Y9($))return"网页搜索";if(e8($))return"网页读取";if(Q9($))return"图片生成";if($6($))return"读取文件";if(Z6($))return"写入文件";if(J6($)||Y6($))return"编辑文件";if($==="Glob")return"匹配文件";if($==="Grep")return"搜索文件";if($==="LS")return"列目录";if(Q6($))return"更新待办";if(V6($))return"确认计划";if($==="Task")return"子任务";return iL($)?"Bash":$}function Q1($,Z){let J=(Y,Q)=>Y.length>Q?Y.slice(0,Q)+"…":Y;if(H6($))return J(nL($,Z),80);if(!Z||typeof Z!=="object")return"";if(r8($))return aL(Z);if(s8($))return oL(Z);if(t8($))return J(tL(Z),80);if(Y9($))return J(KH(Z),80);if(e8($))return J(Vq(Z),80);if(w5($))return J(Xq(Z),80);if(Q9($))return J(Wq(Z),80);if(v5($))return J(Gq(Z),80);if($6($))return J(eL(Z),80);if(Z6($))return J($q(Z),80);if(J6($))return J(Zq(Z),80);if(Y6($))return J(Jq(Z),80);if(f5($))return J(Yq($,Z),80);if(Q6($))return J(Qq(Z),80);if(V6($))return J(V9(Z)||"提交计划",80);switch($){case"Skill":return J(String(Z.skill??""),80)}for(let Y of Object.values(Z))if(typeof Y==="string"&&Y)return J(Y,80);return""}function nL($,Z){let J=typeof Z?.tool==="string"&&Z.tool?Z.tool:aV($),Y=V9(Z?.input);return Y?`${J}: ${Y}`:J}function aL($){let Z=(V,H)=>V.length>H?V.slice(0,H)+"…":V,J=rV($);if(J.description)return Z(J.description.replace(/\s+/g," "),80);let Y=J.command;if(!Y)return"";let Q=Y.split(/\r?\n/).map((V)=>V.trim()).filter(Boolean);if(Q.length<=1)return Z(Y.replace(/\s+/g," "),80);return`Shell 脚本 · ${Q.length} 行 · ${Z(G2(Y),46)}`}function oV($){let Z=typeof $?.chars==="string"?$.chars:"";if(Z==="")return"读取会话输出";if(Z==="\x03")return"中断会话";return"发送输入"}function oL($){let Z=$?.session_id??$?.sessionId,J=Z===void 0?"":` ${Z}`;return`${oV($)}${J}`}function rV($){let Z=String($?.command??$?.cmd??$?.script??""),J=String($?.description??$?.reason??"").trim(),Y=c7(Z);return{description:Y.description||J,command:Y.command}}function i0($,Z=""){let J="```";while($.includes(J))J+="`";return`${J}${Z}
|
|
126
126
|
${$}
|
|
127
|
-
${J}`}function f$($,Z=
|
|
127
|
+
${J}`}function f$($,Z=dL,J=""){if($.length<=Z)return i0($,J);let Y=$.slice(0,Z).trimEnd();return[`_已截断: 仅显示前 ${Z} / ${$.length} 字符。_`,i0(`${Y}
|
|
128
128
|
... output 已截断 ...`,J)].join(`
|
|
129
|
-
`)}function m($){return"`"+String($??"").replace(/`/g,"'")+"`"}function J$($,Z=3000){return i0(JSON.stringify($??null,null,2).slice(0,Z),"json")}function V9($){if(!$||typeof $!=="object")return"";let Z=$;for(let J of["query","prompt","path","file_path","url","name","id"]){let Y=Z[J];if(typeof Y==="string"&&Y.length>0)return Y}for(let J of Object.values(Z))if(typeof J==="string"&&J.length>0)return J;return""}function
|
|
130
|
-
`)}function
|
|
131
|
-
`)}function
|
|
132
|
-
... diff 已截断 ...`:$}function
|
|
133
|
-
`):i0(JSON.stringify($??{},null,2).slice(0,2000))}let H=Y.map((W)=>
|
|
134
|
-
`)}function V1($){return String($?.file_path??$?.path??$?.notebook_path??"")}function
|
|
135
|
-
`):J$($??{},2000)}function
|
|
136
|
-
`):J$($??{},2000)}function
|
|
137
|
-
`):J$($??{},2000)}function
|
|
138
|
-
`)}function
|
|
139
|
-
`)}function
|
|
140
|
-
`)}function
|
|
141
|
-
`)}function
|
|
142
|
-
`)}function
|
|
129
|
+
`)}function m($){return"`"+String($??"").replace(/`/g,"'")+"`"}function J$($,Z=3000){return i0(JSON.stringify($??null,null,2).slice(0,Z),"json")}function V9($){if(!$||typeof $!=="object")return"";let Z=$;for(let J of["query","prompt","path","file_path","url","name","id"]){let Y=Z[J];if(typeof Y==="string"&&Y.length>0)return Y}for(let J of Object.values(Z))if(typeof J==="string"&&J.length>0)return J;return""}function sV($,Z,J){let Y=rV($),Q=Y.command,V=Y.description,H=[];if(V)H.push(`**目的**: ${V}`);let X=$?.cwd??$?.workdir;if(X)H.push(`**cwd**: ${m(X)}`);if($?.source)H.push(`**source**: ${m($.source)}`);if(H.length>0)H.push("");if(H.push("**命令**"),H.push(i0(Q||"(空命令)","bash")),J)H.push(""),H.push(J);if(Z!=null)H.push(""),H.push("---"),H.push("**output:**"),H.push(f$(Z));return H.join(`
|
|
130
|
+
`)}function tV($,Z,J){let Y=[],Q=$?.session_id??$?.sessionId;if(Y.push(`**操作**: ${oV($)}`),Q!==void 0)Y.push(`**session**: ${m(Q)}`);if(typeof $?.chars==="string"&&$.chars.length>0){let V=$.chars==="\x03"?"^C":$.chars;Y.push(""),Y.push("**输入**"),Y.push(i0(V))}if(J)Y.push(""),Y.push(J);if(Z!=null)Y.push(""),Y.push("---"),Y.push("**output:**"),Y.push(f$(Z));return Y.join(`
|
|
131
|
+
`)}function eV($){return Array.isArray($?.changes)?$.changes:[]}function $H($){let Z=$?.cwd??$?.grantRoot;return typeof Z==="string"&&Z.length>0?Z:void 0}function J9($,Z){let J=String($??"");if(!J)return"(无 path)";if(Z&&x5(J)&&x5(Z)){let Y=lL(Z,J);if(Y&&!Y.startsWith("..")&&!x5(Y))return Y}return J}function rL($){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 ZH($){return $?.kind?.move_path??$?.kind?.movePath??$?.move_path??$?.movePath}function b5($){let Z=rL($);if(ZH($))return Z==="update"?"移动/修改":"移动";switch(Z){case"add":return"新增";case"delete":return"删除";case"update":return"修改";default:return"变更"}}function C5($){let Z=$?.diff??$?.unified_diff;return typeof Z==="string"?Z:""}function k5($){let Z=0,J=0;for(let Y of $.split(/\r?\n/)){if(Y.startsWith("+++")||Y.startsWith("---"))continue;if(Y.startsWith("+"))Z++;if(Y.startsWith("-"))J++}return{added:Z,removed:J}}function JH($,Z){return{added:$.added+Z.added,removed:$.removed+Z.removed}}function y5($){return $.added>0||$.removed>0?`+${$.added} -${$.removed}`:""}function sL($){return $.length>1800?$.slice(0,1800)+`
|
|
132
|
+
... diff 已截断 ...`:$}function tL($){let Z=eV($),J=$H($);if(Z.length===0){let z=typeof $?.reason==="string"?$.reason.trim():"",W=$?.grantRoot?J9($.grantRoot):"";if(z&&W)return`${z} · ${W}`;return z||(W?`申请修改 ${W}`:"")}let Y=Z.map((z)=>k5(C5(z))).reduce(JH,{added:0,removed:0}),Q=y5(Y),V=[...new Set(Z.map(b5))],H=J9(Z[0]?.path,J),X=Q?` · ${Q}`:"";if(Z.length===1)return`${V[0]} ${H}${X}`;return`${Z.length} 个文件 · ${V.join("/")} · ${H} 等${X}`}function YH($,Z,J){let Y=eV($),Q=$H($),V=[];if(Y.length===0){let W=typeof $?.reason==="string"?$.reason.trim():"";if(W)V.push(`**原因**: ${W}`);if($?.grantRoot)V.push(`**范围**: ${m(J9($.grantRoot))}`);if(J)V.push(""),V.push(J);if(Z!=null)V.push(""),V.push("---"),V.push("**output:**"),V.push(i0(Z.slice(0,3000)));return V.length>0?V.join(`
|
|
133
|
+
`):i0(JSON.stringify($??{},null,2).slice(0,2000))}let H=Y.map((W)=>k5(C5(W))).reduce(JH,{added:0,removed:0}),X=y5(H);if(V.push(`**文件**: ${Y.length} 个`),X)V.push(`**行数**: ${X}`);if($?.status)V.push(`**状态**: ${m($.status)}`);let z=Y.slice(0,5);for(let W of z){let G=C5(W),B=y5(k5(G)),_=J9(W?.path,Q),j=B?`**${b5(W)}** ${m(_)} · ${B}`:`**${b5(W)}** ${m(_)}`;V.push(""),V.push(j);let q=ZH(W);if(q)V.push(`来自 ${m(J9(q,Q))}`);V.push(G?i0(sL(G),"diff"):"_无 diff 内容_")}if(Y.length>z.length)V.push(""),V.push(`还有 ${Y.length-z.length} 个文件未展开显示。`);if(J)V.push(""),V.push(J);return V.join(`
|
|
134
|
+
`)}function V1($){return String($?.file_path??$?.path??$?.notebook_path??"")}function eL($){let Z=V1($),J=[$?.offset!=null?`offset ${$.offset}`:"",$?.limit!=null?`limit ${$.limit}`:""].filter(Boolean).join(" · ");return J&&Z?`${Z} · ${J}`:Z}function $q($){let Z=V1($),J=typeof $?.content==="string"?$.content:"",Y=J?J.split(/\r?\n/).length:0;return Z&&Y?`${Z} · ${Y} 行`:Z}function Zq($){let Z=V1($),J=$?.replace_all?"全局替换":"替换";return Z?`${J} ${Z}`:J}function Jq($){let Z=V1($),J=Array.isArray($?.edits)?$.edits.length:0,Y=J?` · ${J} 处`:"";return Z?`批量编辑 ${Z}${Y}`:`批量编辑${Y}`}function Yq($,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 QH($){switch($){case"pending":return"待办";case"in_progress":return"进行中";case"completed":return"完成";default:return String($??"未知")}}function Qq($){let Z=Array.isArray($?.todos)?$.todos:[];if(Z.length===0)return"";let J=new Map;for(let Q of Z){let V=QH(Q?.status);J.set(V,(J.get(V)??0)+1)}let Y=[...J.entries()].map(([Q,V])=>`${Q} ${V}`).join(" · ");return`${Z.length} 项${Y?` · ${Y}`:""}`}function Vq($){let Z=String($?.url??""),J=typeof $?.prompt==="string"?$.prompt.trim():"";return Z&&J?`${Z} · ${J}`:Z||J}function f2($,Z){if(Z==null)return;$.push(""),$.push("---"),$.push("**结果**"),$.push(f$(Z,1200))}function VH($,Z,J){let Y=[],Q=V1($);if(Q)Y.push(`**路径**: ${m(Q)}`);if($?.offset!=null)Y.push(`**offset**: ${m($.offset)}`);if($?.limit!=null)Y.push(`**limit**: ${m($.limit)}`);if(J)Y.push(""),Y.push(J);if(Z!=null)Y.push(""),Y.push("_内容已读取,未展开到群聊卡片。_");return Y.length>0?Y.join(`
|
|
135
|
+
`):J$($??{},2000)}function HH($,Z,J){let Y=[],Q=V1($),V=typeof $?.content==="string"?$.content:"";if(Q)Y.push(`**路径**: ${m(Q)}`);if(V){let H=V.split(/\r?\n/).length;Y.push(`**内容**: ${H} 行 / ${V.length} 字符`),Y.push(f$(V,1200))}if(J)Y.push(""),Y.push(J);return f2(Y,Z),Y.length>0?Y.join(`
|
|
136
|
+
`):J$($??{},2000)}function XH($,Z,J){let Y=[],Q=V1($);if(Q)Y.push(`**路径**: ${m(Q)}`);if($?.cell_id)Y.push(`**cell**: ${m($.cell_id)}`);if($?.edit_mode)Y.push(`**模式**: ${m($.edit_mode)}`);if($?.replace_all)Y.push("**范围**: 全局替换");if(typeof $?.old_string==="string")Y.push(""),Y.push("**查找**"),Y.push(f$($.old_string,800));let V=typeof $?.new_string==="string"?$.new_string:typeof $?.new_source==="string"?$.new_source:"";if(V)Y.push(""),Y.push("**替换为**"),Y.push(f$(V,800));if(J)Y.push(""),Y.push(J);return f2(Y,Z),Y.length>0?Y.join(`
|
|
137
|
+
`):J$($??{},2000)}function zH($,Z,J){let Y=[],Q=V1($),V=Array.isArray($?.edits)?$.edits:[];if(Q)Y.push(`**路径**: ${m(Q)}`);Y.push(`**编辑**: ${V.length} 处`);for(let[H,X]of V.slice(0,5).entries()){if(Y.push(""),Y.push(`**#${H+1}${X?.replace_all?" · 全局替换":""}**`),typeof X?.old_string==="string")Y.push("查找:"),Y.push(f$(X.old_string,500));if(typeof X?.new_string==="string")Y.push("替换为:"),Y.push(f$(X.new_string,500))}if(V.length>5)Y.push(""),Y.push(`还有 ${V.length-5} 处编辑未展开显示。`);if(J)Y.push(""),Y.push(J);return f2(Y,Z),Y.join(`
|
|
138
|
+
`)}function WH($,Z,J,Y){let Q=[];if($==="Glob"){if(Q.push("**动作**: 匹配文件"),Z?.pattern)Q.push(`**pattern**: ${m(Z.pattern)}`);if(Z?.path)Q.push(`**path**: ${m(Z.path)}`)}else if($==="Grep"){if(Q.push("**动作**: 搜索文件"),Z?.pattern)Q.push(`**pattern**: ${m(Z.pattern)}`);if(Z?.path)Q.push(`**path**: ${m(Z.path)}`);if(Z?.glob)Q.push(`**glob**: ${m(Z.glob)}`);if(Z?.type)Q.push(`**type**: ${m(Z.type)}`);if(Z?.output_mode)Q.push(`**output**: ${m(Z.output_mode)}`)}else{if(Q.push("**动作**: 列目录"),Z?.path)Q.push(`**path**: ${m(Z.path)}`);if(Array.isArray(Z?.ignore)&&Z.ignore.length)Q.push(`**ignore**: ${Z.ignore.map(m).join(" ")}`)}if(Y)Q.push(""),Q.push(Y);return f2(Q,J),Q.join(`
|
|
139
|
+
`)}function GH($,Z,J){let Y=Array.isArray($?.todos)?$.todos:[],Q=[`**待办**: ${Y.length} 项`];for(let V of Y.slice(0,12)){let H=QH(V?.status),X=String(V?.content??V?.activeForm??"").trim()||"(空)";Q.push(`- ${H}: ${X}`)}if(Y.length>12)Q.push(`- 还有 ${Y.length-12} 项未显示`);if(J)Q.push(""),Q.push(J);return f2(Q,Z),Q.join(`
|
|
140
|
+
`)}function h5($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function I5($,Z){return h5(Z)??$?.action??{}}function g5($,Z){let J=I5($,Z),Y=Array.isArray(J?.queries)?J.queries.filter((V)=>typeof V==="string"&&V.length>0):[],Q=typeof J?.query==="string"&&J.query.length>0?J.query:typeof $?.query==="string"&&$.query.length>0?$.query:"";return Y.length>0?Y:Q?[Q]:[]}function m5($,Z){let J=I5($,Z);return String(J?.url??$?.url??"")}function KH($){let Z=g5($,null);if(Z.length===1)return Z[0];if(Z.length>1)return`${Z.length} 条查询 · ${Z[0]}`;let J=m5($,null);if(J)return J;let Y=$?.action?.type;return typeof Y==="string"&&Y!=="other"?Y:""}function Hq($,Z){let J=g5($,Z);if(J.length===1)return J[0];if(J.length>1)return`${J.length} 条查询 · ${J[0]}`;let Y=m5($,Z);if(Y)return Y;return KH($)}function BH($,Z,J){let Y=I5($,Z),Q=g5($,Z),V=m5($,Z),H=[],X=typeof Y?.type==="string"?Y.type:"";if(X==="search"||Q.length>0){if(H.push("**动作**: 搜索"),Q.length>0){H.push(""),H.push("**查询**");for(let z of Q.slice(0,6))H.push(`- ${m(z)}`);if(Q.length>6)H.push(`- 还有 ${Q.length-6} 条未显示`)}}else if(X==="open_page"){if(H.push("**动作**: 打开页面"),V)H.push(`**URL**: ${m(V)}`)}else if(X==="find_in_page"){if(H.push("**动作**: 页内查找"),V)H.push(`**URL**: ${m(V)}`);if(Y?.pattern)H.push(`**关键词**: ${m(Y.pattern)}`)}else if(H.push(`**动作**: ${X?m(X):"网页搜索"}`),V)H.push(`**URL**: ${m(V)}`);if(J)H.push(""),H.push(J);if(H.length===1&&!Q.length&&!V&&Z!=null)H.push(""),H.push("---"),H.push("**output:**"),H.push(i0(Z.slice(0,3000),"json"));return H.join(`
|
|
141
|
+
`)}function _H($,Z,J){let Y=["**动作**: 读取网页"];if($?.url)Y.push(`**URL**: ${m($.url)}`);if($?.prompt)Y.push(""),Y.push("**问题**"),Y.push(String($.prompt).slice(0,1200));if(J)Y.push(""),Y.push(J);return f2(Y,Z),Y.join(`
|
|
142
|
+
`)}function Xq($){let Z=String($?.server??""),J=String($?.tool??""),Y=Z&&J?`${Z}.${J}`:J||Z,Q=V9($?.arguments);return Q&&Y?`${Y}: ${Q}`:Y||Q}function jH($,Z,J){let Y=[];if($?.server)Y.push(`**server**: ${m($.server)}`);if($?.tool)Y.push(`**tool**: ${m($.tool)}`);let Q=$?.arguments;if(Q&&typeof Q==="object"&&Object.keys(Q).length>0){if(Y.length>0)Y.push("");Y.push("**arguments**"),Y.push(J$(Q,2000))}if(J)Y.push(""),Y.push(J);if(Z!=null){let V=h5(Z);if(Y.push(""),Y.push("---"),Y.push("**结果**"),V&&Array.isArray(V.content)){let H=V.content.map((X)=>typeof X?.text==="string"?X.text:"").filter(Boolean);if(H.length>0)Y.push(H.join(`
|
|
143
143
|
`).slice(0,3000));if(V.structuredContent)Y.push(""),Y.push("**structuredContent**"),Y.push(J$(V.structuredContent,2000));if(H.length===0&&!V.structuredContent)Y.push(J$(V,3000))}else Y.push(V?J$(V,3000):i0(Z.slice(0,3000)))}return Y.length>0?Y.join(`
|
|
144
|
-
`):J$($??{},2000)}function
|
|
145
|
-
`)}function
|
|
146
|
-
`):J$($??{},2000)}function
|
|
147
|
-
`):J$($??{},2000)}function R$($,Z,J,Y,Q="⏳",V,H){let X=Y9(Z)&&Y!=null?
|
|
144
|
+
`):J$($??{},2000)}function zq($,Z,J,Y){let Q=["**类型**: 模型服务端内置工具",`**tool**: ${m(typeof Z?.tool==="string"&&Z.tool?Z.tool:aV($))}`],V=Z?.input;if(V&&typeof V==="object")if(Q.push(""),Q.push("**input**"),Object.keys(V).length>0)Q.push(J$(V,2000));else Q.push("_provider 未提供结构化 input_");else if(V!=null&&V!=="")Q.push(`**input**: ${m(V)}`);if(Y)Q.push(""),Q.push(Y);if(J!=null)Q.push(""),Q.push("---"),Q.push("**结果**"),Q.push(f$(J,3000));return Q.join(`
|
|
145
|
+
`)}function Wq($){return typeof $?.status==="string"?$.status:""}function LH($,Z,J,Y){let Q=[];if($?.status)Q.push(`**状态**: ${m($.status)}`);if($?.prompt)Q.push("","**提示词**",i0(String($.prompt)));if($?.revisedPrompt){if($.revisedPrompt!==$.prompt)Q.push("",$.prompt?"**实际提示词**":"**提示词**",i0(String($.revisedPrompt)))}if(J)Q.push(""),Q.push(J);if(!Y&&Z!=null&&Z.trim())Q.push(""),Q.push("---"),Q.push("**输出**"),Q.push(m(Z.trim()));return Q.length>0?Q.join(`
|
|
146
|
+
`):J$($??{},2000)}function Gq($){let Z=typeof $?.tool==="string"?$.tool:"",J=typeof $?.prompt==="string"?$.prompt:"",Y=typeof $?.description==="string"?$.description:"",Q=typeof $?.subject==="string"?$.subject:"",V=Y||Q||J;return Z&&V?`${Z}: ${V}`:V||Z}function o8($,Z,J){let Y=[];if($?.tool)Y.push(`**tool**: ${m($.tool)}`);if($?.model)Y.push(`**model**: ${m($.model)}`);if($?.description)Y.push(`**描述**: ${$.description}`);if($?.subagent_type)Y.push(`**类型**: ${m($.subagent_type)}`);if($?.prompt){if(Y.length>0)Y.push("");Y.push("**prompt**"),Y.push(String($.prompt).slice(0,2000))}if(J)Y.push(""),Y.push(J);if(Z!=null){Y.push(""),Y.push("---"),Y.push("**状态**");let Q=h5(Z);Y.push(Q?J$(Q,3000):i0(Z.slice(0,3000)))}return Y.length>0?Y.join(`
|
|
147
|
+
`):J$($??{},2000)}function R$($,Z,J,Y,Q="⏳",V,H){let X=Y9(Z)&&Y!=null?Hq(J,Y):Q1(Z,J),z=X.length>80?X.slice(0,80)+"…":X,W=f1(Z),G=z?`${Q} \uD83D\uDD27 ${W}: ${z}`:`${Q} \uD83D\uDD27 ${W}`,B=V?`
|
|
148
148
|
|
|
149
|
-
${V}`:"",_=
|
|
149
|
+
${V}`:"",_=r8(Z)?sV(J,Y,V):s8(Z)?tV(J,Y,V):H6(Z)?zq(Z,J,Y,V):t8(Z)?YH(J,Y,V):Y9(Z)?BH(J,Y,V):e8(Z)?_H(J,Y,V):w5(Z)?jH(J,Y,V):Q9(Z)?LH(J,Y,V,H):$6(Z)?VH(J,Y,V):Z6(Z)?HH(J,Y,V):J6(Z)?XH(J,Y,V):Y6(Z)?zH(J,Y,V):f5(Z)?WH(Z,J,Y,V):Q6(Z)?GH(J,Y,V):V6(Z)?o8({prompt:V9(J)||"提交计划"},Y,V):v5(Z)?o8(J,Y,V):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```"+B+(Y!=null?`
|
|
150
150
|
---
|
|
151
151
|
**output:**
|
|
152
152
|
\`\`\`
|
|
153
|
-
`+Y.slice(0,3000)+"\n```":"");return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:G}},expanded:!1,elements:[{tag:"markdown",content:Z0(_)},...Q9(Z)&&H?[{tag:"img",img_key:H,alt:{tag:"plain_text",content:"生成的图片"},scale_type:"fit_horizontal",preview:!0}]:[]]}}function H9($,Z){let J=Z.length,Y=Z.some((z)=>z.isError),Q=Z.every((z)=>z.output!==null),V=Y?"❌":Q?"✅":"⏳",H=J===1?(()=>{let z=
|
|
154
|
-
`))}]}}function
|
|
155
|
-
`))}]}}function
|
|
156
|
-
`).map((z)=>z.trim()).filter((z)=>z.length>0);if(Z.length===0)return{services:[],error:null};let J=[];for(let z of Z){let G=z.replace(/^●\s*/,"").split(/\s+/)[0];if(!G)continue;if(!
|
|
157
|
-
`)){let _=B.indexOf("=");if(_<=0)continue;W[B.slice(0,_)]=B.slice(_+1)}let G=W.Id??"";if(!
|
|
158
|
-
`);let Z=[];if($.cpu){let{cores:J,load1:Y,load5:Q,load15:V}=$.cpu;Z.push(`**负载** ${Y.toFixed(2)} / ${Q.toFixed(2)} / ${V.toFixed(2)} (${J}核)`)}else Z.push("**负载** _n/a_");if($.mem)Z.push(`**内存** ${$.mem.percent}% (${
|
|
159
|
-
`)}function
|
|
160
|
-
`)}function
|
|
161
|
-
`)}function
|
|
162
|
-
`):
|
|
163
|
-
${J}`:Z}function
|
|
164
|
-
选账号进入模型选择。`},...["claude","codex","dsh"].flatMap((Z)=>{let J=$.providers.filter((Y)=>(Y.provider??"codex")===Z);return J.length?[{tag:"collapsible_panel",element_id:N.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((Y)=>
|
|
165
|
-
${Y}`}]},{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
|
|
166
|
-
`)},...$.models.length?Z:[{tag:"markdown",content:$.editable?$.mode==="add"?"_没有待显示的接口模型_":"_列表为空,可显示接口模型或补录_":"_未返回可用模型列表_"}],...$.pagination?
|
|
153
|
+
`+Y.slice(0,3000)+"\n```":"");return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:G}},expanded:!1,elements:[{tag:"markdown",content:Z0(_)},...Q9(Z)&&H?[{tag:"img",img_key:H,alt:{tag:"plain_text",content:"生成的图片"},scale_type:"fit_horizontal",preview:!0}]:[]]}}function H9($,Z){let J=Z.length,Y=Z.some((z)=>z.isError),Q=Z.every((z)=>z.output!==null),V=Y?"❌":Q?"✅":"⏳",H=J===1?(()=>{let z=iV(Z[0]);return z?`${V} \uD83D\uDD27 编辑文件: ${z}`:`${V} \uD83D\uDD27 编辑文件`})():`${V} \uD83D\uDD27 编辑文件 · ${J} 次`,X=Z.map((z)=>{let W=iV(z);return W?`\`${W}\``:"`(无 path)`"});return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:H}},expanded:!1,elements:[{tag:"markdown",content:Z0(X.join(`
|
|
154
|
+
`))}]}}function iV($){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 X9($,Z){let J=Z.length,Y=Z.some((z)=>z.isError),Q=Z.every((z)=>z.output!==null),V=Y?"❌":Q?"✅":"⏳",H=J===1?(()=>{let z=Q1("Read",Z[0]?.input);return z?`${V} \uD83D\uDD27 Read: ${z}`:`${V} \uD83D\uDD27 Read`})():`${V} \uD83D\uDD27 Read · ${J} 次`,X=Z.map((z)=>`\`${String(z.input.file_path??"(无 path)")}\``);return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:H}},expanded:!1,elements:[{tag:"markdown",content:Z0(X.join(`
|
|
155
|
+
`))}]}}function p5($,Z,J,Y){let Q=Q1(Z,J),V=f1(Z),H=Q?`\uD83D\uDD10 等审批 · ${V}: ${Q}`:`\uD83D\uDD10 等审批 · ${V}`,X=r8(Z)?sV(J,null):s8(Z)?tV(J,null):t8(Z)?YH(J,null):Y9(Z)?BH(J,null):e8(Z)?_H(J,null):w5(Z)?jH(J,null):Q9(Z)?LH(J,null):$6(Z)?VH(J,null):Z6(Z)?HH(J,null):J6(Z)?XH(J,null):Y6(Z)?zH(J,null):f5(Z)?WH(Z,J,null):Q6(Z)?GH(J,null):V6(Z)?o8({prompt:V9(J)||"提交计划"},null):v5(Z)?o8(J,null):"```\n"+JSON.stringify(J??{},null,2).slice(0,2000)+"\n```";return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:H}},expanded:!0,elements:[{tag:"markdown",content:X},{tag:"column_set",columns:[S5("✅ 允许","primary",Y,"allow"),S5("♾️ 始终允许","default",Y,"allow_always"),S5("❌ 拒绝","danger",Y,"deny")]}]}}function S5($,Z,J,Y){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:Y}}]}]}}var dL=300,nV="server_tool:";var qH=R(()=>{x0();s9()});import{execFile as Kq}from"node:child_process";import{readFileSync as c5,statfsSync as Bq,statSync as PH}from"node:fs";import{cpus as _q,homedir as jq}from"node:os";import{promisify as Lq}from"node:util";function Pq(){try{let $=c5("/proc/loadavg","utf8").trim().split(/\s+/);return{cores:_q().length,load1:parseFloat($[0]??"0"),load5:parseFloat($[1]??"0"),load15:parseFloat($[2]??"0")}}catch($){return K(`sysinfo: read /proc/loadavg failed: ${$}`),null}}function Dq(){try{let $=c5("/proc/meminfo","utf8"),Z=(V)=>{let H=$.match(new RegExp(`^${V}:\\s+(\\d+)\\s*kB`,"m"));return H?parseInt(H[1],10)*1024:0},J=Z("MemTotal"),Y=Z("MemAvailable");if(!J)return null;let Q=Math.max(0,J-Y);return{totalBytes:J,availBytes:Y,usedBytes:Q,percent:Math.round(Q/J*100)}}catch($){return K(`sysinfo: read /proc/meminfo failed: ${$}`),null}}function DH($,Z){try{let J=Bq(Z,{bigint:!1}),Y=J.blocks*J.bsize,Q=J.bavail*J.bsize,V=Math.max(0,Y-Q);if(!Y)return null;return{label:$,path:Z,totalBytes:Y,availBytes:Q,usedBytes:V,percent:Math.round(V/Y*100)}}catch(J){return K(`sysinfo: statfs ${Z} failed: ${J}`),null}}function Fq(){let $=[],Z=DH("/","/");if(Z)$.push(Z);let J=jq();if(J&&J!=="/"){let Y=!1;try{let Q=PH("/"),V=PH(J);Y=Q.dev===V.dev}catch{}if(!Y){let Q=DH("$HOME",J);if(Q)$.push(Q)}}return $}function Mq(){try{let $=c5("/proc/uptime","utf8").trim().split(/\s+/);return parseFloat($[0]??"0")}catch{return null}}async function FH($,Z=2000){try{let{stdout:J}=await qq("systemctl",["--user",...$],{timeout:Z,maxBuffer:4194304});return J}catch(J){return K(`sysinfo: systemctl ${$.join(" ")} failed: ${J}`),null}}function MH($){return UH.some((Z)=>$.startsWith(Z))&&$.endsWith(".service")}async function Uq(){let $=await FH(["list-units","--type=service","--all","--no-legend","--plain",...UH.map((z)=>`${z}*`)]);if($===null)return{services:[],error:"systemctl 不可用"};let Z=$.split(`
|
|
156
|
+
`).map((z)=>z.trim()).filter((z)=>z.length>0);if(Z.length===0)return{services:[],error:null};let J=[];for(let z of Z){let G=z.replace(/^●\s*/,"").split(/\s+/)[0];if(!G)continue;if(!MH(G))continue;J.push(G)}if(J.length===0)return{services:[],error:null};let Y=await FH(["show",...J,"-p","Id","-p","ActiveState","-p","SubState","-p","ActiveEnterTimestampMonotonic","-p","StateChangeTimestampMonotonic"]);if(Y===null)return{services:[],error:"systemctl show 失败"};let Q=Mq(),V=Y.split(/\n\s*\n/),H=[],X=(z)=>{let W=parseInt(z??"0",10);if(W<=0||Q===null)return null;return Math.max(0,Q-W/1e6)};for(let z of V){let W={};for(let B of z.split(`
|
|
157
|
+
`)){let _=B.indexOf("=");if(_<=0)continue;W[B.slice(0,_)]=B.slice(_+1)}let G=W.Id??"";if(!MH(G))continue;H.push({name:G.replace(/\.service$/,""),active:W.ActiveState??"unknown",sub:W.SubState??"",lastActiveAgoSec:X(W.ActiveEnterTimestampMonotonic),stateAgoSec:X(W.StateChangeTimestampMonotonic)})}return H.sort((z,W)=>z.name.localeCompare(W.name)),{services:H,error:null}}async function AH(){if(process.platform==="win32")return{cpu:null,mem:null,disks:[],services:[],servicesError:"Windows: sysinfo 暂未支持"};let $=Pq(),Z=Dq(),J=Fq(),{services:Y,error:Q}=await Uq();return{cpu:$,mem:Z,disks:J,services:Y,servicesError:Q}}var qq,UH,z9="cc-* / codex-*";var u5=R(()=>{I();qq=Lq(Kq),UH=["cc-","codex-"]});function G9($,Z){return Z}function l5($){return{schema:"2.0",config:{update_multi:!0,streaming_mode:!0,summary:{content:$.status}},body:{elements:[{tag:"markdown",element_id:N.footer,content:G9($.title,$.status)}]}}}function OH($){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 Aq($){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 W9($){if($<60000)return`${Math.round($/1000)}s`;let Z=Math.floor($/60000);if(Z<60)return`${Z}m`;let J=Math.floor(Z/60),Y=Z%60;if(J<24)return`${J}h ${Y}m`;return`${Math.floor(J/24)}d ${J%24}h`}function Tq($){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 Eq($){if(!$)return["**负载** _n/a_","**内存** _n/a_",`**服务** ${z9} _n/a_`].join(`
|
|
158
|
+
`);let Z=[];if($.cpu){let{cores:J,load1:Y,load5:Q,load15:V}=$.cpu;Z.push(`**负载** ${Y.toFixed(2)} / ${Q.toFixed(2)} / ${V.toFixed(2)} (${J}核)`)}else Z.push("**负载** _n/a_");if($.mem)Z.push(`**内存** ${$.mem.percent}% (${OH($.mem.usedBytes)}/${OH($.mem.totalBytes)})`);else Z.push("**内存** _n/a_");if($.servicesError)Z.push(`**服务** ${z9} _${$.servicesError}_`);else if($.services.length===0)Z.push(`**服务** ${z9} _无_`);else{Z.push(`**服务** ${z9} (${$.services.length})`);for(let J of $.services){let Y=Nq[J.active]??"·",Q=J.lastActiveAgoSec,V=J.stateAgoSec,H=[J.active];if(J.active==="active"){if(V!=null)H.push(`已运行 ${W9(V*1000)}`)}else if(J.active==="inactive"||J.active==="failed"){if(Q!=null)H.push(`上次活跃 ${W9(Q*1000)}前`);else H.push("从未启动");if(V!=null){let X=J.active==="failed"?"已挂":"已停";H.push(`${X} ${W9(V*1000)}`)}}else if(V!=null)H.push(`已 ${W9(V*1000)}`);Z.push(` · ${Y} \`${J.name}\` · ${H.join(" · ")}`)}}return Z.join(`
|
|
159
|
+
`)}function xq($){let Z=$.peers??[];if(Z.length===0)return"_无_";return Z.map((J)=>{let Y=Oq[J.status]??"·",Q=Rq[J.status]??J.status,V=J.uptimeMs!=null&&J.uptimeMs>0?` · ${W9(J.uptimeMs)}`:"",H=J.isCurrent?" · 当前":"",X=J.codexAccountName===void 0?"":` · Codex:${H1(z$(J.codexAccountName))}`;return` · ${Y} \`${J.name}\` · ${Q}${V}${H}${X}`}).join(`
|
|
160
|
+
`)}function X6($,Z=N.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:xq($)}]}}function Sq($){let Z=$.model?`${$.model}${$.effort?`/${$.effort}`:""}`:$.effort?`强度 ${$.effort}`:"未就绪";return[`**\uD83E\uDD16 当前模型${$.provider==="claude"?` (${r5($.provider)})`:""}** \`${Z}\``,...$.worktreeInstructionNotice?[$.worktreeInstructionNotice]:[]].join(`
|
|
161
|
+
`)}function z6($,Z=N.consoleCurrentModel){return{tag:"markdown",element_id:Z,content:Sq($)}}function W6($,Z=N.consoleHost){let J=Tq($);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:Eq($)}]}}function G6($){let Z=$?.kind==="balance"?"余额":"额度";if(!$)return`${Z} 加载中…`;if($.state==="not_applicable")return`${Z} —`;if($.state!=="ok")return`${Z} MISS`;let J=(Y,Q)=>`${Q==="USD"?"$":Q==="CNY"?"¥":`${Q} `}${Y.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)}`;if(!$.windows.length)return"额度 MISS";return`额度 ${$.windows.map(bq).join(" · ")}`}function bq($){let Z=typeof $.used==="number"&&typeof $.total==="number"?`${$.used}/${$.total}`:$.percent===null?"MISS":`${Math.round($.percent)}%`;return`${$.label} 已用 ${Z}`}function Cq($){let Z=$?.state==="ok"&&$.kind!=="balance"&&!$.quota&&$.windows.length?["**\uD83D\uDCCA 额度**",...$.windows.flatMap((Y)=>N2(Y,Y.label).map((Q)=>Q.content))].join(`
|
|
162
|
+
`):G6($).replace(/^(额度|余额)/,"**\uD83D\uDCCA $1**"),J=RH($);return J?`${Z}
|
|
163
|
+
${J}`:Z}function RH($){return $?.resetCredits===void 0?"":`**重置卡** ${$.resetCredits===null?"MISS":`${$.resetCredits} 次可用`}`}function K9($){let Z=$.unifiedUsage;if(Z?.state==="ok"&&Z.kind!=="balance"&&!Z.quota&&Z.windows.length){let J=[];for(let Q of Z.windows){if(J.length)J.push({tag:"hr"});J.push(...N2(Q,Q.label))}let Y=RH(Z);if(Y)J.push({tag:"hr"},{tag:"markdown",content:Y});return{tag:"collapsible_panel",element_id:N.consoleUsage,expanded:!0,header:{title:{tag:"plain_text",content:"\uD83D\uDCCA 额度"},background_color:"blue-50"},border:{color:"blue-100",corner_radius:"8px"},padding:"12px",vertical_spacing:"4px",elements:J}}return{tag:"markdown",element_id:N.consoleUsage,content:Cq(Z)}}function NH($,Z){return[z6($,Z),X6($),W6($.sysinfo),K9($)]}function d5($){let{sessionName:Z,status:J}=$,Y=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:Y},body:{elements:NH($)}}}function i5($){return h2($.sessionName,{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"选择账号"}},expanded:!0,elements:[{tag:"markdown",content:`当前: ${H1($.currentDisplay??"未选择")}
|
|
164
|
+
选账号进入模型选择。`},...["claude","codex","dsh"].flatMap((Z)=>{let J=$.providers.filter((Y)=>(Y.provider??"codex")===Z);return J.length?[{tag:"collapsible_panel",element_id:N.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((Y)=>kq(Y,$.panelId))}]:[]})]})}function kq($,Z){if(!$.enabled)return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`⚙️ **${z$($.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} 个模型`,Y=[$.selected?"当前账号":"",J].filter(Boolean).join(" · ");return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`**${z$($.display)}**
|
|
165
|
+
${Y}`}]},{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 n5($){return h2($.sessionName,TH($))}function a5($){return h2($.sessionName,_6($))}function K6($){return h2($.sessionName,j6($),"green")}function h2($,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 TH($){let Z=vq($.models,$.panelId,$.mode,$.editable);return{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:$.mode==="add"?"显示模型":"选择模型"}},expanded:!0,elements:[{tag:"markdown",content:[`当前: ${EH($.currentModel,$.currentEffort)}`,$.mode==="add"?"显示账号接口中的模型。":"接口模型可隐藏,补录模型可删除。有多个 effort 档位时再选择档位。"].join(`
|
|
166
|
+
`)},...$.models.length?Z:[{tag:"markdown",content:$.editable?$.mode==="add"?"_没有待显示的接口模型_":"_列表为空,可显示接口模型或补录_":"_未返回可用模型列表_"}],...$.pagination?yq($.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 yq($,Z){let{sourceId:J,page:Y,totalPages:Q}=Z,V=(H,X)=>({tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:H},type:"default",behaviors:[{type:"callback",value:{kind:"model_page",panel_id:$,source_id:J,page:X}}]}]});return[{tag:"markdown",content:`第 ${Y+1} / ${Q} 页`},{tag:"column_set",columns:[...Y>0?[V("上一页",Y-1)]:[],...Y+1<Q?[V("下一页",Y+1)]:[]]}]}function B6($,Z="cancelled"){return h2($,{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:Z==="stale"?"_此补录面板已失效 — 当前等待中的补录未受影响_":"_已取消补录 — 列表未改动_"}]},"grey")}function o5($,Z,J){return h2($,{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:[`**直接回复模型名补录到 ${Z}**`,"补录后可选择 effort 并使用;模型是否接受该档位由实际请求确认。","_裸词命令(hi/stop/model 等)不受影响_"].join(`
|
|
167
167
|
`)},{tag:"button",text:{tag:"plain_text",content:"取消"},type:"default",width:"default",behaviors:[{type:"callback",value:{kind:"model_panel_cancel",panel_id:J}}]}]},"blue")}function I2($,Z,J){return{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"补录模型"}},expanded:!0,elements:[{tag:"markdown",content:$?`✅ \`${Z}\` 已加入列表${J?`
|
|
168
|
-
${J}`:""}`:`❌ \`${Z}\` 未加入 — ${J}`}]}}function
|
|
169
|
-
`)},...$.model.efforts.length?$.model.efforts.map((Z)=>
|
|
170
|
-
`)}]}}function
|
|
171
|
-
${z$($.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 Q=$.displayName&&$.displayName!==$.model?`**${z$($.displayName)}**`:`**${H1($.model)}**`,V=[$.isDefault?`${
|
|
172
|
-
`+z$(
|
|
173
|
-
`)+H}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[...J==="add"?[X("model_add","显")]:$.unavailableReason?[{tag:"markdown",content:"**MISS**"}]:[{tag:"button",text:{tag:"plain_text",content:"选"},type:$.selected?"primary":"default",behaviors:[{type:"callback",value:
|
|
174
|
-
`)}]},{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
|
|
168
|
+
${J}`:""}`:`❌ \`${Z}\` 未加入 — ${J}`}]}}function _6($){return{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"选择 effort"}},expanded:!0,elements:[{tag:"markdown",content:[`模型: ${Iq($.model)}`,`当前: ${EH($.currentModel,$.currentEffort)}`].join(`
|
|
169
|
+
`)},...$.model.efforts.length?$.model.efforts.map((Z)=>fq($.model,Z,$.panelId,$.currentModel,$.currentEffort)):[{tag:"markdown",content:"_该模型未返回可用 effort_"}]]}}function j6($){return{tag:"collapsible_panel",element_id:N.modelPanel,header:{title:{tag:"plain_text",content:"选择已保存"}},expanded:!0,elements:[{tag:"markdown",content:["**已保存**",H1(xH($.model,$.effort,$.provider)),z$($.scope)].join(`
|
|
170
|
+
`)}]}}function wq($,Z,J,Y=!1){if($.enabled===!1)return[{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`⚙️ **${z$($.displayName)}** · 未配置
|
|
171
|
+
${z$($.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 Q=$.displayName&&$.displayName!==$.model?`**${z$($.displayName)}**`:`**${H1($.model)}**`,V=[$.isDefault?`${r5($.provider)} 默认`:"",$.selected?"当前模型":""].filter(Boolean),H=$.description?`
|
|
172
|
+
`+z$(gq($.description,110)):"",X=(W,G)=>({tag:"button",text:{tag:"plain_text",content:G},type:"default",behaviors:[{type:"callback",value:{kind:W,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:[Q,$.displayName&&$.displayName!==$.model?H1($.model):"",V.length?V.join(" · "):""].filter(Boolean).join(`
|
|
173
|
+
`)+H}]},{tag:"column",width:"weighted",weight:1,vertical_align:"center",elements:[...J==="add"?[X("model_add","显")]:$.unavailableReason?[{tag:"markdown",content:"**MISS**"}]:[{tag:"button",text:{tag:"plain_text",content:"选"},type:$.selected?"primary":"default",behaviors:[{type:"callback",value:hq($,Z)}]}],...Y&&J!=="add"?[$.origin==="custom"?X("model_custom_remove","删"):X("model_remove","隐")]:[]]}]}]}function vq($,Z,J,Y=!1){let Q=[{title:"Codex",models:$.filter((X)=>(X.provider??"codex")==="codex")},{title:"Claude Code 后端",models:$.filter((X)=>X.provider==="claude")},{title:"DeepSeek Harness",models:$.filter((X)=>X.provider==="dsh")}].filter((X)=>X.models.length>0),V=(X)=>X.flatMap((z,W)=>[...W?[{tag:"hr"}]:[],...wq(z,Z,J,Y)]);if(Q.length<=1)return V($);let H=[];for(let X of Q)H.push({tag:"markdown",content:`**${X.title}**`}),H.push(...V(X.models));return H}function fq($,Z,J,Y,Q){let V=Y===$.model&&Q===Z.effort,H=[Z.isDefault?"默认":"",V?"当前":""].filter(Boolean).join(" · ");return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:[`**${Z.effort==="default"?"模型默认":z$(Z.effort)}**`,H,Z.description?z$(Z.description):""].filter(Boolean).join(`
|
|
174
|
+
`)}]},{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 hq($,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 Iq($){return $.displayName&&$.displayName!==$.model?`${z$($.displayName)} (${H1($.model)})`:H1($.model)}function EH($,Z){return H1(xH($,Z))}function xH($,Z,J){let Y=J&&J!=="codex"?`${r5(J)} · `:"";if($&&Z)return`${Y}${$}/${Z}`;if($)return`${Y}${$}`;if(Z)return`${Y}${Z}`;return"未选择"}function r5($){return _$($??"codex")}function gq($,Z){return $.length<=Z?$:$.slice(0,Z-1)+"…"}function z$($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function H1($){return"`"+$.replace(/`/g,"\\`")+"`"}function h$($){let Z=[];if(Z.push($.suffix??"✅"),$.durationSec!=null)Z.push(`⏱ ${G0($.durationSec)}`);if($.outputTokens!=null&&$.outputTokens>0)Z.push(`\uD83D\uDCF6 ${Aq($.outputTokens)}`);return{config:{streaming_mode:!1,summary:{content:Z.join(" · ")}}}}var Oq,Rq,Nq;var SH=R(()=>{D0();u5();x0();Oq={idle:"\uD83D\uDFE2",working:"⚙️",awaiting_permission:"\uD83D\uDD10",starting:"\uD83D\uDE80",stopped:"⚪"},Rq={idle:"闲",working:"工作中",awaiting_permission:"等审批",starting:"启动中",stopped:"未运行"},Nq={active:"\uD83D\uDFE2",activating:"\uD83D\uDE80",reloading:"\uD83D\uDD04",inactive:"⚪",deactivating:"\uD83D\uDFE1",failed:"❌"}});function s5($){let Z=cq($);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83C\uDF3F wt"},template:mq($.notice)},body:{elements:[...$.notice?[pq($.notice)]:[],...Z?[{tag:"markdown",content:Z}]:[],...$.entries.flatMap(uq)]}}}function mq($){if($?.type==="error")return"red";if($?.type==="success")return"green";return"turquoise"}function pq($){let Z=$.type==="error"?"red":$.type==="success"?"green":"grey";return{tag:"markdown",content:$.content.split(`
|
|
175
175
|
`).map((J)=>`<font color='${Z}'>${J||" "}</font>`).join(`
|
|
176
|
-
`)}}function
|
|
176
|
+
`)}}function cq($){let Z=$.hiddenMergedUnmountedCount??0;if(!$.entries.length&&Z===0)return`_无 work/* 分支。发 ${L6("wt name")} 创建。_`;if(Z>0)return`${Z}个已归档分支`;return""}function uq($){let Z=$.error?"出错":$.mounted&&$.dirtyCount&&$.dirtyCount>0?`有未提交改动 ${$.dirtyCount}`:$.state==="merged"?"已合并":$.state==="stale"?"两边都有新改动":$.mounted?"进行中":"未挂载",J=$.duplicateChatCount>1?`群重复 ${$.duplicateChatCount} 个`:$.chatId?"群正常":"无群",Y=[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:`**${L6($.slug)}**
|
|
177
177
|
${Z} · ${J}
|
|
178
|
-
${
|
|
179
|
-
`)}]}}}function
|
|
178
|
+
${L6($.branch)}`}]}];if($.mounted||$.chatId)Y.push({tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"删"},type:"danger",behaviors:[{type:"callback",value:{kind:"worktree_disband",slug:$.slug}}]}]});return[{tag:"column_set",columns:Y}]}function B9($){return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83C\uDF3F ${$.slug}`},template:$.template??"green"},body:{elements:[{tag:"markdown",content:[$.status,L6($.branch),...$.body?[$.body]:[]].join(`
|
|
179
|
+
`)}]}}}function L6($){return"`"+$.replace(/`/g,"\\`")+"`"}function e5($){let Z=$.mode==="fork",J=Z?"分叉":"回退",Y=Z?"temp_fork_select":"temp_back_select",Q=Z?`\uD83D\uDCA1 选择一条「用户输入」,将在临时群从它**之前**创建独立对话分支;选中的输入本身不包含。
|
|
180
180
|
分支与本群共享 cwd 和磁盘文件;只分叉对话历史,不复制或回滚文件,原会话不动。`:`⚠️ 选择一条「用户输入」,将停止本群当前 turn 和后台任务,并从它**之前**创建后续对话分支;选中的输入本身不包含。
|
|
181
|
-
只回退对话历史,不会回滚 cwd 中的文件。`,V=[];if($.notice)V.push({tag:"markdown",content:
|
|
182
|
-
${X1(H.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:Y,panel_id:$.panelId,choice_id:H.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
|
|
183
|
-
新分支共享当前 cwd 和磁盘文件;只分叉对话历史,不复制或回滚文件。`});for(let J of $.entries)Z.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:5,elements:[{tag:"markdown",content:`**${
|
|
184
|
-
${X1(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
|
|
181
|
+
只回退对话历史,不会回滚 cwd 中的文件。`,V=[];if($.notice)V.push({tag:"markdown",content:lq($.notice)});if(!$.entries.length)V.push({tag:"markdown",content:"_当前会话还没有已完成的 turn,无法分叉/回退。_"});else{V.push({tag:"markdown",content:Q});for(let H of $.entries)V.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:5,elements:[{tag:"markdown",content:`**${YZ(H.ts)}**
|
|
182
|
+
${X1(H.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:Y,panel_id:$.panelId,choice_id:H.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 $Z($){let Z=[];if(!$.entries.length)Z.push({tag:"markdown",content:`_项目「${$.projectName}」没有可创建分支的历史会话。_`});else{Z.push({tag:"markdown",content:`\uD83D\uDCA1 选择一个历史会话,在**当前群**创建独立对话分支;源会话不动。
|
|
183
|
+
新分支共享当前 cwd 和磁盘文件;只分叉对话历史,不复制或回滚文件。`});for(let J of $.entries)Z.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:5,elements:[{tag:"markdown",content:`**${YZ(J.ts)}**
|
|
184
|
+
${X1(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 ZZ($){let Z=$.entries.length===0?"(回退范围内未观察到 Write/Edit/FileChange 类文件变更)":$.entries.map((J)=>{let Y=J.body.length>800?J.body.slice(0,800)+`
|
|
185
185
|
…(截断)`:J.body;return`${J.path} (${J.tool})
|
|
186
186
|
${Y}`}).join(`
|
|
187
187
|
|
|
188
|
-
`);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDCCB 观察到的文件变更 · ${$.projectName}`},template:"grey"},body:{elements:[{tag:"markdown",content:"以下是回退范围内观察到的文件变更,可复制、编辑后交给新分支参考。bk 只回退对话历史,不会回滚磁盘文件;Shell/MCP 等工具造成的副作用可能未被记录。"},{tag:"markdown",content:"```\n"+Z+"\n```"}]}}}function z1($){return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:$.title},template:$.ok?"green":"red"},body:{elements:[{tag:"markdown",content:`${$.ok?"✅":"❌"} ${
|
|
188
|
+
`);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDCCB 观察到的文件变更 · ${$.projectName}`},template:"grey"},body:{elements:[{tag:"markdown",content:"以下是回退范围内观察到的文件变更,可复制、编辑后交给新分支参考。bk 只回退对话历史,不会回滚磁盘文件;Shell/MCP 等工具造成的副作用可能未被记录。"},{tag:"markdown",content:"```\n"+Z+"\n```"}]}}}function z1($){return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:$.title},template:$.ok?"green":"red"},body:{elements:[{tag:"markdown",content:`${$.ok?"✅":"❌"} ${t5($.message)}`}]}}}function JZ($){let Z=$.provider==="codex"?"Codex":"Claude",J=$.bindingState==="changed"?"已接入":$.bindingState==="prepared"?"已准备":$.bindingState==="unchanged"?"未切换":"状态待确认",Y=$.bindingState==="changed"?"✅":$.bindingState==="prepared"?"⏳":$.bindingState==="unchanged"?"❌":"⚠️",Q=$.selectedPreview.slice(0,80)||"(无摘要)",V=$.sourceStatus?` · 状态 ${X1($.sourceStatus)}`:"",H=$.bindingState==="changed"?["**当前群**",`新会话 ${X1(q6($.newSessionId))}`,"","源会话未修改;新分支与当前群共享 cwd 和磁盘文件。"].join(`
|
|
189
189
|
`):$.bindingState==="prepared"?["**当前群**","Claude 独立分支已准备;发送下一条消息时生成并接入新会话。","","源会话未修改;新分支与当前群共享 cwd 和磁盘文件。"].join(`
|
|
190
|
-
`):$.bindingState==="unchanged"?[`${
|
|
191
|
-
`):[`${
|
|
192
|
-
`);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDD01 rs ${J} · ${$.projectName}`},template:$.bindingState==="changed"?"green":$.bindingState==="prepared"?"purple":$.bindingState==="unchanged"?"red":"orange"},body:{elements:[{tag:"markdown",content:`${Y} ${$.bindingState==="changed"?"已从所选历史创建独立分支":$.bindingState==="prepared"?"已准备从所选历史创建独立分支":$.bindingState==="unchanged"?"历史分支创建失败":"分支结果需要确认"}`},{tag:"markdown",content:[`**所选历史 · ${Z}**`,`**${
|
|
193
|
-
`)},{tag:"markdown",content:H}]}}}function
|
|
190
|
+
`):$.bindingState==="unchanged"?[`${t5($.message)}`,"",`本群原绑定 ${X1(q6($.previousSessionId))};源会话未修改。`].join(`
|
|
191
|
+
`):[`${t5($.message)}`,"",`后端返回会话 ${X1(q6($.newSessionId))};当前绑定无法确认。`,"请发送 hi 或 rs 检查当前状态,不要把本卡视为成功回执。"].join(`
|
|
192
|
+
`);return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:`\uD83D\uDD01 rs ${J} · ${$.projectName}`},template:$.bindingState==="changed"?"green":$.bindingState==="prepared"?"purple":$.bindingState==="unchanged"?"red":"orange"},body:{elements:[{tag:"markdown",content:`${Y} ${$.bindingState==="changed"?"已从所选历史创建独立分支":$.bindingState==="prepared"?"已准备从所选历史创建独立分支":$.bindingState==="unchanged"?"历史分支创建失败":"分支结果需要确认"}`},{tag:"markdown",content:[`**所选历史 · ${Z}**`,`**${YZ($.selectedTs)}**${V}`,X1(Q),`源会话 ${X1(q6($.sourceSessionId))}`].join(`
|
|
193
|
+
`)},{tag:"markdown",content:H}]}}}function YZ($){let Z=new Date($),J=(Y)=>String(Y).padStart(2,"0");return`${J(Z.getMonth()+1)}-${J(Z.getDate())} ${J(Z.getHours())}:${J(Z.getMinutes())}`}function X1($){return"`"+bH($.replace(/`/g,"\\`").replace(/\n/g," "))+"`"}function q6($){let Z=$?.trim()??"";if(!Z)return"MISS";return Z.length>13?`${Z.slice(0,8)}…${Z.slice(-4)}`:Z}function t5($){return bH($).replace(/\\/g,"\\\\").replace(/([`*_{}\[\]()#+\-.!|>~])/g,"\\$1")}function bH($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function lq($){let Z=$.type==="error"?"red":"grey";return $.content.split(`
|
|
194
194
|
`).map((J)=>`<font color='${Z}'>${J||" "}</font>`).join(`
|
|
195
|
-
`)}function
|
|
195
|
+
`)}function CH($){if(!$||typeof $!=="object")return"";if(typeof $.content==="string")return $.content;if(typeof $.new_string==="string")return $.new_string;if(typeof $.new_source==="string")return $.new_source;if(Array.isArray($.edits))return $.edits.map((Z)=>typeof Z?.new_string==="string"?Z.new_string:"").filter(Boolean).join(`
|
|
196
196
|
---
|
|
197
|
-
`);return""}function
|
|
198
|
-
`);if(Z.push("","已启用"),Z.push(`GUID:${
|
|
199
|
-
`)}function
|
|
200
|
-
`).map((J)=>`<font color='${Z}'>${
|
|
201
|
-
`)}}function
|
|
197
|
+
`);return""}function QZ($,Z){if(!Z||typeof Z!=="object")return[];if($==="FileChange"||$==="fileChange"){if(!Array.isArray(Z.changes))return[];return Z.changes.filter((Y)=>Y&&typeof Y==="object").map((Y)=>({tool:$,path:typeof Y.path==="string"&&Y.path?Y.path:"?",body:typeof Y.diff==="string"?Y.diff:typeof Y.unified_diff==="string"?Y.unified_diff:""}))}if(!["Write","Edit","NotebookEdit","MultiEdit"].includes($))return[];let J=Z.file_path??Z.path??Z.notebook_path;return[{tool:$,path:typeof J==="string"&&J?J:"?",body:CH(Z)}]}function HZ($){let Z=!!$.binding,J=$.notice?.type==="error"?"red":$.confirmDelete?"red":Z?"green":"blue";return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"task"},template:J},body:{elements:[...$.notice?[nq($.notice)]:[],{tag:"markdown",element_id:N.tasklistPanel,content:dq($)},iq($)]}}}function dq($){let Z=[`项目:${VZ($.projectName)}`,`清单:${VZ($.tasklistName)}`];if(!$.binding)return Z.push("","未启用"),Z.join(`
|
|
198
|
+
`);if(Z.push("","已启用"),Z.push(`GUID:${VZ($.binding.guid)}`),$.binding.url)Z.push(`链接:${$.binding.url}`);if($.confirmDelete)Z.push(""),Z.push("<font color='red'>确认后会删除该清单以及清单内所有任务。</font>");return Z.join(`
|
|
199
|
+
`)}function iq($){if(!$.binding)return{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:"tasklist_enable"}}]}]}]};if($.confirmDelete)return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:4,elements:[{tag:"markdown",content:"<font color='red'>会删除所有清单内任务</font>"}]},{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"确认"},type:"danger",behaviors:[{type:"callback",value:{kind:"tasklist_delete_confirm",guid:$.binding.guid}}]}]}]};return{tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:"删"},type:"danger",behaviors:[{type:"callback",value:{kind:"tasklist_delete_prompt",guid:$.binding.guid}}]}]}]}}function nq($){let Z=$.type==="error"?"red":$.type==="success"?"green":"grey";return{tag:"markdown",content:$.content.split(`
|
|
200
|
+
`).map((J)=>`<font color='${Z}'>${aq(J)||" "}</font>`).join(`
|
|
201
|
+
`)}}function VZ($){return"`"+$.replace(/`/g,"\\`")+"`"}function aq($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var kH=R(()=>{x0()});import{createHash as oq}from"node:crypto";function zZ($){let Z=[{tag:"markdown",element_id:N.agentIdentityPanel,content:["**全局 Agent 身份**","选择一个或多个 Agent 执行任务,由主 Agent 统一分配和汇总结果。",`目录第 ${$.page+1}/${$.totalPages} 页`].join(`
|
|
202
202
|
`)}];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)=>`- **${N$(J.display)}**:${N$(J.reason)}`).join(`
|
|
203
|
-
`)}]});return Z.push(...$.catalog.map(
|
|
204
|
-
${
|
|
203
|
+
`)}]});return Z.push(...$.catalog.map(tq),eq($)),{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:"\uD83E\uDDE0 可用 Agent"},template:"purple"},body:{elements:Z}}}function WZ($){return{schema:"2.0",config:{update_multi:!0,streaming_mode:!KZ($.status),summary:{content:P6($)}},body:{elements:[_9($)]}}}function _9($){return{tag:"collapsible_panel",element_id:j9($.runId),header:{title:{tag:"plain_text",content:P6($)}},expanded:!1,elements:[{tag:"markdown",content:[`**${N$($.description??"说明 MISS")}**`,fH($).content,`**任务说明**
|
|
204
|
+
${ZP($.prompt)}`,...$.workers.map((Z)=>vH(Z,hH($.workers.length)).content)].join(`
|
|
205
205
|
|
|
206
|
-
`)}]}}function j9($){return`ar_${
|
|
207
|
-
`)}}function
|
|
208
|
-
`)}}function
|
|
206
|
+
`)}]}}function j9($){return`ar_${oq("sha256").update($).digest("hex").slice(0,16)}`}function GZ($){if($.length===1)return P6($[0]);let Z=$.filter((Q)=>KZ(Q.status)).length,J=$.filter((Q)=>Q.status==="failed").length,Y=$.filter((Q)=>Q.status==="needs_input").length;return`\uD83E\uDDE0 委派任务 · 已结束 ${Z}/${$.length}${J?` · 失败 ${J}`:""}${Y?` · 待答 ${Y}`:""}`}function vH($,Z=wH){let J=$P($),Y=[`模型 ${h1($.model)} · 推理 ${h1($.effort)}`];if($.durationMs!=null)Y.push(`用时 ${G0($.durationMs/1000)}`);if($.status==="queued"&&$.queuedReason)Y.push("",N$($.queuedReason));if($.pendingInput){Y.push("","**等待主 Agent 回答**");for(let Q of $.pendingInput.questions)if(Y.push(`- ${N$(Q.question)}`),Q.options.length)Y.push(` 选项:${Q.options.map((V)=>h1(V.label)).join(" / ")}`)}if($.error)Y.push("",$.status==="cancelled"?"**停止原因**":"**失败原因**",Z0($.error));if($.output)Y.push("",$.status==="failed"||$.status==="cancelled"?"**已生成的内容**":"**结果**",JP(Z0($.output),Z));if(!$.output&&!$.error&&!$.pendingInput)Y.push("",$.status==="completed"?"_任务已完成,没有正文输出。_":$.status==="cancelled"?"_任务已取消。_":$.status==="queued"?"_等待开始执行。_":"_正在执行任务,结果会显示在这里。_");if($.steps.length){Y.push("","**最近动作**");for(let Q of $.steps.slice(-3)){let V=Q.tool==="tool error"?"❌":Q.phase==="completed"?"✓":Q.phase==="started"?"→":"·",H=Q.tool==="tool error"?"工具执行失败":Q.tool==="tool result"?"工具执行完成":Q.tool;Y.push(`- ${V} ${h1(H)} ${N$(gH(Q.detail,180))}`)}}return{tag:"markdown",content:[`**${J} · ${N$($.identityName)}**`,...Y].join(`
|
|
207
|
+
`)}}function fH($){let Z=$.workers.filter((G)=>G.status==="completed").length,J=$.workers.filter((G)=>G.status==="failed").length,Y=$.workers.filter((G)=>G.status==="needs_input").length,Q=$.workers.filter((G)=>G.status==="running").length,V=$.workers.filter((G)=>G.status==="queued").length,H=$.workers.filter((G)=>G.status==="cancelled").length,X=[Q?`执行中 ${Q}`:"",V?`排队 ${V}`:"",Y?`待答 ${Y}`:"",J?`失败 ${J}`:"",H?`已取消 ${H}`:""].filter(Boolean),z=$.finishedAt?Date.parse($.finishedAt)-Date.parse($.createdAt):null;return{tag:"markdown",content:[`**${IH($)}** · 完成 ${Z}/${$.workers.length}`,...X.length?[X.join(" · ")]:[],...z!=null&&Number.isFinite(z)?[`⏱ 用时 ${G0(z/1000)}`]:[],...$.error?[N$($.error)]:[]].join(`
|
|
208
|
+
`)}}function hH($){let Z=Math.max(1,Math.floor($));return Math.min(wH,Math.max(sq,Math.floor(rq/Z)))}function P6($){let Z=$.workers.filter((J)=>J.status==="completed").length;return`${IH($)} · ${gH($.description??"说明 MISS",40)}${$.workers.length>1?` · ${Z}/${$.workers.length}`:""}`}function tq($){let J=$.status==="ready"?"可用":`不可用:${$.reason??"MISS"}`;return{tag:"markdown",content:[`**${N$($.displayName)}** ${$.sourceDefault?"· 默认":""}`,`${h1($.id)}
|
|
209
209
|
${h1($.model)} · 默认 ${h1($.defaultEffort??"MISS")} · ${N$(J)}`].join(`
|
|
210
|
-
`)}}function
|
|
210
|
+
`)}}function eq($){return{tag:"column_set",columns:[XZ("上一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.max(0,$.page-1)}),XZ("刷新",{kind:"agent_identity_page",panel_id:$.panelId,page:$.page}),XZ("下一页",{kind:"agent_identity_page",panel_id:$.panelId,page:Math.min($.totalPages-1,$.page+1)})]}}function XZ($,Z){return{tag:"column",width:"weighted",weight:1,elements:[{tag:"button",text:{tag:"plain_text",content:$},type:"default",behaviors:[{type:"callback",value:Z}]}]}}function $P($){switch($.status){case"completed":return"✅ 完成";case"failed":return"❌ 失败";case"cancelled":return"\uD83D\uDED1 取消";case"needs_input":return"❓ 等待输入";case"running":return"⏳ 运行中";default:return"⏳ 排队中"}}function KZ($){return $==="completed"||$==="failed"||$==="cancelled"}function IH($){switch($.status){case"completed":return"✅ 委派完成";case"failed":return"❌ 委派失败";case"cancelled":return"\uD83D\uDED1 委派已取消";case"needs_input":return"❓ 等待主 Agent 回复";case"queued":return"⏳ 等待执行";case"running":return $.workers.length>0&&$.workers.every((Z)=>KZ(Z.status))?"⏳ 正在收尾":"⏳ 正在执行"}}function ZP($){let Z=Z0($);if(Z.length<=yH)return Z;let J="_这里仅显示任务预览,Agent 使用的是完整任务内容。_";return`${Z.slice(0,yH-J.length-2)}
|
|
211
211
|
|
|
212
|
-
${J}`}function
|
|
212
|
+
${J}`}function JP($,Z){if($.length<=Z)return $;let J="_这里仅显示结果预览,完整内容已保存。_";return`${$.slice(0,Math.max(0,Z-J.length-2))}
|
|
213
213
|
|
|
214
|
-
${J}`}function h1($){return"`"+$.replace(/`/g,"\\`")+"`"}function N$($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function
|
|
215
|
-
`)}function W1($,Z,J,Y){let Q=
|
|
214
|
+
${J}`}function h1($){return"`"+$.replace(/`/g,"\\`")+"`"}function N$($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function gH($,Z){let J=$.replace(/\s+/g," ").trim();return J.length<=Z?J:`${J.slice(0,Z-1)}…`}var yH=1e4,rq=48000,wH=8000,sq=512;var mH=R(()=>{x0()});function g1($){return YP.has($)?$:null}function D6($){if(!$)return null;try{let Z=JSON.parse($);return Z&&typeof Z==="object"?Z:null}catch{return null}}function g2($){return String($?.taskId??$?.id??$?.task_id??"").trim()}function I1($){return String($?.subject??$?.content??"").trim()}function BZ($){let Z=$?.status;return Z==="pending"||Z==="in_progress"||Z==="completed"||Z==="deleted"?Z:void 0}function uH($){return`subj:${$}`}function pH($){let Z=$.match(/#\s*(\d+)/);return Z?Z[1]:""}function XP($){let Z=I1($);if(!Z)return null;return{id:g2($)||uH(Z),subject:Z,description:typeof $?.description==="string"?$.description:void 0,activeForm:typeof $?.activeForm==="string"?$.activeForm:void 0,status:BZ($)??"pending"}}function _Z($,Z,J,Y){if(Z==="TaskList"){let Q=D6(Y),V=Array.isArray(Q?.tasks)?Q.tasks:Array.isArray(Q)?Q:null;if(V===null)return $;let H=[];for(let X of V){let z=XP(X);if(z)H.push(z)}return H}if(Z==="TaskCreate"){let Q=Array.isArray(J?.tasks)?J.tasks:null;if(Q){let W=D6(Y),G=Array.isArray(W?.tasks)?W.tasks:Array.isArray(W)?W:null,B=$;return Q.forEach((_,j)=>{let q=I1(_);if(!q)return;let P=G?.[j],D=P&&g2(P)||pH(Y??"");B=cH(B,D,q,_)}),B}let V=D6(Y),H=V?.task??V,X=g2(H)||pH(Y??""),z=I1(H)||I1(J);if(!z)return $;return cH($,X,z,J)}if(Z==="TaskUpdate"){let Q=g2(J);if(!Q)return $;let V=BZ(J);if(V==="deleted")return $.filter((X)=>X.id!==Q);let H=I1(J);if($.some((X)=>X.id===Q))return $.map((X)=>X.id===Q?{...X,...V?{status:V}:{},...H?{subject:H}:{},...typeof J?.activeForm==="string"?{activeForm:J.activeForm}:{}}:X);return $}if(Z==="TaskGet"){let Q=D6(Y),V=Q?.task??Q,H=g2(V)||g2(J);if(!H)return $;let X=$.find((G)=>G.id===H),z=I1(V)||X?.subject||I1(J);if(!z)return $;let W={id:H,subject:z,description:typeof V?.description==="string"?V.description:X?.description,activeForm:typeof V?.activeForm==="string"?V.activeForm:X?.activeForm,status:BZ(V)??X?.status??"pending"};return X?$.map((G)=>G.id===H?W:G):[...$,W]}return $}function cH($,Z,J,Y){let Q=Z||uH(J),V={...typeof Y?.activeForm==="string"&&Y.activeForm?{activeForm:Y.activeForm}:{},...typeof Y?.description==="string"&&Y.description?{description:Y.description}:{}};if($.some((H)=>H.id===Q))return $.map((H)=>H.id===Q?{...H,id:Q,subject:J,...V}:H);return[...$,{id:Q,subject:J,status:"pending",...V}]}function jZ($){let Z=$.filter((V)=>V.status!=="deleted");if(Z.length===0)return"空";let J=new Map;for(let V of Z){let H=VP[V.status];J.set(H,(J.get(H)??0)+1)}let Q=["进行中","待办","完成"].map((V)=>J.has(V)?`${V} ${J.get(V)}`:"").filter(Boolean).join(" · ");return`${Z.length} 项${Q?` · ${Q}`:""}`}function lH($,Z){let J=$.filter((H)=>H.status!=="deleted"),Y=[`**待办**: ${J.length} 项`],Q=(H)=>{let X=parseInt(H,10);return Number.isNaN(X)?Number.MAX_SAFE_INTEGER:X},V=[...J].sort((H,X)=>{let z=Q(H.id)-Q(X.id);return z!==0?z:H.id.localeCompare(X.id)});for(let H of V.slice(0,12)){let X=HP[H.status],z=H.status==="in_progress"&&H.activeForm?H.activeForm:H.subject;Y.push(`- ${X} ${z||"(空)"}`)}if(V.length>12)Y.push(`- 还有 ${V.length-12} 项未显示`);if(Z)Y.push(""),Y.push(Z);return Y.join(`
|
|
215
|
+
`)}function W1($,Z,J,Y){let Q=QP[J.name],V=jZ(Z),H=`${J.status} \uD83D\uDD27 ${Q}: ${V}`;return{tag:"collapsible_panel",element_id:N.tool($),header:{title:{tag:"plain_text",content:H}},expanded:!1,elements:[{tag:"markdown",content:lH(Z,Y)}]}}function m1($){return{tag:"collapsible_panel",element_id:N.taskBoardLive,header:{title:{tag:"plain_text",content:`\uD83D\uDCCB 任务总览 · ${jZ($)}`}},expanded:!0,elements:[{tag:"markdown",content:lH($)}]}}var YP,QP,VP,HP;var dH=R(()=>{x0();YP=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet"]);QP={TaskCreate:"创建任务",TaskUpdate:"更新任务",TaskList:"任务列表",TaskGet:"查看任务"},VP={pending:"待办",in_progress:"进行中",completed:"完成",deleted:"已删"},HP={pending:"⬜",in_progress:"\uD83D\uDD04",completed:"✅",deleted:"\uD83D\uDDD1️"}});var Y$=R(()=>{x0();c8();dV();qH();SH();kH();mH();dH();B3()});import{readFileSync as zP}from"node:fs";import{homedir as WP}from"node:os";import{join as oH}from"node:path";function GP(){return process.env.CLAUDE_CONFIG_DIR||oH(WP(),".claude")}function qZ(){try{let $=zP(oH(GP(),"settings.json"),"utf8"),Z=JSON.parse($)?.env;return Z&&typeof Z==="object"?Z:{}}catch($){return K(`glm-usage: read settings.json env failed: ${$}`),{}}}function p1($){try{let Z=new URL($).hostname.toLowerCase();return Z==="open.bigmodel.cn"||Z==="dev.bigmodel.cn"||Z==="api.z.ai"}catch{return!1}}function KP($){try{let Z=new URL($);return`${Z.protocol}//${Z.host}`}catch{return null}}function BP($){let Z=KP($);return Z&&p1($)?Z:null}function nH($){return typeof $==="number"&&isFinite($)?Math.max(0,Math.min(100,$)):null}function aH($){return typeof $==="number"&&isFinite($)&&$>0?new Date($):null}function _P($){let Z=Array.isArray($?.limits)?$.limits:[],J=Z.filter((G)=>G?.type==="TOKENS_LIMIT"),Y=J.find((G)=>G?.unit===3&&G?.number===5),Q=J.find((G)=>G?.unit===6&&G?.number===1),V=Z.find((G)=>G?.type==="TIME_LIMIT"),H=(G)=>G?{percent:nH(G.percentage),resetsAt:aH(G.nextResetTime)}:null,X=H(Y),z=H(Q),W=V?{percent:nH(V.percentage),resetsAt:aH(V.nextResetTime),...typeof V.currentValue==="number"?{used:V.currentValue}:{},...typeof V.usage==="number"?{total:V.usage}:{}}:null;return{state:"ok",level:typeof $?.level==="string"&&$.level?$.level:void 0,fiveHour:X,weekly:z,monthly:W,fetchedAt:Date.now()}}async function L9($,Z){let J=$&&Z?{ANTHROPIC_BASE_URL:$,ANTHROPIC_AUTH_TOKEN:Z}:qZ(),Y=J.ANTHROPIC_AUTH_TOKEN,Q=J.ANTHROPIC_BASE_URL||"";if(!Y)return{state:"no_credentials"};let V=BP(Q);if(!V)return{state:"not_glm",baseUrl:Q||void 0};let H=`${V}/api/monitor/usage/quota/limit`,X=new AbortController,z=setTimeout(()=>X.abort(),iH);try{let W=await $0(H,{headers:{Authorization:Y,"Content-Type":"application/json","Accept-Language":"en-US,en"},signal:X.signal});if(W.status===429)return{state:"rate_limited"};if(!W.ok)return{state:"network",reason:`HTTP ${W.status}`};let G=await W.json();if(G?.success===!1||typeof G?.code==="number"&&G.code!==200)return{state:"network",reason:G?.msg?String(G.msg):`code ${G?.code}`};let B=G?.data??G;return _P(B)}catch(W){let G=W?.name==="AbortError"?`timeout ${iH}ms`:W?.message??String(W);return K(`glm-usage: quota/limit fetch failed: ${G}`),{state:"network",reason:G}}finally{clearTimeout(z)}}async function rH(){if(m2)return m2;return m2=L9().then(($)=>{if(m2=null,$.state==="network")return LZ??$;return LZ=$,$}).catch(($)=>{return K(`glm-usage: fetchGlmUsage threw: ${$}`),m2=null,LZ??{state:"network",reason:String($)}}),m2}var iH=1e4,LZ=null,m2=null;var q9=R(()=>{h0();I()});function sH($){let Z=[];for(let J of $.matchAll(jP)){let Y=J[1]?.trim();if(Y)Z.push(Y)}return Z}function F6($,Z=process.platform){if(Z!=="win32")return $;let J=LP.exec($);if(!J)return $;return`${J[1].toUpperCase()}:\\`+$.slice(J[0].length).replace(/\//g,"\\")}var jP,LP;var PZ=R(()=>{jP=/\[\[send:[ \t]*([^\n]*?)[ \t]*\]\]/g;LP=/^\/([a-zA-Z])\//});function $X($){if(tH.test($))return{marker:"start",body:$.replace(tH,"")};if(eH.test($))return{marker:"end",body:$.replace(eH,"")};return{marker:"none",body:$}}var tH,eH;var ZX=R(()=>{tH=/^>{3,}[ \t]?/,eH=/^<{3,}[ \t]?/});async function JX($,Z,J,Y,Q){let{marker:V,body:H}=$X(Z);if(V==="start"){if($.multiMsgBuffer!==null&&$.multiMsgBuffer.length>0)FZ($,"reopen");return $.multiMsgBuffer=[],DZ($,H,J,Y,Q),!0}if(V==="end"){if($.multiMsgBuffer===null){if(H.trim()||J.length)return!1;return K(`session "${$.sessionName}": end marker without active multi-msg buffer, ignoring`),!0}DZ($,H,J,Y,Q);let{multiMsgBuffer:X,multiMsgReactions:z}=$;return $.multiMsgBuffer=null,$.multiMsgReactions=new Map,await PP($,X,z),!0}if($.multiMsgBuffer!==null)return DZ($,Z,J,Y,Q),!0;return!1}function DZ($,Z,J,Y,Q){if(Z.trim()||J.length)$.multiMsgBuffer.push({text:Z,files:J,userOpenId:Y,msgId:Q});if(Q)qP($,Q)}function qP($,Z){$.multiMsgReactions.set(Z,""),(async()=>{let J=await l0(Z,"Pin");if(!J)return;if($.multiMsgReactions.has(Z))$.multiMsgReactions.set(Z,J);else C0(Z,J)})()}async function PP($,Z,J){for(let[H,X]of J)if(X)C0(H,X);let Y=Z.filter((H)=>H.text.trim()||H.files.length);if(Y.length===0){K(`session "${$.sessionName}": multi-msg flush with empty buffer, not sent`),await E($.chatId,"⚠️ 多条消息缓冲为空,未发送(只收到标记没有正文)。");return}let Q=Y.map((H)=>{return(H.files.length?H.files.map((z)=>`[file: ${z}]`).join(" ")+`
|
|
216
216
|
`:"")+H.text}).join(`
|
|
217
217
|
|
|
218
|
-
`),V=Y[Y.length-1];K(`session "${$.sessionName}": multi-msg flush ${Y.length} segment(s) → 1 turn`),await $.onUserMessage(Q,[],V.userOpenId,V.msgId)}function MZ($,Z){if($.multiMsgBuffer===null)return;let J=$.multiMsgBuffer.length;K(`session "${$.sessionName}": clear multi-msg buffer (${Z}): ${J} segment(s)`);for(let[Y,Q]of $.multiMsgReactions){if(Q)C0(Y,Q);l0(Y,"CrossMark")}$.multiMsgBuffer=null,$.multiMsgReactions=new Map}var QX=R(()=>{t();I();JX()});import{mkdtemp as FP,rm as DP,writeFile as MP}from"node:fs/promises";import{createRequire as UP}from"node:module";import{tmpdir as AP}from"node:os";import{join as VX}from"node:path";function bP($){let Z=WX.get($);if(Z)return Z;let{liteAdaptor:J}=u1("mathjax-full/js/adaptors/liteAdaptor.js"),{RegisterHTMLHandler:Y}=u1("mathjax-full/js/handlers/html.js"),{mathjax:Q}=u1("mathjax-full/js/mathjax.js"),{TeX:V}=u1("mathjax-full/js/input/tex.js"),{AllPackages:H}=u1("mathjax-full/js/input/tex/AllPackages.js"),{SVG:X}=u1("mathjax-full/js/output/svg.js"),z=J({fontSize:$});Y(z);let W=Q.document("",{InputJax:new V({packages:H}),OutputJax:new X({fontCache:"none"})}),G={adaptor:z,doc:W};return WX.set($,G),G}function GX($,Z){let J=Number.parseFloat($??"");if(!Number.isFinite(J)||J<=0)throw Error(`MathJax SVG missing valid ${Z}`);return J}function CP($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function kP($,Z=OZ,J=!0){try{let Y=Z*OP,{adaptor:Q,doc:V}=bP(Z),H=V.convert($,{display:J,em:Z,ex:Y,containerWidth:80*Z}),X=Q.outerHTML(H);if(/data-mjx-error=|mjx-merror/.test(X)){let K0=X.match(/data-mjx-error="([^"]+)"/)?.[1]??"MathJax parse error";throw Error(K0)}let z=X.indexOf("<svg"),W=X.lastIndexOf("</svg>");if(z<0||W<0)throw Error("MathJax returned no SVG");let G=X.slice(z,W+6),B=G.match(/^<svg\b[^>]*>/)?.[0];if(!B)throw Error("MathJax returned malformed SVG root");let _=GX(B.match(/\bwidth="([\d.]+)ex"/)?.[1],"width"),j=GX(B.match(/\bheight="([\d.]+)ex"/)?.[1],"height"),q=B.match(/\bviewBox="([^"]+)"/)?.[1];if(!q)throw Error("MathJax SVG missing viewBox");let P=q.trim().split(/[\s,]+/).map(Number);if(P.length!==4||P.some((K0)=>!Number.isFinite(K0))||P[2]<=0||P[3]<=0)throw Error("MathJax SVG has invalid viewBox");let[F,T,M,A]=P,U=/<text\b/.test(G)?xP:0,S=`${F} ${T} ${M+U} ${A}`,b=_*Y,v=U*(b/M),y=Math.max(1,Math.ceil(b+v)),g=Math.max(1,Math.ceil(j*Y)),x=RP-UZ*2,h=Math.min(1,x/y),p=Math.max(1,Math.round(y*h)),l=Math.max(1,Math.round(g*h));if(h<1&&l<NP)throw Error(`formula would be unreadable after width cap (${p}x${l})`);let D=p+UZ*2,C=l+XX*2,d=G.slice(B.length,-6).replace(/currentColor/g,HX).replace(/font-family="serif"/g,`font-family="${SP}"`);return{svg:[`<svg xmlns="http://www.w3.org/2000/svg" width="${D}" height="${C}" viewBox="0 0 ${D} ${C}" style="color:${HX}">`,`<rect x="0" y="0" width="${D}" height="${C}" rx="6" fill="${jX}"/>`,`<svg x="${UZ}" y="${XX}" width="${p}" height="${l}" viewBox="${CP(S)}" preserveAspectRatio="xMidYMid meet">`,d,"</svg>","</svg>"].join(""),width:D,height:C}}catch(Y){return K(`math-render: TeX→SVG failed for ${$.slice(0,80)}…: ${Y}`),null}}function yP($,Z=OZ,J=!0){let Y=kP($,Z,J);if(!Y)return null;try{let{Resvg:Q}=u1("@resvg/resvg-js"),H=new Q(Y.svg,{background:jX,fitTo:{mode:"original"},shapeRendering:2,textRendering:1,font:{loadSystemFonts:!0,serifFamily:zX,sansSerifFamily:zX}}).render().asPng(),X=new DataView(H.buffer,H.byteOffset,H.byteLength),z=X.getUint32(16),W=X.getUint32(20);if(z!==Y.width||W!==Y.height)throw Error(`PNG dimensions ${z}x${W} != SVG ${Y.width}x${Y.height}`);return{png:H,width:z,height:W}}catch(Q){return K(`math-render: SVG→PNG failed for ${$.slice(0,80)}…: ${Q}`),null}}function wP($){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 KX($,Z){let J=[],Y=(G,B,_)=>{let j=G[0],q=B.trim();if(!q)return;J.push({start:Z+G.index,end:Z+G.index+j.length,tex:q,raw:j,display:_})},Q,V=/(?<!\\)\$\$([\s\S]+?)(?<!\\)\$\$|\\\[([\s\S]+?)\\\]/g;while((Q=V.exec($))!==null)Y(Q,Q[1]??Q[2]??"",!0);let H=/\\\(([\s\S]+?)\\\)/g;while((Q=H.exec($))!==null)Y(Q,Q[1]??"",!1);let X=/(?<![\\$])\$(?!\$)([^$\n]+?)(?<![\\$])\$(?!\$)/g;while((Q=X.exec($))!==null){let G=(Q[1]??"").trim();if(wP(G))Y(Q,G,!1)}J.sort((G,B)=>G.start-B.start||B.end-G.end);let z=[],W=-1;for(let G of J){if(G.start<W)continue;z.push(G),W=G.end}return z}function LX($){let Z=t7($),J=[],Y=0;for(let Q of Z){if(Y<Q.start)J.push(...KX($.slice(Y,Q.start),Y));Y=Math.max(Y,Q.end)}if(Y<$.length)J.push(...KX($.slice(Y),Y));return J}function vP($){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,Y)=>{if(BX[Y])return BX[Y];if(Y==="times")return"×";if(Y==="cdot")return"·";if(Y==="div")return"÷";if(Y==="pm")return"±";if(Y==="leq"||Y==="le")return"≤";if(Y==="geq"||Y==="ge")return"≥";if(Y==="neq"||Y==="ne")return"≠";if(Y==="approx")return"≈";if(Y==="sim")return"~";if(Y==="infty")return"∞";if(Y==="partial")return"∂";if(Y==="nabla")return"∇";if(Y==="sqrt")return"√";if(Y==="to")return"→";return J}),/\\/.test(Z))return null;if(Z=Z.replace(/([_^])\{([^{}]+)\}/g,(J,Y,Q)=>Q.length===1?`${Y}${Q}`:`${Y}(${Q})`),Z=Z.replace(/√\{([^{}]+)\}/g,"√($1)"),/[{}]/.test(Z))return null;return Z}function gP($){let Z=_X.get($);if(Z!==void 0)return Z;return Z=hP++,_X.set($,Z),Z}function mP($,Z){return`${EP}\x00${gP(Z)}\x00${$}`}function pP($){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 cP($,Z){let J=mP($,Z),Y=c1.get(J);if(Y)return Y;let Q=AZ.get(J);if(Q)return Q;let V=(async()=>{let H=yP($,OZ,!0);if(!H)return null;let X=null;try{X=await FP(VX(AP(),"lodestar-math-"));let z=VX(X,`formula-${pP($)}.png`);await MP(z,H.png);let W=await Z(z,{tex:$,width:H.width,height:H.height});if(!W)return K(`math-render: upload returned no image key for ${$.slice(0,80)}…`),null;let G={key:W,width:H.width,height:H.height};if(c1.has(J))c1.delete(J);c1.set(J,G);while(c1.size>IP){let B=c1.keys().next().value;if(typeof B!=="string")break;c1.delete(B)}return G}catch(z){return K(`math-render: upload failed for ${$.slice(0,80)}…: ${z}`),null}finally{if(X)try{await DP(X,{recursive:!0,force:!0})}catch(z){K(`math-render: temp cleanup failed for ${X}: ${z}`)}}})();AZ.set(J,V);try{return await V}finally{AZ.delete(J)}}function uP($,Z,J){let Y=$.width<=TP;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:Y?"crop_center":"fit_horizontal",...Y?{size:`${$.width}px ${$.height}px`}:{},preview:!1}}}async function qX($,Z={}){let J=LX($);if(!J.length)return{blocks:[{type:"markdown",text:$}],formulaCount:0,renderedImageCount:0};let Y=Z.uploader??fP,Q=await Promise.all(J.map(async(G)=>{if(!G.display){let B=vP(G.tex);if(B!==null)return{unicode:B,uploaded:null}}return{unicode:null,uploaded:await cP(G.tex,Y)}})),V=[],H="",X=0,z=0,W=()=>{if(!H)return;if(H.trim())V.push({type:"markdown",text:H});H=""};for(let G=0;G<J.length;G++){let B=J[G],_=Q[G];if(H+=$.slice(X,B.start),_.unicode!==null){H+=_.unicode,X=B.end;continue}let j=_.uploaded;if(!j){H+=B.raw,X=B.end;continue}W(),V.push(uP(j,B,z++)),X=B.end}if(H+=$.slice(X),W(),!V.length)V.push({type:"markdown",text:$});return{blocks:V,formulaCount:J.length,renderedImageCount:z}}function RZ($){return LX($).length>0}var u1,OP=0.5,OZ=22,HX="#1F2329",jX="#F7F8FA",UZ=12,XX=8,RP=720,NP=14,TP=278,EP="v4-native-cjk-tail-pad",xP=1100,zX,SP="Noto Sans CJK SC, Noto Sans CJK JP, Microsoft YaHei, PingFang SC, Arial Unicode MS, sans-serif",WX,BX,fP=async($)=>{let{uploadImageKey:Z}=await Promise.resolve().then(() => (t(),Y0));return Z($)},_X,hP=1,c1,AZ,IP=512;var PX=R(()=>{I();u1=UP(import.meta.url),zX=process.platform==="win32"?"Microsoft YaHei":process.platform==="darwin"?"PingFang SC":"Noto Sans CJK SC",WX=new Map;BX={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:"Ω"};_X=new WeakMap,c1=new Map,AZ=new Map});import{readFileSync as dP}from"node:fs";function p2($){return NZ.has($)}function P9($){NZ.add($)}function F9($){NZ.delete($)}function c2(){try{let $={};for(let[Z,J]of n0)$[Z]=J;s(U6,$)}catch($){throw K(`notify-callbacks: save failed (${U6}): ${$}`),$}}function UX(){let $=[],Z;try{Z=dP(U6,"utf8")}catch{return[]}try{let J=JSON.parse(Z),Y=Date.now()-MX,Q=0,V=0;for(let H of Object.values(J)){if(!H||typeof H!=="object")continue;if(typeof H.notifyId!=="string"||typeof H.callbackUrl!=="string")continue;if(typeof H.createdAt!=="number"||H.createdAt<Y){Q++;continue}if(H.replyState?.status==="sending"&&!H.resolvedAt&&!H.unknownAt)H.unknownAt=Date.now(),H.unknownBy={openId:H.replyState.openId},H.unknownReason="服务在文字回复回传期间中断,无法确认是否送达,禁止自动重试",V++;if(n0.set(H.notifyId,H),H.replyState?.status==="sending"&&H.unknownAt)$.push(H)}if(K(`notify-callbacks: loaded ${n0.size} registration(s)${Q?`, dropped ${Q} stale`:""}`),V)K(`notify-callbacks: ${V} interrupted text reply(s) marked UNKNOWN`);if(Q>0||V>0)c2()}catch(J){K(`notify-callbacks: load failed (${U6}): ${J}`)}return $}function AX($){let Z=Date.now();if(Z-DX>=iP)nP(Z),DX=Z;n0.set($.notifyId,$),c2()}function I$($){return n0.get($)}function TZ($){return[...n0.values()].filter((Z)=>Z.chatId===$&&!Z.resolvedAt&&!Z.unknownAt&&(Z.replyState?.status==="waiting"||Z.replyState?.status==="sending"))}function D9($,Z){if(!$)return;return TZ($).find((J)=>Z===void 0||J.replyState?.openId===Z)}function OX($,Z){return!!Z&&[...n0.values()].some((J)=>J.chatId===$&&(J.replyMessageIds?.includes(Z)||J.replyState?.response?.message_id===Z))}function u2($,Z){let J=n0.get($);if(!J)throw Error(`notify registration not found: ${$}`);let{replyState:Y,replyMessageIds:Q}=J;if(J.replyState=Z,Z.response&&!J.replyMessageIds?.includes(Z.response.message_id))J.replyMessageIds=[...J.replyMessageIds??[],Z.response.message_id];try{c2()}catch(V){if(Y)J.replyState=Y;else delete J.replyState;if(Q)J.replyMessageIds=Q;else delete J.replyMessageIds;throw V}}function M9($,Z,J){let Y=n0.get($);if(!Y)throw Error(`notify registration not found: ${$}`);let Q={resolvedAt:Y.resolvedAt,resolvedBy:Y.resolvedBy,unknownAt:Y.unknownAt,unknownBy:Y.unknownBy,unknownReason:Y.unknownReason};Y.resolvedAt=Date.now(),Y.resolvedBy={...Z!==void 0?{buttonId:Z}:{},openId:J},delete Y.unknownAt,delete Y.unknownBy,delete Y.unknownReason;try{c2()}catch(V){if(Q.resolvedAt===void 0)delete Y.resolvedAt;else Y.resolvedAt=Q.resolvedAt;if(Q.resolvedBy===void 0)delete Y.resolvedBy;else Y.resolvedBy=Q.resolvedBy;if(Q.unknownAt===void 0)delete Y.unknownAt;else Y.unknownAt=Q.unknownAt;if(Q.unknownBy===void 0)delete Y.unknownBy;else Y.unknownBy=Q.unknownBy;if(Q.unknownReason===void 0)delete Y.unknownReason;else Y.unknownReason=Q.unknownReason;throw V}}function EZ($,Z,J,Y){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);delete Q.resolvedAt,delete Q.resolvedBy,Q.unknownAt=Date.now(),Q.unknownBy={...Z!==void 0?{buttonId:Z}:{},openId:J},Q.unknownReason=Y,c2()}function A6($,Z,J){try{return M9($,Z,J),{state:"complete"}}catch(Y){let V=`resolved tombstone persistence failed: ${Y instanceof Error?Y.message:String(Y)}`;try{EZ($,Z,J,V)}catch(H){let X=H instanceof Error?H.message:String(H);V+=`; unknown tombstone persistence also failed: ${X}`;let z=n0.get($);if(z)z.unknownReason=V}return{state:"unknown",detail:V}}}function nP($=Date.now()){let Z=$-MX,J=0;for(let[Y,Q]of n0)if(typeof Q.createdAt!=="number"||Q.createdAt<Z)n0.delete(Y),J++;if(J>0)c2();return J}async function xZ($,Z,J){let Y={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)},Q=new AbortController,V=setTimeout(()=>Q.abort(),FX);try{let H=await XY($.callbackUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y),signal:Q.signal});if(H.status>=200&&H.status<300){let z;try{let W=(await H.text()).trim();if(W.startsWith("{")){let G=JSON.parse(W),B=typeof G?.text==="string"?G.text:typeof G?.reply==="string"?G.reply:typeof G?.message==="string"?G.message:"";if(B.trim())z=B.trim().slice(0,500)}else if(W)z=W.slice(0,500)}catch{}return{ok:!0,detail:`${H.status}`,reply:z}}let X="";try{X=(await H.text()).slice(0,120)}catch{}return{ok:!1,detail:`HTTP ${H.status}${X?` ${X}`:""}`}}catch(H){if(H?.name==="AbortError")return{ok:!1,detail:`回调超时 ${FX}ms(本地服务未在窗口内 2xx)`};return{ok:!1,detail:`回调失败: ${String(H?.message??H).slice(0,160)}`}}finally{clearTimeout(V)}}function RX($){let Z=!!$.resolvedAt,J=!!$.unknownAt,Y=$.resolvedBy?.buttonId??$.unknownBy?.buttonId,Q=Y?$.buttons.find((X)=>X.id===Y):void 0,V=$.replyState?.response,H=Y!==void 0?{button:Q?{id:Q.id,text:Q.text,type:Q.type}:{id:Y}}:V?{response:{type:"text",...V}}:{};return{notify_id:$.notifyId,project:$.project,message_id:$.messageId,resolved:Z,unknown:J,...$.replyState?{reply:{status:Z&&Y===void 0?"resolved":J&&Y===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?{...H,resolved_at:$.resolvedAt,resolved_by:$.resolvedBy?.openId??null}:{},...J?{...H,unknown_at:$.unknownAt,unknown_by:$.unknownBy?.openId??null,unknown_reason:$.unknownReason}:{}}}var MX=604800000,FX=2500,n0,DX,iP=86400000,NZ,U6;var U9=R(()=>{h0();I();Q0();T0();n0=new Map,DX=Date.now(),NZ=new Set;U6=aJ});function O6($){return[...$.pendingAsks.entries()].find(([,Z])=>Z.currentIdx!==void 0)}function l2($,Z){let J=$.pendingAsks.get(Z);if(!J||J.currentIdx===void 0)return null;if(D9($.chatId))return"请先完成或取消通知回复,再回答 Agent 的提问";if(O6($)?.[0]!==Z)return"请先回答当前问题,再回答排队中的提问";return null}function SZ($,Z){let J=$.pendingAsks.get(Z);if(!J)throw Error(`missing pending ask: ${Z}`);let Y=J.currentIdx===void 0?void 0:D9($.chatId)?"notification":O6($)?.[0]!==Z?"question":void 0;return{currentIdx:J.currentIdx,answered:J.answered,waitingFor:Y}}function bZ($,Z){let J=$.pendingAsks.get(Z),Y=$.currentTurn;if(!J||J.currentIdx===void 0||J.announced||l2($,Z)||!Y?.userOpenId||!Y.messageId)return;J.announced=!0;let Q=(J.announcementVersion??0)+1;J.announcementVersion=Q;let V=J.questions[J.currentIdx]?.question.trim()??"",H=V.length>40?V.slice(0,40)+"…":V,X=J.questions.length>1?`❓ 待回答 ${J.questions.length} 题${H?`: ${H}`:""}`:H?`❓ ${H}`:"❓ 等你回答问题";(async()=>{if(A0(Y.cardId),await c8(Y.cardId,{config:{summary:{content:X}}}),$.currentTurn!==Y||$.pendingAsks.get(Z)!==J||J.announcementVersion!==Q||J.currentIdx===void 0||l2($,Z))return;await C1(Y.messageId,[Y.userOpenId])})().catch((z)=>K(`session "${$.sessionName}": question notification failed: ${z}`))}function R6($){let Z=$.currentTurn;if(!Z)return;for(let[J,Y]of $.pendingAsks){let Q=Z.toolByUseId.get(J);if(!Q||Y.currentIdx===void 0)continue;let V=SZ($,J);if(V.waitingFor)Y.announced=!1,Y.announcementVersion=(Y.announcementVersion??0)+1;J0(Z.cardId,N.tool(Q.i),v2(Q.i,J,Y.questions,"\uD83E\uDD14",V)),bZ($,J)}}function NX($){return O6($)!==void 0}async function TX($,Z,J,Y){let Q=O6($);if(!Q){K(`session "${$.sessionName}": no unanswered question; routing text to Agent`),await $.onUserMessage(Z,[],J,Y);return}let[V,H]=Q,X=l2($,V);if(X){let W=`${X}。这条文字未提交,请稍后重新发送。`;if(!await E($.chatId,W))throw Error(`提问等待提示发送失败: ${W}`);return}if(await CZ($,V,H.currentIdx,Z,J)&&Y)l0(Y,"CheckMark")}async function EX($,Z,J,Y,Q){let V=$.pendingAsks.get(Z);if(!V)return K(`session "${$.sessionName}": stray ask answer for ${Z}`),!1;if(J!==V.currentIdx)return K(`session "${$.sessionName}": stale ask click q=${J} current=${V.currentIdx}`),!1;return xX($,Z,{optionIdx:Y,user:Q})}async function CZ($,Z,J,Y,Q){let V=$.pendingAsks.get(Z);if(!V)return K(`session "${$.sessionName}": stray ask custom for ${Z}`),!1;let H=(Y??"").trim();if(!H)return K(`session "${$.sessionName}": empty custom answer, ignoring`),!1;if(J!==V.currentIdx)return K(`session "${$.sessionName}": stale ask custom q=${J} current=${V.currentIdx}`),!1;return xX($,Z,{customText:H,user:Q})}function xX($,Z,J){let Y=$.pendingAsks.get(Z);if(!Y||Y.currentIdx===void 0)return!1;let Q=l2($,Z);if(Q)return K(`session "${$.sessionName}": ask ${Z} waiting: ${Q}`),!1;let V=Y.currentIdx,H=Y.questions[V];if(!H)return K(`session "${$.sessionName}": advanceAsk currentIdx=${V} out of range`),!1;let X;if(J.customText!==void 0)X=J.customText;else if(J.optionIdx!==void 0){let _=H.options?.[J.optionIdx];if(!_)return K(`session "${$.sessionName}": advanceAsk option ${J.optionIdx} out of range`),!1;X=_.label}else return K(`session "${$.sessionName}": advanceAsk with neither customText nor optionIdx`),!1;Y.answers[H.question]=X,Y.answered.set(V,{optionIdx:J.optionIdx,customText:J.customText,user:J.user});let z=Y.questions.length,W=void 0;for(let _=V+1;_<z;_++)if(!Y.answered.has(_)){W=_;break}Y.currentIdx=W;let G=$.currentTurn,B=G?.toolByUseId.get(Z);if(G&&B){let _=v2(B.i,Z,Y.questions,W===void 0?"✅":"\uD83E\uDD14",{currentIdx:W,answered:Y.answered});J0(G.cardId,N.tool(B.i),_)}if(W===void 0)if(Y.requestId)kZ($,Z);else K(`session "${$.sessionName}": ask ${Z} all answered, waiting for can_use_tool`),R6($);return!0}function kZ($,Z){let J=$.pendingAsks.get(Z);if(!J||!J.requestId)return;let Y=$.currentTurn?.toolByUseId.get(Z),Q=Y?.input??{};if($.proc?.sendPermissionResponse(J.requestId,"allow",{updatedInput:{...Q,answers:J.answers}}),$.pendingPermissions.delete(J.requestId),Y)Y.output=JSON.stringify({answers:J.answers}),Y.isError=!1;if($.pendingAsks.delete(Z),R6($),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working"}var N6=R(()=>{v$();Y$();t();I();U9()});import{isAbsolute as oP}from"node:path";function O0($){if($?.planLiveInserted)return N.planLive;return $?.taskLiveInserted?N.taskBoardLive:N.footer}function rP($){return $==="ImageGeneration"||$==="imageGeneration"}function sP($,Z,J){if(J||!rP($))return null;let Y=M6(Z.trim());return oP(Y)?Y:null}function tP($){if($==="Read")return"read";if($==="Edit"||$==="MultiEdit"||$==="NotebookEdit")return"edit";return null}function SX($,Z,J){return $==="read"?X9(Z,J):H9(Z,J)}function bX($,Z,J,Y){if(!$.currentTurn)return;if($.maybeMidTurnRotate(),$.startWorkingFooter($.currentTurn),$.currentTurn.currentAssistantSegmentId)$.finalizeCurrentAssistantSegment();let Q=tP(J);if(Q&&$.currentTurn.openBatchI!==null){let z=$.currentTurn.openBatchI,W=$.currentTurn.toolBatches.get(z);if(W&&W.kind===Q){let G=W.items.length;W.items.push({toolUseId:Z,input:Y,output:null,isError:!1}),$.currentTurn.toolByUseId.set(Z,{i:z,name:J,input:Y,batchSlot:G});let B=Q==="read"?X9(z,W.items):H9(z,W.items);J0($.currentTurn.cardId,N.tool(z),B),T6($.currentTurn,J,Y);return}}if(!Q)$.currentTurn.openBatchI=null;let V=g1(J);if(V){let z=$.currentTurn;if(V==="TaskCreate"&&!z.taskBoardResetThisTurn)$.taskBoard=[],z.taskBoardResetThisTurn=!0;if(!z.taskLiveInserted)z.taskLiveInserted=!0,D0(z.cardId,m1($.taskBoard),{type:"insert_before",targetElementId:N.footer});else J0(z.cardId,N.taskBoardLive,m1($.taskBoard));let W=V==="TaskCreate";if(W)z.taskUpdateI=null;else z.taskCreateI=null;let G=(W?z.taskCreateI:z.taskUpdateI)===null;if(G)if(W)z.taskCreateI=z.toolCount++;else z.taskUpdateI=z.toolCount++;let B=W?z.taskCreateI:z.taskUpdateI;z.toolByUseId.set(Z,{i:B,name:J,input:Y});let _=W1(B,$.taskBoard,{name:V,status:"⏳"});G?D0(z.cardId,_,{type:"insert_before",targetElementId:O0(z)}):J0(z.cardId,N.tool(B),_),T6(z,J,Y);return}$.currentTurn.taskCreateI=null,$.currentTurn.taskUpdateI=null;let H=$.currentTurn.toolCount++;if(Q){$.currentTurn.openBatchI=H;let z=[{toolUseId:Z,input:Y,output:null,isError:!1}];$.currentTurn.toolBatches.set(H,{kind:Q,items:z}),$.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Y,batchSlot:0});let W=Q==="read"?X9(H,z):H9(H,z);D0($.currentTurn.cardId,W,{type:"insert_before",targetElementId:O0($.currentTurn)}),T6($.currentTurn,J,Y);return}if($.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Y}),J==="AskUserQuestion"){let z=Array.isArray(Y?.questions)?Y.questions:[],W=z.length>0?0:void 0,G=new Map;$.pendingAsks.set(Z,{questions:z,i:H,answers:{},answered:G,currentIdx:W});let B=v2(H,Z,z,"\uD83E\uDD14",SZ($,Z));D0($.currentTurn.cardId,B,{type:"insert_before",targetElementId:O0($.currentTurn)}),bZ($,Z);return}let X=R$(H,J,Y,null,"⏳");D0($.currentTurn.cardId,X,{type:"insert_before",targetElementId:O0($.currentTurn)}),T6($.currentTurn,J,Y)}function T6($,Z,J){if(!$)return;let Y=Q1(Z,J),Q=Y.length>80?Y.slice(0,80)+"…":Y,V=f1(Z),H=Q?`\uD83D\uDD27 ${V}: ${Q}`:`\uD83D\uDD27 ${V}`;w1($.cardId,H)}function CX($,Z,J,Y,Q){if(!$.currentTurn)return;let V=$.currentTurn.toolByUseId.get(Z);if(!V)return;if(Q&&typeof Q==="object")V.input={...V.input,...Object.fromEntries(Object.entries(Q).filter(([,G])=>G!==void 0))};let H=typeof J==="string"?J:Array.isArray(J)?J.map((G)=>G?.text??JSON.stringify(G)).join(`
|
|
219
|
-
`):JSON.stringify(J);if(V.output=H,V.isError=Y,$.currentTurn.cardRotationFailed)$.maybeMidTurnRotate();let X=sP(V.name,H,Y);if(X){eP($,$.currentTurn,V,X),A9($);return}if(V.name==="AskUserQuestion"){A9($);return}if(V.batchSlot!=null){let G=$.currentTurn.toolBatches.get(V.i);if(G){let B=G.items[V.batchSlot];if(B)B.output=H,B.isError=Y;let _=SX(G.kind,V.i,G.items);J0($.currentTurn.cardId,N.tool(V.i),_)}A9($);return}let z=g1(V.name);if(z){$F($,V,z,V.input,H,Y,V.resolvedNote);return}let W=R$(V.i,V.name,V.input,H,Y?"❌":"✅",V.resolvedNote);J0($.currentTurn.cardId,N.tool(V.i),W),A9($)}function eP($,Z,J,Y){if(Z.outboundSeenPaths.has(Y))return;Z.outboundSeenPaths.add(Y);let Q=Z.cardId,V=N.tool(J.i),H=Z.imageDeliveryInflight??=new Map,X=H.get(Q)??new Set;H.set(Q,X);let z=(async()=>{let W=null;try{W=await q5(Y)}catch(B){K(`generated image upload failed: ${B}`)}if(W){let B=!1;try{B=await M0(Q,V,R$(J.i,J.name,J.input,J.output??null,"✅",J.resolvedNote,W),{notifyCardFailure:!1})}catch(_){K(`generated image embed failed: ${_}`)}if(B){J.imageKey=W,Z.outboundSentPaths.add(Y);return}K(`generated image could not be embedded in card ${Q}; sending it as a separate message`)}let G=W?await m8($.chatId,W)!==null:await o4($.chatId,Y);if(G)Z.outboundSentPaths.add(Y);else K(`generated image delivery failed: ${Y}`);if(J.resolvedNote=G?"图片已单独发送。":"图片发送失败。",await M0(Q,V,R$(J.i,J.name,J.input,J.output??null,G?"✅":"❌",J.resolvedNote),{notifyCardFailure:!1}),!G&&W)await E($.chatId,"❌ 生成图片发送失败,请稍后重试。")})().catch(async(W)=>{K(`generated image delivery failed: ${W}`),await E($.chatId,`❌ 生成图片发送失败:${W instanceof Error?W.message:String(W)}`)});X.add(z),z.finally(()=>{if(X.delete(z),!X.size)H.delete(Q)}).catch((W)=>K(`generated image failure notice failed: ${W}`))}async function yZ($,Z){let J=Z?[...$.imageDeliveryInflight?.get(Z)??[]]:[...$.imageDeliveryInflight?.values()??[]].flatMap((Y)=>[...Y]);await Promise.allSettled(J)}function $F($,Z,J,Y,Q,V,H){if(!$.currentTurn)return;if(!V)$.taskBoard=jZ($.taskBoard,J,Y,Q);let X=W1(Z.i,$.taskBoard,{name:J,status:V?"❌":"✅"},H);if(J0($.currentTurn.cardId,N.tool(Z.i),X),$.currentTurn.taskLiveInserted)J0($.currentTurn.cardId,N.taskBoardLive,m1($.taskBoard));A9($)}function A9($){let Z=$.currentTurn;if(!Z)return;for(let J of Z.toolByUseId.values())if(J.output==null)return;$.startThinkingFooter(Z)}function wZ($,Z,J,Y,Q,V=$.currentTurn){let H=V;if(!H)return;for(let[X,z]of Y){if(H.toolByUseId.has(X))continue;let W=z.batchSlot??null,G=z.input,B,_;if(W!=null){let M=Q.get(z.i)?.items[W];if(!M)continue;G=M.input,B=M.output,_=M.isError}else B=z.output??null,_=z.isError??!1;let j=B!=null,q=k2(Z,N.tool(z.i));if(j&&!q)continue;if(W!=null){let M=Q.get(z.i)?.kind;if(!M)continue;let A=H.toolCount++,U={toolUseId:X,input:G,output:B,isError:_};H.toolBatches.set(A,{kind:M,items:[U]}),H.toolByUseId.set(X,{...z,i:A,batchSlot:0}),D0(J,SX(M,A,[U]),{type:"insert_before",targetElementId:O0(H)});continue}let P=g1(z.name);if(P){let M=P==="TaskCreate";if(M)H.taskUpdateI=null;else H.taskCreateI=null;let A=(M?H.taskCreateI:H.taskUpdateI)===null;if(A)if(M)H.taskCreateI=H.toolCount++;else H.taskUpdateI=H.toolCount++;let U=M?H.taskCreateI:H.taskUpdateI;H.toolByUseId.set(X,{...z,i:U});let S=!j?"⏳":_?"❌":"✅",b=W1(U,$.taskBoard,{name:P,status:S},z.resolvedNote);A?D0(J,b,{type:"insert_before",targetElementId:O0(H)}):J0(J,N.tool(U),b);continue}let F=H.toolCount++;H.toolByUseId.set(X,{...z,i:F});let T=!j?"⏳":_?"❌":"✅";D0(J,R$(F,z.name,z.input,B,T,z.resolvedNote,z.imageKey),{type:"insert_before",targetElementId:O0(H)})}}var kX=R(()=>{FZ();v$();Y$();t();I();N6()});async function yX($,Z,J,Y){let Q=$.pendingPermissions.get(Z);if(!Q)return K(`session "${$.sessionName}": stray permission ${Z}`),{ok:!1,message:"此权限请求已失效或已处理"};let V=$.proc;if(!V)return K(`session "${$.sessionName}": permission ${Z} has no active process`),{ok:!1,message:"后端进程已退出,权限决定未送达"};let H=J==="deny"?"deny":"allow";try{V.sendPermissionResponse(Z,H,J==="allow_always"?{updatedPermissions:Q.permissionSuggestions}:void 0)}catch(W){return K(`session "${$.sessionName}": permission response ${Z} failed: ${W}`),{ok:!1,message:`权限决定发送失败: ${W instanceof Error?W.message:W}`}}$.pendingPermissions.delete(Z);let X=$.currentTurn,z=X?.toolByUseId.get(Q.toolUseId);if(X&&z){let W=g1(z.name);if(J==="deny"){let G=`\uD83D\uDEAB 已拒绝 by ${Y||"匿名"}`,B=W?W1(z.i,$.taskBoard,{name:W,status:"❌"},G):R$(z.i,z.name,z.input,G,"❌");J0(X.cardId,N.tool(z.i),B)}else{let G=J==="allow_always"?"始终允许":"已允许";z.resolvedNote=`✅ **${G}** by ${Y||"匿名"}`;let B=W?W1(z.i,$.taskBoard,{name:W,status:"⏳"},z.resolvedNote):R$(z.i,z.name,z.input,null,"⏳",z.resolvedNote);J0(X.cardId,N.tool(z.i),B)}}if(K(`session "${$.sessionName}": permission decision request=${Z} tool_use_id=${Q.toolUseId} decision=${J}`),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working";return{ok:!0,message:J==="deny"?"已拒绝":J==="allow_always"?"已始终允许":"已允许"}}function wX($,Z){let J=$.currentTurn;if(!J){K(`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 Y=Z.tool_use_id;if(!Y){K(`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 Q=J.toolByUseId.get(Y);if(!Q){K(`session "${$.sessionName}": can_use_tool for unknown tool_use_id=${Y} — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"unknown tool_use_id"});return}if(Q.name==="AskUserQuestion"){let H=$.pendingAsks.get(Y);if(!H){K(`session "${$.sessionName}": AskUserQuestion ${Y} missing pendingAsk — deny`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no pending ask"});return}if(H.requestId=Z.request_id,$.pendingPermissions.set(Z.request_id,{toolUseId:Y}),H.currentIdx===void 0)kZ($,Y);return}$.status="awaiting_permission",$.pendingPermissions.set(Z.request_id,{toolUseId:Y,permissionSuggestions:Z.permission_suggestions}),K(`session "${$.sessionName}": can_use_tool request=${Z.request_id} tool_use_id=${Y} tool=${Q.name}`);let V=c5(Q.i,Q.name,Q.input,Z.request_id);if(J0(J.cardId,N.tool(Q.i),V),J.userOpenId&&J.messageId){let H=Q1(Q.name,Q.input),X=f1(Q.name),z=H&&H.length>30?H.slice(0,30)+"…":H,W=z?`\uD83D\uDD10 等审批: ${X} · ${z}`:`\uD83D\uDD10 等审批: ${X}`;(async()=>{A0(J.cardId),await c8(J.cardId,{config:{summary:{content:W}}}),await C1(J.messageId,[J.userOpenId])})()}}var vX=R(()=>{v$();Y$();t();I();N6()});class fX{createClient;waitMs;recordLogin;stateWaitMs;attempts=new Map;stopping=!1;constructor($=(Q)=>new T1({accountId:Q,login:!0}),Z=900000,J=(Q,V)=>{k.recordLogin(Q,V),O2(Q)},Y=1e4){this.createClient=$;this.waitMs=Z;this.recordLogin=J;this.stateWaitMs=Y}async start($,Z){if(this.stopping)throw Error("服务正在退出,无法开始登录");if(!Z.userOpenId)throw Error("无法确认登录发起者");if(this.attempts.has($))throw Error("该账号已有登录任务;使用 codex-login-cancel 取消后再登录");let J=JQ($),Y;try{Y=this.createClient($)}catch(z){throw J(),z}let Q,V,H=new Promise((z,W)=>{Q=z,V=W});H.catch(()=>{});let X={owner:Z,client:Y,accountId:$,loginId:null,loginRequested:!1,loginSucceeded:!1,authUpdated:!1,finishing:!1,done:H,resolve:Q,reject:V,timer:null,notification:()=>{},closed:()=>{},early:[],releaseAuth:J};X.notification=(z,W)=>{if(X.finishing||!X.loginRequested)return;if(z==="account/updated"){if(W?.authMode==="chatgpt"){if(X.authUpdated=!0,X.loginSucceeded)this.finish(X)}return}if(z!=="account/login/completed")return;if(!X.loginId){X.early.push(W);return}if(W?.loginId!==X.loginId)return;if(W?.success!==!0){this.finish(X,Error(typeof W?.error==="string"?W.error:"Codex 登录未成功"));return}if(X.loginSucceeded)return;if(X.loginSucceeded=!0,K(`codex-login: authorization completed account=${$} authUpdated=${X.authUpdated}`),X.timer)clearTimeout(X.timer);if(X.authUpdated)this.finish(X);else X.timer=setTimeout(()=>{this.finish(X,Error("设备码授权已完成,但 Codex 未及时更新账号状态;认证文件已保留,可用 codex-accounts 检查"))},this.stateWaitMs)},X.closed=(z)=>{this.finish(X,z)},Y.on("notification",X.notification),Y.on("closed",X.closed),Y.on("protocolError",X.closed),this.attempts.set($,X);try{await Y.initialize("lodestar-login"),X.loginRequested=!0;let z=await Y.request("account/login/start",{type:"chatgptDeviceCode"},30000);if(z?.type!=="chatgptDeviceCode"||typeof z.loginId!=="string"||!z.loginId||typeof z.userCode!=="string"||!z.userCode||typeof z.verificationUrl!=="string"||new URL(z.verificationUrl).protocol!=="https:")throw Error("Codex 设备码登录响应不完整");if(X.loginId=z.loginId,X.finishing)throw await H,Error("登录已结束");X.timer=setTimeout(()=>{this.cancelAttempt(X,"登录等待超过 15 分钟,请重新发送 codex-login [备注]").catch(()=>{})},this.waitMs);for(let W of X.early)X.notification("account/login/completed",W);return X.early.length=0,{accountId:$,loginId:z.loginId,verificationUrl:z.verificationUrl,userCode:z.userCode,done:H}}catch(z){return await this.finish(X,E6(z)),await H}}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(Y){J=Error(`${Z};取消请求失败:${E6(Y).message}`)}await this.complete($,J)}async finish($,Z){if($.finishing)return;if($.finishing=!0,$.timer)clearTimeout($.timer);let J;if(!Z)try{let Y=await $.client.request("account/read",{refreshToken:!1});if(Y?.account?.type!=="chatgpt"){let Q=typeof Y?.account?.type==="string"?Y.account.type:"null";throw Error(`设备码授权已完成,但账号状态校验失败(account/read.type=${Q});认证文件已保留`)}J=Y.account,this.recordLogin($.accountId,J)}catch(Y){Z=E6(Y)}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(Y){Z=Error([Z?.message,`登录进程关闭失败:${E6(Y).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 E6($){return $ instanceof Error?$:Error(String($))}var l1;var vZ=R(()=>{w$();p0();I();l1=new fX});function hX($){let Z=new Map,J=$.map((G)=>{let B=G.fingerprint?Z.get(G.fingerprint):void 0;if(G.fingerprint&&!B)Z.set(G.fingerprint,G.account.name);return{...G,...B?{duplicateOf:B}:{}}}),Y=J.filter((G)=>!G.duplicateOf),V=(Y.length<=1||Y.every((G)=>G.fingerprint!==null))&&Y.every((G)=>G.usage.state==="ok"),H=Y.flatMap((G)=>G.usage.state==="ok"?[G.usage]:[]),X=V&&H.every((G)=>[G.fiveHour,G.weekly].filter(Boolean).every((B)=>B.percent!==null))?H.filter((G)=>[G.fiveHour,G.weekly].filter(Boolean).every((B)=>B.percent<100)).length:null,z=V&&H.every((G)=>G.resetCredits!=null)?H.reduce((G,B)=>G+B.resetCredits,0):null,W=["fiveHour","weekly"].map((G)=>{let B=H.map((j)=>j[G]).filter((j)=>j!==null),_=V&&B.every((j)=>j.percent!==null&&j.percent>=0&&j.percent<=100);return{kind:G,count:B.length,remaining:_?B.reduce((j,q)=>j+(100-q.percent)/100,0):null}}).filter((G)=>G.count||!V);return{entries:J,complete:V,available:X,resetCredits:z,windows:W}}var IX=R(()=>{p0();w$()});class d2{cardId;deps;tail=Promise.resolve();terminal=null;constructor($,Z){this.cardId=$;this.deps=Z}static async open($,Z,J=YF){let Y=await J.sendCard($,V$(Z,!0));if(!Y)throw Error("Codex 账号卡片发送失败");let Q=await J.convertMessageToCard(Y);return J.recordCardCreated(Q,1),new d2(Q,J)}update($){if(this.terminal)return Promise.reject(Error("Codex 账号卡片已结束"));let Z=h4($);return this.enqueue(()=>this.write($,Z,!1))}finish($){if(this.terminal)return this.terminal;let Z=h4($);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 Y=await this.deps.replaceElementChecked(this.cardId,N.codexAccountPanel,Z,{notifyCardFailure:!1}),Q=await this.deps.patchSettingsChecked(this.cardId,{config:{streaming_mode:!J,summary:{content:f4($)}}});if(!Y||!Q)throw Error(`Codex 账号卡片更新失败:内容 ${Y?"OK":"MISS"},状态 ${Q?"OK":"MISS"}`);if(J)await this.deps.dispose(this.cardId)}}var YF;var gX=R(()=>{t();v$();x0();T2();YF={sendCard:c,convertMessageToCard:Z$,recordCardCreated:d0,replaceElementChecked:M0,patchSettingsChecked:P0,dispose:v0}});var hZ={};E$(hZ,{settleCodexAccountCards:()=>fZ,runCodexNamedHi:()=>VF,runCodexAccountCommand:()=>HF});import{createHash as QF}from"node:crypto";function O9($,Z){let J=$ instanceof Error?$.message:String($),Y=!/失败|未完全退出/.test(J)&&/登录已取消|服务退出/.test(J),Q=/过期|等待超过|expired/i.test(J),V=J.split(/[\n;]/)[0];return{phase:Y?"cancelled":Q?"expired":"error",name:Z,message:V.length>80?V.slice(0,77)+"…":V,...J!==V||V.length>80?{details:J}:{}}}async function mX($,Z){if(!await c($.chatId,V$(O9(Z))))throw Error("Codex 错误卡片发送失败")}async function VF($,Z){let J=await d2.open($.chatId,{phase:"checking",name:Z,message:"正在启动指定账号…"});try{let Y=k.find(Z),Q="";if(!await $.startWithCodexAccount(Y.id,{announce:!1,onStatus:(H)=>{Q=H}}))throw Error(Q||"指定账号启动失败");await J.finish({phase:"current",name:Y.name,current:Y.name,title:"已指定账号",hint:"本次手动指定 · 不参与自动排序"}),await $.showConsole()}catch(Y){await J.finish(O9(Y,Z))}}async function fZ(){let Z=(await Promise.allSettled([...d1.values()])).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 账号卡片未全部写入")}async function HF($,Z,J,Y,Q){if(Z==="reset"){await zF($,J,Q);return}let V={chatId:$.chatId,userOpenId:Y};if(Z==="login-cancel"){try{let z=l1.pending(V);if(!J&&z.length!==1)throw Error(z.length?"有多个登录任务;请指定 codex-login-cancel 备注":"本群没有你的登录任务");let W=J?k.find(J).id:z[0];await l1.cancel(W,V),await d1.get(W)}catch(z){await mX($,z)}return}let H=Z==="login"?J||"默认":Z==="account"||Z==="account-delete"?J||void 0:void 0,X=await d2.open($.chatId,{phase:Z==="login"?"connecting":"checking",name:H,...Z==="login"?{flow:"login"}:{},message:Z==="accounts"?"正在读取各账号额度…":Z==="login"?"正在获取设备码…":"正在核对账号…"});try{if(Z==="account-delete"){if(!J)throw Error("请指定要删除的账号;使用 codex-account-delete 备注");let _=k.find(J);if(d1.has(_.id))throw Error("账号登录或结果更新尚未结束;请先完成或取消登录后重试");let{clearedSelections:j}=k.remove(_.id);O2(_.id),await X.finish({phase:"deleted",name:_.name,message:"已删除本地账号记录与独立凭据,共享会话历史保留。",hint:j?`已清除 ${j} 个群的指定,下次启动自动选号 · codex-accounts 查看`:"codex-accounts 查看剩余账号"});return}if(Z==="accounts"){if(J&&!/^[1-9]\d*$/.test(J))throw Error("页码无效;使用 codex-accounts [页码]");let _=J?Number(J):1,j=$.currentProvider()==="codex"?$.currentModelLabel():H0("codex-sub")?.defaultModel;if(!j)throw Error("Codex 模型 MISS,无法计算调度顺序");let q=$.currentProvider()==="codex"?$.currentEffortLabel()??void 0:void 0,P=await R8.choose({model:j,effort:q}),F=hX(P.candidates.flatMap((T)=>T.usage?[{account:T.account,usage:T.usage,fingerprint:T.identity.startsWith("record:")?null:T.identity}]:[]));await X.finish({phase:"accounts",total:F,currentId:$.codexAccountId(),...k.preferred($.sessionName)?{selectedId:k.selected($.sessionName)}:{},page:_,scheduling:{candidates:P.candidates,ultra:q==="ultra"}});return}if(Z==="auto"){if(J)throw Error("codex-auto 不需要备注");k.selectAuto($.sessionName),await X.finish({phase:"selected",name:"自动选择",current:k.get($.codexAccountId()).name,selected:"自动 · 最高分优先",hint:"Ultra:Pro 且周余量 ≥ 0.5 份"});return}if(Z==="account"){if(!J){await X.finish({phase:"current",current:k.get($.codexAccountId()).name,selected:k.preferred($.sessionName)===null?"自动 · 最高分优先":k.get(k.selected($.sessionName)).name,hint:"周剩余份额 ÷ 重置小时 · codex-auto"});return}let _=k.find(J),j=$.currentProvider()==="codex"?$.currentModelLabel():null,q=$.currentProvider()==="codex"?$.currentEffortLabel():null,P=k.get($.codexAccountId()).name;if($.currentProvider()==="codex")b1($.sessionName,"codex",j,q,"codex-sub");if(k.select($.sessionName,_.id),$.currentProvider()==="codex")$.selectedModel=j,$.selectedEffort=q,$.selectedTokenSourceId="codex-sub";await X.finish({phase:"selected",name:_.name,current:P,selected:_.name,hint:"restart 直接使用 · 不检查调度门槛"});return}if(Z!=="login")throw Error("未知 Codex 账号命令");if(!Y)throw Error("无法确认登录发起者");let z=k.ensure(J);if(Y8(z.id))throw Error("账号正在使用中;重新登录前先 kill 使用该账号的会话,或用新备注添加账号");if(d1.has(z.id))throw Error("登录结果正在更新,请稍等");let W=await l1.start(z.id,V);try{await X.update({phase:"waiting",flow:"login",name:z.name,verification:{url:W.verificationUrl,code:W.userCode},hint:`取消:codex-login-cancel${J?` ${z.name}`:""}`})}catch(_){throw await l1.cancel(z.id,V),_}let G=(async()=>{let _;try{_=await W.done}catch(q){await X.finish(O9(q,z.name));return}await X.update({phase:"checking",flow:"login",name:z.name,message:"授权完成,正在读取模型…"});let j;try{await A2();let q=H0("codex-sub",z.id);if(!q)throw Error("Codex 订阅来源尚未初始化");if(await q.refreshModels(),q.modelCatalogState?.status!=="ready")throw Error(q.modelCatalogState?.error??"模型目录未就绪")}catch(q){j=q instanceof Error?q.message:String(q)}await X.finish({phase:j?"warning":"success",flow:"login",name:z.name,email:_.email,plan:_.planType,...j?{title:"已登录 · 目录 MISS",details:j}:{},hint:`已加入自动选择 · 优先使用:codex-account ${z.id==="default"?"default":z.name}`})})();d1.set(z.id,G);let B=()=>{if(d1.get(z.id)===G)d1.delete(z.id)};G.then(B,(_)=>{K(`codex-login: terminal card write failed: ${_}`),B()})}catch(z){K(`codex-${Z}: ${z}`),await X.finish(O9(z,H))}}async function zF($,Z,J){let Y;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 指定默认账号");Y=Z?k.find(Z):k.get(r0($.proc))}catch(W){K(`codex-reset: ${W}`),await mX($,W);return}let Q=await d2.open($.chatId,{phase:"checking",name:Y.name,title:"正在使用重置卡",message:"正在提交重置请求…"}),V;try{let W=QF("sha256").update(JSON.stringify(["lodestar-codex-reset",$.chatId,J])).digest("hex");V=await iQ(Y.id,W)}catch(W){K(`codex-reset: ${W}`),await Q.finish(O9(W,Y.name));return}let H=XF[V.outcome],z=[V.usage.state==="ok"?void 0:`额度刷新失败:${V.usage.state==="network"?V.usage.reason??"MISS":V.usage.state}`,V.cleanupError].filter(Boolean).join(`
|
|
220
|
-
`);await Q.finish({...H,name:Y.name,resetUsage:V.usage,...z?{phase:"warning",details:z}:{},hint:"codex-accounts 查看各账号额度"})}var d1,XF;var x6=R(()=>{t();p0();vZ();V0();IX();b3();gX();T2();I();w$();d1=new Map;XF={reset:{phase:"success",title:"额度已重置",message:"已使用 1 次重置卡。"},alreadyRedeemed:{phase:"success",title:"本次重置已完成",message:"本次请求此前已处理,没有重复使用重置卡。"},nothingToReset:{phase:"current",title:"无需重置",message:"当前没有符合条件的额度窗口,未使用重置卡。"},noCredit:{phase:"warning",title:"没有可用重置卡",message:"该账号没有可用的重置卡,额度未重置。"}}});function k0($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function IZ($,Z){let J=$.agent==="claude"?C7.filter((Q)=>Q!=="default"):$.agent==="codex"?[...s7]:["off","minimal","low","medium","high","xhigh","max"],Y=Z.effort?.trim();return{efforts:J,defaultEffort:Y&&J.includes(Y)?Y:$.agent==="claude"?"max":$.agent==="codex"?"xhigh":"high"}}function S6($,Z){let J=$.modelSelection,Y=new Set(k0(Z.hidden_models)),Q=[...new Set([...k0(Z.custom_models),...J?[]:k0(Z.models)])],V=$.modelSelection=J??{mode:"catalog",modelIds:[],availableModels:[]},H=$.refreshModels.bind($);return $.refreshModels=async()=>{if($.models=[],V.availableModels=[],!J)V.modelIds=[];try{await H()}catch(G){throw $.models=[],$.modelCatalogState={status:"failed",updatedAt:Date.now(),error:G instanceof Error?G.message:String(G)},G}if($.modelCatalogState?.status!=="ready")return;let X=$.models,z=(J?V.availableModels:X).map((G)=>({...G,origin:G.origin??"upstream"}));for(let G of Q){if(z.some((B)=>B.model.toLowerCase()===G.toLowerCase()))continue;z.push({model:G,display:G,origin:"custom",...IZ($,Z)})}V.availableModels=z;let W=J?X.map((G)=>z.find((B)=>B.model===G.model)??{...G,origin:"upstream"}):z;$.models=[...W.filter((G)=>G.origin==="custom"||!Y.has(G.model)),...z.filter((G)=>G.origin==="custom"&&!W.some((B)=>B.model===G.model))],V.modelIds=$.models.map((G)=>G.model)},$}var i2=R(()=>{F0();O1()});import{homedir as WF}from"node:os";function uX($,Z=cX){return new Promise((J,Y)=>{let Q=setTimeout(()=>Y(Error(`timeout ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Q),J(V)},(V)=>{clearTimeout(Q),Y(V)})})}function pX($){return typeof $==="string"&&GF.includes($)?$:null}async function lX(){let{ClaudeAgentProcess:$}=await Promise.resolve().then(() => (x4(),mQ)),Z=new $({workDir:WF(),effort:"high",settingSources:["user"],allowDelegation:!1,profile:{loadProjectMcp:!1}});Z.on("error",(J)=>K(`Claude model catalog MISS: ${J.message}`));try{let J=await uX(Z.listModels());if(!J.length)throw Error("Claude SDK model catalog is empty");return J.map((Y)=>({model:Y.model.replace(/^claude:/,""),display:Y.displayName,efforts:Y.supportedReasoningEfforts.map((Q)=>Q.reasoningEffort),defaultEffort:Y.defaultReasoningEffort}))}finally{await Z.kill()}}async function dX($="default"){let Z=new T1({accountId:$});try{if(await Z.initialize("lodestar-models"),(await Z.request("account/read",{refreshToken:!1}))?.account?.type!=="chatgpt")throw Object.assign(Error("Codex 订阅未登录;发送 codex-login 或 codex-login 备注完成授权"),{code:"CODEX_AUTH_MISSING"});let Y=await uX(Z.request("model/list",{}));if(!Array.isArray(Y?.data))throw Error("Codex model/list 缺少 data 数组");let Q=Y.data,V=[];for(let H of Q){if(!H||H.hidden||!H.id)continue;let X=(Array.isArray(H.supportedReasoningEfforts)?H.supportedReasoningEfforts:[]).map((W)=>pX(W?.reasoningEffort)).filter((W)=>W!==null);if(!X.length)continue;let z=pX(H.defaultReasoningEffort)??X[0];V.push({model:String(H.id),display:typeof H.displayName==="string"&&H.displayName?String(H.displayName):String(H.id),efforts:X,defaultEffort:z})}return V}finally{await Z.close()}}async function iX($,Z){let J=new URL($),Y=J.pathname.replace(/\/+$/,""),Q=`${J.protocol}//${J.host}${Y}/v1/models`,V=await $0(Q,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(cX)});if(!V.ok)throw Error(`HTTP ${V.status}`);let H=await V.json();if(!Array.isArray(H?.data))throw Error("GLM models 缺少 data 数组");return H.data.filter((z)=>z&&(z.display_name||z.id)).map((z)=>{let W=String(z.display_name||z.id);return{model:W,display:W,efforts:n2,defaultEffort:"max"}})}var cX=1e4,GF,n2;var R9=R(()=>{h0();w$();I();GF=["none","minimal","low","medium","high","xhigh","max","ultra"];n2=["max","xhigh","high","medium","low"]});import{existsSync as KF}from"node:fs";import{join as BF}from"node:path";function nX($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt,...$.unreportedFull===void 0?{}:{unreportedFull:$.unreportedFull}}}function _F($){if($.state!=="ok")return{state:$.state==="auth_failed"?"no_credentials":$.state==="no_credentials"?"no_credentials":$.state==="rate_limited"?"rate_limited":"network",windows:[],resetCredits:null};let Z=[];if($.fiveHour)Z.push(nX($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(nX($.weekly,"weekly","周配额"));return{state:"ok",planLabel:$.subscriptionType,windows:Z,fetchedAt:$.fetchedAt,resetCredits:$.resetCredits??null}}function aX($){return $===u||KF(BF(k.home($),"auth.json"))}var oX=R(()=>{y0();V0();w$();R9();I();p0();i2();S0({kind:"codex-subscription",configSectionId:"codex-sub",build:($)=>{let Z=new Map,J=(V)=>{let H=aX(V),X=$.model?.trim()||void 0,z=$.effort?.trim()||void 0,W={id:"codex-sub",kind:"codex-subscription",agent:"codex",display:$.display?.trim()||"Codex 订阅",spawnRevision:JSON.stringify([$.model,$.effort,k.revision(V)]),enabled:H,models:[],modelCatalogState:{status:H?"idle":"disabled",updatedAt:Date.now()},defaultModel:X??"",async refreshModels(){if(W.enabled=aX(V),!W.enabled){W.models=[],W.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}W.modelCatalogState={status:"loading",updatedAt:null};try{if(W.models=await dX(V),z)for(let G of W.models)G.defaultEffort=z;if(!X)W.defaultModel=W.models[0]?.model??"";W.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){if(K(`codex-sub ${V} refreshModels MISS: ${G?.message??G}`),W.models=[],G?.code==="CODEX_AUTH_MISSING")W.enabled=!1;W.modelCatalogState={status:W.enabled?"failed":"disabled",updatedAt:Date.now(),error:G?.message??String(G)}}},spawnEnv(G){let B=j$(G);return Object.assign(B,f.codex.env),k.env(V,B)},resolveSpawnModel(G){return G},async readUsage(){return _F(await E1(V))}};return W},Y=J(u);Y.forAccount=(V)=>{if(V===u)return Y;let H=k.revision(V),X=Z.get(V);if(X?.revision===H)return X.source;let z=S6(J(V),$);return Z.set(V,{revision:H,source:z}),z};let Q=Y.refreshModels.bind(Y);return Y.refreshModels=async()=>{await Promise.all([Q(),...k.list().filter((V)=>V.id!==u).map((V)=>Y.forAccount(V.id).refreshModels())])},Y}})});function LF($){let Z=new URL($),J=Z.pathname.replace(/\/+$/,"");return`${Z.protocol}//${Z.host}${J}/v1/messages`}async function b6($,Z,J){try{let Y=await $0(LF($),{method:"POST",headers:{"Content-Type":"application/json",...Z},body:JSON.stringify({model:J,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:AbortSignal.timeout(jF)});if(Y.ok)return"exists";if(Y.status===400){let Q=await Y.text();return Q.includes("1214")||Q.includes("不存在")||Q.includes("not exist")?"not_found":"no_verdict"}return K(`model-existence: ${J} HTTP ${Y.status}, no verdict`),"no_verdict"}catch(Y){return K(`model-existence: ${J} MISS (${Y?.message??Y})`),"no_verdict"}}var jF=15000;var gZ=R(()=>{h0();I()});function rX($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function qF($){return{kind:"monthly",label:"月度工具",percent:$.percent,resetsAt:$.resetsAt,...$.used!=null?{used:$.used}:{},...$.total!=null?{total:$.total}:{}}}function sX($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function PF($){let Z=(J)=>{let Y=J.match(/(\d+(?:\.\d+)?)/);return Y?Number(Y[1]):-1};return[...$].sort((J,Y)=>Z(Y)-Z(J))[0]??""}function FF($){let Z={};for(let J of($??"").split(",")){let Y=J.indexOf("=");if(Y<=0)continue;let Q=J.slice(0,Y).trim().toLowerCase(),V=J.slice(Y+1).trim();if((Q==="opus"||Q==="sonnet"||Q==="haiku")&&V)Z[Q]=V}return Z}function mZ($){if($.state!=="ok")return{state:$.state==="no_credentials"?"no_credentials":$.state==="not_glm"?"not_applicable":$.state==="rate_limited"?"rate_limited":"network",windows:[],...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(rX($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(rX($.weekly,"weekly","周额度"));if($.monthly)Z.push(qF($.monthly));return{state:"ok",planLabel:$.level?`${$.level} 套餐`:void 0,windows:Z,fetchedAt:$.fetchedAt}}var pZ=R(()=>{V0();q9();R9();E4();gZ();I();S0({kind:"glm-coding-plan",configSectionId:"glm",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||"",Y=$.auth_token?.trim()||Z?.auth_token?.trim()||"",Q=!!(J&&Y)&&p1(J),V=$.model?.trim()||void 0,H=FF($.slots),X={id:"glm",kind:"glm-coding-plan",agent:"claude",display:$.display?.trim()||"GLM Coding Plan",enabled:Q,models:[],modelCatalogState:{status:Q?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!X.enabled){X.models=[],X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await iX(J,Y),G=[...new Set([...sX($.models),...sX($.custom_models)])].filter((B)=>!z.some((_)=>_.model.toLowerCase()===B.toLowerCase())).map((B)=>({model:B,display:B,efforts:n2,defaultEffort:"max",origin:"custom"}));if(X.models=[...z,...G],!V)X.defaultModel=PF(X.models.map((B)=>B.model));for(let B of X.models){let _=L2("glm",B.model);B.context1m=_!=null&&_>=1e6||void 0}X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){K(`glm refreshModels MISS: ${z?.message??z}`),X.models=[],X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:z?.message??String(z)}}},spawnEnv(z){let G={...j$(z)};if(G.ANTHROPIC_BASE_URL=J,G.ANTHROPIC_AUTH_TOKEN=Y,H.opus)G.ANTHROPIC_DEFAULT_OPUS_MODEL=H.opus;if(H.sonnet)G.ANTHROPIC_DEFAULT_SONNET_MODEL=H.sonnet;if(H.haiku)G.ANTHROPIC_DEFAULT_HAIKU_MODEL=H.haiku;return G},resolveSpawnModel(z){return K8("glm",z)},async verifyModel(z){return b6(J,{Authorization:`Bearer ${Y}`},z)},async readUsage(){return mZ(await L9(J,Y))}};return X},setup:{commandSuffix:"glm",hint:($)=>`启用 ${$}:发送
|
|
218
|
+
`),V=Y[Y.length-1];K(`session "${$.sessionName}": multi-msg flush ${Y.length} segment(s) → 1 turn`),await $.onUserMessage(Q,[],V.userOpenId,V.msgId)}function FZ($,Z){if($.multiMsgBuffer===null)return;let J=$.multiMsgBuffer.length;K(`session "${$.sessionName}": clear multi-msg buffer (${Z}): ${J} segment(s)`);for(let[Y,Q]of $.multiMsgReactions){if(Q)C0(Y,Q);l0(Y,"CrossMark")}$.multiMsgBuffer=null,$.multiMsgReactions=new Map}var YX=R(()=>{t();I();ZX()});import{mkdtemp as FP,rm as MP,writeFile as UP}from"node:fs/promises";import{createRequire as AP}from"node:module";import{tmpdir as OP}from"node:os";import{join as QX}from"node:path";function CP($){let Z=zX.get($);if(Z)return Z;let{liteAdaptor:J}=u1("mathjax-full/js/adaptors/liteAdaptor.js"),{RegisterHTMLHandler:Y}=u1("mathjax-full/js/handlers/html.js"),{mathjax:Q}=u1("mathjax-full/js/mathjax.js"),{TeX:V}=u1("mathjax-full/js/input/tex.js"),{AllPackages:H}=u1("mathjax-full/js/input/tex/AllPackages.js"),{SVG:X}=u1("mathjax-full/js/output/svg.js"),z=J({fontSize:$});Y(z);let W=Q.document("",{InputJax:new V({packages:H}),OutputJax:new X({fontCache:"none"})}),G={adaptor:z,doc:W};return zX.set($,G),G}function WX($,Z){let J=Number.parseFloat($??"");if(!Number.isFinite(J)||J<=0)throw Error(`MathJax SVG missing valid ${Z}`);return J}function kP($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function yP($,Z=AZ,J=!0){try{let Y=Z*RP,{adaptor:Q,doc:V}=CP(Z),H=V.convert($,{display:J,em:Z,ex:Y,containerWidth:80*Z}),X=Q.outerHTML(H);if(/data-mjx-error=|mjx-merror/.test(X)){let K0=X.match(/data-mjx-error="([^"]+)"/)?.[1]??"MathJax parse error";throw Error(K0)}let z=X.indexOf("<svg"),W=X.lastIndexOf("</svg>");if(z<0||W<0)throw Error("MathJax returned no SVG");let G=X.slice(z,W+6),B=G.match(/^<svg\b[^>]*>/)?.[0];if(!B)throw Error("MathJax returned malformed SVG root");let _=WX(B.match(/\bwidth="([\d.]+)ex"/)?.[1],"width"),j=WX(B.match(/\bheight="([\d.]+)ex"/)?.[1],"height"),q=B.match(/\bviewBox="([^"]+)"/)?.[1];if(!q)throw Error("MathJax SVG missing viewBox");let P=q.trim().split(/[\s,]+/).map(Number);if(P.length!==4||P.some((K0)=>!Number.isFinite(K0))||P[2]<=0||P[3]<=0)throw Error("MathJax SVG has invalid viewBox");let[D,T,M,A]=P,U=/<text\b/.test(G)?SP:0,S=`${D} ${T} ${M+U} ${A}`,b=_*Y,v=U*(b/M),y=Math.max(1,Math.ceil(b+v)),g=Math.max(1,Math.ceil(j*Y)),x=NP-MZ*2,h=Math.min(1,x/y),p=Math.max(1,Math.round(y*h)),l=Math.max(1,Math.round(g*h));if(h<1&&l<TP)throw Error(`formula would be unreadable after width cap (${p}x${l})`);let F=p+MZ*2,C=l+HX*2,d=G.slice(B.length,-6).replace(/currentColor/g,VX).replace(/font-family="serif"/g,`font-family="${bP}"`);return{svg:[`<svg xmlns="http://www.w3.org/2000/svg" width="${F}" height="${C}" viewBox="0 0 ${F} ${C}" style="color:${VX}">`,`<rect x="0" y="0" width="${F}" height="${C}" rx="6" fill="${_X}"/>`,`<svg x="${MZ}" y="${HX}" width="${p}" height="${l}" viewBox="${kP(S)}" preserveAspectRatio="xMidYMid meet">`,d,"</svg>","</svg>"].join(""),width:F,height:C}}catch(Y){return K(`math-render: TeX→SVG failed for ${$.slice(0,80)}…: ${Y}`),null}}function wP($,Z=AZ,J=!0){let Y=yP($,Z,J);if(!Y)return null;try{let{Resvg:Q}=u1("@resvg/resvg-js"),H=new Q(Y.svg,{background:_X,fitTo:{mode:"original"},shapeRendering:2,textRendering:1,font:{loadSystemFonts:!0,serifFamily:XX,sansSerifFamily:XX}}).render().asPng(),X=new DataView(H.buffer,H.byteOffset,H.byteLength),z=X.getUint32(16),W=X.getUint32(20);if(z!==Y.width||W!==Y.height)throw Error(`PNG dimensions ${z}x${W} != SVG ${Y.width}x${Y.height}`);return{png:H,width:z,height:W}}catch(Q){return K(`math-render: SVG→PNG failed for ${$.slice(0,80)}…: ${Q}`),null}}function vP($){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 GX($,Z){let J=[],Y=(G,B,_)=>{let j=G[0],q=B.trim();if(!q)return;J.push({start:Z+G.index,end:Z+G.index+j.length,tex:q,raw:j,display:_})},Q,V=/(?<!\\)\$\$([\s\S]+?)(?<!\\)\$\$|\\\[([\s\S]+?)\\\]/g;while((Q=V.exec($))!==null)Y(Q,Q[1]??Q[2]??"",!0);let H=/\\\(([\s\S]+?)\\\)/g;while((Q=H.exec($))!==null)Y(Q,Q[1]??"",!1);let X=/(?<![\\$])\$(?!\$)([^$\n]+?)(?<![\\$])\$(?!\$)/g;while((Q=X.exec($))!==null){let G=(Q[1]??"").trim();if(vP(G))Y(Q,G,!1)}J.sort((G,B)=>G.start-B.start||B.end-G.end);let z=[],W=-1;for(let G of J){if(G.start<W)continue;z.push(G),W=G.end}return z}function jX($){let Z=s7($),J=[],Y=0;for(let Q of Z){if(Y<Q.start)J.push(...GX($.slice(Y,Q.start),Y));Y=Math.max(Y,Q.end)}if(Y<$.length)J.push(...GX($.slice(Y),Y));return J}function fP($){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,Y)=>{if(KX[Y])return KX[Y];if(Y==="times")return"×";if(Y==="cdot")return"·";if(Y==="div")return"÷";if(Y==="pm")return"±";if(Y==="leq"||Y==="le")return"≤";if(Y==="geq"||Y==="ge")return"≥";if(Y==="neq"||Y==="ne")return"≠";if(Y==="approx")return"≈";if(Y==="sim")return"~";if(Y==="infty")return"∞";if(Y==="partial")return"∂";if(Y==="nabla")return"∇";if(Y==="sqrt")return"√";if(Y==="to")return"→";return J}),/\\/.test(Z))return null;if(Z=Z.replace(/([_^])\{([^{}]+)\}/g,(J,Y,Q)=>Q.length===1?`${Y}${Q}`:`${Y}(${Q})`),Z=Z.replace(/√\{([^{}]+)\}/g,"√($1)"),/[{}]/.test(Z))return null;return Z}function mP($){let Z=BX.get($);if(Z!==void 0)return Z;return Z=IP++,BX.set($,Z),Z}function pP($,Z){return`${xP}\x00${mP(Z)}\x00${$}`}function cP($){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 uP($,Z){let J=pP($,Z),Y=c1.get(J);if(Y)return Y;let Q=UZ.get(J);if(Q)return Q;let V=(async()=>{let H=wP($,AZ,!0);if(!H)return null;let X=null;try{X=await FP(QX(OP(),"lodestar-math-"));let z=QX(X,`formula-${cP($)}.png`);await UP(z,H.png);let W=await Z(z,{tex:$,width:H.width,height:H.height});if(!W)return K(`math-render: upload returned no image key for ${$.slice(0,80)}…`),null;let G={key:W,width:H.width,height:H.height};if(c1.has(J))c1.delete(J);c1.set(J,G);while(c1.size>gP){let B=c1.keys().next().value;if(typeof B!=="string")break;c1.delete(B)}return G}catch(z){return K(`math-render: upload failed for ${$.slice(0,80)}…: ${z}`),null}finally{if(X)try{await MP(X,{recursive:!0,force:!0})}catch(z){K(`math-render: temp cleanup failed for ${X}: ${z}`)}}})();UZ.set(J,V);try{return await V}finally{UZ.delete(J)}}function lP($,Z,J){let Y=$.width<=EP;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:Y?"crop_center":"fit_horizontal",...Y?{size:`${$.width}px ${$.height}px`}:{},preview:!1}}}async function LX($,Z={}){let J=jX($);if(!J.length)return{blocks:[{type:"markdown",text:$}],formulaCount:0,renderedImageCount:0};let Y=Z.uploader??hP,Q=await Promise.all(J.map(async(G)=>{if(!G.display){let B=fP(G.tex);if(B!==null)return{unicode:B,uploaded:null}}return{unicode:null,uploaded:await uP(G.tex,Y)}})),V=[],H="",X=0,z=0,W=()=>{if(!H)return;if(H.trim())V.push({type:"markdown",text:H});H=""};for(let G=0;G<J.length;G++){let B=J[G],_=Q[G];if(H+=$.slice(X,B.start),_.unicode!==null){H+=_.unicode,X=B.end;continue}let j=_.uploaded;if(!j){H+=B.raw,X=B.end;continue}W(),V.push(lP(j,B,z++)),X=B.end}if(H+=$.slice(X),W(),!V.length)V.push({type:"markdown",text:$});return{blocks:V,formulaCount:J.length,renderedImageCount:z}}function OZ($){return jX($).length>0}var u1,RP=0.5,AZ=22,VX="#1F2329",_X="#F7F8FA",MZ=12,HX=8,NP=720,TP=14,EP=278,xP="v4-native-cjk-tail-pad",SP=1100,XX,bP="Noto Sans CJK SC, Noto Sans CJK JP, Microsoft YaHei, PingFang SC, Arial Unicode MS, sans-serif",zX,KX,hP=async($)=>{let{uploadImageKey:Z}=await Promise.resolve().then(() => (t(),Y0));return Z($)},BX,IP=1,c1,UZ,gP=512;var qX=R(()=>{I();u1=AP(import.meta.url),XX=process.platform==="win32"?"Microsoft YaHei":process.platform==="darwin"?"PingFang SC":"Noto Sans CJK SC",zX=new Map;KX={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:"Ω"};BX=new WeakMap,c1=new Map,UZ=new Map});import{readFileSync as iP}from"node:fs";function p2($){return RZ.has($)}function P9($){RZ.add($)}function D9($){RZ.delete($)}function c2(){try{let $={};for(let[Z,J]of n0)$[Z]=J;s(M6,$)}catch($){throw K(`notify-callbacks: save failed (${M6}): ${$}`),$}}function MX(){let $=[],Z;try{Z=iP(M6,"utf8")}catch{return[]}try{let J=JSON.parse(Z),Y=Date.now()-FX,Q=0,V=0;for(let H of Object.values(J)){if(!H||typeof H!=="object")continue;if(typeof H.notifyId!=="string"||typeof H.callbackUrl!=="string")continue;if(typeof H.createdAt!=="number"||H.createdAt<Y){Q++;continue}if(H.replyState?.status==="sending"&&!H.resolvedAt&&!H.unknownAt)H.unknownAt=Date.now(),H.unknownBy={openId:H.replyState.openId},H.unknownReason="服务在文字回复回传期间中断,无法确认是否送达,禁止自动重试",V++;if(n0.set(H.notifyId,H),H.replyState?.status==="sending"&&H.unknownAt)$.push(H)}if(K(`notify-callbacks: loaded ${n0.size} registration(s)${Q?`, dropped ${Q} stale`:""}`),V)K(`notify-callbacks: ${V} interrupted text reply(s) marked UNKNOWN`);if(Q>0||V>0)c2()}catch(J){K(`notify-callbacks: load failed (${M6}): ${J}`)}return $}function UX($){let Z=Date.now();if(Z-DX>=nP)aP(Z),DX=Z;n0.set($.notifyId,$),c2()}function I$($){return n0.get($)}function NZ($){return[...n0.values()].filter((Z)=>Z.chatId===$&&!Z.resolvedAt&&!Z.unknownAt&&(Z.replyState?.status==="waiting"||Z.replyState?.status==="sending"))}function F9($,Z){if(!$)return;return NZ($).find((J)=>Z===void 0||J.replyState?.openId===Z)}function AX($,Z){return!!Z&&[...n0.values()].some((J)=>J.chatId===$&&(J.replyMessageIds?.includes(Z)||J.replyState?.response?.message_id===Z))}function u2($,Z){let J=n0.get($);if(!J)throw Error(`notify registration not found: ${$}`);let{replyState:Y,replyMessageIds:Q}=J;if(J.replyState=Z,Z.response&&!J.replyMessageIds?.includes(Z.response.message_id))J.replyMessageIds=[...J.replyMessageIds??[],Z.response.message_id];try{c2()}catch(V){if(Y)J.replyState=Y;else delete J.replyState;if(Q)J.replyMessageIds=Q;else delete J.replyMessageIds;throw V}}function M9($,Z,J){let Y=n0.get($);if(!Y)throw Error(`notify registration not found: ${$}`);let Q={resolvedAt:Y.resolvedAt,resolvedBy:Y.resolvedBy,unknownAt:Y.unknownAt,unknownBy:Y.unknownBy,unknownReason:Y.unknownReason};Y.resolvedAt=Date.now(),Y.resolvedBy={...Z!==void 0?{buttonId:Z}:{},openId:J},delete Y.unknownAt,delete Y.unknownBy,delete Y.unknownReason;try{c2()}catch(V){if(Q.resolvedAt===void 0)delete Y.resolvedAt;else Y.resolvedAt=Q.resolvedAt;if(Q.resolvedBy===void 0)delete Y.resolvedBy;else Y.resolvedBy=Q.resolvedBy;if(Q.unknownAt===void 0)delete Y.unknownAt;else Y.unknownAt=Q.unknownAt;if(Q.unknownBy===void 0)delete Y.unknownBy;else Y.unknownBy=Q.unknownBy;if(Q.unknownReason===void 0)delete Y.unknownReason;else Y.unknownReason=Q.unknownReason;throw V}}function TZ($,Z,J,Y){let Q=n0.get($);if(!Q)throw Error(`notify registration not found: ${$}`);delete Q.resolvedAt,delete Q.resolvedBy,Q.unknownAt=Date.now(),Q.unknownBy={...Z!==void 0?{buttonId:Z}:{},openId:J},Q.unknownReason=Y,c2()}function U6($,Z,J){try{return M9($,Z,J),{state:"complete"}}catch(Y){let V=`resolved tombstone persistence failed: ${Y instanceof Error?Y.message:String(Y)}`;try{TZ($,Z,J,V)}catch(H){let X=H instanceof Error?H.message:String(H);V+=`; unknown tombstone persistence also failed: ${X}`;let z=n0.get($);if(z)z.unknownReason=V}return{state:"unknown",detail:V}}}function aP($=Date.now()){let Z=$-FX,J=0;for(let[Y,Q]of n0)if(typeof Q.createdAt!=="number"||Q.createdAt<Z)n0.delete(Y),J++;if(J>0)c2();return J}async function EZ($,Z,J){let Y={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)},Q=new AbortController,V=setTimeout(()=>Q.abort(),PX);try{let H=await HY($.callbackUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Y),signal:Q.signal});if(H.status>=200&&H.status<300){let z;try{let W=(await H.text()).trim();if(W.startsWith("{")){let G=JSON.parse(W),B=typeof G?.text==="string"?G.text:typeof G?.reply==="string"?G.reply:typeof G?.message==="string"?G.message:"";if(B.trim())z=B.trim().slice(0,500)}else if(W)z=W.slice(0,500)}catch{}return{ok:!0,detail:`${H.status}`,reply:z}}let X="";try{X=(await H.text()).slice(0,120)}catch{}return{ok:!1,detail:`HTTP ${H.status}${X?` ${X}`:""}`}}catch(H){if(H?.name==="AbortError")return{ok:!1,detail:`回调超时 ${PX}ms(本地服务未在窗口内 2xx)`};return{ok:!1,detail:`回调失败: ${String(H?.message??H).slice(0,160)}`}}finally{clearTimeout(V)}}function OX($){let Z=!!$.resolvedAt,J=!!$.unknownAt,Y=$.resolvedBy?.buttonId??$.unknownBy?.buttonId,Q=Y?$.buttons.find((X)=>X.id===Y):void 0,V=$.replyState?.response,H=Y!==void 0?{button:Q?{id:Q.id,text:Q.text,type:Q.type}:{id:Y}}:V?{response:{type:"text",...V}}:{};return{notify_id:$.notifyId,project:$.project,message_id:$.messageId,resolved:Z,unknown:J,...$.replyState?{reply:{status:Z&&Y===void 0?"resolved":J&&Y===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?{...H,resolved_at:$.resolvedAt,resolved_by:$.resolvedBy?.openId??null}:{},...J?{...H,unknown_at:$.unknownAt,unknown_by:$.unknownBy?.openId??null,unknown_reason:$.unknownReason}:{}}}var FX=604800000,PX=2500,n0,DX,nP=86400000,RZ,M6;var U9=R(()=>{h0();I();Q0();T0();n0=new Map,DX=Date.now(),RZ=new Set;M6=nJ});function A6($){return[...$.pendingAsks.entries()].find(([,Z])=>Z.currentIdx!==void 0)}function l2($,Z){let J=$.pendingAsks.get(Z);if(!J||J.currentIdx===void 0)return null;if(F9($.chatId))return"请先完成或取消通知回复,再回答 Agent 的提问";if(A6($)?.[0]!==Z)return"请先回答当前问题,再回答排队中的提问";return null}function xZ($,Z){let J=$.pendingAsks.get(Z);if(!J)throw Error(`missing pending ask: ${Z}`);let Y=J.currentIdx===void 0?void 0:F9($.chatId)?"notification":A6($)?.[0]!==Z?"question":void 0;return{currentIdx:J.currentIdx,answered:J.answered,waitingFor:Y}}function SZ($,Z){let J=$.pendingAsks.get(Z),Y=$.currentTurn;if(!J||J.currentIdx===void 0||J.announced||l2($,Z)||!Y?.userOpenId||!Y.messageId)return;J.announced=!0;let Q=(J.announcementVersion??0)+1;J.announcementVersion=Q;let V=J.questions[J.currentIdx]?.question.trim()??"",H=V.length>40?V.slice(0,40)+"…":V,X=J.questions.length>1?`❓ 待回答 ${J.questions.length} 题${H?`: ${H}`:""}`:H?`❓ ${H}`:"❓ 等你回答问题";(async()=>{if(A0(Y.cardId),await p8(Y.cardId,{config:{summary:{content:X}}}),$.currentTurn!==Y||$.pendingAsks.get(Z)!==J||J.announcementVersion!==Q||J.currentIdx===void 0||l2($,Z))return;await C1(Y.messageId,[Y.userOpenId])})().catch((z)=>K(`session "${$.sessionName}": question notification failed: ${z}`))}function O6($){let Z=$.currentTurn;if(!Z)return;for(let[J,Y]of $.pendingAsks){let Q=Z.toolByUseId.get(J);if(!Q||Y.currentIdx===void 0)continue;let V=xZ($,J);if(V.waitingFor)Y.announced=!1,Y.announcementVersion=(Y.announcementVersion??0)+1;J0(Z.cardId,N.tool(Q.i),v2(Q.i,J,Y.questions,"\uD83E\uDD14",V)),SZ($,J)}}function RX($){return A6($)!==void 0}async function NX($,Z,J,Y){let Q=A6($);if(!Q){K(`session "${$.sessionName}": no unanswered question; routing text to Agent`),await $.onUserMessage(Z,[],J,Y);return}let[V,H]=Q,X=l2($,V);if(X){let W=`${X}。这条文字未提交,请稍后重新发送。`;if(!await E($.chatId,W))throw Error(`提问等待提示发送失败: ${W}`);return}if(await bZ($,V,H.currentIdx,Z,J)&&Y)l0(Y,"CheckMark")}async function TX($,Z,J,Y,Q){let V=$.pendingAsks.get(Z);if(!V)return K(`session "${$.sessionName}": stray ask answer for ${Z}`),!1;if(J!==V.currentIdx)return K(`session "${$.sessionName}": stale ask click q=${J} current=${V.currentIdx}`),!1;return EX($,Z,{optionIdx:Y,user:Q})}async function bZ($,Z,J,Y,Q){let V=$.pendingAsks.get(Z);if(!V)return K(`session "${$.sessionName}": stray ask custom for ${Z}`),!1;let H=(Y??"").trim();if(!H)return K(`session "${$.sessionName}": empty custom answer, ignoring`),!1;if(J!==V.currentIdx)return K(`session "${$.sessionName}": stale ask custom q=${J} current=${V.currentIdx}`),!1;return EX($,Z,{customText:H,user:Q})}function EX($,Z,J){let Y=$.pendingAsks.get(Z);if(!Y||Y.currentIdx===void 0)return!1;let Q=l2($,Z);if(Q)return K(`session "${$.sessionName}": ask ${Z} waiting: ${Q}`),!1;let V=Y.currentIdx,H=Y.questions[V];if(!H)return K(`session "${$.sessionName}": advanceAsk currentIdx=${V} out of range`),!1;let X;if(J.customText!==void 0)X=J.customText;else if(J.optionIdx!==void 0){let _=H.options?.[J.optionIdx];if(!_)return K(`session "${$.sessionName}": advanceAsk option ${J.optionIdx} out of range`),!1;X=_.label}else return K(`session "${$.sessionName}": advanceAsk with neither customText nor optionIdx`),!1;Y.answers[H.question]=X,Y.answered.set(V,{optionIdx:J.optionIdx,customText:J.customText,user:J.user});let z=Y.questions.length,W=void 0;for(let _=V+1;_<z;_++)if(!Y.answered.has(_)){W=_;break}Y.currentIdx=W;let G=$.currentTurn,B=G?.toolByUseId.get(Z);if(G&&B){let _=v2(B.i,Z,Y.questions,W===void 0?"✅":"\uD83E\uDD14",{currentIdx:W,answered:Y.answered});J0(G.cardId,N.tool(B.i),_)}if(W===void 0)if(Y.requestId)CZ($,Z);else K(`session "${$.sessionName}": ask ${Z} all answered, waiting for can_use_tool`),O6($);return!0}function CZ($,Z){let J=$.pendingAsks.get(Z);if(!J||!J.requestId)return;let Y=$.currentTurn?.toolByUseId.get(Z),Q=Y?.input??{};if($.proc?.sendPermissionResponse(J.requestId,"allow",{updatedInput:{...Q,answers:J.answers}}),$.pendingPermissions.delete(J.requestId),Y)Y.output=JSON.stringify({answers:J.answers}),Y.isError=!1;if($.pendingAsks.delete(Z),O6($),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working"}var R6=R(()=>{v$();Y$();t();I();U9()});import{isAbsolute as rP}from"node:path";function O0($){if($?.planLiveInserted)return N.planLive;return $?.taskLiveInserted?N.taskBoardLive:N.footer}function sP($){return $==="ImageGeneration"||$==="imageGeneration"}function tP($,Z,J){if(J||!sP($))return null;let Y=F6(Z.trim());return rP(Y)?Y:null}function eP($){if($==="Read")return"read";if($==="Edit"||$==="MultiEdit"||$==="NotebookEdit")return"edit";return null}function xX($,Z,J){return $==="read"?X9(Z,J):H9(Z,J)}function SX($,Z,J,Y){if(!$.currentTurn)return;if($.maybeMidTurnRotate(),$.startWorkingFooter($.currentTurn),$.currentTurn.currentAssistantSegmentId)$.finalizeCurrentAssistantSegment();let Q=eP(J);if(Q&&$.currentTurn.openBatchI!==null){let z=$.currentTurn.openBatchI,W=$.currentTurn.toolBatches.get(z);if(W&&W.kind===Q){let G=W.items.length;W.items.push({toolUseId:Z,input:Y,output:null,isError:!1}),$.currentTurn.toolByUseId.set(Z,{i:z,name:J,input:Y,batchSlot:G});let B=Q==="read"?X9(z,W.items):H9(z,W.items);J0($.currentTurn.cardId,N.tool(z),B),N6($.currentTurn,J,Y);return}}if(!Q)$.currentTurn.openBatchI=null;let V=g1(J);if(V){let z=$.currentTurn;if(V==="TaskCreate"&&!z.taskBoardResetThisTurn)$.taskBoard=[],z.taskBoardResetThisTurn=!0;if(!z.taskLiveInserted)z.taskLiveInserted=!0,F0(z.cardId,m1($.taskBoard),{type:"insert_before",targetElementId:N.footer});else J0(z.cardId,N.taskBoardLive,m1($.taskBoard));let W=V==="TaskCreate";if(W)z.taskUpdateI=null;else z.taskCreateI=null;let G=(W?z.taskCreateI:z.taskUpdateI)===null;if(G)if(W)z.taskCreateI=z.toolCount++;else z.taskUpdateI=z.toolCount++;let B=W?z.taskCreateI:z.taskUpdateI;z.toolByUseId.set(Z,{i:B,name:J,input:Y});let _=W1(B,$.taskBoard,{name:V,status:"⏳"});G?F0(z.cardId,_,{type:"insert_before",targetElementId:O0(z)}):J0(z.cardId,N.tool(B),_),N6(z,J,Y);return}$.currentTurn.taskCreateI=null,$.currentTurn.taskUpdateI=null;let H=$.currentTurn.toolCount++;if(Q){$.currentTurn.openBatchI=H;let z=[{toolUseId:Z,input:Y,output:null,isError:!1}];$.currentTurn.toolBatches.set(H,{kind:Q,items:z}),$.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Y,batchSlot:0});let W=Q==="read"?X9(H,z):H9(H,z);F0($.currentTurn.cardId,W,{type:"insert_before",targetElementId:O0($.currentTurn)}),N6($.currentTurn,J,Y);return}if($.currentTurn.toolByUseId.set(Z,{i:H,name:J,input:Y}),J==="AskUserQuestion"){let z=Array.isArray(Y?.questions)?Y.questions:[],W=z.length>0?0:void 0,G=new Map;$.pendingAsks.set(Z,{questions:z,i:H,answers:{},answered:G,currentIdx:W});let B=v2(H,Z,z,"\uD83E\uDD14",xZ($,Z));F0($.currentTurn.cardId,B,{type:"insert_before",targetElementId:O0($.currentTurn)}),SZ($,Z);return}let X=R$(H,J,Y,null,"⏳");F0($.currentTurn.cardId,X,{type:"insert_before",targetElementId:O0($.currentTurn)}),N6($.currentTurn,J,Y)}function N6($,Z,J){if(!$)return;let Y=Q1(Z,J),Q=Y.length>80?Y.slice(0,80)+"…":Y,V=f1(Z),H=Q?`\uD83D\uDD27 ${V}: ${Q}`:`\uD83D\uDD27 ${V}`;w1($.cardId,H)}function bX($,Z,J,Y,Q){if(!$.currentTurn)return;let V=$.currentTurn.toolByUseId.get(Z);if(!V)return;if(Q&&typeof Q==="object")V.input={...V.input,...Object.fromEntries(Object.entries(Q).filter(([,G])=>G!==void 0))};let H=typeof J==="string"?J:Array.isArray(J)?J.map((G)=>G?.text??JSON.stringify(G)).join(`
|
|
219
|
+
`):JSON.stringify(J);if(V.output=H,V.isError=Y,$.currentTurn.cardRotationFailed)$.maybeMidTurnRotate();let X=tP(V.name,H,Y);if(X){$D($,$.currentTurn,V,X),A9($);return}if(V.name==="AskUserQuestion"){A9($);return}if(V.batchSlot!=null){let G=$.currentTurn.toolBatches.get(V.i);if(G){let B=G.items[V.batchSlot];if(B)B.output=H,B.isError=Y;let _=xX(G.kind,V.i,G.items);J0($.currentTurn.cardId,N.tool(V.i),_)}A9($);return}let z=g1(V.name);if(z){ZD($,V,z,V.input,H,Y,V.resolvedNote);return}let W=R$(V.i,V.name,V.input,H,Y?"❌":"✅",V.resolvedNote);J0($.currentTurn.cardId,N.tool(V.i),W),A9($)}function $D($,Z,J,Y){if(Z.outboundSeenPaths.has(Y))return;Z.outboundSeenPaths.add(Y);let Q=Z.cardId,V=N.tool(J.i),H=Z.imageDeliveryInflight??=new Map,X=H.get(Q)??new Set;H.set(Q,X);let z=(async()=>{let W=null;try{W=await L5(Y)}catch(B){K(`generated image upload failed: ${B}`)}if(W){let B=!1;try{B=await M0(Q,V,R$(J.i,J.name,J.input,J.output??null,"✅",J.resolvedNote,W),{notifyCardFailure:!1})}catch(_){K(`generated image embed failed: ${_}`)}if(B){J.imageKey=W,Z.outboundSentPaths.add(Y);return}K(`generated image could not be embedded in card ${Q}; sending it as a separate message`)}let G=W?await g8($.chatId,W)!==null:await o4($.chatId,Y);if(G)Z.outboundSentPaths.add(Y);else K(`generated image delivery failed: ${Y}`);if(J.resolvedNote=G?"图片已单独发送。":"图片发送失败。",await M0(Q,V,R$(J.i,J.name,J.input,J.output??null,G?"✅":"❌",J.resolvedNote),{notifyCardFailure:!1}),!G&&W)await E($.chatId,"❌ 生成图片发送失败,请稍后重试。")})().catch(async(W)=>{K(`generated image delivery failed: ${W}`),await E($.chatId,`❌ 生成图片发送失败:${W instanceof Error?W.message:String(W)}`)});X.add(z),z.finally(()=>{if(X.delete(z),!X.size)H.delete(Q)}).catch((W)=>K(`generated image failure notice failed: ${W}`))}async function kZ($,Z){let J=Z?[...$.imageDeliveryInflight?.get(Z)??[]]:[...$.imageDeliveryInflight?.values()??[]].flatMap((Y)=>[...Y]);await Promise.allSettled(J)}function ZD($,Z,J,Y,Q,V,H){if(!$.currentTurn)return;if(!V)$.taskBoard=_Z($.taskBoard,J,Y,Q);let X=W1(Z.i,$.taskBoard,{name:J,status:V?"❌":"✅"},H);if(J0($.currentTurn.cardId,N.tool(Z.i),X),$.currentTurn.taskLiveInserted)J0($.currentTurn.cardId,N.taskBoardLive,m1($.taskBoard));A9($)}function A9($){let Z=$.currentTurn;if(!Z)return;for(let J of Z.toolByUseId.values())if(J.output==null)return;$.startThinkingFooter(Z)}function yZ($,Z,J,Y,Q,V=$.currentTurn){let H=V;if(!H)return;for(let[X,z]of Y){if(H.toolByUseId.has(X))continue;let W=z.batchSlot??null,G=z.input,B,_;if(W!=null){let M=Q.get(z.i)?.items[W];if(!M)continue;G=M.input,B=M.output,_=M.isError}else B=z.output??null,_=z.isError??!1;let j=B!=null,q=k2(Z,N.tool(z.i));if(j&&!q)continue;if(W!=null){let M=Q.get(z.i)?.kind;if(!M)continue;let A=H.toolCount++,U={toolUseId:X,input:G,output:B,isError:_};H.toolBatches.set(A,{kind:M,items:[U]}),H.toolByUseId.set(X,{...z,i:A,batchSlot:0}),F0(J,xX(M,A,[U]),{type:"insert_before",targetElementId:O0(H)});continue}let P=g1(z.name);if(P){let M=P==="TaskCreate";if(M)H.taskUpdateI=null;else H.taskCreateI=null;let A=(M?H.taskCreateI:H.taskUpdateI)===null;if(A)if(M)H.taskCreateI=H.toolCount++;else H.taskUpdateI=H.toolCount++;let U=M?H.taskCreateI:H.taskUpdateI;H.toolByUseId.set(X,{...z,i:U});let S=!j?"⏳":_?"❌":"✅",b=W1(U,$.taskBoard,{name:P,status:S},z.resolvedNote);A?F0(J,b,{type:"insert_before",targetElementId:O0(H)}):J0(J,N.tool(U),b);continue}let D=H.toolCount++;H.toolByUseId.set(X,{...z,i:D});let T=!j?"⏳":_?"❌":"✅";F0(J,R$(D,z.name,z.input,B,T,z.resolvedNote,z.imageKey),{type:"insert_before",targetElementId:O0(H)})}}var CX=R(()=>{PZ();v$();Y$();t();I();R6()});async function kX($,Z,J,Y){let Q=$.pendingPermissions.get(Z);if(!Q)return K(`session "${$.sessionName}": stray permission ${Z}`),{ok:!1,message:"此权限请求已失效或已处理"};let V=$.proc;if(!V)return K(`session "${$.sessionName}": permission ${Z} has no active process`),{ok:!1,message:"后端进程已退出,权限决定未送达"};let H=J==="deny"?"deny":"allow";try{V.sendPermissionResponse(Z,H,J==="allow_always"?{updatedPermissions:Q.permissionSuggestions}:void 0)}catch(W){return K(`session "${$.sessionName}": permission response ${Z} failed: ${W}`),{ok:!1,message:`权限决定发送失败: ${W instanceof Error?W.message:W}`}}$.pendingPermissions.delete(Z);let X=$.currentTurn,z=X?.toolByUseId.get(Q.toolUseId);if(X&&z){let W=g1(z.name);if(J==="deny"){let G=`\uD83D\uDEAB 已拒绝 by ${Y||"匿名"}`,B=W?W1(z.i,$.taskBoard,{name:W,status:"❌"},G):R$(z.i,z.name,z.input,G,"❌");J0(X.cardId,N.tool(z.i),B)}else{let G=J==="allow_always"?"始终允许":"已允许";z.resolvedNote=`✅ **${G}** by ${Y||"匿名"}`;let B=W?W1(z.i,$.taskBoard,{name:W,status:"⏳"},z.resolvedNote):R$(z.i,z.name,z.input,null,"⏳",z.resolvedNote);J0(X.cardId,N.tool(z.i),B)}}if(K(`session "${$.sessionName}": permission decision request=${Z} tool_use_id=${Q.toolUseId} decision=${J}`),$.pendingPermissions.size===0&&$.status==="awaiting_permission")$.status="working";return{ok:!0,message:J==="deny"?"已拒绝":J==="allow_always"?"已始终允许":"已允许"}}function yX($,Z){let J=$.currentTurn;if(!J){K(`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 Y=Z.tool_use_id;if(!Y){K(`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 Q=J.toolByUseId.get(Y);if(!Q){K(`session "${$.sessionName}": can_use_tool for unknown tool_use_id=${Y} — auto-deny req=${Z.request_id}`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"unknown tool_use_id"});return}if(Q.name==="AskUserQuestion"){let H=$.pendingAsks.get(Y);if(!H){K(`session "${$.sessionName}": AskUserQuestion ${Y} missing pendingAsk — deny`),$.proc?.sendPermissionResponse(Z.request_id,"deny",{denyMessage:"no pending ask"});return}if(H.requestId=Z.request_id,$.pendingPermissions.set(Z.request_id,{toolUseId:Y}),H.currentIdx===void 0)CZ($,Y);return}$.status="awaiting_permission",$.pendingPermissions.set(Z.request_id,{toolUseId:Y,permissionSuggestions:Z.permission_suggestions}),K(`session "${$.sessionName}": can_use_tool request=${Z.request_id} tool_use_id=${Y} tool=${Q.name}`);let V=p5(Q.i,Q.name,Q.input,Z.request_id);if(J0(J.cardId,N.tool(Q.i),V),J.userOpenId&&J.messageId){let H=Q1(Q.name,Q.input),X=f1(Q.name),z=H&&H.length>30?H.slice(0,30)+"…":H,W=z?`\uD83D\uDD10 等审批: ${X} · ${z}`:`\uD83D\uDD10 等审批: ${X}`;(async()=>{A0(J.cardId),await p8(J.cardId,{config:{summary:{content:W}}}),await C1(J.messageId,[J.userOpenId])})()}}var wX=R(()=>{v$();Y$();t();I();R6()});class vX{createClient;waitMs;recordLogin;stateWaitMs;attempts=new Map;stopping=!1;constructor($=(Q)=>new T1({accountId:Q,login:!0}),Z=900000,J=(Q,V)=>{k.recordLogin(Q,V),O2(Q)},Y=1e4){this.createClient=$;this.waitMs=Z;this.recordLogin=J;this.stateWaitMs=Y}async start($,Z){if(this.stopping)throw Error("服务正在退出,无法开始登录");if(!Z.userOpenId)throw Error("无法确认登录发起者");if(this.attempts.has($))throw Error("该账号已有登录任务;使用 codex-login-cancel 取消后再登录");let J=ZQ($),Y;try{Y=this.createClient($)}catch(z){throw J(),z}let Q,V,H=new Promise((z,W)=>{Q=z,V=W});H.catch(()=>{});let X={owner:Z,client:Y,accountId:$,loginId:null,loginRequested:!1,loginSucceeded:!1,authUpdated:!1,finishing:!1,done:H,resolve:Q,reject:V,timer:null,notification:()=>{},closed:()=>{},early:[],releaseAuth:J};X.notification=(z,W)=>{if(X.finishing||!X.loginRequested)return;if(z==="account/updated"){if(W?.authMode==="chatgpt"){if(X.authUpdated=!0,X.loginSucceeded)this.finish(X)}return}if(z!=="account/login/completed")return;if(!X.loginId){X.early.push(W);return}if(W?.loginId!==X.loginId)return;if(W?.success!==!0){this.finish(X,Error(typeof W?.error==="string"?W.error:"Codex 登录未成功"));return}if(X.loginSucceeded)return;if(X.loginSucceeded=!0,K(`codex-login: authorization completed account=${$} authUpdated=${X.authUpdated}`),X.timer)clearTimeout(X.timer);if(X.authUpdated)this.finish(X);else X.timer=setTimeout(()=>{this.finish(X,Error("设备码授权已完成,但 Codex 未及时更新账号状态;认证文件已保留,可用 codex-accounts 检查"))},this.stateWaitMs)},X.closed=(z)=>{this.finish(X,z)},Y.on("notification",X.notification),Y.on("closed",X.closed),Y.on("protocolError",X.closed),this.attempts.set($,X);try{await Y.initialize("lodestar-login"),X.loginRequested=!0;let z=await Y.request("account/login/start",{type:"chatgptDeviceCode"},30000);if(z?.type!=="chatgptDeviceCode"||typeof z.loginId!=="string"||!z.loginId||typeof z.userCode!=="string"||!z.userCode||typeof z.verificationUrl!=="string"||new URL(z.verificationUrl).protocol!=="https:")throw Error("Codex 设备码登录响应不完整");if(X.loginId=z.loginId,X.finishing)throw await H,Error("登录已结束");X.timer=setTimeout(()=>{this.cancelAttempt(X,"登录等待超过 15 分钟,请重新发送 codex-login [备注]").catch(()=>{})},this.waitMs);for(let W of X.early)X.notification("account/login/completed",W);return X.early.length=0,{accountId:$,loginId:z.loginId,verificationUrl:z.verificationUrl,userCode:z.userCode,done:H}}catch(z){return await this.finish(X,T6(z)),await H}}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(Y){J=Error(`${Z};取消请求失败:${T6(Y).message}`)}await this.complete($,J)}async finish($,Z){if($.finishing)return;if($.finishing=!0,$.timer)clearTimeout($.timer);let J;if(!Z)try{let Y=await $.client.request("account/read",{refreshToken:!1});if(Y?.account?.type!=="chatgpt"){let Q=typeof Y?.account?.type==="string"?Y.account.type:"null";throw Error(`设备码授权已完成,但账号状态校验失败(account/read.type=${Q});认证文件已保留`)}J=Y.account,this.recordLogin($.accountId,J)}catch(Y){Z=T6(Y)}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(Y){Z=Error([Z?.message,`登录进程关闭失败:${T6(Y).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 T6($){return $ instanceof Error?$:Error(String($))}var l1;var wZ=R(()=>{w$();p0();I();l1=new vX});function fX($){let Z=new Map,J=$.map((G)=>{let B=G.fingerprint?Z.get(G.fingerprint):void 0;if(G.fingerprint&&!B)Z.set(G.fingerprint,G.account.name);return{...G,...B?{duplicateOf:B}:{}}}),Y=J.filter((G)=>!G.duplicateOf),V=(Y.length<=1||Y.every((G)=>G.fingerprint!==null))&&Y.every((G)=>G.usage.state==="ok"),H=Y.flatMap((G)=>G.usage.state==="ok"?[G.usage]:[]),X=V&&H.every((G)=>[G.fiveHour,G.weekly].filter(Boolean).every((B)=>B.percent!==null))?H.filter((G)=>[G.fiveHour,G.weekly].filter(Boolean).every((B)=>B.percent<100)).length:null,z=V&&H.every((G)=>G.resetCredits!=null)?H.reduce((G,B)=>G+B.resetCredits,0):null,W=["fiveHour","weekly"].map((G)=>{let B=H.map((j)=>j[G]).filter((j)=>j!==null),_=V&&B.every((j)=>j.percent!==null&&j.percent>=0&&j.percent<=100);return{kind:G,count:B.length,remaining:_?B.reduce((j,q)=>j+(100-q.percent)/100,0):null}}).filter((G)=>G.count||!V);return{entries:J,complete:V,available:X,resetCredits:z,windows:W}}var hX=R(()=>{p0();w$()});class d2{cardId;deps;tail=Promise.resolve();terminal=null;constructor($,Z){this.cardId=$;this.deps=Z}static async open($,Z,J=QD){let Y=await J.sendCard($,V$(Z,!0));if(!Y)throw Error("Codex 账号卡片发送失败");let Q=await J.convertMessageToCard(Y);return J.recordCardCreated(Q,1),new d2(Q,J)}update($){if(this.terminal)return Promise.reject(Error("Codex 账号卡片已结束"));let Z=h4($);return this.enqueue(()=>this.write($,Z,!1))}finish($){if(this.terminal)return this.terminal;let Z=h4($);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 Y=await this.deps.replaceElementChecked(this.cardId,N.codexAccountPanel,Z,{notifyCardFailure:!1}),Q=await this.deps.patchSettingsChecked(this.cardId,{config:{streaming_mode:!J,summary:{content:f4($)}}});if(!Y||!Q)throw Error(`Codex 账号卡片更新失败:内容 ${Y?"OK":"MISS"},状态 ${Q?"OK":"MISS"}`);if(J)await this.deps.dispose(this.cardId)}}var QD;var IX=R(()=>{t();v$();x0();T2();QD={sendCard:c,convertMessageToCard:Z$,recordCardCreated:d0,replaceElementChecked:M0,patchSettingsChecked:P0,dispose:v0}});var fZ={};E$(fZ,{settleCodexAccountCards:()=>vZ,runCodexNamedHi:()=>HD,runCodexAccountCommand:()=>XD});import{createHash as VD}from"node:crypto";function O9($,Z){let J=$ instanceof Error?$.message:String($),Y=!/失败|未完全退出/.test(J)&&/登录已取消|服务退出/.test(J),Q=/过期|等待超过|expired/i.test(J),V=J.split(/[\n;]/)[0];return{phase:Y?"cancelled":Q?"expired":"error",name:Z,message:V.length>80?V.slice(0,77)+"…":V,...J!==V||V.length>80?{details:J}:{}}}async function gX($,Z){if(!await c($.chatId,V$(O9(Z))))throw Error("Codex 错误卡片发送失败")}async function HD($,Z){let J=await d2.open($.chatId,{phase:"checking",name:Z,message:"正在启动指定账号…"});try{let Y=k.find(Z),Q="";if(!await $.startWithCodexAccount(Y.id,{announce:!1,onStatus:(H)=>{Q=H}}))throw Error(Q||"指定账号启动失败");await J.finish({phase:"current",name:Y.name,current:Y.name,title:"已指定账号",hint:"本次手动指定 · 不参与自动排序"}),await $.showConsole()}catch(Y){await J.finish(O9(Y,Z))}}async function vZ(){let Z=(await Promise.allSettled([...d1.values()])).filter((J)=>J.status==="rejected").map((J)=>J.reason);if(Z.length)throw AggregateError(Z,"Codex 账号卡片未全部写入")}async function XD($,Z,J,Y,Q){if(Z==="reset"){await WD($,J,Q);return}let V={chatId:$.chatId,userOpenId:Y};if(Z==="login-cancel"){try{let z=l1.pending(V);if(!J&&z.length!==1)throw Error(z.length?"有多个登录任务;请指定 codex-login-cancel 备注":"本群没有你的登录任务");let W=J?k.find(J).id:z[0];await l1.cancel(W,V),await d1.get(W)}catch(z){await gX($,z)}return}let H=Z==="login"?J||"默认":Z==="account"||Z==="account-delete"?J||void 0:void 0,X=await d2.open($.chatId,{phase:Z==="login"?"connecting":"checking",name:H,...Z==="login"?{flow:"login"}:{},message:Z==="accounts"?"正在读取各账号额度…":Z==="login"?"正在获取设备码…":"正在核对账号…"});try{if(Z==="account-delete"){if(!J)throw Error("请指定要删除的账号;使用 codex-account-delete 备注");let _=k.find(J);if(d1.has(_.id))throw Error("账号登录或结果更新尚未结束;请先完成或取消登录后重试");let{clearedSelections:j}=k.remove(_.id);O2(_.id),await X.finish({phase:"deleted",name:_.name,message:"已删除本地账号记录与独立凭据,共享会话历史保留。",hint:j?`已清除 ${j} 个群的指定,下次启动自动选号 · codex-accounts 查看`:"codex-accounts 查看剩余账号"});return}if(Z==="accounts"){if(J&&!/^[1-9]\d*$/.test(J))throw Error("页码无效;使用 codex-accounts [页码]");let _=J?Number(J):1,j=$.currentProvider()==="codex"?$.currentModelLabel():H0("codex-sub")?.defaultModel;if(!j)throw Error("Codex 模型 MISS,无法计算调度顺序");let q=$.currentProvider()==="codex"?$.currentEffortLabel()??void 0:void 0,P=await O8.choose({model:j,effort:q}),D=fX(P.candidates.flatMap((T)=>T.usage?[{account:T.account,usage:T.usage,fingerprint:T.identity.startsWith("record:")?null:T.identity}]:[]));await X.finish({phase:"accounts",total:D,currentId:$.codexAccountId(),...k.preferred($.sessionName)?{selectedId:k.selected($.sessionName)}:{},page:_,scheduling:{candidates:P.candidates,ultra:q==="ultra"}});return}if(Z==="auto"){if(J)throw Error("codex-auto 不需要备注");k.selectAuto($.sessionName),await X.finish({phase:"selected",name:"自动选择",current:k.get($.codexAccountId()).name,selected:"自动 · 最高分优先",hint:"Ultra:Pro 且周余量 ≥ 0.5 份"});return}if(Z==="account"){if(!J){await X.finish({phase:"current",current:k.get($.codexAccountId()).name,selected:k.preferred($.sessionName)===null?"自动 · 最高分优先":k.get(k.selected($.sessionName)).name,hint:"周剩余份额 ÷ 重置小时 · codex-auto"});return}let _=k.find(J),j=$.currentProvider()==="codex"?$.currentModelLabel():null,q=$.currentProvider()==="codex"?$.currentEffortLabel():null,P=k.get($.codexAccountId()).name;if($.currentProvider()==="codex")b1($.sessionName,"codex",j,q,"codex-sub");if(k.select($.sessionName,_.id),$.currentProvider()==="codex")$.selectedModel=j,$.selectedEffort=q,$.selectedTokenSourceId="codex-sub";await X.finish({phase:"selected",name:_.name,current:P,selected:_.name,hint:"restart 直接使用 · 不检查调度门槛"});return}if(Z!=="login")throw Error("未知 Codex 账号命令");if(!Y)throw Error("无法确认登录发起者");let z=k.ensure(J);if(J8(z.id))throw Error("账号正在使用中;重新登录前先 kill 使用该账号的会话,或用新备注添加账号");if(d1.has(z.id))throw Error("登录结果正在更新,请稍等");let W=await l1.start(z.id,V);try{await X.update({phase:"waiting",flow:"login",name:z.name,verification:{url:W.verificationUrl,code:W.userCode},hint:`取消:codex-login-cancel${J?` ${z.name}`:""}`})}catch(_){throw await l1.cancel(z.id,V),_}let G=(async()=>{let _;try{_=await W.done}catch(q){await X.finish(O9(q,z.name));return}await X.update({phase:"checking",flow:"login",name:z.name,message:"授权完成,正在读取模型…"});let j;try{await A2();let q=H0("codex-sub",z.id);if(!q)throw Error("Codex 订阅来源尚未初始化");if(await q.refreshModels(),q.modelCatalogState?.status!=="ready")throw Error(q.modelCatalogState?.error??"模型目录未就绪")}catch(q){j=q instanceof Error?q.message:String(q)}await X.finish({phase:j?"warning":"success",flow:"login",name:z.name,email:_.email,plan:_.planType,...j?{title:"已登录 · 目录 MISS",details:j}:{},hint:`已加入自动选择 · 优先使用:codex-account ${z.id==="default"?"default":z.name}`})})();d1.set(z.id,G);let B=()=>{if(d1.get(z.id)===G)d1.delete(z.id)};G.then(B,(_)=>{K(`codex-login: terminal card write failed: ${_}`),B()})}catch(z){K(`codex-${Z}: ${z}`),await X.finish(O9(z,H))}}async function WD($,Z,J){let Y;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 指定默认账号");Y=Z?k.find(Z):k.get(r0($.proc))}catch(W){K(`codex-reset: ${W}`),await gX($,W);return}let Q=await d2.open($.chatId,{phase:"checking",name:Y.name,title:"正在使用重置卡",message:"正在提交重置请求…"}),V;try{let W=VD("sha256").update(JSON.stringify(["lodestar-codex-reset",$.chatId,J])).digest("hex");V=await dQ(Y.id,W)}catch(W){K(`codex-reset: ${W}`),await Q.finish(O9(W,Y.name));return}let H=zD[V.outcome],z=[V.usage.state==="ok"?void 0:`额度刷新失败:${V.usage.state==="network"?V.usage.reason??"MISS":V.usage.state}`,V.cleanupError].filter(Boolean).join(`
|
|
220
|
+
`);await Q.finish({...H,name:Y.name,resetUsage:V.usage,...z?{phase:"warning",details:z}:{},hint:"codex-accounts 查看各账号额度"})}var d1,zD;var E6=R(()=>{t();p0();wZ();V0();hX();S3();IX();T2();I();w$();d1=new Map;zD={reset:{phase:"success",title:"额度已重置",message:"已使用 1 次重置卡。"},alreadyRedeemed:{phase:"success",title:"本次重置已完成",message:"本次请求此前已处理,没有重复使用重置卡。"},nothingToReset:{phase:"current",title:"无需重置",message:"当前没有符合条件的额度窗口,未使用重置卡。"},noCredit:{phase:"warning",title:"没有可用重置卡",message:"该账号没有可用的重置卡,额度未重置。"}}});function k0($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function hZ($,Z){let J=$.agent==="claude"?b7.filter((Q)=>Q!=="default"):$.agent==="codex"?[...r7]:["off","minimal","low","medium","high","xhigh","max"],Y=Z.effort?.trim();return{efforts:J,defaultEffort:Y&&J.includes(Y)?Y:$.agent==="claude"?"max":$.agent==="codex"?"xhigh":"high"}}function x6($,Z){let J=$.modelSelection,Y=new Set(k0(Z.hidden_models)),Q=[...new Set([...k0(Z.custom_models),...J?[]:k0(Z.models)])],V=$.modelSelection=J??{mode:"catalog",modelIds:[],availableModels:[]},H=$.refreshModels.bind($);return $.refreshModels=async()=>{if($.models=[],V.availableModels=[],!J)V.modelIds=[];try{await H()}catch(G){throw $.models=[],$.modelCatalogState={status:"failed",updatedAt:Date.now(),error:G instanceof Error?G.message:String(G)},G}if($.modelCatalogState?.status!=="ready")return;let X=$.models,z=(J?V.availableModels:X).map((G)=>({...G,origin:G.origin??"upstream"}));for(let G of Q){if(z.some((B)=>B.model.toLowerCase()===G.toLowerCase()))continue;z.push({model:G,display:G,origin:"custom",...hZ($,Z)})}V.availableModels=z;let W=J?X.map((G)=>z.find((B)=>B.model===G.model)??{...G,origin:"upstream"}):z;$.models=[...W.filter((G)=>G.origin==="custom"||!Y.has(G.model)),...z.filter((G)=>G.origin==="custom"&&!W.some((B)=>B.model===G.model))],V.modelIds=$.models.map((G)=>G.model)},$}var i2=R(()=>{D0();O1()});import{homedir as GD}from"node:os";function cX($,Z=pX){return new Promise((J,Y)=>{let Q=setTimeout(()=>Y(Error(`timeout ${Z}ms`)),Z);$.then((V)=>{clearTimeout(Q),J(V)},(V)=>{clearTimeout(Q),Y(V)})})}function mX($){return typeof $==="string"&&KD.includes($)?$:null}async function uX(){let{ClaudeAgentProcess:$}=await Promise.resolve().then(() => (x4(),gQ)),Z=new $({workDir:GD(),effort:"high",settingSources:["user"],allowDelegation:!1,profile:{loadProjectMcp:!1}});Z.on("error",(J)=>K(`Claude model catalog MISS: ${J.message}`));try{let J=await cX(Z.listModels());if(!J.length)throw Error("Claude SDK model catalog is empty");return J.map((Y)=>({model:Y.model.replace(/^claude:/,""),display:Y.displayName,efforts:Y.supportedReasoningEfforts.map((Q)=>Q.reasoningEffort),defaultEffort:Y.defaultReasoningEffort}))}finally{await Z.kill()}}async function lX($="default"){let Z=new T1({accountId:$});try{if(await Z.initialize("lodestar-models"),(await Z.request("account/read",{refreshToken:!1}))?.account?.type!=="chatgpt")throw Object.assign(Error("Codex 订阅未登录;发送 codex-login 或 codex-login 备注完成授权"),{code:"CODEX_AUTH_MISSING"});let Y=await cX(Z.request("model/list",{}));if(!Array.isArray(Y?.data))throw Error("Codex model/list 缺少 data 数组");let Q=Y.data,V=[];for(let H of Q){if(!H||H.hidden||!H.id)continue;let X=(Array.isArray(H.supportedReasoningEfforts)?H.supportedReasoningEfforts:[]).map((W)=>mX(W?.reasoningEffort)).filter((W)=>W!==null);if(!X.length)continue;let z=mX(H.defaultReasoningEffort)??X[0];V.push({model:String(H.id),display:typeof H.displayName==="string"&&H.displayName?String(H.displayName):String(H.id),efforts:X,defaultEffort:z})}return V}finally{await Z.close()}}async function dX($,Z){let J=new URL($),Y=J.pathname.replace(/\/+$/,""),Q=`${J.protocol}//${J.host}${Y}/v1/models`,V=await $0(Q,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(pX)});if(!V.ok)throw Error(`HTTP ${V.status}`);let H=await V.json();if(!Array.isArray(H?.data))throw Error("GLM models 缺少 data 数组");return H.data.filter((z)=>z&&(z.display_name||z.id)).map((z)=>{let W=String(z.display_name||z.id);return{model:W,display:W,efforts:n2,defaultEffort:"max"}})}var pX=1e4,KD,n2;var R9=R(()=>{h0();w$();I();KD=["none","minimal","low","medium","high","xhigh","max","ultra"];n2=["max","xhigh","high","medium","low"]});import{existsSync as BD}from"node:fs";import{join as _D}from"node:path";function iX($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt,...$.unreportedFull===void 0?{}:{unreportedFull:$.unreportedFull}}}function jD($){if($.state!=="ok")return{state:$.state==="auth_failed"?"no_credentials":$.state==="no_credentials"?"no_credentials":$.state==="rate_limited"?"rate_limited":"network",windows:[],resetCredits:null};let Z=[];if($.fiveHour)Z.push(iX($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(iX($.weekly,"weekly","周配额"));return{state:"ok",planLabel:$.subscriptionType,windows:Z,fetchedAt:$.fetchedAt,resetCredits:$.resetCredits??null}}function nX($){return $===u||BD(_D(k.home($),"auth.json"))}var aX=R(()=>{y0();V0();w$();R9();I();p0();i2();S0({kind:"codex-subscription",configSectionId:"codex-sub",build:($)=>{let Z=new Map,J=(V)=>{let H=nX(V),X=$.model?.trim()||void 0,z=$.effort?.trim()||void 0,W={id:"codex-sub",kind:"codex-subscription",agent:"codex",display:$.display?.trim()||"Codex 订阅",spawnRevision:JSON.stringify([$.model,$.effort,k.revision(V)]),enabled:H,models:[],modelCatalogState:{status:H?"idle":"disabled",updatedAt:Date.now()},defaultModel:X??"",async refreshModels(){if(W.enabled=nX(V),!W.enabled){W.models=[],W.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}W.modelCatalogState={status:"loading",updatedAt:null};try{if(W.models=await lX(V),z)for(let G of W.models)G.defaultEffort=z;if(!X)W.defaultModel=W.models[0]?.model??"";W.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(G){if(K(`codex-sub ${V} refreshModels MISS: ${G?.message??G}`),W.models=[],G?.code==="CODEX_AUTH_MISSING")W.enabled=!1;W.modelCatalogState={status:W.enabled?"failed":"disabled",updatedAt:Date.now(),error:G?.message??String(G)}}},spawnEnv(G){let B=j$(G);return Object.assign(B,f.codex.env),k.env(V,B)},resolveSpawnModel(G){return G},async readUsage(){return jD(await E1(V))}};return W},Y=J(u);Y.forAccount=(V)=>{if(V===u)return Y;let H=k.revision(V),X=Z.get(V);if(X?.revision===H)return X.source;let z=x6(J(V),$);return Z.set(V,{revision:H,source:z}),z};let Q=Y.refreshModels.bind(Y);return Y.refreshModels=async()=>{await Promise.all([Q(),...k.list().filter((V)=>V.id!==u).map((V)=>Y.forAccount(V.id).refreshModels())])},Y}})});function qD($){let Z=new URL($),J=Z.pathname.replace(/\/+$/,"");return`${Z.protocol}//${Z.host}${J}/v1/messages`}async function S6($,Z,J){try{let Y=await $0(qD($),{method:"POST",headers:{"Content-Type":"application/json",...Z},body:JSON.stringify({model:J,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:AbortSignal.timeout(LD)});if(Y.ok)return"exists";if(Y.status===400){let Q=await Y.text();return Q.includes("1214")||Q.includes("不存在")||Q.includes("not exist")?"not_found":"no_verdict"}return K(`model-existence: ${J} HTTP ${Y.status}, no verdict`),"no_verdict"}catch(Y){return K(`model-existence: ${J} MISS (${Y?.message??Y})`),"no_verdict"}}var LD=15000;var IZ=R(()=>{h0();I()});function oX($,Z,J){return{kind:Z,label:J,percent:$.percent,resetsAt:$.resetsAt}}function PD($){return{kind:"monthly",label:"月度工具",percent:$.percent,resetsAt:$.resetsAt,...$.used!=null?{used:$.used}:{},...$.total!=null?{total:$.total}:{}}}function rX($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function DD($){let Z=(J)=>{let Y=J.match(/(\d+(?:\.\d+)?)/);return Y?Number(Y[1]):-1};return[...$].sort((J,Y)=>Z(Y)-Z(J))[0]??""}function FD($){let Z={};for(let J of($??"").split(",")){let Y=J.indexOf("=");if(Y<=0)continue;let Q=J.slice(0,Y).trim().toLowerCase(),V=J.slice(Y+1).trim();if((Q==="opus"||Q==="sonnet"||Q==="haiku")&&V)Z[Q]=V}return Z}function gZ($){if($.state!=="ok")return{state:$.state==="no_credentials"?"no_credentials":$.state==="not_glm"?"not_applicable":$.state==="rate_limited"?"rate_limited":"network",windows:[],...$.state==="network"&&$.reason?{reason:$.reason}:{}};let Z=[];if($.fiveHour)Z.push(oX($.fiveHour,"fiveHour","5h 窗口"));if($.weekly)Z.push(oX($.weekly,"weekly","周额度"));if($.monthly)Z.push(PD($.monthly));return{state:"ok",planLabel:$.level?`${$.level} 套餐`:void 0,windows:Z,fetchedAt:$.fetchedAt}}var mZ=R(()=>{V0();q9();R9();E4();IZ();I();S0({kind:"glm-coding-plan",configSectionId:"glm",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||"",Y=$.auth_token?.trim()||Z?.auth_token?.trim()||"",Q=!!(J&&Y)&&p1(J),V=$.model?.trim()||void 0,H=FD($.slots),X={id:"glm",kind:"glm-coding-plan",agent:"claude",display:$.display?.trim()||"GLM Coding Plan",enabled:Q,models:[],modelCatalogState:{status:Q?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!X.enabled){X.models=[],X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await dX(J,Y),G=[...new Set([...rX($.models),...rX($.custom_models)])].filter((B)=>!z.some((_)=>_.model.toLowerCase()===B.toLowerCase())).map((B)=>({model:B,display:B,efforts:n2,defaultEffort:"max",origin:"custom"}));if(X.models=[...z,...G],!V)X.defaultModel=DD(X.models.map((B)=>B.model));for(let B of X.models){let _=L2("glm",B.model);B.context1m=_!=null&&_>=1e6||void 0}X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){K(`glm refreshModels MISS: ${z?.message??z}`),X.models=[],X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:z?.message??String(z)}}},spawnEnv(z){let G={...j$(z)};if(G.ANTHROPIC_BASE_URL=J,G.ANTHROPIC_AUTH_TOKEN=Y,H.opus)G.ANTHROPIC_DEFAULT_OPUS_MODEL=H.opus;if(H.sonnet)G.ANTHROPIC_DEFAULT_SONNET_MODEL=H.sonnet;if(H.haiku)G.ANTHROPIC_DEFAULT_HAIKU_MODEL=H.haiku;return G},resolveSpawnModel(z){return G8("glm",z)},async verifyModel(z){return S6(J,{Authorization:`Bearer ${Y}`},z)},async readUsage(){return gZ(await L9(J,Y))}};return X},setup:{commandSuffix:"glm",hint:($)=>`启用 ${$}:发送
|
|
221
221
|
\`\`\`
|
|
222
222
|
glm-setup <base_url> <token>
|
|
223
|
-
\`\`\``,parseArgs:($)=>{let Z=$.trim().split(/\s+/);if(Z.length<2)return{error:"用法:`glm-setup <base_url> <token>`"};return{config:{agent:"claude",base_url:Z[0],auth_token:Z[1]}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!p1(Z))return null;let J=$.ANTHROPIC_AUTH_TOKEN?.trim()??"";return J?{base_url:Z,auth_token:J}:null}}})});var
|
|
223
|
+
\`\`\``,parseArgs:($)=>{let Z=$.trim().split(/\s+/);if(Z.length<2)return{error:"用法:`glm-setup <base_url> <token>`"};return{config:{agent:"claude",base_url:Z[0],auth_token:Z[1]}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!p1(Z))return null;let J=$.ANTHROPIC_AUTH_TOKEN?.trim()??"";return J?{base_url:Z,auth_token:J}:null}}})});var sX=R(()=>{V0();R9();S0({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 uX(),!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}})});function tX($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}function UD($){let Z=(J)=>{let Y=J.match(/(\d+(?:\.\d+)?)/);return Y?Number(Y[1]):-1};return[...$].sort((J,Y)=>Z(Y)-Z(J))[0]??""}function AD($){let Z={};for(let J of($??"").split(",")){let Y=J.indexOf("=");if(Y<=0)continue;let Q=J.slice(0,Y).trim().toLowerCase(),V=J.slice(Y+1).trim();if((Q==="opus"||Q==="sonnet"||Q==="haiku")&&V)Z[Q]=V}return Z}function OD($){try{return new URL($).hostname.toLowerCase()==="api.deepseek.com"}catch{return!1}}async function RD($,Z){let J=new URL($).origin,Y=await $0(`${J}/models`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(1e4)});if(!Y.ok)throw Error(`HTTP ${Y.status}`);let Q=await Y.json();if(!Array.isArray(Q?.data))throw Error("DeepSeek models 缺少 data 数组");return Q.data.filter((H)=>H&&typeof H.id==="string"&&H.id).map((H)=>({model:H.id,display:H.id,efforts:n2,defaultEffort:"high"}))}async function pZ($,Z){let J;try{J=new URL($).origin}catch{return{kind:"balance",state:"network",windows:[],reason:"bad base_url"}}try{let Y=await $0(`${J}/user/balance`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(ND)});if(!Y.ok)throw Error(`HTTP ${Y.status}`);let Q=await Y.json(),H=(Array.isArray(Q?.balance_infos)?Q.balance_infos:[])[0],X=typeof H?.currency==="string"?H.currency:"",z=H?.total_balance;if(!X||typeof z!=="string"&&typeof z!=="number"||String(z).trim()===""||!Number.isFinite(Number(z)))throw Error("余额明细缺失或无效");return{kind:"balance",state:"ok",windows:[],balance:{remaining:Number(z),currency:X}}}catch(Y){return K(`deepseek readUsage MISS: ${Y?.message??Y}`),{kind:"balance",state:"network",windows:[],reason:Y?.message??String(Y)}}}var MD="https://api.deepseek.com/anthropic",ND=1e4;var cZ=R(()=>{h0();V0();R9();E4();IZ();I();S0({kind:"deepseek",configSectionId:"deepseek",build:($,Z)=>{let J=$.base_url?.trim()||Z?.base_url?.trim()||MD,Y=$.api_key?.trim()||Z?.api_key?.trim()||"",Q=!!Y,V=$.model?.trim()||void 0,H=AD($.slots),X={id:"deepseek",kind:"deepseek",agent:"claude",display:$.display?.trim()||"DeepSeek",enabled:Q,models:[],modelCatalogState:{status:Q?"idle":"disabled",updatedAt:Date.now()},defaultModel:V??"",async refreshModels(){if(!X.enabled){X.models=[],X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await RD(J,Y),G=[...new Set([...tX($.models),...tX($.custom_models)])].filter((B)=>!z.some((_)=>_.model.toLowerCase()===B.toLowerCase())).map((B)=>({model:B,display:B,efforts:n2,defaultEffort:"high",origin:"custom"}));if(X.models=[...z,...G],!V)X.defaultModel=UD(X.models.map((B)=>B.model));for(let B of X.models){let _=L2("deepseek",B.model);B.context1m=_!=null&&_>=1e6||void 0}X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){K(`deepseek refreshModels MISS: ${z?.message??z}`),X.models=[],X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:z?.message??String(z)}}},spawnEnv(z){let G={...j$(z)};if(G.ANTHROPIC_BASE_URL=J,G.ANTHROPIC_API_KEY=Y,H.opus)G.ANTHROPIC_DEFAULT_OPUS_MODEL=H.opus;if(H.sonnet)G.ANTHROPIC_DEFAULT_SONNET_MODEL=H.sonnet;if(H.haiku)G.ANTHROPIC_DEFAULT_HAIKU_MODEL=H.haiku;return G},resolveSpawnModel(z){return G8("deepseek",z)},async verifyModel(z){return S6(J,{"x-api-key":Y},z)},async readUsage(){if(!Y)return{kind:"balance",state:"no_credentials",windows:[]};return pZ(J,Y)}};return X},setup:{commandSuffix:"deepseek",hint:($)=>`启用 ${$}:发送
|
|
224
224
|
\`\`\`
|
|
225
225
|
deepseek-setup <api_key>
|
|
226
226
|
\`\`\`
|
|
227
|
-
默认官方 Anthropic 端点;自建中转用 \`deepseek-setup <base_url> <api_key>\`。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(!Z.length)return{error:"用法:`deepseek-setup <api_key>`(官方端点)或 `deepseek-setup <base_url> <api_key>`(自建中转)"};let J=Z.length>=2?Z[0]:void 0,Y=Z.length>=2?Z[1]:Z[0];return{config:{agent:"claude",...J?{base_url:J}:{},api_key:Y}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!AF(Z))return null;let J=$.ANTHROPIC_API_KEY?.trim()??"";return J?{base_url:Z,api_key:J}:null}}})});function i1($){let Z=$.toLowerCase().replace(/^~/,"");return/^(openai|deepseek|z-ai|zai-org|thudm)\//.test(Z)||/^(openrouter\/|@)/.test(Z)}var lZ;var $z=R(()=>{lZ=[{rank:1,lab:"Anthropic",model:"anthropic/claude-fable-5.1",effort:"max"},{rank:3,lab:"Moonshot",model:"moonshotai/kimi-k3",effort:"max"},{rank:4,lab:"Tencent",model:"tencent/hy4-preview",effort:"high"},{rank:7,lab:"Google",model:"google/gemini-3.8-flash",effort:"high"},{rank:8,lab:"SpaceXAI",model:"x-ai/grok-4.5",effort:"high"},{rank:9,lab:"Alibaba",model:"qwen/qwen3.8-max-0902",effort:"xhigh"},{rank:10,lab:"Meta",model:"meta/muse-spark-1.2",effort:"xhigh"},{rank:11,lab:"Xiaomi",model:"xiaomi/mimo-v2.5-pro",effort:"default"},{rank:12,lab:"MiniMax",model:"minimax/minimax-m3",effort:"default"},{lab:"ByteDance",model:"bytedance-seed/seed-2-1-turbo",effort:"default"},{lab:"Meituan",model:"meituan/longcat-2.0",effort:"default"}]});function G1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function iZ($){return $ instanceof Error?$.message:String($)}function Zz($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function a2($){return $.replace(/\[1m\]$/,"")}function C6($){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 Yz($,Z,J){if(!Z)throw Error("OpenRouter API key missing");let Y=await $0(`${C6($)}/v1/${J}`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(TF)});if(!Y.ok){let Q=await Y.text(),V="";if(Q.trim().startsWith("{"))try{let H=JSON.parse(Q);if(G1(H)&&G1(H.error)&&typeof H.error.message==="string")V=H.error.message}catch{}throw new nZ(Y.status,V.replaceAll(Z,"[redacted]"))}return Y.json()}async function EF($,Z){let J=await Yz($,Z,"models/user");if(!G1(J)||!Array.isArray(J.data))throw Error("OpenRouter models: data 数组缺失");let Y=[],Q=new Set;for(let V of J.data){if(!G1(V)||typeof V.id!=="string"||!V.id||typeof V.name!=="string")throw Error("OpenRouter models: 模型 id/name 无效");if(!G1(V.architecture)||!Array.isArray(V.architecture.output_modalities)||!Array.isArray(V.supported_parameters))throw Error(`OpenRouter models: ${V.id} 的模型能力缺失`);if(i1(V.id)||!V.architecture.output_modalities.includes("text")||!V.supported_parameters.includes("tools")||V.id.endsWith(":batch")||Q.has(V.id))continue;let H=G1(V.reasoning)?V.reasoning:void 0,X=H?.supported_efforts,z=X===null||X===void 0&&V.supported_parameters.includes("reasoning_effort")?["max","xhigh","high","medium","low"]:Array.isArray(X)?[...new Set(X.filter((_)=>_!=="default"&&E0(_)))]:["default"],W=lZ.find((_)=>_.model===V.id),G=W?z.includes(W.effort)?W.effort:null:z[0]==="default"?"default":E0(H?.default_effort)&&z.includes(H.default_effort)?H.default_effort:null,B=L2("openrouter",V.id);Y.push({model:V.id,display:V.name,efforts:z,defaultEffort:G,context1m:B!==void 0&&B>=1e6||void 0}),Q.add(V.id)}if(!Y.length)throw Error("OpenRouter 未返回支持文本和工具调用的交互模型");return Y}function Jz($){return typeof $==="number"&&Number.isFinite($)&&$>=0}async function xF($,Z){if(!Z)return{kind:"balance",state:"no_credentials",windows:[]};try{let J=await Yz($,Z,"credits");if(!G1(J)||!G1(J.data))throw Error("OpenRouter credits: data 对象缺失");let{total_credits:Y,total_usage:Q}=J.data;if(!Jz(Y)||!Jz(Q))throw Error("OpenRouter credits: total_credits/total_usage 缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Y-Q,currency:"USD"}}}catch(J){let Y=iZ(J);return K(`openrouter readUsage MISS: ${Y}`),{kind:"balance",state:J instanceof nZ&&J.status===429?"rate_limited":"network",windows:[],reason:Y}}}var NF="https://openrouter.ai/api",TF=1e4,dZ,nZ;var Qz=R(()=>{h0();F0();V0();E4();I();$z();dZ={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL"};nZ=class nZ extends Error{status;constructor($,Z){super(`HTTP ${$}${Z?`: ${Z}`:""}`);this.status=$}};S0({kind:"openrouter",configSectionId:"openrouter",build($,Z){let J=$.api_key||$.auth_token||$.base_url?$:Z,Y=J?.api_key?.trim()||J?.auth_token?.trim()||"",Q=J?.base_url?.trim()||NF,V=$.model?.trim()||"",H=$.models===void 0?lZ.map((z)=>z.model):Zz($.models),X={id:"openrouter",kind:"openrouter",agent:"claude",display:$.display?.trim()||"OpenRouter",enabled:!!Y,models:[],defaultModel:V,modelSelection:{mode:"allowlist",modelIds:H,availableModels:[]},validateCustomModelId(z){if(i1(z))throw Error(`OpenRouter 已排除此厂商或自动路由: ${z}`);if(!z.includes("/"))throw Error("OpenRouter 模型请填写完整的 作者/模型 ID")},modelEnvironmentRevision(z){let W=X.modelSelection.availableModels.find((G)=>a2(G.model)===a2(z));if(!W||W.unavailableReason||!W.efforts.length)return"model-unavailable";return W.efforts.includes("default")?"effort-unset":"effort-level"},modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},async refreshModels(){if(X.models=[],X.modelSelection.availableModels=[],!X.enabled){X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await EF(Q,Y),W=z.find((B)=>B.model===a2(V));if(V&&!W)throw Error(`OpenRouter 默认模型不在账号目录中: ${V}`);if($.effort){if(!V)throw Error("OpenRouter effort 需要同时配置 model");if(!E0($.effort)||!W.efforts.includes($.effort))throw Error(`OpenRouter 模型 ${V} 不支持 effort ${$.effort}`);W.defaultEffort=$.effort}let G=H.map((B)=>{let _=z.find((j)=>j.model===a2(B));if(!_)return{model:B,display:B,efforts:[],defaultEffort:null,unavailableReason:i1(B)?"此厂商或自动路由已被排除":"账号目录未返回该模型"};return{..._,model:B}});X.models=G,X.modelSelection.availableModels=z,X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){let W=iZ(z);K(`openrouter refreshModels MISS: ${W}`),X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:W}}},spawnEnv(z,W){if(!Y)throw Error("OpenRouter API key missing");let G=W||V;if(!G)throw Error("OpenRouter 未选择模型,请通过 model 面板选择或配置 model");if(i1(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);let B=j$(z);B.ANTHROPIC_BASE_URL=C6(Q),B.ANTHROPIC_AUTH_TOKEN=Y,B.ANTHROPIC_API_KEY="",B.CLAUDE_CODE_NO_MODEL_FALLBACK="1",B.ANTHROPIC_MODEL=G,B.ANTHROPIC_SMALL_FAST_MODEL=G,B.CLAUDE_CODE_SUBAGENT_MODEL=G,B.ANTHROPIC_DEFAULT_FABLE_MODEL=G;for(let _ of Object.values(dZ))B[_]=G;for(let _ of Zz($.slots)){let j=_.indexOf("="),q=_.slice(0,j).trim(),P=_.slice(j+1).trim();if(j<1||!Object.hasOwn(dZ,q)||!P)throw Error(`OpenRouter slots 无效: ${_}`);if(i1(P)||!X.modelSelection.availableModels.some((F)=>!F.unavailableReason&&a2(F.model)===a2(P)))throw Error(`OpenRouter slot 模型不在账号目录中: ${P}`);if(X.modelEnvironmentRevision(P)!==X.modelEnvironmentRevision(G))throw Error(`OpenRouter slot 不能混合无 effort 档位与有 effort 档位的模型: ${P}`);B[dZ[q]]=P}return B},resolveSpawnModel(z){if(i1(z))throw Error(`OpenRouter 已排除此厂商或自动路由: ${z}`);return z||void 0},readUsage(){return xF(Q,Y)}};return X},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:C6(Z[0])}:{}}}}catch(J){return{error:iZ(J)}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim(),J=$.ANTHROPIC_AUTH_TOKEN?.trim();if(!Z||!J)return null;try{let Y=C6(Z);if(new URL(Y).hostname!=="openrouter.ai")return null;return{base_url:Y,api_key:J}}catch{return null}}}})});var Vz=R(()=>{V0();F0();P4();Q0();uZ();i2();S0({kind:"deepseek-harness",configSectionId:"deepseek-harness",build($){let Z=$.api_key?.trim()??"",J=$.base_url?.trim()||"https://api.deepseek.com",Y={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(Q){let V=S4(Q);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(!Y.enabled){Y.models=[],Y.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}Y.modelCatalogState={status:"loading",updatedAt:null};try{let Q=await X2({cwd:Y2,env:Y.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list",{models:[...k0($.models),...k0($.custom_models)]});if(!Array.isArray(Q)||!Q.length)throw Error("DeepSeek Harness model catalog is empty");for(let H of Q)if(!H.model||!H.efforts.length||!H.efforts.every(B0)||!B0(H.defaultEffort)||!H.efforts.includes(H.defaultEffort))throw Error(`Invalid DSH model/effort catalog: ${H.model}`);let V=$.model?.trim()||Q.find((H)=>H.isDefault)?.model;if(!V||!Q.some((H)=>H.model===V))throw Error("DSH default model is not in its catalog");Y.models=Q.map(({model:H,display:X,efforts:z,defaultEffort:W,isCustom:G})=>{let B=$.effort?.trim();if(B&&(!B0(B)||!z.includes(B)))throw Error(`DSH model ${H} does not support configured effort ${B}`);return{model:H,display:X,efforts:z,defaultEffort:B?B:W,origin:G?"custom":"upstream"}}),Y.defaultModel=V,Y.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(Q){throw Y.models=[],Y.modelCatalogState={status:"failed",updatedAt:Date.now(),error:Q instanceof Error?Q.message:String(Q)},Q}},resolveSpawnModel(Q){return F2(Y).find((V)=>V.model===Q)?.model},readUsage(){return Z?cZ(J,Z):Promise.resolve({kind:"balance",state:"no_credentials",windows:[]})}};return Y},setup:{commandSuffix:"deepseek-harness",hint:()=>"启用 DeepSeek Harness:发送 `deepseek-harness-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)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]}:{}}}}}})});function aZ($){let Z=new URL($);if(!p1(Z.origin))throw Error("DSH GLM 需要 bigmodel.cn 或 z.ai 的 Coding Plan 端点");return Z.pathname="/api/coding/paas/v4",Z.search="",Z.hash="",Z.toString().replace(/\/$/,"")}async function SF($,Z){let J=await $0(`${$}/models`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(1e4)});if(!J.ok)throw Error(`GLM Coding Plan models HTTP ${J.status}`);let Y=await J.json();if(!Array.isArray(Y?.data)||!Y.data.length)throw Error("GLM Coding Plan 模型目录为空或无效");return Y.data.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 Hz=R(()=>{h0();y0();F0();V0();P4();Q0();q9();pZ();i2();S0({kind:"dsh-glm",configSectionId:"dsh-glm",detect:{fromSettingsEnv($){let Z=f.token_sources?.glm,J=Z?.auth_token?.trim()||$.ANTHROPIC_AUTH_TOKEN?.trim(),Y=Z?.base_url?.trim()||$.ANTHROPIC_BASE_URL?.trim();return J&&Y&&p1(Y)?{api_key:J,base_url:aZ(Y)}:null}},build($,Z){let J=$.api_key?.trim()||$.auth_token?.trim()||Z?.api_key?.trim()||"",Y=aZ($.base_url?.trim()||Z?.base_url?.trim()||"https://open.bigmodel.cn/api/coding/paas/v4"),Q=new URL(Y).hostname.endsWith("bigmodel.cn")?"zai-coding-cn":"zai",V,H={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([...V??[]].sort())},modelCatalogState:{status:J?"idle":"disabled",updatedAt:Date.now()},spawnEnv(X){if(!J)throw Error("DSH GLM Coding Plan API key is missing");let z=S4(X);if(z.LODESTAR_DSH_PROVIDER=Q,z.LODESTAR_DSH_GLM_API_KEY=J,z.LODESTAR_DSH_BASE_URL=Y,z.LODESTAR_DSH_DEFAULT_MODEL=H.defaultModel,V)z.LODESTAR_DSH_MODELS=JSON.stringify(V);if($.bin)z.LODESTAR_DSH_NODE=$.bin;return z},async refreshModels(){if(H.models=[],V=void 0,!H.enabled){H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{let X=await SF(Y,J),z=[...X];for(let G of[...k0($.models),...k0($.custom_models)])if(!z.some((B)=>B.model.toLowerCase()===G.toLowerCase()))z.push({model:G,display:G});if(V=z.map((G)=>G.model),!$.model?.trim()){let G=(B)=>Number(B.match(/\d+(?:\.\d+)?/)?.[0]??-1);H.defaultModel=[...X].sort((B,_)=>G(_.model)-G(B.model))[0].model}let W=await X2({cwd:Y2,env:H.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list");H.models=z.map((G)=>{let B=W.find((P)=>P.model===G.model),_=IZ(H,$),j=B?B.efforts.filter(B0):_.efforts,q=$.effort?.trim()||B?.defaultEffort||_.defaultEffort;return{...G,display:B?.display??G.display,efforts:j,defaultEffort:B0(q)&&j.includes(q)?q:null,origin:X.some((P)=>P.model===G.model)?"upstream":"custom"}}),H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(X){throw H.models=[],V=[],H.modelCatalogState={status:"failed",updatedAt:Date.now(),error:X instanceof Error?X.message:String(X)},X}},resolveSpawnModel(X){return F2(H).find((z)=>z.model===X&&!z.unavailableReason)?.model},async readUsage(){return J?mZ(await L9(Y,J)):{state:"no_credentials",windows:[]}}};return H},setup:{commandSuffix:"dsh-glm",hint:()=>"DSH 可复用已配置的 GLM Coding Plan;独立账号用 `dsh-glm-setup [base_url] <api_key>`。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2)return{error:"用法:dsh-glm-setup [base_url] <api_key>"};try{return{config:{agent:"dsh",api_key:Z.at(-1),base_url:aZ(Z.length===2?Z[0]:"https://open.bigmodel.cn/api/coding/paas/v4")}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}}}})});var zz={};E$(zz,{tokenSourceSpawnRevision:()=>Xz,buildTokenSourcesFromConfig:()=>oZ});import{createHash as bF}from"node:crypto";function oZ(){T3();let $=PZ(),Z=M2().map((V)=>{let H=V.configSectionId?(f.token_sources??{})[V.configSectionId]??{}:{},X=V.detect?.fromSettingsEnv($)??null,z=S6(V.build(H,X),H);return z.spawnRevision=Xz(V.kind,H,X),z}),J=Z.find((V)=>V.kind==="claude-native");if(J){let V=Z.some((H)=>H.agent==="claude"&&H.enabled&&H.kind!=="claude-native");J.enabled=!V,J.modelCatalogState={status:J.enabled?"idle":"disabled",updatedAt:Date.now()}}for(let V of Z)R3(V);let Q=Z.find((V)=>V.enabled&&f.token_sources?.[V.id]?.default===!0)??Z.find((V)=>V.enabled);if(Q)N3(Q.id);return Z.length}function Xz($,Z,J){let Y=(Q)=>({agent:Q?.agent,auth:Q?.auth,base_url:Q?.base_url,auth_token:Q?.auth_token,api_key:Q?.api_key,bin:Q?.bin,model:Q?.model,effort:Q?.effort,slots:Q?.slots});return bF("sha256").update(JSON.stringify({kind:$,configured:Y(Z),detected:Y(J)})).digest("hex")}var rZ=R(()=>{y0();V0();q9();i2();oX();pZ();tX();uZ();Qz();Vz();Hz()});import{readFileSync as CF}from"node:fs";function kF($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function yF($,Z){let J=[`[token_source.${$}]`],Y=(Q,V)=>{if(V!==void 0)J.push(`${Q} = "${kF(V)}"`)};if(Y("agent",Z.agent),Y("display",Z.display),Y("auth",Z.auth),Y("base_url",Z.base_url),Y("auth_token",Z.auth_token),Y("api_key",Z.api_key),Y("bin",Z.bin),Y("model",Z.model),Y("effort",Z.effort),Y("models",Z.models),Y("hidden_models",Z.hidden_models),Y("custom_models",Z.custom_models),Y("slots",Z.slots),Y("usage",Z.usage),Z.default!==void 0)J.push(`default = "${Z.default}"`);return J.join(`
|
|
228
|
-
`)}function
|
|
229
|
-
`),V=!1,H=
|
|
227
|
+
默认官方 Anthropic 端点;自建中转用 \`deepseek-setup <base_url> <api_key>\`。`,parseArgs:($)=>{let Z=$.trim().split(/\s+/).filter(Boolean);if(!Z.length)return{error:"用法:`deepseek-setup <api_key>`(官方端点)或 `deepseek-setup <base_url> <api_key>`(自建中转)"};let J=Z.length>=2?Z[0]:void 0,Y=Z.length>=2?Z[1]:Z[0];return{config:{agent:"claude",...J?{base_url:J}:{},api_key:Y}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim()??"";if(!OD(Z))return null;let J=$.ANTHROPIC_API_KEY?.trim()??"";return J?{base_url:Z,api_key:J}:null}}})});function i1($){let Z=$.toLowerCase().replace(/^~/,"");return/^(openai|deepseek|z-ai|zai-org|thudm)\//.test(Z)||/^(openrouter\/|@)/.test(Z)}var uZ;var eX=R(()=>{uZ=[{rank:1,lab:"Anthropic",model:"anthropic/claude-fable-5.1",effort:"max"},{rank:3,lab:"Moonshot",model:"moonshotai/kimi-k3",effort:"max"},{rank:4,lab:"Tencent",model:"tencent/hy4-preview",effort:"high"},{rank:7,lab:"Google",model:"google/gemini-3.8-flash",effort:"high"},{rank:8,lab:"SpaceXAI",model:"x-ai/grok-4.5",effort:"high"},{rank:9,lab:"Alibaba",model:"qwen/qwen3.8-max-0902",effort:"xhigh"},{rank:10,lab:"Meta",model:"meta/muse-spark-1.2",effort:"xhigh"},{rank:11,lab:"Xiaomi",model:"xiaomi/mimo-v2.5-pro",effort:"default"},{rank:12,lab:"MiniMax",model:"minimax/minimax-m3",effort:"default"},{lab:"ByteDance",model:"bytedance-seed/seed-2-1-turbo",effort:"default"},{lab:"Meituan",model:"meituan/longcat-2.0",effort:"default"}]});function G1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function dZ($){return $ instanceof Error?$.message:String($)}function $z($){return[...new Set(($??"").split(",").map((Z)=>Z.trim()).filter(Boolean))]}function a2($){return $.replace(/\[1m\]$/,"")}function b6($){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 Jz($,Z,J){if(!Z)throw Error("OpenRouter API key missing");let Y=await $0(`${b6($)}/v1/${J}`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(ED)});if(!Y.ok){let Q=await Y.text(),V="";if(Q.trim().startsWith("{"))try{let H=JSON.parse(Q);if(G1(H)&&G1(H.error)&&typeof H.error.message==="string")V=H.error.message}catch{}throw new iZ(Y.status,V.replaceAll(Z,"[redacted]"))}return Y.json()}async function xD($,Z){let J=await Jz($,Z,"models/user");if(!G1(J)||!Array.isArray(J.data))throw Error("OpenRouter models: data 数组缺失");let Y=[],Q=new Set;for(let V of J.data){if(!G1(V)||typeof V.id!=="string"||!V.id||typeof V.name!=="string")throw Error("OpenRouter models: 模型 id/name 无效");if(!G1(V.architecture)||!Array.isArray(V.architecture.output_modalities)||!Array.isArray(V.supported_parameters))throw Error(`OpenRouter models: ${V.id} 的模型能力缺失`);if(i1(V.id)||!V.architecture.output_modalities.includes("text")||!V.supported_parameters.includes("tools")||V.id.endsWith(":batch")||Q.has(V.id))continue;let H=G1(V.reasoning)?V.reasoning:void 0,X=H?.supported_efforts,z=X===null||X===void 0&&V.supported_parameters.includes("reasoning_effort")?["max","xhigh","high","medium","low"]:Array.isArray(X)?[...new Set(X.filter((_)=>_!=="default"&&E0(_)))]:["default"],W=uZ.find((_)=>_.model===V.id),G=W?z.includes(W.effort)?W.effort:null:z[0]==="default"?"default":E0(H?.default_effort)&&z.includes(H.default_effort)?H.default_effort:null,B=L2("openrouter",V.id);Y.push({model:V.id,display:V.name,efforts:z,defaultEffort:G,context1m:B!==void 0&&B>=1e6||void 0}),Q.add(V.id)}if(!Y.length)throw Error("OpenRouter 未返回支持文本和工具调用的交互模型");return Y}function Zz($){return typeof $==="number"&&Number.isFinite($)&&$>=0}async function SD($,Z){if(!Z)return{kind:"balance",state:"no_credentials",windows:[]};try{let J=await Jz($,Z,"credits");if(!G1(J)||!G1(J.data))throw Error("OpenRouter credits: data 对象缺失");let{total_credits:Y,total_usage:Q}=J.data;if(!Zz(Y)||!Zz(Q))throw Error("OpenRouter credits: total_credits/total_usage 缺失或无效");return{kind:"balance",state:"ok",fetchedAt:Date.now(),windows:[],balance:{remaining:Y-Q,currency:"USD"}}}catch(J){let Y=dZ(J);return K(`openrouter readUsage MISS: ${Y}`),{kind:"balance",state:J instanceof iZ&&J.status===429?"rate_limited":"network",windows:[],reason:Y}}}var TD="https://openrouter.ai/api",ED=1e4,lZ,iZ;var Yz=R(()=>{h0();D0();V0();E4();I();eX();lZ={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL"};iZ=class iZ extends Error{status;constructor($,Z){super(`HTTP ${$}${Z?`: ${Z}`:""}`);this.status=$}};S0({kind:"openrouter",configSectionId:"openrouter",build($,Z){let J=$.api_key||$.auth_token||$.base_url?$:Z,Y=J?.api_key?.trim()||J?.auth_token?.trim()||"",Q=J?.base_url?.trim()||TD,V=$.model?.trim()||"",H=$.models===void 0?uZ.map((z)=>z.model):$z($.models),X={id:"openrouter",kind:"openrouter",agent:"claude",display:$.display?.trim()||"OpenRouter",enabled:!!Y,models:[],defaultModel:V,modelSelection:{mode:"allowlist",modelIds:H,availableModels:[]},validateCustomModelId(z){if(i1(z))throw Error(`OpenRouter 已排除此厂商或自动路由: ${z}`);if(!z.includes("/"))throw Error("OpenRouter 模型请填写完整的 作者/模型 ID")},modelEnvironmentRevision(z){let W=X.modelSelection.availableModels.find((G)=>a2(G.model)===a2(z));if(!W||W.unavailableReason||!W.efforts.length)return"model-unavailable";return W.efforts.includes("default")?"effort-unset":"effort-level"},modelCatalogState:{status:Y?"idle":"disabled",updatedAt:Date.now()},async refreshModels(){if(X.models=[],X.modelSelection.availableModels=[],!X.enabled){X.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}X.modelCatalogState={status:"loading",updatedAt:null};try{let z=await xD(Q,Y),W=z.find((B)=>B.model===a2(V));if(V&&!W)throw Error(`OpenRouter 默认模型不在账号目录中: ${V}`);if($.effort){if(!V)throw Error("OpenRouter effort 需要同时配置 model");if(!E0($.effort)||!W.efforts.includes($.effort))throw Error(`OpenRouter 模型 ${V} 不支持 effort ${$.effort}`);W.defaultEffort=$.effort}let G=H.map((B)=>{let _=z.find((j)=>j.model===a2(B));if(!_)return{model:B,display:B,efforts:[],defaultEffort:null,unavailableReason:i1(B)?"此厂商或自动路由已被排除":"账号目录未返回该模型"};return{..._,model:B}});X.models=G,X.modelSelection.availableModels=z,X.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(z){let W=dZ(z);K(`openrouter refreshModels MISS: ${W}`),X.modelCatalogState={status:"failed",updatedAt:Date.now(),error:W}}},spawnEnv(z,W){if(!Y)throw Error("OpenRouter API key missing");let G=W||V;if(!G)throw Error("OpenRouter 未选择模型,请通过 model 面板选择或配置 model");if(i1(G))throw Error(`OpenRouter 已排除此厂商或自动路由: ${G}`);let B=j$(z);B.ANTHROPIC_BASE_URL=b6(Q),B.ANTHROPIC_AUTH_TOKEN=Y,B.ANTHROPIC_API_KEY="",B.CLAUDE_CODE_NO_MODEL_FALLBACK="1",B.ANTHROPIC_MODEL=G,B.ANTHROPIC_SMALL_FAST_MODEL=G,B.CLAUDE_CODE_SUBAGENT_MODEL=G,B.ANTHROPIC_DEFAULT_FABLE_MODEL=G;for(let _ of Object.values(lZ))B[_]=G;for(let _ of $z($.slots)){let j=_.indexOf("="),q=_.slice(0,j).trim(),P=_.slice(j+1).trim();if(j<1||!Object.hasOwn(lZ,q)||!P)throw Error(`OpenRouter slots 无效: ${_}`);if(i1(P)||!X.modelSelection.availableModels.some((D)=>!D.unavailableReason&&a2(D.model)===a2(P)))throw Error(`OpenRouter slot 模型不在账号目录中: ${P}`);if(X.modelEnvironmentRevision(P)!==X.modelEnvironmentRevision(G))throw Error(`OpenRouter slot 不能混合无 effort 档位与有 effort 档位的模型: ${P}`);B[lZ[q]]=P}return B},resolveSpawnModel(z){if(i1(z))throw Error(`OpenRouter 已排除此厂商或自动路由: ${z}`);return z||void 0},readUsage(){return SD(Q,Y)}};return X},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:b6(Z[0])}:{}}}}catch(J){return{error:dZ(J)}}}},detect:{fromSettingsEnv($){let Z=$.ANTHROPIC_BASE_URL?.trim(),J=$.ANTHROPIC_AUTH_TOKEN?.trim();if(!Z||!J)return null;try{let Y=b6(Z);if(new URL(Y).hostname!=="openrouter.ai")return null;return{base_url:Y,api_key:J}}catch{return null}}}})});var Qz=R(()=>{V0();D0();P4();Q0();cZ();i2();S0({kind:"deepseek-harness",configSectionId:"deepseek-harness",build($){let Z=$.api_key?.trim()??"",J=$.base_url?.trim()||"https://api.deepseek.com",Y={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(Q){let V=S4(Q);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(!Y.enabled){Y.models=[],Y.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}Y.modelCatalogState={status:"loading",updatedAt:null};try{let Q=await X2({cwd:Y2,env:Y.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list",{models:[...k0($.models),...k0($.custom_models)]});if(!Array.isArray(Q)||!Q.length)throw Error("DeepSeek Harness model catalog is empty");for(let H of Q)if(!H.model||!H.efforts.length||!H.efforts.every(B0)||!B0(H.defaultEffort)||!H.efforts.includes(H.defaultEffort))throw Error(`Invalid DSH model/effort catalog: ${H.model}`);let V=$.model?.trim()||Q.find((H)=>H.isDefault)?.model;if(!V||!Q.some((H)=>H.model===V))throw Error("DSH default model is not in its catalog");Y.models=Q.map(({model:H,display:X,efforts:z,defaultEffort:W,isCustom:G})=>{let B=$.effort?.trim();if(B&&(!B0(B)||!z.includes(B)))throw Error(`DSH model ${H} does not support configured effort ${B}`);return{model:H,display:X,efforts:z,defaultEffort:B?B:W,origin:G?"custom":"upstream"}}),Y.defaultModel=V,Y.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(Q){throw Y.models=[],Y.modelCatalogState={status:"failed",updatedAt:Date.now(),error:Q instanceof Error?Q.message:String(Q)},Q}},resolveSpawnModel(Q){return D2(Y).find((V)=>V.model===Q)?.model},readUsage(){return Z?pZ(J,Z):Promise.resolve({kind:"balance",state:"no_credentials",windows:[]})}};return Y},setup:{commandSuffix:"deepseek-harness",hint:()=>"启用 DeepSeek Harness:发送 `deepseek-harness-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)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]}:{}}}}}})});function nZ($){let Z=new URL($);if(!p1(Z.origin))throw Error("DSH GLM 需要 bigmodel.cn 或 z.ai 的 Coding Plan 端点");return Z.pathname="/api/coding/paas/v4",Z.search="",Z.hash="",Z.toString().replace(/\/$/,"")}async function bD($,Z){let J=await $0(`${$}/models`,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(1e4)});if(!J.ok)throw Error(`GLM Coding Plan models HTTP ${J.status}`);let Y=await J.json();if(!Array.isArray(Y?.data)||!Y.data.length)throw Error("GLM Coding Plan 模型目录为空或无效");return Y.data.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 Vz=R(()=>{h0();y0();D0();V0();P4();Q0();q9();mZ();i2();S0({kind:"dsh-glm",configSectionId:"dsh-glm",detect:{fromSettingsEnv($){let Z=f.token_sources?.glm,J=Z?.auth_token?.trim()||$.ANTHROPIC_AUTH_TOKEN?.trim(),Y=Z?.base_url?.trim()||$.ANTHROPIC_BASE_URL?.trim();return J&&Y&&p1(Y)?{api_key:J,base_url:nZ(Y)}:null}},build($,Z){let J=$.api_key?.trim()||$.auth_token?.trim()||Z?.api_key?.trim()||"",Y=nZ($.base_url?.trim()||Z?.base_url?.trim()||"https://open.bigmodel.cn/api/coding/paas/v4"),Q=new URL(Y).hostname.endsWith("bigmodel.cn")?"zai-coding-cn":"zai",V,H={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([...V??[]].sort())},modelCatalogState:{status:J?"idle":"disabled",updatedAt:Date.now()},spawnEnv(X){if(!J)throw Error("DSH GLM Coding Plan API key is missing");let z=S4(X);if(z.LODESTAR_DSH_PROVIDER=Q,z.LODESTAR_DSH_GLM_API_KEY=J,z.LODESTAR_DSH_BASE_URL=Y,z.LODESTAR_DSH_DEFAULT_MODEL=H.defaultModel,V)z.LODESTAR_DSH_MODELS=JSON.stringify(V);if($.bin)z.LODESTAR_DSH_NODE=$.bin;return z},async refreshModels(){if(H.models=[],V=void 0,!H.enabled){H.modelCatalogState={status:"disabled",updatedAt:Date.now()};return}H.modelCatalogState={status:"loading",updatedAt:null};try{let X=await bD(Y,J),z=[...X];for(let G of[...k0($.models),...k0($.custom_models)])if(!z.some((B)=>B.model.toLowerCase()===G.toLowerCase()))z.push({model:G,display:G});if(V=z.map((G)=>G.model),!$.model?.trim()){let G=(B)=>Number(B.match(/\d+(?:\.\d+)?/)?.[0]??-1);H.defaultModel=[...X].sort((B,_)=>G(_.model)-G(B.model))[0].model}let W=await X2({cwd:Y2,env:H.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"model/list");H.models=z.map((G)=>{let B=W.find((P)=>P.model===G.model),_=hZ(H,$),j=B?B.efforts.filter(B0):_.efforts,q=$.effort?.trim()||B?.defaultEffort||_.defaultEffort;return{...G,display:B?.display??G.display,efforts:j,defaultEffort:B0(q)&&j.includes(q)?q:null,origin:X.some((P)=>P.model===G.model)?"upstream":"custom"}}),H.modelCatalogState={status:"ready",updatedAt:Date.now()}}catch(X){throw H.models=[],V=[],H.modelCatalogState={status:"failed",updatedAt:Date.now(),error:X instanceof Error?X.message:String(X)},X}},resolveSpawnModel(X){return D2(H).find((z)=>z.model===X&&!z.unavailableReason)?.model},async readUsage(){return J?gZ(await L9(Y,J)):{state:"no_credentials",windows:[]}}};return H},setup:{commandSuffix:"dsh-glm",hint:()=>"DSH 可复用已配置的 GLM Coding Plan;独立账号用 `dsh-glm-setup [base_url] <api_key>`。",parseArgs($){let Z=$.trim().split(/\s+/).filter(Boolean);if(Z.length<1||Z.length>2)return{error:"用法:dsh-glm-setup [base_url] <api_key>"};try{return{config:{agent:"dsh",api_key:Z.at(-1),base_url:nZ(Z.length===2?Z[0]:"https://open.bigmodel.cn/api/coding/paas/v4")}}}catch(J){return{error:J instanceof Error?J.message:String(J)}}}}})});var Xz={};E$(Xz,{tokenSourceSpawnRevision:()=>Hz,buildTokenSourcesFromConfig:()=>aZ});import{createHash as CD}from"node:crypto";function aZ(){N3();let $=qZ(),Z=M2().map((V)=>{let H=V.configSectionId?(f.token_sources??{})[V.configSectionId]??{}:{},X=V.detect?.fromSettingsEnv($)??null,z=x6(V.build(H,X),H);return z.spawnRevision=Hz(V.kind,H,X),z}),J=Z.find((V)=>V.kind==="claude-native");if(J){let V=Z.some((H)=>H.agent==="claude"&&H.enabled&&H.kind!=="claude-native");J.enabled=!V,J.modelCatalogState={status:J.enabled?"idle":"disabled",updatedAt:Date.now()}}for(let V of Z)O3(V);let Q=Z.find((V)=>V.enabled&&f.token_sources?.[V.id]?.default===!0)??Z.find((V)=>V.enabled);if(Q)R3(Q.id);return Z.length}function Hz($,Z,J){let Y=(Q)=>({agent:Q?.agent,auth:Q?.auth,base_url:Q?.base_url,auth_token:Q?.auth_token,api_key:Q?.api_key,bin:Q?.bin,model:Q?.model,effort:Q?.effort,slots:Q?.slots});return CD("sha256").update(JSON.stringify({kind:$,configured:Y(Z),detected:Y(J)})).digest("hex")}var oZ=R(()=>{y0();V0();q9();i2();aX();mZ();sX();cZ();Yz();Qz();Vz()});import{readFileSync as kD}from"node:fs";function yD($){return $.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function wD($,Z){let J=[`[token_source.${$}]`],Y=(Q,V)=>{if(V!==void 0)J.push(`${Q} = "${yD(V)}"`)};if(Y("agent",Z.agent),Y("display",Z.display),Y("auth",Z.auth),Y("base_url",Z.base_url),Y("auth_token",Z.auth_token),Y("api_key",Z.api_key),Y("bin",Z.bin),Y("model",Z.model),Y("effort",Z.effort),Y("models",Z.models),Y("hidden_models",Z.hidden_models),Y("custom_models",Z.custom_models),Y("slots",Z.slots),Y("usage",Z.usage),Z.default!==void 0)J.push(`default = "${Z.default}"`);return J.join(`
|
|
228
|
+
`)}function vD($,Z){let J=kD(N0,"utf8"),Y=`[token_source.${$}]`,Q=J.split(`
|
|
229
|
+
`),V=!1,H=n9().token_sources[$]??{},X=[];for(let B of Q){let _=B.match(/^\s*(\[[^\]]+\])\s*(?:#.*)?$/)?.[1];if(_)V=_===Y;if(!V)X.push(B)}let z={...H},W={...Z};for(let B of Object.keys(W))if(W[B]!==void 0)z[B]=W[B];let G=z;while(X.length&&X[X.length-1]==="")X.pop();I0(N0,X.join(`
|
|
230
230
|
`)+`
|
|
231
231
|
|
|
232
|
-
`+
|
|
233
|
-
`)}function
|
|
234
|
-
⚠️ kill 状态卡片终态写入失败: ${O(
|
|
235
|
-
请重新发送 model 打开面板。`;if(!await w($.chatId,P))K(`model-custom: visible fallback send MISS (${j})`);return!1},z=(_)=>X(I2(!1,Q,_),`❌ ${Q?`模型 ${Q}`:"模型名"} 未加入:${_}。`);if(!V||!V.enabled)return await z("账号不可用"),!0;if(!Q)return await z("模型名为空"),!0;if(V.models.some((_)=>_.model.toLowerCase()===Q.toLowerCase()))return await X(I2(!1,Q,"已在列表中"),`ℹ️ 模型 ${Q} 已在列表中,未重复加入。`),!0;try{await Bz(V.id,Q,$.codexAccountId())}catch(_){return K(`model-custom: config/refresh MISS (${O(_)})`),await z(`配置写入或模型刷新失败:${O(_)}`),!0}K(`model-custom: ${V.id} 补录 ${Q} by ${J}(记录已持久化)`);for(let _ of G$.all)for(let[j,q]of _.modelPanels)if(q.sourceId===V.id&&(_!==$||j!==Y.panelId))_.modelPanels.delete(j);let W=$.tokenSource(V.id);if(!W||W.modelCatalogState?.status!=="ready")return await z(W?.modelCatalogState?.error??"刷新后的账号目录不可用"),!0;let G=ZJ($,W),B=G.find((_)=>_.model===Q);if(!B)return await z("补录已保存,但刷新后的模型列表未返回该项"),!0;if($.modelPanels.set(Y.panelId,{models:G,messageId:Y.cardMessageId}),B.unavailableReason||!B.efforts.length)return await X(I2(!0,Q,`**MISS**:${B.unavailableReason??"后端未确认 effort"}。记录已保存,可在模型面板删除。`),`模型 ${Q} 已补录,能力尚未确认。`),!0;if(B.efforts.length===1){let _=await $.onModelEffortSelect(B.model,B.efforts[0].effort,Y.panelId,J,B.provider);return await X(_.ok?L6({sessionName:$.sessionName,provider:B.provider,model:B.model,effort:B.efforts[0].effort,scope:Rz($,B.provider??"codex")}):I2(!0,Q,_.message),_.message),!0}return await X(j6({sessionName:$.sessionName,panelId:Y.panelId,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:B}),`✅ 模型 ${Q} 已补录成功。`),!0}async function Oz($,Z=""){let J=Z.trim(),Y=$.modelCustomPrompt;if(!J||!Y||Y.panelId!==J)return{ok:!1,message:"此补录面板已失效",card:_6($.sessionName,"stale")};return $.modelCustomPrompt=null,{ok:!0,message:"已取消",card:_6($.sessionName)}}function iF($,Z){return B$(Z?.provider)?Z.provider:z2($)}function Rz($,Z){if($.currentTurn)return"当前 turn 不变,后续新 turn 使用。";if($.proc?.isAlive()&&$.proc.provider===Z)return Z==="codex"?"Codex 需重启进程生效(发 restart)。":"下一轮开始使用。";return`下次启动 ${_$(Z)} 时使用。`}async function Nz($,Z,J="",Y="",Q=null){let V=Z.trim();if(!V)return await E($.chatId,`❌ ${"模型为空"}`),{ok:!1,message:"模型为空"};let H=iF(V,Q),X=$.modelPanels.get(J.trim())?.models.find((z)=>z.model===V&&(z.provider??"codex")===H);if(!X)return{ok:!1,message:"模型不在当前选项中,请重新发送 model"};if($.modelPanels.get(J.trim())?.mode==="add")return{ok:!1,message:"请先将模型添加到可选列表"};if(X.unavailableReason)return{ok:!1,message:X.unavailableReason};if(X.enabled===!1)return{ok:!1,message:`${X.displayName} 未配置,请先点「启用」`};if(X.efforts.length===0)return{ok:!1,message:"模型未返回 effort"};if(X.efforts.length===1)return YJ($,V,X.efforts[0].effort,J,Y,H);return{ok:!0,message:"",card:o5({sessionName:$.sessionName,panelId:J.trim(),currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:X})}}async function YJ($,Z,J,Y="",Q="",V=""){let H=Z.trim(),X=J.trim();if(!H)return{ok:!1,message:"模型为空"};let z=Y.trim(),W=$.modelPanels.get(z),G=B$(V)?V:W?.models.find((U)=>U.model===H)?.provider??z2(H);if(G==="dsh"){if(!B0(X))return{ok:!1,message:"DSH reasoning effort 无效"}}else if(G==="claude"){if(!E0(X))return{ok:!1,message:"Claude reasoning effort 无效"}}else if(!s0(X))return{ok:!1,message:"Codex reasoning effort 无效"};let B=X,_=W?.models.find((U)=>U.model===H&&(U.provider??"codex")===G);if(!_||!_.efforts.some((U)=>U.effort===B))return{ok:!1,message:`${_$(G)} · ${H}/${B} 不在选项中`};let j=$.tokenSource(_.sourceId);if(j?.modelCatalogState){if(!j.enabled||j.modelCatalogState.status!=="ready")return{ok:!1,message:`模型目录 MISS:${j.modelCatalogState.error??j.modelCatalogState.status}`};if(!j.models.some((U)=>U.model===H&&U.efforts.includes(B)))return{ok:!1,message:"模型或 effort 已不在账号目录中,请重新发送 model"}}let q=!!_.sourceId&&$.currentTokenSource()?.id!==_.sourceId,P=!$.processSourceMatches(j,H)||!!j?.modelEnvironmentRevision&&j.modelEnvironmentRevision($.currentModelLabel()??"")!==j.modelEnvironmentRevision(H);if($.currentProvider()===G&&!q&&$.currentModelLabel()===H&&$.currentEffortLabel()===B)return $.modelPanels.delete(z),{ok:!0,message:`当前已是 ${_$(G)} · ${H} / ${B}`,card:B6({sessionName:$.sessionName,provider:G,model:H,effort:B,scope:"当前已是此设置,无需变更。"})};if($.proc?.isAlive()&&$.proc.provider!==G&&($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0))return{ok:!1,message:`当前 ${$.backendLabel($.proc.provider)} turn 正在执行或排队;请等结束或 stop 后再切换到 ${_$(G)}`};let M=$.currentModelLabel()!==H||q,A=!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0);if(P&&$.proc?.isAlive()&&A)return{ok:!1,message:"新模型需要更新进程配置,请等当前任务结束后再选择"};if(G==="claude"&&$.proc?.isAlive()&&$.proc.provider==="claude"&&M&&A)return{ok:!1,message:"当前 Claude turn 正在执行或排队;Claude 模型 profile 通过 env 生效,请等结束或 stop 后再切换"};try{if($.proc?.isAlive()&&$.proc.provider===G&&!q&&!P){let S=_.sourceId?$.tokenSource(_.sourceId)?.resolveSpawnModel(H)??H:H;await rY($.proc.setModelSettings(S,B),20000,"thread/settings/update")}await $.applyModelSelectionUnlocked(G,H,B,_.sourceId);let U=Rz($,G);return $.modelPanels.delete(z),{ok:!0,message:`已选择 ${_$(G)} · ${H} / ${B}`,card:B6({sessionName:$.sessionName,provider:G,model:H,effort:B,scope:U})}}catch(U){let S=`模型切换失败: ${O(U)}`;return K(`session "${$.sessionName}": set model settings failed: ${O(U)}`),await E($.chatId,`❌ ${S}`),{ok:!1,message:S}}}var $J=20;var Tz=R(()=>{F0();QJ();V0();sZ();O1();F0();Y$();v$();t();I()});import{createHash as aF}from"node:crypto";function oF($,Z){return`agent:${Buffer.from(`${$}\x00${Z}`,"utf8").toString("base64url")}`}function n1($="default"){return rF(y$().map((Z)=>Z.forAccount?.($)??Z))}function rF($){let Z=[],J=[];for(let Y of $)sF(Y,Z,J);return{catalogGeneration:aF("sha256").update(JSON.stringify({identities:Z,sourceFailures:J})).digest("hex").slice(0,16),identities:Z,sourceFailures:J}}function sF($,Z,J){let Y=$.modelCatalogState?.status??(!$.enabled?"disabled":$.models.length>0?"ready":"idle");if(!$.enabled)J.push({tokenSourceId:$.id,display:$.display,status:"disabled",reason:"账号未启用"});else if(Y==="loading"||Y==="idle")J.push({tokenSourceId:$.id,display:$.display,status:"loading",reason:"模型目录正在刷新"});else if(Y==="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 Q of $.models)Z.push(tF($,Q,Y))}function tF($,Z,J){let Y="ready",Q;if(!$.enabled)Y="source_disabled",Q="所属 Token Source 未启用";else if(J==="loading"||J==="idle")Y="catalog_loading",Q="模型目录正在刷新";else if(J==="failed")Y="catalog_failed",Q=$.modelCatalogState?.error??"模型目录刷新失败";else if(Z.unavailableReason||!Z.efforts.length)Y="model_unavailable",Q=Z.unavailableReason??"effort MISS:上游未声明该后端支持的推理档位";return{id:oF($.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:Ez($.defaultModel)===Ez(Z.model),status:Y,...Q?{reason:Q}:{},spawnRevision:$.spawnRevision}}function Ez($){return $.replace(/\[1m\]$/i,"").toLowerCase()}var v6=R(()=>{V0()});import{randomUUID as eF}from"node:crypto";async function xz($,Z){if(!Z.trim()){await w($.chatId,"❌ 无法确认操作者身份,未打开 agents 面板");return}Cz(),await U2();let J=`agents_${eF()}`;if(N9.set(J,{ownerOpenId:Z,codexAccountId:$.codexAccountId(),page:0,createdAt:Date.now()}),!await c($.chatId,bz(J)))await w($.chatId,"❌ agents 面板发送失败")}function Sz($,Z,J){let Y=JD($,J),Q=Number(Z);if(!Number.isInteger(Q))return YD("无效页码");let V=ZD(Y.codexAccountId);return Y.page=Math.max(0,Math.min(V-1,Q)),Y.createdAt=Date.now(),{ok:!0,message:"已更新",card:bz($)}}function bz($){let Z=N9.get($);if(!Z)throw Error("Agent 身份面板已过期");let J=n1(Z.codexAccountId),Y=Math.max(1,Math.ceil(J.identities.length/f6));Z.page=Math.min(Z.page,Y-1);let Q=Z.page*f6;return WZ({panelId:$,page:Z.page,totalPages:Y,catalog:J.identities.slice(Q,Q+f6),failures:J.sourceFailures})}function ZD($){return Math.max(1,Math.ceil(n1($).identities.length/f6))}function JD($,Z){Cz();let J=N9.get($);if(!J)throw Error("Agent 身份面板已过期,请重新发送 agents");if(!J.ownerOpenId||!Z||J.ownerOpenId!==Z)throw Error("只有打开该面板的用户可操作");return J}function YD($){return{ok:!1,message:$,card:z1({title:"agents",message:$,ok:!1})}}function Cz(){let $=Date.now()-$D;for(let[Z,J]of N9)if(J.createdAt<$)N9.delete(Z)}var f6=8,$D=1800000,N9;var kz=R(()=>{Y$();t();v6();V0();N9=new Map});var XJ={};E$(XJ,{withTasklistLifecycleLock:()=>m6,tasklistNameForProject:()=>g6,reconcileTasklistDeletions:()=>XD,isTasklistAlreadyDeletedError:()=>yz,getTasklistBinding:()=>m$,enableTasklist:()=>VJ,deleteTasklistRemoteIdempotently:()=>wz,deleteTasklist:()=>HJ});import{existsSync as VD,readFileSync as HD}from"node:fs";function g6($){return`${$}[lodestar]`}function m$($){let Z=g$.get($);return Z?o2(Z):null}async function m6($,Z){let J=h6.get($)??Promise.resolve(),Y,Q=new Promise((H)=>{Y=H}),V=J.catch(()=>{}).then(()=>Q);h6.set($,V),await J.catch(()=>{});try{return await Z()}finally{if(Y(),h6.get($)===V)h6.delete($)}}function yz($){if($&&typeof $==="object"&&$.code===1470404)return!0;let Z=$ instanceof Error?$.message:String($);return/\bcode=1470404\b/.test(Z)}async function wz($,Z=c3){try{return await Z($),"deleted"}catch(J){if(yz(J))return"already_deleted";throw J}}async function VJ($,Z){return await m6($,async()=>{let J=m$($);if(J?.deleting)throw Error(`tasklist deletion is pending for ${$}`);if(J)return J;let Y=g6($);if(Y.length>100)throw Error(`tasklist name is too long (${Y.length}/100): ${Y}`);let Q=await m3(Z),V=await p3(Y,Q),H={guid:V.guid,name:V.name,url:V.url,projectName:$,ownerOpenId:Q,createdAt:V.createdAt};return I6($,H),o2(H)})}async function HJ($,Z){return await m6($,async()=>{let J=m$($);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},I6($,J);return await vz($,Z)})}async function vz($,Z){let J=m$($);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,I6($,J);try{if(await wz(Z)==="already_deleted")K(`tasklist: ${$} remote list ${Z} already deleted; finishing tombstone`);let Q=new Map(g$);return Q.delete($),fz(Q),g$.delete($),o2(J)}catch(Y){let Q=m$($);if(Q?.guid===Z&&Q.deleting)Q.deleting.lastError=Y instanceof Error?Y.message:String(Y),I6($,Q);throw Y}}async function XD(){let $=[...g$.entries()].filter(([,J])=>!!J.deleting).map(([J,Y])=>({projectName:J,guid:Y.guid})),Z=[];for(let J of $)try{await m6(J.projectName,()=>vz(J.projectName,J.guid)),K(`tasklist: reconciled pending deletion for ${J.projectName}`)}catch(Y){Z.push(`${J.projectName}: ${Y instanceof Error?Y.message:String(Y)}`)}if(Z.length)throw Error(`tasklist deletion reconcile failed: ${Z.join("; ")}`)}function zD(){if(!VD(k9))return;try{let $=JSON.parse(HD(k9,"utf8"));if(!$||typeof $!=="object")return;for(let[Z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let Y=J;if(typeof Y.guid!=="string"||!Y.guid||typeof Y.name!=="string"||!Y.name)continue;let Q={guid:Y.guid,name:Y.name,url:typeof Y.url==="string"?Y.url:"",projectName:Z,ownerOpenId:typeof Y.ownerOpenId==="string"?Y.ownerOpenId:"",createdAt:typeof Y.createdAt==="string"?Y.createdAt:void 0,deleting:WD(Y.deleting)};g$.set(Z,Q)}K(`tasklist: loaded ${g$.size} project bindings`)}catch($){K(`tasklist: load map failed: ${$}`)}}function WD($){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 I6($,Z){let J=new Map(g$);J.set($,o2(Z)),fz(J),g$.set($,o2(Z))}function fz($=g$){let Z={};for(let[J,Y]of $)Z[J]=o2(Y);s(k9,Z)}function o2($){return JSON.parse(JSON.stringify($))}var g$,h6;var zJ=R(()=>{Q0();t();I();T0();g$=new Map,h6=new Map;zD()});function K1($,Z,J=!1){let Y=$.worktreeProjectName();return XZ({projectName:Y,tasklistName:g6(Y),binding:m$(Y),notice:Z,confirmDelete:J})}async function hz($){if(!await c($.chatId,K1($)))await w($.chatId,"❌ task 面板发送失败")}async function Iz($){let Z=$.worktreeProjectName();try{let J=m$(Z),Y=await VJ(Z,$.chatId),Q=J?"已启用":`已启用 ${Y.name}`;return{ok:!0,message:Q,card:K1($,{type:"success",content:`✅ ${Q}`})}}catch(J){let Y=`启用失败: ${O(J)}`;return K(`session "${$.sessionName}": tasklist enable failed: ${O(J)}`),{ok:!1,message:Y,card:K1($,{type:"error",content:`❌ ${Y}`})}}}function gz($,Z){let J=$.worktreeProjectName(),Y=m$(J),Q=Z.trim();if(!Y)return{ok:!1,message:"未启用",card:K1($,{type:"error",content:"❌ 未启用"})};if(Y.guid!==Q)return{ok:!1,message:"清单绑定已变化",card:K1($,{type:"error",content:"❌ 清单绑定已变化,请重新打开 task 面板"})};return{ok:!0,message:"请再次确认删除",card:K1($,{type:"error",content:"⚠️ 删除会删除所有清单内任务"},!0)}}async function mz($,Z){let J=$.worktreeProjectName(),Y=Z.trim();try{let V=`已删除 ${(await HJ(J,Y)).name}`;return{ok:!0,message:V,card:K1($,{type:"success",content:`✅ ${V}`})}}catch(Q){let V=`删除失败: ${O(Q)}`;return K(`session "${$.sessionName}": tasklist delete failed: ${O(Q)}`),{ok:!1,message:V,card:K1($,{type:"error",content:`❌ ${V}`})}}}var pz=R(()=>{Y$();t();I();zJ()});import{open as KD}from"node:fs/promises";import{basename as BD}from"node:path";function WJ($){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 p$($,Z){if(typeof $!=="string"||!$.trim())throw Error(`${Z} MISS`);return $}class cz{deps;queue=Promise.resolve();lastStartedAt=0;constructor($={fetch:$0,getToken:M$,retry:x1,wait:(Z)=>new Promise((J)=>setTimeout(J,Z)),intervalMs:250}){this.deps=$}request($,Z,J="GET",Y,Q){let V=this.queue.then(()=>this.deps.retry($,async()=>{Q?.throwIfAborted();let H=await this.deps.getToken(),X=Y?.(),z=X instanceof FormData,W=this.deps.intervalMs-(Date.now()-this.lastStartedAt);if(W>0)await this.deps.wait(W);Q?.throwIfAborted(),this.lastStartedAt=Date.now();let G=AbortSignal.timeout(LD),B=new AbortController,_=()=>B.abort(G.reason),j=()=>B.abort(Q.reason);G.addEventListener("abort",_,{once:!0}),Q?.addEventListener("abort",j,{once:!0});let q=B.signal;try{let P=await this.deps.fetch(`https://open.feishu.cn/open-apis${Z}`,{method:J,headers:{Authorization:`Bearer ${H}`,...!z&&X!==void 0?{"Content-Type":"application/json"}:{}},...X!==void 0?{body:z?X:JSON.stringify(X)}:{},signal:q});return(await E2(P,$)).data}catch(P){if(q.aborted&&q.reason?.name==="TimeoutError")throw q.reason;throw P}finally{G.removeEventListener("abort",_),Q?.removeEventListener("abort",j)}}));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:p$(J?.token,"交付文件夹"),url:WJ(J?.url)}}async getChatName($,Z){let J=await this.request("读取群名称",`/im/v1/chats/${encodeURIComponent($)}`,"GET",void 0,Z);return p$(J?.name,"群名称")}async getFolder($,Z){let J=await this.request("读取群文件夹",`/drive/explorer/v2/folder/${encodeURIComponent($.token)}/meta`,"GET",void 0,Z),Y=p$(J?.token,"群文件夹");if(Y!==$.token)throw Error("群文件夹返回了不同的标识");return{token:Y,url:WJ($.url),name:p$(J?.name,"群文件夹名称")}}async renameFolder($,Z,J){try{await this.request("同步群文件夹名称",`/drive/v1/files/${encodeURIComponent($.token)}?type=folder`,"PATCH",()=>({new_title:Z}),J)}catch(Q){if(Q instanceof F$&&Q.code===99991672)throw new F$("同步群文件夹名称需要应用身份权限 drive:file:upload(飞书错误码 99991672)",Q.status,Q.code);throw Q}let Y=await this.getFolder($,J);if(Y.name!==Z)throw Error("群文件夹名称更新未生效");return Y}async grantFolderAccess($,Z,J,Y){p$(Z,"交付群"),p$(J,"交付发起人");let Q=`/drive/v1/permissions/${encodeURIComponent($.token)}/members?type=folder`;for(let H 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("设置交付文件夹权限",Q,"POST",()=>H,Y);let V=await this.request("核对交付文件夹权限",Q,"GET",void 0,Y);if(!Array.isArray(V?.items))throw Error("交付文件夹权限列表 MISS");for(let[H,X,z]of[["openid",J,"full_access"],["openchat",Z,"view"]])if(V.items.find((G)=>G.member_type===H&&G.member_id===X)?.perm!==z)throw Error(`交付文件夹权限未生效:${H} / ${z}`)}async closeFileLinkSharing($,Z){p$($,"交付文件");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,Y){Y?.throwIfAborted();let Q=await KD($,"r");try{let V=await Q.stat();if(!V.isFile())throw Error("交付路径不是普通文件");if(!Number.isSafeInteger(V.size)||V.size<=0)throw Error("不能上传空文件或无效大小的文件");let H=BD($),X={file_name:H,parent_type:"explorer",parent_node:Z.token,size:V.size},z;if(V.size<=_D){let q=await Q.readFile(),P=await Q.stat();if(q.length!==V.size||P.mtimeMs!==V.mtimeMs||P.ctimeMs!==V.ctimeMs)throw Error("交付文件在读取时发生变化");z=await this.request("上传交付文件","/drive/v1/files/upload_all","POST",()=>{let F=new FormData;for(let[T,M]of Object.entries(X))F.append(T,String(M));return F.append("file",new Blob([Uint8Array.from(q)]),H),F},Y)}else{let q=await this.request("准备上传交付文件","/drive/v1/files/upload_prepare","POST",()=>X,Y),P=p$(q?.upload_id,"分片上传事务"),F=q?.block_size,T=q?.block_num;if(!Number.isSafeInteger(F)||F<=0||F>jD||!Number.isSafeInteger(T)||T!==Math.ceil(V.size/F))throw Error("云空间返回的分片策略无效");for(let A=0;A<T;A++){Y?.throwIfAborted();let U=Math.min(F,V.size-A*F),S=Buffer.alloc(U),b=0;while(b<U){let v=await Q.read(S,b,U-b,A*F+b);if(!v.bytesRead)throw Error("交付文件在分片读取时发生变化");b+=v.bytesRead}await this.request("上传交付文件分片","/drive/v1/files/upload_part","POST",()=>{let v=new FormData;return v.append("upload_id",P),v.append("seq",String(A)),v.append("size",String(U)),v.append("file",new Blob([Uint8Array.from(S)]),H),v},Y)}let M=await Q.stat();if(M.size!==V.size||M.mtimeMs!==V.mtimeMs||M.ctimeMs!==V.ctimeMs)throw Error("交付文件在上传期间被修改,未完成上传");z=await this.request("完成交付文件上传","/drive/v1/files/upload_finish","POST",()=>({upload_id:P,block_num:T}),Y)}let W=p$(z?.file_token,"已上传文件"),G={token:W,url:"",name:H,bytes:V.size};J(G),await this.closeFileLinkSharing(W,Y);let B=await this.request("读取交付文件链接","/drive/v1/metas/batch_query","POST",()=>({request_docs:[{doc_token:W,doc_type:"file"}],with_url:!0}),Y),_=B?.metas?.find((q)=>q.doc_token===W&&q.doc_type==="file");if(B?.failed_list?.length||!_)throw Error("已上传文件的元数据 MISS");let j={...G,url:WJ(_.url)};return J(j),j}finally{await Q.close()}}}var _D=20971520,jD=20971520,LD=60000,a1;var uz=R(()=>{h0();t();E8();a1=new cz});import{randomUUID as lz}from"node:crypto";import{basename as qD}from"node:path";class GJ{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:lz(),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:lz(),path:$,name:qD($),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(),Y=await this.deps.uploadFile($,J,(Q)=>{Z.file={...Q},Z.bytes=Q.bytes,this.save()},this.abort.signal);Z.file=Y,Z.bytes=Y.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(Y){this.snapshot.error=Y instanceof Error?Y.message:String(Y)}if(!this.abort.signal.aborted)try{await this.deps.reportError(`❌ 文件交付失败:${Z.name}
|
|
232
|
+
`+wD($,G)+`
|
|
233
|
+
`)}function C6($){let Z=zz.then($);return zz=Z.then(()=>{},()=>{}),Z}async function k6($,Z){vD($,Z),lY(),aZ(),await C4()}function Wz($,Z){return C6(()=>k6($,Z))}function Gz($,Z,J,Y="default"){return C6(async()=>{let Q=H0($,Y);if(!Q?.enabled||!Q.modelSelection)throw Error("此账号不支持维护可选模型列表");let V=Q.modelSelection.modelIds.filter((_)=>Q.models.find((j)=>j.model===_)?.origin!=="custom");if(J==="add"){if(Q.modelCatalogState?.status!=="ready")throw Error(Q.modelCatalogState?.error??"模型目录未就绪");let _=Q.modelSelection.availableModels.find((j)=>j.model===Z);if(_?.origin==="custom")throw Error("补录模型请使用删除操作");if(!_||Q.modelSelection.mode!=="catalog"&&(_.unavailableReason||!_.efforts.length))throw Error("模型不在允许添加的账号目录中");if(V.includes(Z))throw Error("模型已在可选列表中")}else if(!V.includes(Z))throw Error("模型已不在可选列表中");let H=J==="add"?[...V,Z]:V.filter((_)=>_!==Z),X=f.token_sources[$],z=Q.modelSelection.mode==="catalog",W=k0(X?.hidden_models),G=z?{hidden_models:(J==="remove"?[...new Set([...W,Z])]:W.filter((_)=>_!==Z)).join(",")}:{models:H.join(",")};await k6($,G);let B=H0($,Y);if(B?.modelCatalogState?.status!=="ready")throw Error(`配置已保存,但目录刷新失败:${B?.modelCatalogState?.error??"MISS"}`)})}function Kz($,Z,J="default"){return C6(async()=>{let Y=Z.trim();if(!Y||Y.length>256||/[\s,`<>\\\u0000-\u001f]/.test(Y))throw Error("模型 ID 无效,请只填写一个完整模型名");let Q=H0($,J);if(!Q?.enabled)throw Error("账号不可用");if(Q.validateCustomModelId?.(Y),(Q.modelSelection?.availableModels??Q.models).some((z)=>z.model.toLowerCase()===Y.toLowerCase()))throw Error("模型已在目录或补录记录中;隐藏项请使用“显示”");if(Q.modelCatalogState?.status!=="ready")throw Error(Q.modelCatalogState?.error??"模型目录未就绪");if(Q.verifyModel){let z=await Q.verifyModel(Y);if(z!=="exists")throw Error(z==="not_found"?"端点确认不存在":"无法校验模型:端点无响应或凭据问题")}let H=f.token_sources[$];await k6($,{custom_models:[...k0(H?.custom_models),Y].join(",")});let X=H0($,J);if(X?.modelCatalogState?.status!=="ready")throw Error(`补录已保存,但目录刷新失败:${X?.modelCatalogState?.error??"MISS"}`)})}function Bz($,Z,J="default"){return C6(async()=>{let Y=H0($,J),Q=Y?.modelSelection?.availableModels.find((W)=>W.model===Z);if(!Y?.enabled||Q?.origin!=="custom")throw Error("此模型不是补录项,请使用隐藏操作");let V=f.token_sources[$]??{},H=(W)=>W?.trim().replace(/\[1m\]$/,"")===Z.replace(/\[1m\]$/,""),X={custom_models:k0(V.custom_models).filter((W)=>!H(W)).join(","),hidden_models:k0(V.hidden_models).filter((W)=>!H(W)).join(","),...V.models!==void 0?{models:k0(V.models).filter((W)=>!H(W)).join(",")}:{},...H(V.model)?{model:"",effort:""}:{},...V.slots?{slots:V.slots.split(",").filter((W)=>!H(W.slice(W.indexOf("=")+1))).join(",")}:{}};await k6($,X);let z=H0($,J);if(z?.modelCatalogState?.status!=="ready")throw Error(`补录已删除,但目录刷新失败:${z?.modelCatalogState?.error??"MISS"}`)})}var zz;var rZ=R(()=>{Q0();y0();oZ();V0();T0();i2();zz=Promise.resolve()});var sZ={};E$(sZ,{runTokenSourceSetup:()=>hD,onTokenSourceEnable:()=>fD});async function fD($,Z){let J=q$(Z);if(!J){await E($.chatId,`❌ 未知 token source: ${Z}`);return}if(J.enabled){await E($.chatId,`${J.display} 已启用,发 \`model\` 选择。`);return}let Y=M2().find((Q)=>Q.setup?.commandSuffix===Z||Q.configSectionId===Z);if(Y?.setup)await E($.chatId,Y.setup.hint(J.display));else if(J.kind==="codex-subscription"){if(!await c($.chatId,V$({phase:"current",title:"添加账号",message:"通过设备码完成浏览器授权",hint:"默认:codex-login · 额外:codex-login 备注"})))throw Error("Codex 登录引导卡片发送失败")}else if(J.kind==="claude-native")await E($.chatId,`${J.display} 直接使用本机 Claude Code 配置,无需单独启用。`)}async function hD($,Z,J){let Y=M2().find((V)=>V.setup?.commandSuffix===Z);if(!Y?.setup||!Y.configSectionId){await E($.chatId,`❌ 未知或不可配置的 source: ${Z}`);return}let Q=Y.setup.parseArgs(J);if("error"in Q){await E($.chatId,Q.error);return}try{await Wz(Y.configSectionId,Q.config);let V=q$(Y.configSectionId);if(V?.modelCatalogState?.status==="failed"){await E($.chatId,`❌ ${V.display} 配置已保存,但模型目录未就绪:${V.modelCatalogState.error??"MISS"}`);return}await E($.chatId,`✅ ${V?.display??Z} 已启用。发 \`model\` 重新选择。`)}catch(V){await E($.chatId,`❌ 启用失败: ${V?.message??V}`)}}var tZ=R(()=>{t();V0();rZ();T2()});async function _z($,Z,J="",Y){let Q=Z.trim().match(/^hi[ \t]+([^\r\n]+)$/i);if(Q){let{runCodexNamedHi:G}=await Promise.resolve().then(() => (E6(),fZ));return await G($,Q[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:G}=await Promise.resolve().then(() => (E6(),fZ));return await G($,V[1].toLowerCase(),(V[2]??"").trim(),J,Y),!0}let H=Z.trim().match(/^(?:wt|worktree)(?:\s+(.+))?$/i);if(H)return await $.runWorktreeCommand((H[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 X=Z.trim().match(/^files(?:[ \t]+([^\r\n]+))?$/i);if(X)return await $.runFileDeliveryCommand((X[1]??"").trim(),J),!0;if(Z.trim().match(/^(?:agents|agent)$/i))return await $.showAgentIdentityPanel(J),!0;let z=Z.trim().match(/^([\w-]+)-setup(?:\s+([\s\S]+))?$/i);if(z){let{runTokenSourceSetup:G}=await Promise.resolve().then(() => (tZ(),sZ));return await G($,z[1].trim().toLowerCase(),(z[2]??"").trim()),!0}let W=ID.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 G=!$.isRunning(),B=$.backendLabel(),_=G?await $.openStatusCard("hi",$.withModel(`\uD83D\uDE80 启动 ${B}`)):null,j=$.withModel(`\uD83D\uDE80 启动 ${B}`);if(!(G?await $.start({announce:!_,onStatus:(P)=>{j=P,$.setStatusCard(_,P)}}):!0))return await $.closeStatusCard(_,j.startsWith("❌")?j:"❌ 启动失败"),!0;if($.proc?.turnRetry?.reason==="quota"){if(_)await $.closeStatusCard(_,"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消");else{let{codexAccountCard:D}=await Promise.resolve().then(() => (T2(),eQ));if(!await c($.chatId,D({phase:"checking",title:"等待额度",message:"⏳ 等待额度恢复 · 可用后自动启动,stop 可取消"})))throw Error("额度等待卡片发送失败")}return!0}if(_)return await $.replaceStatusCardWithConsole(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`))),!0;if(G)await $.closeStatusCard(_,$.withModel($.withWorktreeInstructionNotice(`✅ ${$.backendLabel()} 已就绪`)))}return await $.showConsole(),!0;case"stop":{let G=$.cancelFileDeliveries("用户停止了任务");if(await $.cancelAgentRuns("stop command"),$.proc?.turnRetry?.reason==="quota"){let _=await $.openStatusCard("stop","\uD83D\uDED1 停止额度等待");try{await $.stop("已取消额度恢复",{announce:!_,onStatus:(j)=>$.setStatusCard(_,j)}),await $.closeStatusCard(_,"\uD83D\uDED1 已取消额度恢复")}catch(j){throw await $.closeStatusCard(_,`❌ ${O(j)}`),j}return!0}if($.clearStaleIdleQueueState("stop"),$.clearMultiMsgBuffer("stop command"),!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0){if(G)return await $.closeTurnCard("\uD83D\uDED1 已取消未完成的文件上传"),await E($.chatId,"\uD83D\uDED1 已取消未完成的文件上传,已上传文件保留"),!0;let _=await $.openStatusCard("stop","⚪ 当前没有正在执行的 turn","grey");if(_)await $.closeStatusCard(_,"⚪ 无正在执行的 turn");else await E($.chatId,"⚪ 当前没有正在执行的 turn");return!0}K(`session "${$.sessionName}": stop command — interrupt + drop count=${$.pendingUserMessageCount} midBuffer=${$.pendingMidTurnMsgs.length}`);let B=new Set;for(let[_,j]of[...$.pendingReactionIds.entries(),...$.currentBatchReactionIds.entries()]){if(j)C0(_,j);l0(_,"CrossMark"),B.add(_)}for(let _ of $.pendingMidTurnMsgs)if(_.msgId&&!B.has(_.msgId))l0(_.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 G=$.isRunning(),B=$.backendLabel($.proc?.provider??$.currentProvider()),_=G?`\uD83D\uDED1 停止 ${B}`:"⚪ session 当前未运行",j=await $.openStatusCard("kill",_,G?"red":"grey"),q=null,P=G?`✅ ${B} 已终止`:`⚪ ${B} 未运行`;try{await $.stop("已终止",{announce:!j,onStatus:(D)=>{$.setStatusCard(j,D)}})}catch(D){q=D,P=$.isRunning()?`❌ ${B} 未确认终止: ${O(D)};会话已阻断,请重试 kill/restart 或等待旧进程退出`:`❌ ${B} 停止收尾失败: ${O(D)}`}finally{try{await $.closeStatusCard(j,P)}catch(D){K(`session "${$.sessionName}": kill status card close failed: ${O(D)}`),await w($.chatId,`${P}
|
|
234
|
+
⚠️ kill 状态卡片终态写入失败: ${O(D)}`)}}if(q&&!j)await w($.chatId,P)}return!0;case"restart":if(!$.isRunning())return await $.showResumeList(J),!0;{let G=$.lastSessionId?U0($.lastSessionId):"",B=$.backendLabel($.proc?.provider??$.currentProvider()),_=$.isRunning()?$.withModel(`\uD83D\uDD01 重启 ${B}`):G?$.withModel(`\uD83D\uDD01 恢复上一会话 thread=${G}`):$.withModel(`\uD83D\uDD01 启动 ${B}`),j=await $.openStatusCard("restart",_),q=_,P=await $.restart(!0,{announce:!j,onStatus:(T)=>{q=T,$.setStatusCard(j,T)}}),D=P?q.startsWith("✅")?q:$.withWorktreeInstructionNotice(G?"✅ 已恢复上一会话":`✅ ${$.backendLabel()} 已就绪`):q.startsWith("❌")?q:"❌ 重启失败";await $.closeStatusCard(j,P?$.withModel(D):D)}return!0;case"clear":if(!$.isRunning()){$.status="stopped",$.opts.onLifecycleChange?.();let G=await $.openStatusCard("clear","⚪ session 当前未运行","grey");if(G)await $.closeStatusCard(G,`⚪ ${$.backendLabel()} 未运行,clear 无效`);else await E($.chatId,`⚪ session "${$.sessionName}" 当前未运行,clear 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return!0}{let G=await $.openStatusCard("clear","\uD83E\uDDF9 清空并启动新会话","orange"),B="\uD83E\uDDF9 清空并启动新会话",_=await $.restart(!1,{announce:!G,onStatus:(j)=>{B=j,$.setStatusCard(G,j)}});await $.closeStatusCard(G,_?$.withModel($.withWorktreeInstructionNotice("✅ 已清空并启动新会话")):B.startsWith("❌")?B:"❌ 清空失败")}return!0}}var ID;var jz=R(()=>{t();I();ID=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"]])});function pD($){let Z=!1,J=()=>{},Y=()=>{},Q=$.sessionId,V=()=>{$.off("context_compacted",z),$.off("exit",W),$.off("error",G)},H=(_)=>{if(Z)return;Z=!0,V(),J(_)},X=(_)=>{if(Z)return;Z=!0,V(),Y(_)},z=(_)=>{if(_.phase==="start")return;if(_.threadId&&Q&&_.threadId!==Q)return;H(_)},W=()=>X(Error(`${$.provider} process exited before context compaction completed`)),G=(_)=>X(_ instanceof Error?_:Error(String(_))),B=new Promise((_,j)=>{J=_,Y=j});return $.on("context_compacted",z),$.once("exit",W),$.once("error",G),{promise:B,cancel(){if(Z)return;Z=!0,V()}}}function cD($,Z){let J=[],Y=new Set,Q=(X,z)=>{let W=z.threadId??Z;if(W&&X.threadId&&X.threadId!==W)return!1;if(z.turnId)return X.turnId===z.turnId;return!0},V=(X)=>{for(let z=J.length-1;z>=0;z--){let W=J[z];if(W&&Q(W,X))return W}return null},H=(X)=>{if(Z&&X.threadId&&X.threadId!==Z)return;let z={usage:X.usage,contextWindow:X.contextWindow,threadId:X.threadId,turnId:X.turnId};J.push(z);for(let W of[...Y])if(Q(z,W.notice))W.finish(z)};return $.on("token_usage",H),{waitFor(X,z){let W=V(X);if(W)return Promise.resolve(W);return new Promise((G)=>{let B=null,_={notice:X,finish:(j)=>{if(B)clearTimeout(B);Y.delete(_),G(j)}};B=setTimeout(()=>_.finish(null),z),Y.add(_)})},cancel(){$.off("token_usage",H);for(let X of[...Y])X.finish(null)}}}function uD($){if(!$)return" · \uD83E\uDDE0 MISS";let Z=u8($.usage);if(Z==null)return" · \uD83E\uDDE0 MISS";let J=l8($.contextWindow);return` · \uD83E\uDDE0 ${gV(Z,J)} (${d8(Z,J)})`}async function Lz($){$.clearStaleIdleQueueState("compact");let Z=!$.currentTurn&&$.pendingUserMessageCount===0&&$.pendingMidTurnMsgs.length===0&&!$.openingTurn;if(!$.isRunning()||!$.proc){$.status="stopped",$.opts.onLifecycleChange?.();let W=await $.openStatusCard("compact","⚪ session 当前未运行","grey");if(W)await $.closeStatusCard(W,"⚪ 后端未运行,compact 无效");else await E($.chatId,`⚪ session "${$.sessionName}" 当前未运行,compact 无效;用 \`hi\` 启动或 \`restart\` 恢复上一会话`);return}if(!Z){let W=await $.openStatusCard("compact","⚠️ 当前 turn 正在执行","grey");if(W)await $.closeStatusCard(W,"⚠️ 先 stop 当前 turn,再 compact");else await E($.chatId,"⚠️ 当前 turn 正在执行,先 `stop` 后再 `compact`。");return}if($.manualContextCompactionPending){let W=await $.openStatusCard("compact","⏳ 上下文压缩已在进行中","grey");if(W)await $.closeStatusCard(W,"⏳ 上下文压缩已在进行中");else await E($.chatId,"⏳ 上下文压缩已在进行中。");return}let J=$.proc,Y=J.sessionId?U0(J.sessionId):"",Q=$.withModel(Y?`\uD83E\uDDE0 压缩上下文 thread=${Y}`:"\uD83E\uDDE0 压缩上下文…"),V=await $.openStatusCard("compact",Q,"orange"),H=async(W)=>{if(V)await $.closeStatusCard(V,W);else await E($.chatId,W)},X=pD(J),z=cD(J,J.sessionId);$.manualContextCompactionPending=!0;try{$.setStatusCard(V,$.withModel("\uD83E\uDDE0 发起上下文压缩")),await J.compactThread(),$.setStatusCard(V,$.withModel("⏳ 等待压缩完成事件"));let W=await X.promise,G=await z.waitFor(W,mD),B=W.threadId?` thread=${U0(W.threadId)}`:"";await H($.withModel(`✅ 上下文已压缩${B}${uD(G)}`))}catch(W){if(X.cancel(),W instanceof U1)await H($.withModel(`ⓘ ${W.message}`));else await H(`❌ 上下文压缩失败: ${O(W)}`)}finally{z.cancel(),$.manualContextCompactionPending=!1}}var mD=1500;var qz=R(()=>{D0();t()});import{randomUUID as dD}from"node:crypto";function iD($){let Z=$.currentTokenSource();return y$().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 $J($,Z,J=Z.models){let Y=$.currentModelLabel(),Q=$.currentEffortLabel(),V=$.currentTokenSource()?.id===Z.id;return J.map((H)=>{let X=V&&Y===H.model;return{provider:Z.agent,sourceId:Z.id,model:H.model,displayName:H.display,description:H.unavailableReason??(H.efforts.length?"":"effort MISS:上游未声明该后端支持的推理档位"),unavailableReason:H.unavailableReason,origin:H.origin,enabled:!0,isDefault:!1,selected:X,efforts:H.efforts.map((z)=>({effort:z,description:z==="default"?"模型未提供 effort 档位,使用模型原生行为。":"",isDefault:z===H.defaultEffort,selected:X&&Q===z}))}})}async function Pz($){await C4();let Z=dD(),J=iD($);$.modelPanels.set(Z,{models:[]});let Y=await c($.chatId,i5({sessionName:$.sessionName,panelId:Z,currentDisplay:$.currentTokenSource()?.display??$.currentModelLabel(),providers:J}));if(!Y)$.modelPanels.delete(Z),await w($.chatId,"❌ 模型面板发送失败");else{let Q=$.modelPanels.get(Z);if(Q)Q.messageId=Y}}async function ZJ($,Z,J=""){let Y=Z.trim(),Q=$.tokenSource(Y);if(!Q)return{ok:!1,message:`未知账号: ${Y}`};if(!Q.enabled)return{ok:!1,message:`${Q.display} 未配置,请先点「启用」`};let V=J.trim();if(!$.modelPanels.has(V))return{ok:!1,message:"模型面板已失效,请重新发送 model"};if(Q.modelCatalogState?.status==="failed")return{ok:!1,message:`模型目录 MISS:${Q.modelCatalogState.error??"刷新失败"}`};let H=$J($,Q),X=$.modelPanels.get(V)?.messageId;return $.modelPanels.set(V,{models:[],catalog:H,sourceId:Y,messageId:X,mode:"select",editable:!!Q.modelSelection,sourceRevision:Q.spawnRevision}),y6($,V,Y,0)}async function y6($,Z,J,Y){let Q=$.modelPanels.get(Z);if(!Q?.catalog||Q.sourceId!==J)return{ok:!1,message:"模型面板已失效,请重新发送 model"};let V=Math.max(1,Math.ceil(Q.catalog.length/eZ));if(!Number.isInteger(Y)||Y<0||Y>=V)return{ok:!1,message:"模型页码无效"};return Q.models=Q.catalog.slice(Y*eZ,(Y+1)*eZ),Q.page=Y,Q.totalPages=V,{ok:!0,message:"",card:n5({sessionName:$.sessionName,panelId:Z,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),models:Q.models,sourceId:J,editable:Q.editable,allowCustom:!0,mode:Q.mode,...V>1?{pagination:{sourceId:J,page:Y,totalPages:V}}:{}})}}async function Dz($,Z,J){let Y=$.modelPanels.get(Z),Q=$.tokenSource(J);if(!Y||Y.sourceId!==J||!Q?.enabled||!Q.modelSelection)return{ok:!1,message:"模型管理面板已失效,请重新发送 md"};if(Q.modelCatalogState?.status!=="ready")return{ok:!1,message:Q.modelCatalogState?.error??"目录未就绪"};let V=Q.modelSelection.availableModels.filter((H)=>H.origin!=="custom"&&!Q.modelSelection.modelIds.includes(H.model)&&(Q.modelSelection.mode==="catalog"||!H.unavailableReason&&H.efforts.length>0));return $.modelPanels.set(Z,{models:[],catalog:$J($,Q,V),sourceId:J,messageId:Y.messageId,mode:"add",editable:!0,sourceRevision:Q.spawnRevision}),y6($,Z,J,0)}async function Fz($,Z,J,Y,Q){let V=$.modelPanels.get(Z),H=$.tokenSource(J);if(!V?.editable||V.sourceId!==J||!H?.modelSelection||V.sourceRevision!==H.spawnRevision||V.mode!==(Q==="add"?"add":"select")||!V.models.some((X)=>X.model===Y))return{ok:!1,message:"模型管理选项已失效,请重新发送 md"};if(Q==="delete"){let X=[...G$.all].filter((z)=>z.currentTokenSource()?.id===J&&z.currentModelLabel()===Y.replace(/\[1m\]$/,""));if(X.length)return{ok:!1,message:`补录模型仍被会话 ${X.map((z)=>z.sessionName).join("、")} 选用,请先切换再删除`}}try{if(Q==="delete")await Bz(J,Y,$.codexAccountId());else await Gz(J,Y,Q,$.codexAccountId());for(let z of G$.all)for(let[W,G]of z.modelPanels)if(G.sourceId===J&&(z!==$||W!==Z))z.modelPanels.delete(W);return{...await ZJ($,J,Z),message:Q==="add"?"模型已显示":Q==="delete"?"补录模型已删除":"模型已隐藏"}}catch(X){return{ok:!1,message:`模型列表更新失败:${O(X)}`}}}async function Mz($,Z,J,Y=""){let Q=$.tokenSource(Z.trim());if(!Q)return{ok:!1,message:`未知账号: ${Z}`};if(!Q.enabled)return{ok:!1,message:`${Q.display} 未配置`};let V=J.trim();if(!V)return{ok:!1,message:"补录面板缺少 panel_id,请重新发送 model"};return $.modelCustomPrompt={sourceId:Q.id,panelId:V,cardMessageId:Y},{ok:!0,message:"等待模型名",card:o5($.sessionName,Q.display,V)}}async function Uz($,Z,J){let Y=$.modelCustomPrompt;if(!Y)return!1;$.modelCustomPrompt=null;let Q=Z.trim(),V=$.tokenSource(Y.sourceId),H=async(_)=>{if(!Y.cardMessageId)return!1;let j="",q=!1,P=!1;try{if(j=await Z$(Y.cardMessageId),d0(j,1),q=await M0(j,N.modelPanel,_,{notifyCardFailure:!1}),!q)throw Error("model panel replace rejected");if(P=await P0(j,{config:{streaming_mode:!1}}),!P)throw Error("model panel streaming-off rejected")}catch(D){K(`model-custom: card update MISS (${D?.message??D})`)}finally{if(j){if(!P)try{P=await P0(j,{config:{streaming_mode:!1}})}catch(D){K(`model-custom: streaming-off retry MISS (${D?.message??D})`)}if(q&&P)try{await v0(j)}catch(D){K(`model-custom: card dispose MISS (${D?.message??D})`)}else K(`model-custom: retain card state after checked MISS mutation=${q} streamingOff=${P} card=${j.slice(0,12)}`)}}return q&&P},X=async(_,j)=>{if(await H(_))return!0;let P=`⚠️ 模型补录结果未能写回原卡。${j}
|
|
235
|
+
请重新发送 model 打开面板。`;if(!await w($.chatId,P))K(`model-custom: visible fallback send MISS (${j})`);return!1},z=(_)=>X(I2(!1,Q,_),`❌ ${Q?`模型 ${Q}`:"模型名"} 未加入:${_}。`);if(!V||!V.enabled)return await z("账号不可用"),!0;if(!Q)return await z("模型名为空"),!0;if(V.models.some((_)=>_.model.toLowerCase()===Q.toLowerCase()))return await X(I2(!1,Q,"已在列表中"),`ℹ️ 模型 ${Q} 已在列表中,未重复加入。`),!0;try{await Kz(V.id,Q,$.codexAccountId())}catch(_){return K(`model-custom: config/refresh MISS (${O(_)})`),await z(`配置写入或模型刷新失败:${O(_)}`),!0}K(`model-custom: ${V.id} 补录 ${Q} by ${J}(记录已持久化)`);for(let _ of G$.all)for(let[j,q]of _.modelPanels)if(q.sourceId===V.id&&(_!==$||j!==Y.panelId))_.modelPanels.delete(j);let W=$.tokenSource(V.id);if(!W||W.modelCatalogState?.status!=="ready")return await z(W?.modelCatalogState?.error??"刷新后的账号目录不可用"),!0;let G=$J($,W),B=G.find((_)=>_.model===Q);if(!B)return await z("补录已保存,但刷新后的模型列表未返回该项"),!0;if($.modelPanels.set(Y.panelId,{models:G,messageId:Y.cardMessageId}),B.unavailableReason||!B.efforts.length)return await X(I2(!0,Q,`**MISS**:${B.unavailableReason??"后端未确认 effort"}。记录已保存,可在模型面板删除。`),`模型 ${Q} 已补录,能力尚未确认。`),!0;if(B.efforts.length===1){let _=await $.onModelEffortSelect(B.model,B.efforts[0].effort,Y.panelId,J,B.provider);return await X(_.ok?j6({sessionName:$.sessionName,provider:B.provider,model:B.model,effort:B.efforts[0].effort,scope:Oz($,B.provider??"codex")}):I2(!0,Q,_.message),_.message),!0}return await X(_6({sessionName:$.sessionName,panelId:Y.panelId,currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:B}),`✅ 模型 ${Q} 已补录成功。`),!0}async function Az($,Z=""){let J=Z.trim(),Y=$.modelCustomPrompt;if(!J||!Y||Y.panelId!==J)return{ok:!1,message:"此补录面板已失效",card:B6($.sessionName,"stale")};return $.modelCustomPrompt=null,{ok:!0,message:"已取消",card:B6($.sessionName)}}function nD($,Z){return B$(Z?.provider)?Z.provider:z2($)}function Oz($,Z){if($.currentTurn)return"当前 turn 不变,后续新 turn 使用。";if($.proc?.isAlive()&&$.proc.provider===Z)return Z==="codex"?"Codex 需重启进程生效(发 restart)。":"下一轮开始使用。";return`下次启动 ${_$(Z)} 时使用。`}async function Rz($,Z,J="",Y="",Q=null){let V=Z.trim();if(!V)return await E($.chatId,`❌ ${"模型为空"}`),{ok:!1,message:"模型为空"};let H=nD(V,Q),X=$.modelPanels.get(J.trim())?.models.find((z)=>z.model===V&&(z.provider??"codex")===H);if(!X)return{ok:!1,message:"模型不在当前选项中,请重新发送 model"};if($.modelPanels.get(J.trim())?.mode==="add")return{ok:!1,message:"请先将模型添加到可选列表"};if(X.unavailableReason)return{ok:!1,message:X.unavailableReason};if(X.enabled===!1)return{ok:!1,message:`${X.displayName} 未配置,请先点「启用」`};if(X.efforts.length===0)return{ok:!1,message:"模型未返回 effort"};if(X.efforts.length===1)return JJ($,V,X.efforts[0].effort,J,Y,H);return{ok:!0,message:"",card:a5({sessionName:$.sessionName,panelId:J.trim(),currentModel:$.currentModelLabel(),currentEffort:$.currentEffortLabel(),model:X})}}async function JJ($,Z,J,Y="",Q="",V=""){let H=Z.trim(),X=J.trim();if(!H)return{ok:!1,message:"模型为空"};let z=Y.trim(),W=$.modelPanels.get(z),G=B$(V)?V:W?.models.find((U)=>U.model===H)?.provider??z2(H);if(G==="dsh"){if(!B0(X))return{ok:!1,message:"DSH reasoning effort 无效"}}else if(G==="claude"){if(!E0(X))return{ok:!1,message:"Claude reasoning effort 无效"}}else if(!s0(X))return{ok:!1,message:"Codex reasoning effort 无效"};let B=X,_=W?.models.find((U)=>U.model===H&&(U.provider??"codex")===G);if(!_||!_.efforts.some((U)=>U.effort===B))return{ok:!1,message:`${_$(G)} · ${H}/${B} 不在选项中`};let j=$.tokenSource(_.sourceId);if(j?.modelCatalogState){if(!j.enabled||j.modelCatalogState.status!=="ready")return{ok:!1,message:`模型目录 MISS:${j.modelCatalogState.error??j.modelCatalogState.status}`};if(!j.models.some((U)=>U.model===H&&U.efforts.includes(B)))return{ok:!1,message:"模型或 effort 已不在账号目录中,请重新发送 model"}}let q=!!_.sourceId&&$.currentTokenSource()?.id!==_.sourceId,P=!$.processSourceMatches(j,H)||!!j?.modelEnvironmentRevision&&j.modelEnvironmentRevision($.currentModelLabel()??"")!==j.modelEnvironmentRevision(H);if($.currentProvider()===G&&!q&&$.currentModelLabel()===H&&$.currentEffortLabel()===B)return $.modelPanels.delete(z),{ok:!0,message:`当前已是 ${_$(G)} · ${H} / ${B}`,card:K6({sessionName:$.sessionName,provider:G,model:H,effort:B,scope:"当前已是此设置,无需变更。"})};if($.proc?.isAlive()&&$.proc.provider!==G&&($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0))return{ok:!1,message:`当前 ${$.backendLabel($.proc.provider)} turn 正在执行或排队;请等结束或 stop 后再切换到 ${_$(G)}`};let M=$.currentModelLabel()!==H||q,A=!!($.currentTurn||$.openingTurn||$.pendingUserMessageCount>0||$.pendingMidTurnMsgs.length>0);if(P&&$.proc?.isAlive()&&A)return{ok:!1,message:"新模型需要更新进程配置,请等当前任务结束后再选择"};if(G==="claude"&&$.proc?.isAlive()&&$.proc.provider==="claude"&&M&&A)return{ok:!1,message:"当前 Claude turn 正在执行或排队;Claude 模型 profile 通过 env 生效,请等结束或 stop 后再切换"};try{if($.proc?.isAlive()&&$.proc.provider===G&&!q&&!P){let S=_.sourceId?$.tokenSource(_.sourceId)?.resolveSpawnModel(H)??H:H;await oY($.proc.setModelSettings(S,B),20000,"thread/settings/update")}await $.applyModelSelectionUnlocked(G,H,B,_.sourceId);let U=Oz($,G);return $.modelPanels.delete(z),{ok:!0,message:`已选择 ${_$(G)} · ${H} / ${B}`,card:K6({sessionName:$.sessionName,provider:G,model:H,effort:B,scope:U})}}catch(U){let S=`模型切换失败: ${O(U)}`;return K(`session "${$.sessionName}": set model settings failed: ${O(U)}`),await E($.chatId,`❌ ${S}`),{ok:!1,message:S}}}var eZ=20;var Nz=R(()=>{D0();YJ();V0();rZ();O1();D0();Y$();v$();t();I()});import{createHash as oD}from"node:crypto";function rD($,Z){return`agent:${Buffer.from(`${$}\x00${Z}`,"utf8").toString("base64url")}`}function n1($="default"){return sD(y$().map((Z)=>Z.forAccount?.($)??Z))}function sD($){let Z=[],J=[];for(let Y of $)tD(Y,Z,J);return{catalogGeneration:oD("sha256").update(JSON.stringify({identities:Z,sourceFailures:J})).digest("hex").slice(0,16),identities:Z,sourceFailures:J}}function tD($,Z,J){let Y=$.modelCatalogState?.status??(!$.enabled?"disabled":$.models.length>0?"ready":"idle");if(!$.enabled)J.push({tokenSourceId:$.id,display:$.display,status:"disabled",reason:"账号未启用"});else if(Y==="loading"||Y==="idle")J.push({tokenSourceId:$.id,display:$.display,status:"loading",reason:"模型目录正在刷新"});else if(Y==="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 Q of $.models)Z.push(eD($,Q,Y))}function eD($,Z,J){let Y="ready",Q;if(!$.enabled)Y="source_disabled",Q="所属 Token Source 未启用";else if(J==="loading"||J==="idle")Y="catalog_loading",Q="模型目录正在刷新";else if(J==="failed")Y="catalog_failed",Q=$.modelCatalogState?.error??"模型目录刷新失败";else if(Z.unavailableReason||!Z.efforts.length)Y="model_unavailable",Q=Z.unavailableReason??"effort MISS:上游未声明该后端支持的推理档位";return{id:rD($.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:Tz($.defaultModel)===Tz(Z.model),status:Y,...Q?{reason:Q}:{},spawnRevision:$.spawnRevision}}function Tz($){return $.replace(/\[1m\]$/i,"").toLowerCase()}var w6=R(()=>{V0()});import{randomUUID as $F}from"node:crypto";async function Ez($,Z){if(!Z.trim()){await w($.chatId,"❌ 无法确认操作者身份,未打开 agents 面板");return}bz(),await U2();let J=`agents_${$F()}`;if(N9.set(J,{ownerOpenId:Z,codexAccountId:$.codexAccountId(),page:0,createdAt:Date.now()}),!await c($.chatId,Sz(J)))await w($.chatId,"❌ agents 面板发送失败")}function xz($,Z,J){let Y=YF($,J),Q=Number(Z);if(!Number.isInteger(Q))return QF("无效页码");let V=JF(Y.codexAccountId);return Y.page=Math.max(0,Math.min(V-1,Q)),Y.createdAt=Date.now(),{ok:!0,message:"已更新",card:Sz($)}}function Sz($){let Z=N9.get($);if(!Z)throw Error("Agent 身份面板已过期");let J=n1(Z.codexAccountId),Y=Math.max(1,Math.ceil(J.identities.length/v6));Z.page=Math.min(Z.page,Y-1);let Q=Z.page*v6;return zZ({panelId:$,page:Z.page,totalPages:Y,catalog:J.identities.slice(Q,Q+v6),failures:J.sourceFailures})}function JF($){return Math.max(1,Math.ceil(n1($).identities.length/v6))}function YF($,Z){bz();let J=N9.get($);if(!J)throw Error("Agent 身份面板已过期,请重新发送 agents");if(!J.ownerOpenId||!Z||J.ownerOpenId!==Z)throw Error("只有打开该面板的用户可操作");return J}function QF($){return{ok:!1,message:$,card:z1({title:"agents",message:$,ok:!1})}}function bz(){let $=Date.now()-ZF;for(let[Z,J]of N9)if(J.createdAt<$)N9.delete(Z)}var v6=8,ZF=1800000,N9;var Cz=R(()=>{Y$();t();w6();V0();N9=new Map});var HJ={};E$(HJ,{withTasklistLifecycleLock:()=>g6,tasklistNameForProject:()=>I6,reconcileTasklistDeletions:()=>zF,isTasklistAlreadyDeletedError:()=>kz,getTasklistBinding:()=>m$,enableTasklist:()=>QJ,deleteTasklistRemoteIdempotently:()=>yz,deleteTasklist:()=>VJ});import{existsSync as HF,readFileSync as XF}from"node:fs";function I6($){return`${$}[lodestar]`}function m$($){let Z=g$.get($);return Z?o2(Z):null}async function g6($,Z){let J=f6.get($)??Promise.resolve(),Y,Q=new Promise((H)=>{Y=H}),V=J.catch(()=>{}).then(()=>Q);f6.set($,V),await J.catch(()=>{});try{return await Z()}finally{if(Y(),f6.get($)===V)f6.delete($)}}function kz($){if($&&typeof $==="object"&&$.code===1470404)return!0;let Z=$ instanceof Error?$.message:String($);return/\bcode=1470404\b/.test(Z)}async function yz($,Z=p3){try{return await Z($),"deleted"}catch(J){if(kz(J))return"already_deleted";throw J}}async function QJ($,Z){return await g6($,async()=>{let J=m$($);if(J?.deleting)throw Error(`tasklist deletion is pending for ${$}`);if(J)return J;let Y=I6($);if(Y.length>100)throw Error(`tasklist name is too long (${Y.length}/100): ${Y}`);let Q=await g3(Z),V=await m3(Y,Q),H={guid:V.guid,name:V.name,url:V.url,projectName:$,ownerOpenId:Q,createdAt:V.createdAt};return h6($,H),o2(H)})}async function VJ($,Z){return await g6($,async()=>{let J=m$($);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},h6($,J);return await wz($,Z)})}async function wz($,Z){let J=m$($);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,h6($,J);try{if(await yz(Z)==="already_deleted")K(`tasklist: ${$} remote list ${Z} already deleted; finishing tombstone`);let Q=new Map(g$);return Q.delete($),vz(Q),g$.delete($),o2(J)}catch(Y){let Q=m$($);if(Q?.guid===Z&&Q.deleting)Q.deleting.lastError=Y instanceof Error?Y.message:String(Y),h6($,Q);throw Y}}async function zF(){let $=[...g$.entries()].filter(([,J])=>!!J.deleting).map(([J,Y])=>({projectName:J,guid:Y.guid})),Z=[];for(let J of $)try{await g6(J.projectName,()=>wz(J.projectName,J.guid)),K(`tasklist: reconciled pending deletion for ${J.projectName}`)}catch(Y){Z.push(`${J.projectName}: ${Y instanceof Error?Y.message:String(Y)}`)}if(Z.length)throw Error(`tasklist deletion reconcile failed: ${Z.join("; ")}`)}function WF(){if(!HF(C9))return;try{let $=JSON.parse(XF(C9,"utf8"));if(!$||typeof $!=="object")return;for(let[Z,J]of Object.entries($)){if(!J||typeof J!=="object")continue;let Y=J;if(typeof Y.guid!=="string"||!Y.guid||typeof Y.name!=="string"||!Y.name)continue;let Q={guid:Y.guid,name:Y.name,url:typeof Y.url==="string"?Y.url:"",projectName:Z,ownerOpenId:typeof Y.ownerOpenId==="string"?Y.ownerOpenId:"",createdAt:typeof Y.createdAt==="string"?Y.createdAt:void 0,deleting:GF(Y.deleting)};g$.set(Z,Q)}K(`tasklist: loaded ${g$.size} project bindings`)}catch($){K(`tasklist: load map failed: ${$}`)}}function GF($){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 h6($,Z){let J=new Map(g$);J.set($,o2(Z)),vz(J),g$.set($,o2(Z))}function vz($=g$){let Z={};for(let[J,Y]of $)Z[J]=o2(Y);s(C9,Z)}function o2($){return JSON.parse(JSON.stringify($))}var g$,f6;var XJ=R(()=>{Q0();t();I();T0();g$=new Map,f6=new Map;WF()});function K1($,Z,J=!1){let Y=$.worktreeProjectName();return HZ({projectName:Y,tasklistName:I6(Y),binding:m$(Y),notice:Z,confirmDelete:J})}async function fz($){if(!await c($.chatId,K1($)))await w($.chatId,"❌ task 面板发送失败")}async function hz($){let Z=$.worktreeProjectName();try{let J=m$(Z),Y=await QJ(Z,$.chatId),Q=J?"已启用":`已启用 ${Y.name}`;return{ok:!0,message:Q,card:K1($,{type:"success",content:`✅ ${Q}`})}}catch(J){let Y=`启用失败: ${O(J)}`;return K(`session "${$.sessionName}": tasklist enable failed: ${O(J)}`),{ok:!1,message:Y,card:K1($,{type:"error",content:`❌ ${Y}`})}}}function Iz($,Z){let J=$.worktreeProjectName(),Y=m$(J),Q=Z.trim();if(!Y)return{ok:!1,message:"未启用",card:K1($,{type:"error",content:"❌ 未启用"})};if(Y.guid!==Q)return{ok:!1,message:"清单绑定已变化",card:K1($,{type:"error",content:"❌ 清单绑定已变化,请重新打开 task 面板"})};return{ok:!0,message:"请再次确认删除",card:K1($,{type:"error",content:"⚠️ 删除会删除所有清单内任务"},!0)}}async function gz($,Z){let J=$.worktreeProjectName(),Y=Z.trim();try{let V=`已删除 ${(await VJ(J,Y)).name}`;return{ok:!0,message:V,card:K1($,{type:"success",content:`✅ ${V}`})}}catch(Q){let V=`删除失败: ${O(Q)}`;return K(`session "${$.sessionName}": tasklist delete failed: ${O(Q)}`),{ok:!1,message:V,card:K1($,{type:"error",content:`❌ ${V}`})}}}var mz=R(()=>{Y$();t();I();XJ()});import{open as BF}from"node:fs/promises";import{basename as _F}from"node:path";function zJ($){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 p$($,Z){if(typeof $!=="string"||!$.trim())throw Error(`${Z} MISS`);return $}class pz{deps;queue=Promise.resolve();lastStartedAt=0;constructor($={fetch:$0,getToken:M$,retry:x1,wait:(Z)=>new Promise((J)=>setTimeout(J,Z)),intervalMs:250}){this.deps=$}request($,Z,J="GET",Y,Q){let V=this.queue.then(()=>this.deps.retry($,async()=>{Q?.throwIfAborted();let H=await this.deps.getToken(),X=Y?.(),z=X instanceof FormData,W=this.deps.intervalMs-(Date.now()-this.lastStartedAt);if(W>0)await this.deps.wait(W);Q?.throwIfAborted(),this.lastStartedAt=Date.now();let G=AbortSignal.timeout(qF),B=new AbortController,_=()=>B.abort(G.reason),j=()=>B.abort(Q.reason);G.addEventListener("abort",_,{once:!0}),Q?.addEventListener("abort",j,{once:!0});let q=B.signal;try{let P=await this.deps.fetch(`https://open.feishu.cn/open-apis${Z}`,{method:J,headers:{Authorization:`Bearer ${H}`,...!z&&X!==void 0?{"Content-Type":"application/json"}:{}},...X!==void 0?{body:z?X:JSON.stringify(X)}:{},signal:q});return(await E2(P,$)).data}catch(P){if(q.aborted&&q.reason?.name==="TimeoutError")throw q.reason;throw P}finally{G.removeEventListener("abort",_),Q?.removeEventListener("abort",j)}}));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:p$(J?.token,"交付文件夹"),url:zJ(J?.url)}}async getChatName($,Z){let J=await this.request("读取群名称",`/im/v1/chats/${encodeURIComponent($)}`,"GET",void 0,Z);return p$(J?.name,"群名称")}async getFolder($,Z){let J=await this.request("读取群文件夹",`/drive/explorer/v2/folder/${encodeURIComponent($.token)}/meta`,"GET",void 0,Z),Y=p$(J?.token,"群文件夹");if(Y!==$.token)throw Error("群文件夹返回了不同的标识");return{token:Y,url:zJ($.url),name:p$(J?.name,"群文件夹名称")}}async renameFolder($,Z,J){try{await this.request("同步群文件夹名称",`/drive/v1/files/${encodeURIComponent($.token)}?type=folder`,"PATCH",()=>({new_title:Z}),J)}catch(Q){if(Q instanceof D$&&Q.code===99991672)throw new D$("同步群文件夹名称需要应用身份权限 drive:file:upload(飞书错误码 99991672)",Q.status,Q.code);throw Q}let Y=await this.getFolder($,J);if(Y.name!==Z)throw Error("群文件夹名称更新未生效");return Y}async grantFolderAccess($,Z,J,Y){p$(Z,"交付群"),p$(J,"交付发起人");let Q=`/drive/v1/permissions/${encodeURIComponent($.token)}/members?type=folder`;for(let H 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("设置交付文件夹权限",Q,"POST",()=>H,Y);let V=await this.request("核对交付文件夹权限",Q,"GET",void 0,Y);if(!Array.isArray(V?.items))throw Error("交付文件夹权限列表 MISS");for(let[H,X,z]of[["openid",J,"full_access"],["openchat",Z,"view"]])if(V.items.find((G)=>G.member_type===H&&G.member_id===X)?.perm!==z)throw Error(`交付文件夹权限未生效:${H} / ${z}`)}async closeFileLinkSharing($,Z){p$($,"交付文件");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,Y){Y?.throwIfAborted();let Q=await BF($,"r");try{let V=await Q.stat();if(!V.isFile())throw Error("交付路径不是普通文件");if(!Number.isSafeInteger(V.size)||V.size<=0)throw Error("不能上传空文件或无效大小的文件");let H=_F($),X={file_name:H,parent_type:"explorer",parent_node:Z.token,size:V.size},z;if(V.size<=jF){let q=await Q.readFile(),P=await Q.stat();if(q.length!==V.size||P.mtimeMs!==V.mtimeMs||P.ctimeMs!==V.ctimeMs)throw Error("交付文件在读取时发生变化");z=await this.request("上传交付文件","/drive/v1/files/upload_all","POST",()=>{let D=new FormData;for(let[T,M]of Object.entries(X))D.append(T,String(M));return D.append("file",new Blob([Uint8Array.from(q)]),H),D},Y)}else{let q=await this.request("准备上传交付文件","/drive/v1/files/upload_prepare","POST",()=>X,Y),P=p$(q?.upload_id,"分片上传事务"),D=q?.block_size,T=q?.block_num;if(!Number.isSafeInteger(D)||D<=0||D>LF||!Number.isSafeInteger(T)||T!==Math.ceil(V.size/D))throw Error("云空间返回的分片策略无效");for(let A=0;A<T;A++){Y?.throwIfAborted();let U=Math.min(D,V.size-A*D),S=Buffer.alloc(U),b=0;while(b<U){let v=await Q.read(S,b,U-b,A*D+b);if(!v.bytesRead)throw Error("交付文件在分片读取时发生变化");b+=v.bytesRead}await this.request("上传交付文件分片","/drive/v1/files/upload_part","POST",()=>{let v=new FormData;return v.append("upload_id",P),v.append("seq",String(A)),v.append("size",String(U)),v.append("file",new Blob([Uint8Array.from(S)]),H),v},Y)}let M=await Q.stat();if(M.size!==V.size||M.mtimeMs!==V.mtimeMs||M.ctimeMs!==V.ctimeMs)throw Error("交付文件在上传期间被修改,未完成上传");z=await this.request("完成交付文件上传","/drive/v1/files/upload_finish","POST",()=>({upload_id:P,block_num:T}),Y)}let W=p$(z?.file_token,"已上传文件"),G={token:W,url:"",name:H,bytes:V.size};J(G),await this.closeFileLinkSharing(W,Y);let B=await this.request("读取交付文件链接","/drive/v1/metas/batch_query","POST",()=>({request_docs:[{doc_token:W,doc_type:"file"}],with_url:!0}),Y),_=B?.metas?.find((q)=>q.doc_token===W&&q.doc_type==="file");if(B?.failed_list?.length||!_)throw Error("已上传文件的元数据 MISS");let j={...G,url:zJ(_.url)};return J(j),j}finally{await Q.close()}}}var jF=20971520,LF=20971520,qF=60000,a1;var cz=R(()=>{h0();t();T8();a1=new pz});import{randomUUID as uz}from"node:crypto";import{basename as PF}from"node:path";class WJ{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:uz(),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:uz(),path:$,name:PF($),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(),Y=await this.deps.uploadFile($,J,(Q)=>{Z.file={...Q},Z.bytes=Q.bytes,this.save()},this.abort.signal);Z.file=Y,Z.bytes=Y.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(Y){this.snapshot.error=Y instanceof Error?Y.message:String(Y)}if(!this.abort.signal.aborted)try{await this.deps.reportError(`❌ 文件交付失败:${Z.name}
|
|
236
236
|
${Z.error}`)}catch(Y){this.snapshot.error=`错误提示发送失败:${String(Y)}`}}})}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{if($=await this.deps.sendCard(this.snapshot),!$)throw Error("飞书未返回交付卡消息 ID")}catch(Z){let J=`交付卡发送失败:${Z instanceof Error?Z.message:String(Z)}`;this.snapshot.error=J;try{this.save()}catch(Y){this.snapshot.error+=`;${String(Y)}`}return await this.deps.reportError(`❌ ${this.snapshot.error}${this.snapshot.folderAccessReady?`
|
|
237
|
-
已上传文件所在文件夹:${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
|
|
238
|
-
`)}function
|
|
239
|
-
`)}function
|
|
237
|
+
已上传文件所在文件夹:${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 lz=()=>{};class GJ{deps;groups;locks=new Map;constructor($){this.deps=$}get($){return structuredClone(this.load().get($)??{enabled:!1})}mode($){return this.get($).enabled?"drive":"chat"}enable($,Z){return this.exclusive($,async()=>{let J=await this.prepare($,Z,!0);return this.commit($,{enabled:!0,folder:J}),this.get($)})}disable($){return this.exclusive($,async()=>{return this.commit($,{...this.get($),enabled:!1}),this.get($)})}resolveFolder($,Z){return this.exclusive($.chatId,()=>this.prepare($.chatId,$.managerOpenId,!1,Z))}bindExisting($,Z,J){return this.exclusive($,async()=>{let Y=this.get($);if(Y.folder&&Y.folder.token!==J.token)throw Error("本群已经绑定其他文件夹");let Q=await this.deps.getFolder(J);return this.commit($,{...Y,folder:Q}),await this.prepare($,Z,!1),this.get($)})}async prepare($,Z,J,Y){if(Y?.throwIfAborted(),!$.trim()||!Z.trim())throw Error("无法确认交付群或管理权限接收人");let Q=await this.deps.getChatName($,Y);if(!Q.trim())throw Error("群名称 MISS");let V=this.get($),H;if(!V.folder){if(!J)throw Error("本群尚未绑定云空间文件夹,请先发送 files on");H={...await this.deps.createFolder(Q,Y),name:Q},this.commit($,{...V,folder:H})}else H=V.folder;let X=await this.deps.getFolder(H,Y);if(X.token!==H.token)throw Error("云空间返回的文件夹与本群绑定不一致");if(H=X.name===Q?X:await this.deps.renameFolder(X,Q,Y),H.name!==Q)throw Error("文件夹名称尚未与群名同步");return this.commit($,{...this.get($),folder:H}),await this.deps.grantFolderAccess(H,$,Z,Y),H}exclusive($,Z){let Y=(this.locks.get($)??Promise.resolve()).then(Z),Q=Y.then(()=>{},()=>{});return this.locks.set($,Q),Q.then(()=>{if(this.locks.get($)===Q)this.locks.delete($)}),Y}load(){if(this.groups)return this.groups;let $=this.deps.read();if($===void 0)return this.groups=new Map,this.groups;let Z=JSON.parse($);if(Z?.version!==1||!Z.groups||typeof Z.groups!=="object"||Array.isArray(Z.groups))throw Error("群文件交付设置格式无效");let J=new Map;for(let[Y,Q]of Object.entries(Z.groups)){let V=Q;if(!Y||!V||typeof V.enabled!=="boolean")throw Error("群文件交付开关无效");if(V.enabled&&!V.folder)throw Error("已启用的群缺少文件夹绑定");if(V.folder){if(typeof V.folder.token!=="string"||!V.folder.token.trim()||typeof V.folder.name!=="string"||!V.folder.name.trim()||typeof V.folder.url!=="string")throw Error("群文件夹绑定无效");let H=new URL(V.folder.url);if(H.protocol!=="https:"||H.username||H.password)throw Error("群文件夹链接无效")}J.set(Y,structuredClone(V))}return this.groups=J,J}commit($,Z){let J=new Map(this.load());J.set($,structuredClone(Z)),this.deps.write({version:1,groups:Object.fromEntries(J)}),this.groups=J}}import{join as DF}from"node:path";import{readFileSync as FF}from"node:fs";function dz($){return new WJ($,{resolveFolder:(Z,J)=>r2.resolveFolder(Z,J),uploadFile:(Z,J,Y,Q)=>a1.uploadFile(Z,J,Y,Q),sendCard:(Z)=>c($.chatId,M5(Z)),persist:(Z)=>s(DF(aJ,`${Z.id}.json`),Z),reportError:async(Z)=>{if(K(`file delivery ${$.projectName}: ${Z}`),!await E($.chatId,Z))throw Error(Z)}})}var r2;var iz=R(()=>{t();cz();lz();c8();Q0();T0();I();r2=new GJ({read:()=>{try{return FF(B7,"utf8")}catch($){if($?.code==="ENOENT")return;throw $}},write:($)=>s(B7,$),getChatName:($,Z)=>a1.getChatName($,Z),createFolder:($,Z)=>a1.createFolder($,Z),getFolder:($,Z)=>a1.getFolder($,Z),renameFolder:($,Z,J)=>a1.renameFolder($,Z,J),grantFolderAccess:($,Z,J,Y)=>a1.grantFolderAccess($,Z,J,Y)})});async function nz($,Z,J,Y,Q){let V,H="",X="";try{switch(V=Q.get($),Y.trim().toLowerCase()){case"":case"status":break;case"on":V=await Q.enable($,J),H="已开启本群云空间交付;之后新开始的交付使用此模式。";break;case"off":V=await Q.disable($),H="已恢复直接发送聊天附件;云空间中的历史文件保留。";break;default:throw Error("用法:files、files on、files off")}}catch(W){X=W instanceof Error?W.message:String(W);try{V=Q.get($)}catch{V=void 0}}let z=U5({groupName:Z,settings:V,notice:H,error:X});if(!await Q.sendCard(z))await Q.reportError(`❌ 文件交付设置卡发送失败${X?`:${X}`:""}`)}var az=R(()=>{c8()});function rz($){return[`- ${"生成并检查本地文件后,在回复正文中独占一行输出 `[[send: /abs/path]]` 提交交付,路径必须替换成实际存在的绝对路径。只在用户要文件或交付最终产物时使用。"}`,...$==="chat"?["- 本群通过聊天附件交付,交付前检查文件大小,单文件不超过 30 MB(30 × 1024 × 1024 字节);超限先无损压缩或分卷,保持用户要求的内容。"]:[]].join(`
|
|
238
|
+
`)}function sz($,Z){let J={codex:"- 当你有问题需要澄清时,使用 request_user_input 工具向用户提问;不要把多选题写成文本。",claude:"- 当你有问题需要澄清时,使用 Claude Code 自带的 AskUserQuestion 工具向用户提问。",dsh:"- 当你有问题需要澄清时,使用 ask_user_question 工具向用户提问;不要把多选题写成文本。"};return["- 以 `[file: /abs/path]` 开头的文本表示该路径上挂着一个文件,相关时去读它。",rz(Z),"- 文件交付约定由 Lodestar 按群设置生成;后续收到宿主注入的“文件交付约定更新”时,用其完整替换此前的文件交付约定。",`- ${"交付本地任务产物时,上传、权限和卡片均由 Lodestar 处理。Agent 不直接调用这些飞书接口,不为交付读取凭据或查找 token,也不依赖飞书 CLI。被委派的 Agent 只返回文件路径和说明,由主 Agent 提交交付。"}`,`- ${"交付标记只表示提交,不能据此声称上传成功。以 Lodestar 实际发出的附件、交付卡或错误提示为准,不编造云空间链接,不用其他工具重复发送。"}`,`- ${"`files`、`files on`、`files off` 是用户在群里输入的管理命令,不是 Shell 命令;不要擅自切换交付方式或改写群配置。"}`,J[$],...MF].join(`
|
|
239
|
+
`)}function tz($){return`[Lodestar 文件交付约定更新]
|
|
240
240
|
以下约定从本轮起完整替换此前的文件交付约定:
|
|
241
|
-
${
|
|
242
|
-
`)}var
|
|
243
|
-
`).map((V)=>V.trim()).filter(Boolean).filter((V)=>V.startsWith(s2)),Y=
|
|
244
|
-
`).filter(Boolean);_.statusLine=q[0]?.startsWith("## ")?q[0].slice(3):null,_.dirtyCount=q.filter((P)=>!P.startsWith("## ")).length}catch(j){_.error=
|
|
241
|
+
${rz($)}`}function ez(){return["---","name: lodestar-files",`description: ${JSON.stringify("在 Lodestar 飞书会话中交付本地生成或已有的报告、PDF、视频等任务文件。主 Agent 用交付标记交给宿主发送,委派 Agent 返回文件路径;不用于搜索或编辑用户指定的已有云文档。")}`,"---","","# Lodestar 文件交付","","仅用于 Lodestar 托管的会话。交付标记需要宿主处理,不能在普通终端或其他聊天环境里把它当作上传命令。","","生成并检查本地文件后,在回复正文中独占一行输出 `[[send: /abs/path]]` 提交交付,路径必须替换成实际存在的绝对路径。只在用户要文件或交付最终产物时使用。","","交付前完成文件生成与必要检查,确认文件存在、可读取。多个文件各写一行交付标记;把下面的示例路径替换成真实文件路径,不要在说明中原样发送示例标记。","标记写在主 Agent 的回复正文里,不写进脚本的标准输出、文件内容或仅放在工具返回值里。","","```text","[[send: /abs/path/report.pdf]]","[[send: /abs/path/video.mp4]]","```","","交付本地任务产物时,上传、权限和卡片均由 Lodestar 处理。Agent 不直接调用这些飞书接口,不为交付读取凭据或查找 token,也不依赖飞书 CLI。被委派的 Agent 只返回文件路径和说明,由主 Agent 提交交付。","","## 交付要求","","以 Lodestar 启动 Agent 时注入的文件交付约定及后续约定更新为准。只有约定明确给出文件大小上限时,才按该上限检查和处理;不自行查询配置、推断限制或按账号认证状态决定交付方式。","","`files`、`files on`、`files off` 是用户在群里输入的管理命令,不是 Shell 命令;不要擅自切换交付方式或改写群配置。","","## 宿主负责的结果","","云空间模式下,Lodestar 把本群各轮文件放进与群名一致的固定文件夹。独立卡片只列本轮文件,“管理群文件”打开本群所有历史云空间交付文件。目录复用、上传与重试、授权和发卡都由后台实现;这里不需要上传脚本或接口步骤。","","交付标记只表示提交,不能据此声称上传成功。以 Lodestar 实际发出的附件、交付卡或错误提示为准,不编造云空间链接,不用其他工具重复发送。","","系统报告交付失败时,向用户说明实际错误;不要换上传工具、身份或存储来源掩盖失败。用户另行要求管理已有云文档时,按该请求的实际范围处理,不把它混入本地产物交付。","","图像生成工具的图片沿用 Lodestar 自动展示规则,不再重复提交交付标记。",""].join(`
|
|
242
|
+
`)}var oz="lodestar-files",MF;var m6=R(()=>{MF=["- 使用图片生成工具生成图片后,不要再补充说明文字或 `[[send: ...]]`;Lodestar 会自动展示图片和提示词,支持时放进折叠面板,无法嵌入时单独发送。若你用脚本或文件编辑生成图片,按上一条用 `[[send: /abs/path]]` 发出。","- 每次调用 Bash / shell 命令时,第一行都必须写 shell 注释 `# desc: <一句中文说明>`,再写真正命令。这个注释只给 Lodestar 卡片做摘要,不要依赖它改变命令行为。"]});import{execFileSync as UF}from"node:child_process";import{existsSync as o1,readdirSync as AF,readFileSync as OF,realpathSync as KJ,statSync as RF}from"node:fs";import{dirname as NF,join as ZW,resolve as c6}from"node:path";async function u6($,Z){let J=KJ($),Y=process.platform==="win32"?J.toLowerCase():J,Q=p6.get(Y)??Promise.resolve(),V,H=new Promise((z)=>{V=z}),X=Q.catch(()=>{}).then(()=>H);p6.set(Y,X),await Q.catch(()=>{});try{return await Z()}finally{if(V(),p6.get(Y)===X)p6.delete(Y)}}function r1($){let Z=$.trim();if(!TF.test(Z))return null;return Z}function JW($){return $.match(/^(.+)\[[^\[\]]+\]$/)?.[1]??$}function t2($,Z){return`${$}[${Z}]`}function YW($){return`${s2}${$}`}function e2($,Z,J){return ZW(NF($),t2(Z,J))}function QW($,Z,J){let Y=EF($,Z,J);if(!Y)return null;let Q=OF(Y.path,"utf8").trim();if(!Q)return null;return{path:Y.path,content:Q,slug:Y.slug}}function VW($,Z){_J($);let J=R0($,["for-each-ref","--format=%(refname:short)",`refs/heads/${s2}`]).split(`
|
|
243
|
+
`).map((V)=>V.trim()).filter(Boolean).filter((V)=>V.startsWith(s2)),Y=jJ($),Q=[];for(let V of J){let H=V.slice(s2.length);if(!r1(H))continue;let X=t2(Z,H),z=e2($,Z,H),W=Y.get(V)??null,G=!!W&&o1(W),B=WW($,V,G),_={slug:H,chatName:X,branch:V,state:B,expectedPath:z,worktreePath:G?W:null,mounted:G,dirtyCount:null,statusLine:null,error:null};if(W&&o1(W))try{let q=R0(W,["status","--porcelain=v1","--branch"]).split(`
|
|
244
|
+
`).filter(Boolean);_.statusLine=q[0]?.startsWith("## ")?q[0].slice(3):null,_.dirtyCount=q.filter((P)=>!P.startsWith("## ")).length}catch(j){_.error=LJ(j)}Q.push(_)}return Q.sort((V,H)=>V.slug.localeCompare(H.slug))}function HW($,Z,J){let Y=r1(J);if(!Y)throw Error(`invalid worktree name "${J}"`);_J($);let Q=YW(Y),V=t2(Z,Y),H=e2($,Z,Y),X=CF($,Q),z=jJ($).get(Q)??null,W=X&&!z&&WW($,Q,!1)==="merged"?R0($,["rev-parse","HEAD"]).trim():null;if(z){if(c6(z)!==c6(H))throw Error(`branch ${Q} is already mounted at ${z}`);return zW(H,Q),{slug:Y,chatName:V,branch:Q,worktreePath:H,createdBranch:!1,createdWorktree:!1}}if(o1(H)){if(!RF(H).isDirectory())throw Error(`${H} exists but is not a directory`);if(!X)throw Error(`${H} already exists while branch ${Q} does not`)}if(X){if(R0($,["worktree","add",H,Q]),W)R0(H,["rebase",W]);return{slug:Y,chatName:V,branch:Q,worktreePath:H,createdBranch:!1,createdWorktree:!0}}return R0($,["worktree","add","-b",Q,H,"HEAD"]),{slug:Y,chatName:V,branch:Q,worktreePath:H,createdBranch:!0,createdWorktree:!0}}function XW($,Z,J){let Y=BJ($,Z,J);if(!o1(Y.worktreePath))return Y;return R0($,["worktree","remove",Y.worktreePath]),{...Y,removedWorktree:!0}}function BJ($,Z,J){let Y=r1(J);if(!Y)throw Error(`invalid worktree name "${J}"`);_J($);let Q=YW(Y),V=t2(Z,Y),H=e2($,Z,Y),z=jJ($).get(Q)??null??H;if(!o1(z))return{slug:Y,chatName:V,branch:Q,worktreePath:z,removedWorktree:!1};zW(z,Q);let W=R0(z,["status","--porcelain=v1"]).split(`
|
|
245
245
|
`).filter(Boolean);if(W.length>0){let G=W.slice(0,8).join(`
|
|
246
246
|
`);throw Error(`worktree has uncommitted changes:
|
|
247
|
-
${G}`)}return{slug:Y,chatName:V,branch:Q,worktreePath:z,removedWorktree:!1}}function
|
|
248
|
-
`)){if(Q.startsWith("worktree ")){Y=Q.slice(9);continue}if(Q.startsWith("branch refs/heads/")&&Y)Z.set(Q.slice(18),Y)}return Z}function R0($,Z){try{return
|
|
249
|
-
${Q}`:Y}function
|
|
250
|
-
${J}`:Z}function T9($){let Z=B1($),J=
|
|
251
|
-
`)}async function
|
|
252
|
-
${V}`,card:B9({slug:"wt",branch:"work/*",status:J,body:V,template:"red"})}}}async function DW($,Z){let J=r1(Z);if(!J)return
|
|
253
|
-
`),type:"success"}})}catch(H){V={ok:!1,message:`❌ 解散 ${J} 失败: ${O(H)}`,type:"error"}}return
|
|
254
|
-
`)){let V=Q.trim();if(!V)continue;let H;try{H=JSON.parse(V)}catch{continue}if(H.type==="queue-operation"&&H.operation==="enqueue"&&typeof H.content==="string"){let X=H.content.trim();if(X)return X.slice(0,80)}if(!Y&&H.type==="user"&&H.message){let X=tD(H.message);if(X)Y=X}}return Y.slice(0,80)}function tD($){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 NW($,Z,J){if(!J){await E($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let Y=nD($),Q=aD($),V=new Map,H=[];for(let G=0;G<Y.length;G++){let B=Y[G];if(G===0&&Q===null)continue;let _=MJ(),j=G===0?Q:iD(Y[G-1].checkpoint);V.set(_,{kind:Z,launch:j,branchBase:Q,seedAnchors:Y.slice(0,G),writes:Y.slice(G).flatMap((q)=>q.writes)}),H.push({choiceId:_,preview:B.preview,ts:B.ts})}H.reverse();let X=RW($,Z,J,V),z=$Z({projectName:i6($),panelId:X.id,mode:Z,entries:H}),W;try{W=await c($.chatId,z)}catch(G){throw Z4($).delete(X.id),G}if(!W)Z4($).delete(X.id),await w($.chatId,`❌ ${Z==="fork"?"fk":"bk"} 列表发送失败`)}function TW($,Z){return NW($,"fork",Z)}function EW($,Z){return NW($,"back",Z)}async function xW($,Z){if(!Z){await E($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let J;try{J=$.selectedProvider==="codex"?await $.listCodexConversations():$.selectedProvider==="dsh"?await $.listDshConversations():oD($.workDir)}catch(z){await w($.chatId,`❌ 历史会话读取失败: ${z instanceof Error?z.message:z}`);return}let Y=new Map,Q=rD(J).map((z)=>{let W=MJ();return Y.set(W,{kind:"resume",launch:{kind:"fork",source:{provider:z.provider,sessionId:z.sessionId,cwd:z.cwd}},sourcePreview:z.preview,sourceTs:z.ts,sourceStatus:z.status}),{choiceId:W,preview:z.preview,ts:z.ts}}),V=RW($,"resume",Z,Y),H=ZZ({projectName:i6($),panelId:V.id,entries:Q}),X;try{X=await c($.chatId,H)}catch(z){throw Z4($).delete(V.id),z}if(!X)Z4($).delete(V.id),await w($.chatId,"❌ rs 历史列表发送失败")}async function SW($,Z){if(!Z){await E($.chatId,"❌ 找不到发起人,无法建临时群。");return}if(!$.opts.onCreateTempSession){await E($.chatId,"❌ 临时群能力未就绪(daemon 未注入回调)。");return}let J=AW(i6($));await E($.chatId,`\uD83D\uDE80 正在创建 ${J} · ${$.backendLabel()} 新会话。它与当前群共享工作目录;当前会话不受影响。`);let Y;try{Y=await $.opts.onCreateTempSession({chatName:J,userOpenId:Z,workDir:$.workDir,routing:$.conversationRouting(),launch:{kind:"fresh"},branchBase:{kind:"fresh"},seedAnchors:[]})}finally{OW(J)}if(!Y.ok){await E($.chatId,`❌ 建临时会话失败: ${Y.error??"未知"}`);return}await E($.chatId,`✅ 已创建 ${J}。临时群不会自动删除;在该群发送 bye 可停止并解散。`)}async function bW($){if(!U$($.sessionName)){await E($.chatId,"❌ bye 只能在带 *MMDD-HHMM 后缀的临时会话群里使用。");return}if(!$.opts.onDisbandTempSession){await E($.chatId,"❌ 解散能力未就绪(daemon 未注入回调)。");return}await E($.chatId,`\uD83D\uDC4B 正在停止会话并解散 ${$.sessionName}…`);let Z=await $.opts.onDisbandTempSession($.sessionName,$.chatId);if(!Z.ok)await E($.chatId,`❌ 解散失败: ${Z.error??"未知"}`)}async function CW($,Z,J,Y){let Q=UJ($,"fork",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;try{if(H.kind!=="fork")return{ok:!1,message:"选择项类型不匹配"};if(!$.opts.onCreateTempSession)return{ok:!1,message:"临时群能力未就绪"};let X=AW(V.baseName);K(`session-temp: fork ${$.sessionName} → ${X} (${H.launch.kind})`),await E($.chatId,`\uD83D\uDD31 正在分叉到 ${X}…`);let z;try{z=await $.opts.onCreateTempSession({chatName:X,userOpenId:Y,workDir:V.workDir,routing:V.routing,launch:H.launch,branchBase:H.branchBase,seedAnchors:H.seedAnchors})}finally{OW(X)}if(!z.ok)return{ok:!1,message:`分叉失败: ${z.error??"未知"}`};return{ok:!0,message:`已分叉到 ${X};原会话和磁盘文件未回滚`}}catch(X){return{ok:!1,message:`分叉失败: ${X instanceof Error?X.message:X}`}}finally{d6(V)}}async function kW($,Z,J,Y){let Q=UJ($,"back",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;try{if(H.kind!=="back")return{ok:!1,message:"选择项类型不匹配"};let X="";try{if(!await c($.chatId,JZ({projectName:V.baseName,entries:H.writes})))X=";文件变更记录卡发送失败"}catch(G){X=`;文件变更记录卡发送失败: ${G instanceof Error?G.message:G}`}if(K(`session-temp: back ${$.sessionName} (${H.launch.kind}, writes=${H.writes.length})`),!await $.rollbackTo(H.launch,{anchors:H.seedAnchors,base:H.branchBase}))return{ok:!1,message:`回退失败;原会话绑定未改,请检查日志后重试${X}`};if(V.routing.provider==="claude")return{ok:!0,message:`本群已准备 Claude 新分支;发送下一条消息时生成并接入,旧会话未删除,磁盘文件未回滚${X}`};return{ok:!0,message:`本群已改接新会话${$.lastSessionId?` ${U0($.lastSessionId)}`:""};旧会话未删除,磁盘文件未回滚${X}`}}catch(X){return{ok:!1,message:`回退失败: ${X instanceof Error?X.message:X}`}}finally{d6(V)}}async function yW($,Z,J,Y){let Q=UJ($,"resume",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;if(H.kind!=="resume")throw d6(V),Error("resume panel contained a non-resume choice");let X=H.launch.source.sessionId,z=$.lastSessionId,W=(B,_)=>({projectName:V.baseName,provider:H.launch.source.provider,selectedPreview:H.sourcePreview,selectedTs:H.sourceTs,sourceSessionId:X,...H.sourceStatus?{sourceStatus:H.sourceStatus}:{},previousSessionId:z,newSessionId:B,bindingState:_}),G=(B,_,j,q=null)=>({ok:B,message:_,resumePresentation:W(q,j)});try{if($.isRunning())return G(!1,"当前群已经启动了新进程;为避免误杀,请先停止后重新发送 rs","unchanged");if(H.sourceStatus==="active")return G(!1,"所选 Codex 会话仍在运行;请先在原位置停止后再创建完整分支","unchanged");if(K(`session-temp: history fork ${$.sessionName} ← ${H.launch.source.provider} ${X}`),!await $.rollbackTo(H.launch,{anchors:[],base:H.launch,pendingLaunch:H.launch.source.provider==="claude"?{launch:H.launch,previousSessionId:z}:null}))return G(!1,"历史分支创建失败;原会话绑定未改,请检查日志后重试","unchanged");if(H.launch.source.provider==="claude")return G(!0,"Claude 独立分支已准备;首条消息时生成并接入新会话","prepared");let _=$.lastSessionId;if(!_)return G(!1,"历史分支已启动,但后端没有返回新会话 id","unknown");if(_===X||z&&_===z)return G(!1,"后端没有返回独立的新会话 id;为避免误判,本次不标记为恢复成功","unknown",_);return G(!0,"已创建并接入独立分支;源会话未修改","changed",_)}catch(B){return G(!1,`历史分支创建失败: ${B instanceof Error?B.message:B}`,"unknown")}finally{d6(V)}}var pD=86400000,cD=1800000,uD=3600000,lD=40,UW,DJ;var wW=R(()=>{t();Y$();I();x4();L4();A1();UW=new WeakMap,DJ=new Set});import{existsSync as vW}from"node:fs";import{randomBytes as $M,timingSafeEqual as ZM}from"node:crypto";import{isAbsolute as JM}from"node:path";function OJ($,Z=new Set){if($ instanceof B2)return $;if(!$||typeof $!=="object"&&typeof $!=="function"||Z.has($))return null;if(Z.add($),$ instanceof AggregateError)for(let J of $.errors){let Y=OJ(J,Z);if(Y)return Y}if($ instanceof Error&&$.cause!==void 0)return OJ($.cause,Z);return null}function YM($){return $.itemId||$.turnId||"__latest__"}function fW($){let Z=[];if($.itemId)Z.push(`item:${$.itemId}`);if($.turnId)Z.push(`turn:${$.threadId??$.sessionId??"-"}:${$.turnId}`);return Z}function QM($){let Z=null;for(let J of $.contextCompactionPending.keys())Z=J;return Z}function VM($,Z){if(!$)return Z;return{...$,...Z,phase:"end"}}function s1(){return f.runtime?.live_elapsed??"bucket"}function gW($,Z){return`${$} (${t$(Date.now()-Z,s1()).label})`}var hW="Thinking...",HM="Writing...",XM="Working...",AJ=1e4,n6=720000,zM=50,WM=256,a6=1e4,IW=250,G$;var QJ=R(()=>{L4();P4();F0();O1();_3();F0();y0();y3();V0();p0();T2();x4();v$();Y$();t();I();Q0();l5();w$();q9();FZ();QX();PX();kX();N6();vX();Lz();Pz();Tz();kz();pz();nz();oz();p6();MW();wW();A1();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;currentTurn=null;contextCompactionReceipts=new Map;contextCompactionOwnerIds=new WeakMap;contextCompactionOwnerSequence=0;lastManualContextCompactionCompletedAt=0;lastManualContextCompactionWasAnonymous=!1;backgroundTasks=[];pendingBgTasks=[];backgroundCard=null;settlingBackgroundCard=!1;migratingBackgroundCard=null;backgroundRefreshTimer=null;backgroundRefreshTick=null;openingBackground=!1;openingBackgroundOwner=null;backgroundOpenSequence=0;backgroundGeneration=0;backgroundDetailAdded=new Set;backgroundDetailAdding=new Set;lastMainTaskToolUseId=null;pendingRebuildBackgroundCard=!1;bgResumePending=!1;orphanAssistantSegments=[];orphanAssistantCurrent="";bgResumeCardless=!1;pendingPermissions=new Map;pendingAsks=new Map;currentGoal=null;status="stopped";pendingUserMessageCount=0;pendingMidTurnMsgs=[];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;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;G$.all.add(this);let Y=H5($);this.selectedProvider=Y?.provider??"claude",this.selectedModel=Y?.model??null,this.selectedEffort=Y?.effort??null,this.selectedTokenSourceId=this.deriveTokenSourceId(Y);let Q=q$(this.selectedTokenSourceId);if(Q){if(this.selectedProvider=Q.agent,Q.id==="glm"&&this.selectedModel==="claude:glm")this.selectedModel=Q.defaultModel,this.selectedEffort="max"}if(this.selectedModel)K(`session "${$}": restored selected provider=${this.selectedProvider} model=${this.selectedModel} effort=${this.selectedEffort??"unset"}`);if(this.lastSessionRef=Z1($,this.selectedProvider),this.lastSessionId=this.lastSessionRef?.sessionId??null,this.lastSessionId)K(`session "${$}": restored ${this.selectedProvider} lastSessionId=${this.lastSessionId}`);let V=i4($);if(V)if(this.selectedProvider!=="claude")e0($,[],null,null),K(`session "${$}": cleared pending Claude fork after provider changed`);else{_0(V.launch,"claude",this.workDir);let H=this.lastSessionId===V.previousSessionId,X=this.lastSessionRef,z=!H&&X?.provider==="claude"&&X.cwd===this.workDir&&X.sessionId!==V.launch.source.sessionId&&X.sessionId!==V.previousSessionId;if(!H&&!z)throw Error(`pending Claude fork has inconsistent resume binding for session "${$}"`);this.pendingConversationMaterialization=V,K(`session "${$}": restored ${z?"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.proc.codexAccountSelectionMode?.()!==null&&!(this.proc.turnRetry?.reason==="quota"&&this.proc.turnRetry.phase==="waiting")?{codexAccountName:k.get(r0(this.proc)).name}:{}}}get workDir(){return _W(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 F8(J)[0]?.id??null}currentTokenSource(){return this.tokenSource(this.selectedTokenSourceId)}codexStartAccountOverride;codexAccountId(){return this.proc?.isAlive()&&this.proc.provider==="codex"?r0(this.proc):this.codexStartAccountOverride??k.selected(this.sessionName)}tokenSource($){let Z=q$($);return Z?.forAccount?H0($,this.codexAccountId()):Z}currentProvider(){return this.selectedProvider}conversationRouting(){return{provider:this.selectedProvider,tokenSourceId:this.selectedTokenSourceId,model:this.selectedModel,effort:this.selectedEffort,...this.codexAccountId()===u?{}:{codexAccountId:this.codexAccountId()},...k.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");if($.codexAccountId)k.get($.codexAccountId);let Z=q$($.tokenSourceId);if(Z&&Z.agent!==$.provider)throw Error(`token source "${Z.id}" belongs to ${Z.agent}, not ${$.provider}`);if(this.selectedProvider!==$.provider)e0(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;this.selectedProvider=$.provider,this.selectedTokenSourceId=$.tokenSourceId,this.selectedModel=$.model,this.selectedEffort=$.effort,this.lastSessionRef=Z1(this.sessionName,$.provider),this.lastSessionId=this.lastSessionRef?.sessionId??null,b1(this.sessionName,$.provider,$.model,$.effort,$.tokenSourceId);let J=$.codexAccountId??u;if($.codexAccountAutomatic)k.selectAuto(this.sessionName);else if(k.selected(this.sessionName)!==J)k.select(this.sessionName,J)}dshEffortForSpawn(){if(B0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource(),Z=$&&L$($,this.selectedModel??$.defaultModel);if(!Z||!B0(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 X2({cwd:this.workDir,env:$.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"session/list",{cwd:this.workDir})).filter((J)=>!H2("dsh",J.sessionId))}async listCodexConversations(){if(this.selectedProvider!=="codex")throw Error("Codex history requested for a non-Codex session");if(!r4(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");let $=this.currentTokenSource();if(this.selectedTokenSourceId&&(!$||!$.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Z=$?.enabled?$:void 0,J=Z?(X)=>Z.spawnEnv(X):void 0,Y=new _2({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Z?.id??null,transformEnv:J}),Q=null,V=null;try{Q=await Y.listConversations()}catch(X){V=X}let H=null;try{await Y.kill(2000)}catch(X){H=X}if(V&&H)throw AggregateError([V,H],`Codex history query and cleanup failed: ${O(V)}; ${O(H)}`);if(V)throw V;if(H)throw H;return Q??[]}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=L8(this.workDir,$.sessionId);if(!vW(J))throw Error(`旧 Claude 会话不属于当前 cwd,或 transcript 不存在: ${U0($.sessionId)}`);Z={...$,cwd:this.workDir}}else{if(!r4(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");let J=this.currentTokenSource();if(this.selectedTokenSourceId&&(!J||!J.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Y=J?.enabled?J:void 0,Q=new _2({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Y?.id??null,transformEnv:Y?(X)=>Y.spawnEnv(X):void 0}),V=null;try{Z=await Q.readConversationRef($.sessionId)}catch(X){V=X,Z=$}let H=null;try{await Q.kill(2000)}catch(X){H=X}if(V&&H)throw AggregateError([V,H],`Codex legacy resume lookup and cleanup failed: read=${O(V)}; cleanup=${O(H)}`);if(V)throw V;if(H)throw H}return _0({kind:"resume",source:Z},this.selectedProvider,this.workDir),u4(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 s0(this.selectedEffort)?this.selectedEffort:O4}return O4}claudeEffortForSpawn(){if(this.selectedProvider==="claude"&&E0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude"){let Z=L$($,this.selectedModel??$.defaultModel);if(!E0(Z?.defaultEffort))throw Error("Claude 默认 effort MISS,请通过 model 面板明确选择");return Z.defaultEffort}return a$}currentModelLabel(){return(this.selectedModel??this.currentTokenSource()?.defaultModel??this.proc?.lastModel??null)?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null}currentEffortLabel(){let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude")return this.selectedEffort??L$($,this.selectedModel??$.defaultModel)?.defaultEffort??null;return this.selectedEffort??(this.selectedProvider==="dsh"?this.dshEffortForSpawn():void 0)??this.proc?.lastEffort??(this.selectedProvider==="claude"?a$:O4)}runtimeModelSelection(){let $=this.proc?.isAlive()?this.proc:null,Z=$?.provider??this.selectedProvider,J=!$||$.provider===this.selectedProvider,Y=($?.lastModel??(J?this.currentModelLabel():null))?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null,Q=$?.lastEffort??(J?this.currentEffortLabel():Z==="claude"?a$:O4);return{provider:Z,model:Y,effort:Q}}withModel($,Z){let J=this.modelLine(Z);return $.includes(J)?$:`${$} · ${J}`}replaceFooterContent($,Z){return J0($,N.footer,this.footerElement(Z),void 0,!1)}footerElement($){return{tag:"markdown",element_id:N.footer,content:$.trim()||" "}}modelLine($=this.currentTurn??this.runtimeModelSelection()){return R5($.provider,$.model,$.effort)}backendLabel($=this.selectedProvider){return _$($)}pendingConversationLaunch=null;pendingConversationMaterialization=null;lastTurnUserPreview="";pendingCodexTurnAnchors=[];pendingMaterializationLaunch(){let $=this.pendingConversationMaterialization;if(!$)return null;if(_0($.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($){this.agentCapability=$M(32).toString("base64url");let Z={LODESTAR_AGENT_URL:N8(f.notify.bind,f.notify.port),LODESTAR_AGENT_CAPABILITY:this.agentCapability,LODESTAR_AGENT_SESSION:this.sessionName,LODESTAR_AGENT_ROLE:"main"},J=this.pendingConversationLaunch??this.pendingMaterializationLaunch()??($?{kind:"resume",source:$}:{kind:"fresh"});_0(J,this.selectedProvider,this.workDir);let Y=this.currentTokenSource(),Q=this.selectedProvider==="codex"&&this.selectedTokenSourceId==="codex-sub";if(this.selectedTokenSourceId&&(!Y||!Y.enabled&&!Q))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或在 model 面板选择其他账号`);let V=Y?.enabled||Q?Y:void 0,H=this.currentTurn?.fileDeliveryMode??this.getFileDeliveryMode(),X=v4({provider:this.selectedProvider,workDir:this.workDir,tokenSourceId:V?.id??null,...this.selectedProvider==="codex"?{codexAccountId:k.selected(this.sessionName)}:{},...Q?{codexAccountPreference:this.codexStartAccountOverride??k.preferred(this.sessionName)}:{},model:V?this.selectedModel??V.defaultModel:this.modelForSpawn(),effort:this.selectedProvider==="dsh"?this.dshEffortForSpawn():this.selectedProvider==="claude"?this.claudeEffortForSpawn():this.effortForSpawn(),launch:J,developerInstructions:this.spawnDeveloperInstructions(H),profile:b2(this.worktreeProjectName()),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:F1},hostEnv:Z});return this.procSourceRevisions.set(X.process,X.sourceRevision),this.procFileDeliveryModes.set(X.process,H),X.process}async applyModelSelection($,Z,J,Y){await this.runLifecycle("apply-model-selection",()=>this.applyModelSelectionUnlocked($,Z,J,Y))}async applyModelSelectionUnlocked($,Z,J,Y){if(this.selectedProvider!==$)e0(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;this.selectedProvider=$,this.selectedTokenSourceId=Y??this.selectedTokenSourceId;let V=q$(this.selectedTokenSourceId);if(V)this.selectedModel=Z||null,this.selectedEffort=J??L$(V,Z||V.defaultModel)?.defaultEffort??null;else this.selectedModel=$==="codex"?null:Z,this.selectedEffort=$==="codex"?null:J;this.lastSessionRef=Z1(this.sessionName,$),this.lastSessionId=this.lastSessionRef?.sessionId??null,V5(this.sessionName,$,this.selectedModel,this.selectedEffort,this.selectedTokenSourceId),await this.stopIdleMismatchedProcessUnlocked()}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()===D2($,Z);return!this.proc||!this.procSourceRevisions.has(this.proc)||this.procSourceRevisions.get(this.proc)===D2($,Z)}async stopIdleMismatchedProcessUnlocked(){if(!this.proc?.isAlive())return;let $=this.currentTokenSource(),Z=this.processSourceMatches($,this.selectedModel);if(this.proc.provider===this.selectedProvider&&this.proc.tokenSourceId===this.selectedTokenSourceId&&Z)return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return;let J=this.proc;K(`session "${this.sessionName}": stop idle ${J.provider} process after switching to ${this.selectedProvider}`),this.beginProcStop(J),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let Y=await this.settleProcResumableState(J),Q=null;try{await J.kill(1000)}catch(X){Q=X}Y=await this.settleProcResumableState(J);let V=this.finishProcStop(J,Q);this.opts.onLifecycleChange?.();let H=[...!V?[Q??Error(this.blockedProcReason??"process stop unconfirmed")]:[],...Y?[Error(Y)]:[]];if(H.length===1)throw H[0];if(H.length>1)throw AggregateError(H,`idle process stop failed: ${H.map(O).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;K(`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),Y=null;try{await Z.kill(1000)}catch(H){Y=H}J=await this.settleProcResumableState(Z);let Q=this.finishProcStop(Z,Y);this.opts.onLifecycleChange?.();let V=[...!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(O).join("; ")}`);return!0}startFooterTimer($,Z,J=(Y)=>Y){let Y=Date.now(),Q=Z,V=!1,H=()=>{if(V)return;this.replaceFooterContent($,J(gW(Q,Y)))},X=null,z=()=>{if(V)return;let{nextDelayMs:W}=t$(Date.now()-Y,s1());X=setTimeout(()=>{H(),z()},Math.max(1,Math.ceil(W)))};return H(),z(),{setStatus(W){Q=W,H()},stop(){if(V=!0,X)clearTimeout(X)},elapsedSec(){return(Date.now()-Y)/1000}}}async openStatusCard($,Z,J="blue"){let Y=Date.now(),Q=d5({sessionName:this.sessionName,title:$,status:gW(Z,Y),template:J}),V=await c(this.chatId,Q);if(!V)return K(`session "${this.sessionName}": status card send failed title=${$}`),await w(this.chatId,`❌ 创建状态卡片失败: ${$}`),null;let H;try{H=await Z$(V)}catch(X){return K(`session "${this.sessionName}": status card id_convert failed title=${$}: ${X}`),await w(this.chatId,`❌ 状态卡片初始化失败: ${$}`),null}return d0(H,1),{cardId:H,title:$,timer:this.startFooterTimer(H,Z,(X)=>G9($,X))}}setStatusCard($,Z){$?.timer.setStatus(Z)}async closeStatusCard($,Z){if(!$)return;$.timer.stop();let J=$.timer.elapsedSec(),Y=G9($.title,`${Z} (${G0(J)})`);await O$($.cardId);let Q=await M0($.cardId,N.footer,this.footerElement(Y));A0($.cardId);let V=await P0($.cardId,h$({durationSec:J,suffix:Z}));if(Q&&V)await v0($.cardId);else{let H=`footer=${Q?"ok":"MISS"}, settings=${V?"ok":"MISS"}`;K(`session "${this.sessionName}": status card terminal transaction incomplete card=${$.cardId.slice(0,12)} ${H}`),await w(this.chatId,`⚠️ 状态卡片终态写入失败 (${H}):${Z}`)}}async runLifecycle($,Z){let J=this.lifecycleTail,Y;this.lifecycleTail=new Promise((V)=>{Y=V}),await J;let Q=++this.lifecycleSequence;K(`session "${this.sessionName}": lifecycle#${Q} ${$} begin`);try{return await Z()}finally{Y(),K(`session "${this.sessionName}": lifecycle#${Q} ${$} 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 Y,Q=new Promise((H)=>{Y=H}),V={token:++this.turnOpenSequence,proc:$,procEpoch:Z,sawResult:!1,terminalForcePush:!1,pendingCompactions:[],backendTurnStarted:J,done:Q,resolveDone:Y};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()}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()}beginBackgroundOpen(){if(this.backgroundCard||this.openingBackgroundOwner)return null;let $={token:++this.backgroundOpenSequence,proc:this.proc,procEpoch:this.procEpoch,generation:this.backgroundGeneration};return this.openingBackgroundOwner=$,this.openingBackground=!0,$}ownsBackgroundOpen($){return this.openingBackgroundOwner===$&&this.backgroundGeneration===$.generation&&this.proc===$.proc&&this.procEpoch===$.procEpoch}releaseBackgroundOpen($){if(this.openingBackgroundOwner!==$)return;this.openingBackgroundOwner=null,this.openingBackground=!1}invalidateBackgroundOpen(){this.backgroundGeneration++,this.openingBackgroundOwner=null,this.openingBackground=!1}attachProc($){this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),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.invalidateTurnOpen(),this.invalidateBackgroundOpen(),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($){this.stoppingProc=$,this.agentCapability=null}acceptsAgentCapability($){let Z=this.agentCapability;if(!Z||!$||!this.proc?.isAlive())return!1;let J=Buffer.from(Z),Y=Buffer.from($);return J.length===Y.length&&ZM(J,Y)}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?O(Z):"kill returned while process still reports alive",K(`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(Y){J=Y}return this.finishProcStop($,J)}async settleProcResumableState($){let Z=null,J=$.conversationMaterializationBarrier?.();if(J)try{await J}catch(V){Z=`Codex 会话落盘确认失败: ${O(V)}`}let Y=$.conversationMaterializationFailure?.();if(Y&&$.isConversationResumable?.()!==!0)Z=`Codex 会话落盘确认失败: ${O(Y)}`;let Q=this.persistResumableSessionId(!1,$,!1);return[Z,Q].filter(Boolean).join(";")||null}resetFreshConversationState(){this.daemonRestoreRequired=!1,this.turnCounter=0,this.pendingConversationMaterialization=null,e0(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(k.get($),this.selectedProvider!=="codex"){if(this.proc?.isAlive())await this.stopUnlocked("切换到 Codex",{...Z,announce:!1});let Y=H0("codex-sub",$)?.defaultModel||null;e0(this.sessionName,[],null,null),b1(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=Z1(this.sessionName,"codex"),this.lastSessionId=this.lastSessionRef?.sessionId??null}if(this.selectedTokenSourceId!=="codex-sub")b1(this.sessionName,"codex",this.selectedModel,this.selectedEffort,"codex-sub"),this.selectedTokenSourceId="codex-sub";this.codexStartAccountOverride=$;try{if(this.proc?.isAlive()&&this.proc.provider==="codex"&&r0(this.proc)===$&&this.proc.turnRetry?.reason!=="quota")return Z.onStatus?.(`✅ 正在使用「${k.get($).name}」`),!0;return this.proc?.isAlive()?await this.restartUnlocked(!0,Z):await this.startUnlocked(Z)}finally{this.codexStartAccountOverride=void 0}})}async startUnlocked($={}){let Z=$.announce??!0,J=$.onStatus,Y=this.blockedProcessMessage();if(Y){if(this.status="stopped",J?.(`❌ ${Y}`),Z)await E(this.chatId,`❌ ${Y}。请重试 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?.("\uD83D\uDD0E 检查 Codex 登录");else J?.("\uD83D\uDD0E 检查 Claude Code");if(this.selectedProvider==="codex"&&this.selectedTokenSourceId!=="codex-sub"&&!r4(this.codexAccountId())){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.("❌ Codex 未登录 ChatGPT 账号"),Z){if(!await c(this.chatId,V$({phase:"warning",title:"需要登录",hint:"默认:codex-login · 额外:codex-login 备注"})))throw Error("Codex 登录引导卡片发送失败")}return!1}if(!vW(this.workDir)){if(J?.(`\uD83C\uDD95 创建项目目录 ~/${this.sessionName}`),Z)await E(this.chatId,`\uD83C\uDD95 目录 ~/${this.sessionName} 不存在,正在创建…`);try{P5(this.workDir)}catch(G){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.(`❌ 创建项目失败: ${G}`),Z)await E(this.chatId,`❌ 创建项目失败: ${G}`);return!1}}if(!$.freshConversationStateAlreadyReset&&!this.pendingConversationMaterialization)this.resetFreshConversationState();this.status="starting",J?.(this.withModel(`\uD83D\uDE80 启动 ${this.backendLabel()}`));let Q;try{if(this.selectedProvider!=="codex"||!this.codexStartAccountOverride&&k.preferred(this.sessionName)===null)await A2();Q=this.spawnAgent()}catch(G){let B=`${this.backendLabel()} 启动失败: ${O(G)}`;if(K(`session "${this.sessionName}": ${B}`),J?.(`❌ ${B}`),Z)await E(this.chatId,`❌ ${B}`);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}this.attachProc(Q);let V=this.backendLabel(),H=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(Q,IW):null;J?.(this.selectedProvider==="claude"?`⏳ 检查 ${V} 启动`:`⏳ 等待 ${V} init`);let X,z=null;try{Q.sendInitialize(),X=Q.initializationPromise?.()}catch(G){X=void 0,z=G}let W=z?{state:"error",error:z}:this.selectedProvider==="claude"?await H:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(X),()=>{K(`session "${this.sessionName}": codex init still pending after ${AJ/1000}s`),J?.(this.withModel(`⏳ 仍在等待 ${V} init 确认`))});if(W.state==="error"||W.state==="exit"){let G=W.error?O(W.error):W.state;K(`session "${this.sessionName}": ${this.selectedProvider} init failed: ${G}`);let _=await this.stopOwnedProc(Q,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,j=`❌ ${V} 启动失败: ${G}${_}`;if(J?.(j),Z)await E(this.chatId,j);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(W.state==="timeout"){K(`session "${this.sessionName}": ${this.selectedProvider} init wait timeout (${n6/1000}s)`);let B=await this.stopOwnedProc(Q,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,_=`❌ ${V} 启动超时: ${n6/1000} 秒内初始化事务未完成${B}`;if(J?.(_),Z)await E(this.chatId,_);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(this.proc!==Q||!Q.isAlive()){let G=`${V} 启动期间已退出`;if(K(`session "${this.sessionName}": ${G}`),J?.(`❌ ${G}`),Z)await E(this.chatId,`❌ ${G}`);return this.detachProc(Q),this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(W.state==="waiting_quota"){if(this.status="starting",this.startedAt=Date.now(),this.opts.onLifecycleChange?.(),J?.("⏳ 账号额度用尽 · 自动等待恢复,可用后继续"),Z)await c(this.chatId,V$({phase:"checking",title:"等待额度恢复",message:"额度恢复后自动继续",hint:"stop 可取消等待"}));return!0}if(Z){let G=this.modelLine();await E(this.chatId,[this.withWorktreeInstructionNotice(`✅ Lodestar session "${this.sessionName}" 已就绪,发消息开始对话。`),G].filter(Boolean).join(`
|
|
255
|
-
`))}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 Y=!1,Q=(X,z)=>{if(Y)return;Y=!0,clearTimeout(V),clearTimeout(H),J({state:X,error:z})},V=setTimeout(()=>{if(Y)return;try{Z?.()}catch(X){Q("error",X)}},AJ),H=setTimeout(()=>{Q("timeout",Error(`codex init timed out after ${n6/1000}s`))},n6);$.then(()=>Q("init"),(X)=>Q("error",X)),this.proc?.quotaWaitPromise?.().then(()=>Q("waiting_quota"),(X)=>Q("error",X))})}async waitForProcEarlyFailure($,Z){return await new Promise((J)=>{let Y=!1,Q=(W,G)=>{if(Y)return;Y=!0,clearTimeout(V),$.off("init",H),$.off("error",X),$.off("exit",z),J({state:W,error:G})},V=setTimeout(()=>Q("ready"),Z),H=()=>Q("init"),X=(W)=>Q("error",W),z=(W)=>Q("exit",W);$.once("init",H),$.once("error",X),$.once("exit",z)})}releaseAllReactions(){for(let[$,Z]of[...this.pendingReactionIds.entries(),...this.currentBatchReactionIds.entries()])if(Z)C0($,Z);this.pendingReactionIds=new Map,this.currentBatchReactionIds=new Map}clearStaleIdleQueueState($){if(this.initCount<1||this.currentTurn||this.openingTurn||this.pendingUserMessageCount===0)return;K(`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)C0(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,Y=Z.onStatus;if(this.daemonRestoreRequired=!1,await this.cancelAgentRuns($),!this.proc){if(this.status="stopped",this.opts.onLifecycleChange?.(),Y?.("⚪ session 当前未运行"),J)await E(this.chatId,`⚪ session "${this.sessionName}" 当前未运行`);return}let Q=this.proc,V=this.persistResumableSessionId(!1,Q,!1),H=null;if(Y?.(`\uD83D\uDED1 停止 ${this.backendLabel(this.proc.provider)}`),K(`session "${this.sessionName}": stop (${$})`),this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),this.currentTurn)this.closeTurnCard(`\uD83D\uDED1 ${$}`).catch((F)=>{K(`session "${this.sessionName}": stop current main-card close failed: ${O(F)}`)});let X=this.waitForTurnCloses().catch((F)=>K(`session "${this.sessionName}": stop main-card close failed: ${O(F)}`));this.beginProcStop(Q),this.status="stopped";let z=[];try{this.opts.onLifecycleChange?.()}catch(F){z.push(F),K(`session "${this.sessionName}": stop intent lifecycle write failed: ${O(F)}`)}let W=Q.conversationMaterializationBarrier?.();if(W){try{await W}catch(F){H=`Codex 会话落盘确认失败: ${O(F)}`}V=this.persistResumableSessionId(!1,Q,!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 G=null;try{await Q.kill()}catch(F){G=F}let B=Q.conversationMaterializationFailure?.();if(B&&Q.isConversationResumable?.()!==!0)H=`Codex 会话落盘确认失败: ${O(B)}`;V=this.persistResumableSessionId(!1,Q,!1);let j=(await Promise.allSettled([this.resetBackgroundTasks(),X])).filter((F)=>F.status==="rejected").map((F)=>F.reason);for(let F of j)K(`session "${this.sessionName}": stop terminal cleanup failed: ${O(F)}`);let q=this.finishProcStop(Q,G);try{this.opts.onLifecycleChange?.()}catch(F){z.push(F),K(`session "${this.sessionName}": stop final lifecycle write failed: ${O(F)}`)}let P=[...G?[G]:[],...!q&&!G?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...j,...z,...V?[Error(V)]:[],...H&&Q.isConversationResumable?.()!==!0?[Error(H)]:[]];if(P.length===1)throw P[0];if(P.length>1)throw AggregateError(P,`stop failed: ${P.map(O).join("; ")}`);if(Y?.(`✅ ${$}`),J)await E(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 E(this.chatId,"❌ daemon 重启后没有可用的恢复点。请发送 rs 选择历史会话,或 hi 明确启动新会话。"),!1;return await this.restartUnlocked(!0)})}async restartUnlocked($=!1,Z={},J){let Y=Z.announce??!0,Q=Z.onStatus,V=this.status,H=null;if(!$&&!this.pendingConversationLaunch&&this.pendingConversationMaterialization)H=this.pendingConversationMaterialization,J1(this.sessionName,null),this.pendingConversationMaterialization=null;let X=this.pendingConversationLaunch??this.pendingMaterializationLaunch(),z=this.lastSessionRef;if($&&!X&&z?.cwd===null)try{z=await this.resolveLegacyResumeRef(z),this.lastSessionRef=z,this.lastSessionId=z.sessionId}catch(x){let h=this.invalidateMissingCodexResume(z.sessionId,x,J),p=h?`❌ 旧会话不可恢复: ${O(x)};${h}`:`❌ 旧会话 cwd 校验失败: ${O(x)};请在进程已停时发送 rs 重新选择历史会话`;if(this.status=this.proc?.isAlive()?V:"stopped",Q?.(p),Y)await E(this.chatId,p);return!1}let W=z?.sessionId??null,G=X&&X.kind!=="fresh"?X.source.sessionId:W,B=G?U0(G):"",_=null,j=(x=this.proc)=>{if(!$||X||x?.provider!=="codex"||x.isConversationResumable?.()!==!0)return;_=this.persistResumableSessionId(!1,x,!1),z=this.lastSessionRef,W=z?.sessionId??null,G=W,B=G?U0(G):""},q=null;if(!Q&&Y&&$&&W){let x=this.proc?this.withModel(`\uD83D\uDD01 重启 ${this.backendLabel(this.proc.provider)}`):this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${B}`);if(q=await this.openStatusCard("restart",x),q)Q=(h)=>this.setStatusCard(q,h)}let P=Y&&!q,F=async(x)=>{if(q)await this.closeStatusCard(q,x)},T=Boolean(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0||this.pendingTurnInputs.length>0||this.backgroundTasks.length>0||this.pendingBgTasks.length>0||this.openingBackground);this.bgResumePending=!1,this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),this.discardOrphanAssistant();for(let x of this.fileDeliveries)x.cancel("会话正在重启");if(this.currentTurn)this.closeTurnCard("\uD83D\uDD01 已中止,正在重启").catch((x)=>{K(`session "${this.sessionName}": restart current main-card close failed: ${O(x)}`)});let M=this.waitForTurnCloses().catch((x)=>K(`session "${this.sessionName}": restart main-card close failed: ${O(x)}`)),A=null,U=null;if(this.proc){let x=this.proc;Q?.(`\uD83D\uDED1 停止当前 ${this.backendLabel(x.provider)}`),U=x,this.beginProcStop(x);let h=x.conversationMaterializationBarrier?.();if(h)try{await h}catch(l){_=`Codex 会话落盘确认失败: ${O(l)}`}if(j(x),$&&!X&&_&&!T&&x.isAlive()){if(this.stoppingProc===x)this.stoppingProc=null;this.status=V;let l=`❌ ${this.backendLabel(x.provider)} 恢复点尚未安全落盘,已保留当前进程: ${_}`;if(K(`session "${this.sessionName}": abort restart before kill: ${_}`),Q?.(l),P)await E(this.chatId,l);return await F(l),!1}try{await x.kill()}catch(l){A=l}let p=x.conversationMaterializationFailure?.();if(p&&x.isConversationResumable?.()!==!0)_=`Codex 会话落盘确认失败: ${O(p)}`;j(x)}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 b=(await Promise.allSettled([this.resetBackgroundTasks(),M])).filter((x)=>x.status==="rejected").map((x)=>x.reason);for(let x of b)K(`session "${this.sessionName}": restart terminal cleanup failed: ${O(x)}`);let v=U?this.finishProcStop(U,A):!0,y=[...A?[`kill=${O(A)}`]:[],...!v&&!A?[`kill=${this.blockedProcReason??"process stop unconfirmed"}`]:[],...b.map((x)=>`cleanup=${O(x)}`),..._?[`resume=${_}`]:[]];if(y.length>0&&H)try{J1(this.sessionName,H),this.pendingConversationMaterialization=H}catch(x){y.push(`pendingRestore=${O(x)}`)}if(y.length>0){let x=`❌ 旧 ${this.backendLabel()} 进程停止/清理失败: ${y.join("; ")}`;if(this.status="stopped",this.opts.onLifecycleChange?.(),Q?.(x),P)await E(this.chatId,x);return await F(x),!1}let g=X?.kind==="resume"||X?.kind==="fork";if($&&z||g){this.status="starting",this.usageTotalsSeedUnknown=!0,Q?.(this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${B}`));let x;try{if(this.selectedProvider!=="codex"||!this.codexStartAccountOverride&&k.preferred(this.sessionName)===null)await A2();x=this.spawnAgent(z??void 0)}catch(o){let K0=`❌ ${this.backendLabel()} 恢复失败: ${O(o)}`;if(K(`session "${this.sessionName}": ${this.selectedProvider} resume failed before spawn: ${O(o)}`),Q?.(K0),P)await E(this.chatId,K0);return this.status="stopped",this.opts.onLifecycleChange?.(),await F(K0),!1}this.attachProc(x);let h=this.backendLabel(),p=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(x,IW):null;Q?.(this.selectedProvider==="claude"?`⏳ 检查 ${h} 恢复启动`:`⏳ 等待 ${h} init 确认`);let l,D=null;try{x.sendInitialize(),l=x.initializationPromise?.()}catch(o){l=void 0,D=o}let C=D?{state:"error",error:D}:this.selectedProvider==="claude"?await p:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(l),()=>{K(`session "${this.sessionName}": codex resume init still pending after ${AJ/1000}s`),Q?.(this.withModel(`⏳ 仍在等待 ${h} init 确认 thread=${B}`))});if(C.state==="error"||C.state==="exit"||C.state==="timeout"){let o=C.state==="error"?this.invalidateMissingCodexResume(G,C.error,J):null,K0=[C.error?O(C.error):C.state,o].filter(Boolean).join(";");K(`session "${this.sessionName}": ${this.selectedProvider} resume failed: ${K0}`);let b9=await this.stopOwnedProc(x,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,Z2=C.state==="timeout"?`❌ ${h} 恢复超时${b9}`:`❌ ${h} 恢复失败: ${K0}${b9}`;if(Q?.(Z2),P)await E(this.chatId,Z2);return this.status="stopped",this.opts.onLifecycleChange?.(),await F(Z2),!1}if(this.proc!==x||!x.isAlive()){let o=`❌ ${h} 恢复期间已退出`;if(K(`session "${this.sessionName}": ${this.selectedProvider} resume process exited before ready`),Q?.(o),P)await E(this.chatId,o);return this.detachProc(x),this.status="stopped",this.opts.onLifecycleChange?.(),await F(o),!1}let d=this.withModel(this.withWorktreeInstructionNotice(C.state==="waiting_quota"?"⏳ 账号额度用尽 · 等待后自动恢复原会话":this.selectedProvider==="claude"&&C.state==="ready"?`✅ 已准备恢复上一会话 thread=${B}`:`✅ 已恢复上一会话 thread=${B}`));if(Q?.(d),P)await E(this.chatId,d);if(this.status=C.state==="waiting_quota"?"starting":"idle",this.startedAt=Date.now(),C.state!=="waiting_quota")this.daemonRestoreRequired=!1;this.opts.onLifecycleChange?.();try{await F(d)}catch(o){K(`session "${this.sessionName}": restart succeeded but status-card close failed: ${O(o)}`),await w(this.chatId,`⚠️ ${d}
|
|
256
|
-
状态卡收尾失败: ${O(o)}`)}return!0}else{if($&&!X){if(Q?.("⚠️ 没有可恢复的上一会话,将以新会话启动"),P)await E(this.chatId,"⚠️ 没有可恢复的上一会话,将以新会话启动")}return this.resetFreshConversationState(),await this.startUnlocked({...Z,freshConversationStateAlreadyReset:!0})}}async startForked($,Z={}){return await this.runLifecycle("start-forked",async()=>{_0($,this.selectedProvider,this.workDir);let J=i4(this.sessionName),Y=this.selectedProvider==="claude"?{launch:$,previousSessionId:this.lastSessionId}:null;if(Y)J1(this.sessionName,Y),this.pendingConversationMaterialization=Y;this.pendingConversationLaunch=$;try{let Q=await this.startUnlocked(Z);if(!Q&&Y)J1(this.sessionName,J),this.pendingConversationMaterialization=J;return Q}catch(Q){if(!Y)throw Q;try{J1(this.sessionName,J),this.pendingConversationMaterialization=J}catch(V){throw AggregateError([Q,V],`fork start and pending-intent restore failed: ${O(Q)}; ${O(V)}`)}throw Q}finally{this.pendingConversationLaunch=null}})}async rollbackTo($,Z,J={}){return await this.runLifecycle("rollback",async()=>{_0($,this.selectedProvider,this.workDir);let Y=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,Q=this.proc,V=this.lastSessionId,H=this.lastSessionRef,X=l4(this.sessionName).slice(),z=d4(this.sessionName),W=i4(this.sessionName),G={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},B=!1,_=()=>{if(B)this.lastSessionId=null,this.lastSessionRef=null,C2(this.sessionName,"codex");else if(this.lastSessionId=V,this.lastSessionRef=H,H)u4(this.sessionName,H);else C2(this.sessionName,this.selectedProvider);e0(this.sessionName,X,z,W),this.pendingConversationMaterialization=W,this.turnCounter=G.turnCounter,this.currentGoal=G.currentGoal,this.cumStats=G.cumStats,this.lastTurnDelta=G.lastTurnDelta,this.currentTurnUsageBaseline=G.currentTurnUsageBaseline,this.currentTurnUsageBaselineKnown=G.currentTurnUsageBaselineKnown,this.lastTurnUsage=G.lastTurnUsage,this.usageTotalsSeedUnknown=G.usageTotalsSeedUnknown},j=!1;if(Y?.pendingLaunch)e0(this.sessionName,Y.anchors,Y.base,Y.pendingLaunch),this.pendingConversationMaterialization=Y.pendingLaunch,j=!0;this.pendingConversationLaunch=$;let q=(P)=>{B=H?.provider==="codex"&&H.sessionId===P};try{let P;try{P=$.kind==="fresh"?await this.restartUnlocked(!1,J,q):await this.restartUnlocked(!0,J,q)}catch(F){let T=null,M=this.proc&&this.proc!==Q?this.proc:null;if(M)try{await this.stopUnlocked("回滚启动事务失败",{announce:!1})}catch(b){T=b}let A=!M||this.proc!==M&&!M.isAlive();if(!A&&!T)T=Error("replacement process stop was not confirmed");let U=null;if(A)try{_()}catch(b){U=b}let S=[F,...T?[T]:[],...U?[U]:[]];if(S.length===1)throw F;throw AggregateError(S,`rollback launch and cleanup failed: ${S.map(O).join("; ")}`)}if(!P)return _(),!1;if(Y)try{if(!j)e0(this.sessionName,Y.anchors,Y.base,Y.pendingLaunch);this.pendingConversationMaterialization=Y.pendingLaunch}catch(F){let T=null,M=this.proc;try{await this.stopUnlocked("回滚分支状态持久化失败",{announce:!1})}catch(b){T=b}let A=!M||this.proc!==M&&!M.isAlive();if(!A&&!T)T=Error("replacement process stop was not confirmed");let U=null;if(A)try{_()}catch(b){U=b}let S=[F,...T?[T]:[],...U?[U]:[]];if(S.length===1)throw F;throw AggregateError(S,`rollback branch commit failed: ${S.map(O).join("; ")}`)}return P}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 Y=`拒绝了与当前会话不匹配的 checkpoint provider=${$.provider} source=${$.source.sessionId}`;return K(`session "${this.sessionName}": ${Y}`),this.lastTurnUserPreview="",Y}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((Q)=>Q.proc===Z).length>=64)return K(`session "${this.sessionName}": ${"Codex rollout 长期未确认,延迟 checkpoint 队列已满"} thread=${Z.sessionId}`),"Codex rollout 长期未确认,延迟 checkpoint 队列已满";return this.pendingCodexTurnAnchors.push({proc:Z,anchor:J}),K(`session "${this.sessionName}": defer Codex turn checkpoint until rollout confirmation thread=${Z.sessionId} checkpoint=${$.id}`),null}return this.appendTurnAnchor(J)}appendTurnAnchor($){try{return J5(this.sessionName,$),null}catch(Z){let J=`分叉 checkpoint 持久化失败: ${O(Z)}`;return K(`session "${this.sessionName}": ${J}`),J}}flushPendingCodexTurnAnchors($){let Z=null,J=[];for(let Y of this.pendingCodexTurnAnchors){if(Y.proc!==$||Z){J.push(Y);continue}if(Z=this.appendTurnAnchor(Y.anchor),Z)J.push(Y)}return this.pendingCodexTurnAnchors=J,Z}discardPendingCodexTurnAnchors($,Z){if($.provider!=="codex")return;let J=this.pendingCodexTurnAnchors.length;this.pendingCodexTurnAnchors=this.pendingCodexTurnAnchors.filter((Q)=>Q.proc!==$);let Y=J-this.pendingCodexTurnAnchors.length;if(Y>0)K(`session "${this.sessionName}": dropped ${Y} unmaterialized Codex checkpoint(s): ${Z}`)}collectTurnWrites(){let $=this.currentTurn;if(!$)return[];let Z=[];for(let J of $.toolByUseId.values())Z.push(...VZ(J.name,J.input));return Z}worktreeProjectName(){return B1(this)}worktreeProjectDir(){return $4(this)}spawnDeveloperInstructions($=this.getFileDeliveryMode()){return jW(this,$)}delegatedAgentDeveloperInstructions($){return LW(this,$)}worktreeInstructionLoadedNotice(){return PJ(this)}withWorktreeInstructionNotice($){return qW(this,$)}worktreeExtraInstruction(){return T9(this)}runWorktreeCommand($,Z){return PW(this,$,Z)}showWorktrees(){return FJ(this)}showTasklistPanel(){return hz(this)}showAgentIdentityPanel($=""){return xz(this,$)}onAgentIdentityPage($,Z,J){return Sz($,Z,J)}onTasklistEnable(){return Iz(this)}onTasklistDeletePrompt($){return gz(this,$)}onTasklistDeleteConfirm($){return mz(this,$)}runCompactCommand(){return qz(this)}showModelPanel(){return Fz(this)}onModelSelect($,Z="",J="",Y=null){return this.runLifecycle("model-select",()=>Nz(this,$,Z,J,Y))}onModelEffortSelect($,Z,J="",Y="",Q=""){return this.runLifecycle("model-effort-select",()=>YJ(this,$,Z,J,Y,Q))}onProviderSelect($,Z=""){return JJ(this,$,Z)}onModelPage($,Z,J){return w6(this,$,Z,J)}onModelAddOpen($,Z){return Dz(this,$,Z)}onModelListEdit($,Z,J,Y){return this.runLifecycle("model-list-edit",()=>Mz(this,$,Z,J,Y))}onModelPanelCancel($=""){return Oz(this,$)}onModelCustomPrompt($,Z,J=""){return Uz(this,$,Z,J)}consumeModelCustomMessage($,Z){return Az(this,$,Z)}onWorktreeDisband($){return DW(this,$)}showForkList($=""){return TW(this,$)}showBackList($=""){return EW(this,$)}showResumeList($=""){return xW(this,$)}runBtwCommand($){return SW(this,$)}runByeCommand(){return bW(this)}onForkSelect($,Z,J=""){return CW(this,$,Z,J)}onBackSelect($,Z,J=""){return kW(this,$,Z,J)}onResumeSelect($,Z,J=""){return yW(this,$,Z,J)}runCommand($,Z="",J){return jz(this,$,Z,J)}getFileDeliveryMode(){return r2.mode(this.chatId)}runFileDeliveryCommand($,Z){return az(this.chatId,this.sessionName,Z,$,{get:(J)=>r2.get(J),enable:(J,Y)=>r2.enable(J,Y),disable:(J)=>r2.disable(J),sendCard:(J)=>c(this.chatId,J),reportError:async(J)=>{if(K(`session "${this.sessionName}": ${J}`),!await E(this.chatId,J))throw Error(J)}})}async buildConsoleOpts($,Z){let J=await OH(),Y=this.runtimeModelSelection();return{sessionName:this.sessionName,status:this.status,provider:Y.provider,model:Y.model??void 0,effort:Y.effort??"MISS",worktreeInstructionNotice:this.worktreeInstructionLoadedNotice(),peers:[...G$.all].filter((Q)=>Q.isRunning()).map((Q)=>({...Q.peerSnapshot(),isCurrent:Q===this})),usage:$,glmUsage:Z,sysinfo:J}}async buildConsoleCard($){return i5(await this.buildConsoleOpts($))}async patchConsoleUsage($){let Z=await this.buildConsoleOpts(void 0),J=Z.provider??this.currentProvider(),Y=this.currentTokenSource(),Q=Y&&Y.agent===J&&Y.enabled?Y:this.selectedTokenSourceId?void 0:F8(J)[0];if(Q)Z.unifiedUsage=await Q.readUsage();else if(this.selectedTokenSourceId)Z.unifiedUsage={state:"no_credentials",windows:[],reason:`token source ${this.selectedTokenSourceId} unavailable`};else if(Z.provider==="claude")Z.glmUsage=await sH();else Z.usage=await E1(this.codexAccountId());if(!await M0($,N.consoleUsage,K9(Z),{notifyCardFailure:!1}))throw Error("console usage element replace rejected")}async mutateStaticCard($,Z,J){let Y=!0;try{await J()}catch(V){Y=!1,K(`session "${this.sessionName}": ${Z} mutation failed: ${O(V)}`)}let Q=!1;try{Q=await P0($,{config:{streaming_mode:!1}})}catch(V){K(`session "${this.sessionName}": ${Z} streaming-off failed: ${O(V)}`)}if(!Y||!Q)return K(`session "${this.sessionName}": ${Z} state retained after checked MISS mutation=${Y} streamingOff=${Q} card=${$.slice(0,12)}`),!1;try{await v0($)}catch(V){return K(`session "${this.sessionName}": ${Z} dispose failed: ${O(V)}`),!1}return Y}patchConsoleUsageLater($){this.mutateStaticCard($,"console usage",()=>this.patchConsoleUsage($))}async replaceStatusCardWithConsole($,Z){$.timer.stop();let J=$.timer.elapsedSec(),Y=await this.buildConsoleOpts(void 0);await O$($.cardId);let Q=await M0($.cardId,N.footer,W6(Y,N.footer)),V=await Y1($.cardId,z6(Y),{type:"insert_after",targetElementId:N.footer}),H=await Y1($.cardId,G6(Y.sysinfo),{type:"insert_after",targetElementId:N.consoleProjects}),X=await Y1($.cardId,K9(Y),{type:"insert_after",targetElementId:N.consoleHost});if(!Q||!V||!H||!X){await w(this.chatId,"⚠️ 控制台卡片结构写入失败,请重新发送 hi。"),await this.mutateStaticCard($.cardId,"console structure",async()=>{});return}A0($.cardId),await P0($.cardId,h$({durationSec:J,suffix:Z})),this.patchConsoleUsageLater($.cardId)}async showConsole(){let $=await this.buildConsoleCard(void 0),Z=await c(this.chatId,$);if(!Z)return;(async()=>{let J="";try{J=await Z$(Z),d0(J,4)}catch(Y){K(`session "${this.sessionName}": console card conversion failed: ${O(Y)}`);return}await this.mutateStaticCard(J,"console usage",()=>this.patchConsoleUsage(J))})().catch((J)=>K(`session "${this.sessionName}": console async update rejected: ${O(J)}`))}interrupt(){if(!this.proc)return;K(`session "${this.sessionName}": interrupt`),this.proc.sendInterrupt()}sendClaimedUserText($,Z){let J=this.currentTurn,Y=J?J.fileDeliveryMode??=this.getFileDeliveryMode():this.getFileDeliveryMode(),Q=this.procFileDeliveryModes.get($),V=Q===Y?"":`${ez(Y)}
|
|
247
|
+
${G}`)}return{slug:Y,chatName:V,branch:Q,worktreePath:z,removedWorktree:!1}}function _J($){if(!o1($))throw Error(`project directory does not exist: ${$}`);let Z=R0($,["rev-parse","--show-toplevel"]).trim();if(KJ(Z)!==KJ($))throw Error(`${$} is not the git repository root (${Z})`)}function zW($,Z){let J=R0($,["rev-parse","--abbrev-ref","HEAD"]).trim();if(J!==Z)throw Error(`${$} is on ${J}, expected ${Z}`)}function EF($,Z,J){let Y=xF($);if(!Y?.startsWith(s2))return null;let Q=Y.slice(s2.length);if(!r1(Q))throw Error(`invalid worktree branch "${Y}"`);let V=e2(Z,J,Q);if(c6($)!==c6(V))return null;let H=bF($,SF(Q));return H?{path:H,slug:Q}:null}function xF($){if(!o1($))return null;try{return R0($,["branch","--show-current"]).trim()||null}catch(Z){if(kF(Z))return null;throw Z}}function SF($){return $.split("-",1)[0]??$}function bF($,Z){let J=`agents.${Z}.md`,Y=AF($).filter((Q)=>Q.toLowerCase()===J).sort();if(Y.length>1)throw Error(`multiple worktree instruction files match ${J}: ${Y.join(", ")}`);return Y[0]?ZW($,Y[0]):null}function CF($,Z){try{return R0($,["show-ref","--verify","--quiet",`refs/heads/${Z}`]),!0}catch{return!1}}function WW($,Z,J){let Y=R0($,["rev-parse",Z]).trim(),Q=R0($,["rev-parse","HEAD"]).trim();if(Y===Q)return J?"active":"merged";if($W($,Z,"HEAD"))return"merged";if($W($,"HEAD",Z))return"active";return"stale"}function $W($,Z,J){try{return R0($,["merge-base","--is-ancestor",Z,J]),!0}catch{return!1}}function jJ($){let Z=new Map,J=R0($,["worktree","list","--porcelain"]),Y="";for(let Q of J.split(`
|
|
248
|
+
`)){if(Q.startsWith("worktree ")){Y=Q.slice(9);continue}if(Q.startsWith("branch refs/heads/")&&Y)Z.set(Q.slice(18),Y)}return Z}function R0($,Z){try{return UF("git",Z,{cwd:$,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}catch(J){throw Error(LJ(J))}}function LJ($){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 kF($){return/not a git repository/i.test(LJ($))}var s2="work/",TF,p6;var GW=R(()=>{TF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/,p6=new Map});function B1($){return JW(U$($.sessionName)??$.sessionName)}function $4($){return y8(B1($))}function BW($){let Z=U$($.sessionName)??$.sessionName,J=B1($),Y=y8(J);if(J===Z)return Y;let Q=Z.slice(J.length+1,-1);return e2(Y,J,Q)}function _W($,Z,J=$.currentProvider()){let Y=sz(J,Z),Q=T9($);return Q?`${Y}
|
|
249
|
+
${Q}`:Y}function jW($,Z){return T9($)??""}function qJ($){return T9($)?"已载入wt特殊约定":null}function LW($,Z){let J=qJ($);return J?`${Z}
|
|
250
|
+
${J}`:Z}function T9($){let Z=B1($),J=QW($.workDir,$4($),Z);if(!J)return null;return[`你要把下面这份额外的工作树约定视为和AGENTS.md一样重要。来源文件:${J.path}`,"",`# Additional AGENTS.md instructions for ${$.workDir}`,"","<INSTRUCTIONS>",J.content,"</INSTRUCTIONS>"].join(`
|
|
251
|
+
`)}async function qW($,Z,J){if(!Z){await PJ($);return}let Y=r1(Z);if(!Y){await E($.chatId,"❌ 名称无效。用英文/数字/._-,最长 63。");return}if(!J){await E($.chatId,"❌ 找不到发起人,不能拉群。");return}let Q=B1($),V=$4($);try{await u6(V,async()=>{let H;try{H=HW(V,Q,Y)}catch(X){await E($.chatId,`❌ wt 失败: ${O(X)}`);return}try{let X=await W5(H.chatName,J),z=X.created?"已创建":X.joined?"已加入":"已在群内";if(!await c($.chatId,B9({slug:Y,branch:H.branch,status:z})))await w($.chatId,`❌ wt 卡片失败: ${Y}`);if(!await c(X.chatId,B9({slug:Y,branch:H.branch,status:"就绪",body:"开始吧。"})))await w(X.chatId,`❌ wt 卡片失败: ${Y}`)}catch(X){await E($.chatId,`❌ wt 已建,拉群失败: ${O(X)}`)}})}catch(H){await E($.chatId,`❌ wt 失败: ${O(H)}`)}}async function PW($,Z){let J=B1($),Y=$4($);return await u6(Y,async()=>{return await wF(J,Y,Z)})}async function wF($,Z,J){let Y=VW(Z,$),Q=Y.filter((X)=>X.state==="merged"&&!X.mounted).length,V=Y.filter((X)=>X.state!=="merged"||X.mounted),H=await v8();return s5({projectName:$,projectDir:Z,hiddenMergedUnmountedCount:Q,notice:J,entries:V.map((X)=>{let z=H.get(X.chatName)??[],W=L0.get(X.chatName),G=W&&z.includes(W)?W:z.length===1?z[0]:null;return{slug:X.slug,chatName:X.chatName,branch:X.branch,state:X.state,path:X.worktreePath??X.expectedPath,mounted:X.mounted,dirtyCount:X.dirtyCount,statusLine:X.statusLine,error:X.error,chatId:G,duplicateChatCount:z.length}})})}async function PJ($){try{let Z=await PW($);if(!await c($.chatId,Z))await w($.chatId,"❌ wt 列表失败")}catch(Z){await E($.chatId,`❌ wt 列表失败: ${O(Z)}`)}}async function KW($,Z,J,Y){try{return{ok:Z,message:J,card:await PW($,{type:Y,content:J})}}catch(Q){let V=`列表刷新失败: ${O(Q)}`;return K(`session "${$.sessionName}": wt action panel refresh failed: ${O(Q)}`),{ok:!1,message:`${J}
|
|
252
|
+
${V}`,card:B9({slug:"wt",branch:"work/*",status:J,body:V,template:"red"})}}}async function DW($,Z){let J=r1(Z);if(!J)return KW($,!1,"❌ 名称无效","error");let Y=B1($),Q=$4($),V;try{V=await u6(Q,async()=>{let H=t2(Y,J);if($.hasRunningPeerSession(H))return{ok:!1,message:`❌ 解散 ${J} 失败: Codex 正在运行,请先在 ${H} 群里 stop 或 kill。`,type:"error"};BJ(Q,Y,J);let X=await K5(H),z=XW(Q,Y,J);return{ok:!0,message:[`✅ ${J} 已解散`,z.removedWorktree?"dir removed":"dir missing",X.disbanded?"group removed":"group missing",z.branch].join(`
|
|
253
|
+
`),type:"success"}})}catch(H){V={ok:!1,message:`❌ 解散 ${J} 失败: ${O(H)}`,type:"error"}}return KW($,V.ok,V.message,V.type)}var FW=R(()=>{m6();Y$();t();I();GW()});import{closeSync as fF,openSync as hF,readSync as IF,readdirSync as gF,statSync as mF}from"node:fs";import{randomUUID as FJ}from"node:crypto";import{join as pF}from"node:path";function d6($){return U$($.sessionName)??$.sessionName}function UW($){let Z=J5($,DJ);return DJ.add(Z),Z}function AW($){DJ.delete($)}function Z4($){let Z=MW.get($);if(!Z)Z=new Map,MW.set($,Z);let J=Date.now();for(let[Y,Q]of Z){let V=Q.status==="consumed"?lF:uF,H=Q.consumedAt??Q.createdAt;if(J-H>V)Z.delete(Y)}return Z}function iF($,Z){return $.provider===Z.provider&&($.codexAccountId??"default")===(Z.codexAccountId??"default")&&!!$.codexAccountAutomatic===!!Z.codexAccountAutomatic&&$.tokenSourceId===Z.tokenSourceId&&$.model===Z.model&&$.effort===Z.effort}function OW($,Z,J,Y){let Q={id:FJ(),mode:Z,requesterOpenId:J,provider:$.selectedProvider,sourceSessionId:$.lastSessionId,workDir:$.workDir,baseName:d6($),routing:$.conversationRouting(),createdAt:Date.now(),status:"open",choices:Y};return Z4($).set(Q.id,Q),Q}function MJ($,Z,J,Y,Q){let V=Z4($).get(J);if(!V||V.mode!==Z)return{error:"这张选择卡已过期,请重新发送命令"};if(!Q||V.requesterOpenId!==Q)return{error:"只有打开这张选择卡的用户可以执行;请自行发送命令重新打开"};if(V.status!=="open")return{error:"这张选择卡已执行或正在处理,请勿重复点击"};if(V.provider!==$.selectedProvider||V.workDir!==$.workDir||V.sourceSessionId!==$.lastSessionId||!iF(V.routing,$.conversationRouting()))return{error:"这张卡对应的 provider、目录或源会话已经变化,请重新发送命令"};let H=V.choices.get(Y);if(!H)return{error:"无效的选择项,这张卡可能已过期"};return V.status="processing",{panel:V,choice:H}}function l6($){$.status="consumed",$.consumedAt=Date.now()}function nF($){return{kind:"fork",source:$.source,through:$}}function aF($){return l4($.sessionName).filter((Z)=>Z.checkpoint.provider===$.selectedProvider&&Z.checkpoint.source.cwd===$.workDir)}function oF($){let Z=d4($.sessionName);if(Z===null||Z.kind==="fresh")return Z;try{return _0(Z,$.selectedProvider,$.workDir),Z}catch{return null}}function rF($){let Z=_8($),J;try{J=gF(Z)}catch(Q){if(Q?.code==="ENOENT")return[];throw Error(`读取 Claude 会话目录失败: ${Q?.message??Q}`)}let Y=[];for(let Q of J){if(!Q.endsWith(".jsonl"))continue;let V=Q.slice(0,-6);if(H2("claude",V))continue;let H=pF(Z,Q),X;try{X=mF(H).mtimeMs}catch(z){throw Error(`读取 Claude 会话元数据失败 (${Q}): ${z?.message??z}`)}Y.push({provider:"claude",sessionId:V,cwd:$,preview:tF(H),ts:X})}return Y.sort((Q,V)=>V.ts-Q.ts)}function sF($){let Z=$.slice().sort((Q,V)=>V.ts-Q.ts),J=Date.now()-cF,Y=Z.filter((Q)=>Q.ts>=J).length;return Z.slice(0,Math.min(dF,Math.max(10,Y)))}function tF($){let Z="",J=null;try{J=hF($,"r");let Q=Buffer.alloc(65536),V=IF(J,Q,0,65536,0);Z=Q.subarray(0,V).toString("utf8")}catch(Q){throw Error(`读取 Claude 会话摘要失败 (${$}): ${Q?.message??Q}`)}finally{if(J!==null)fF(J)}let Y="";for(let Q of Z.split(`
|
|
254
|
+
`)){let V=Q.trim();if(!V)continue;let H;try{H=JSON.parse(V)}catch{continue}if(H.type==="queue-operation"&&H.operation==="enqueue"&&typeof H.content==="string"){let X=H.content.trim();if(X)return X.slice(0,80)}if(!Y&&H.type==="user"&&H.message){let X=eF(H.message);if(X)Y=X}}return Y.slice(0,80)}function eF($){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 RW($,Z,J){if(!J){await E($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let Y=aF($),Q=oF($),V=new Map,H=[];for(let G=0;G<Y.length;G++){let B=Y[G];if(G===0&&Q===null)continue;let _=FJ(),j=G===0?Q:nF(Y[G-1].checkpoint);V.set(_,{kind:Z,launch:j,branchBase:Q,seedAnchors:Y.slice(0,G),writes:Y.slice(G).flatMap((q)=>q.writes)}),H.push({choiceId:_,preview:B.preview,ts:B.ts})}H.reverse();let X=OW($,Z,J,V),z=e5({projectName:d6($),panelId:X.id,mode:Z,entries:H}),W;try{W=await c($.chatId,z)}catch(G){throw Z4($).delete(X.id),G}if(!W)Z4($).delete(X.id),await w($.chatId,`❌ ${Z==="fork"?"fk":"bk"} 列表发送失败`)}function NW($,Z){return RW($,"fork",Z)}function TW($,Z){return RW($,"back",Z)}async function EW($,Z){if(!Z){await E($.chatId,"❌ 找不到发起人,无法创建安全选择卡。");return}let J;try{J=$.selectedProvider==="codex"?await $.listCodexConversations():$.selectedProvider==="dsh"?await $.listDshConversations():rF($.workDir)}catch(z){await w($.chatId,`❌ 历史会话读取失败: ${z instanceof Error?z.message:z}`);return}let Y=new Map,Q=sF(J).map((z)=>{let W=FJ();return Y.set(W,{kind:"resume",launch:{kind:"fork",source:{provider:z.provider,sessionId:z.sessionId,cwd:z.cwd}},sourcePreview:z.preview,sourceTs:z.ts,sourceStatus:z.status}),{choiceId:W,preview:z.preview,ts:z.ts}}),V=OW($,"resume",Z,Y),H=$Z({projectName:d6($),panelId:V.id,entries:Q}),X;try{X=await c($.chatId,H)}catch(z){throw Z4($).delete(V.id),z}if(!X)Z4($).delete(V.id),await w($.chatId,"❌ rs 历史列表发送失败")}async function xW($,Z){if(!Z){await E($.chatId,"❌ 找不到发起人,无法建临时群。");return}if(!$.opts.onCreateTempSession){await E($.chatId,"❌ 临时群能力未就绪(daemon 未注入回调)。");return}let J=UW(d6($));await E($.chatId,`\uD83D\uDE80 正在创建 ${J} · ${$.backendLabel()} 新会话。它与当前群共享工作目录;当前会话不受影响。`);let Y;try{Y=await $.opts.onCreateTempSession({chatName:J,userOpenId:Z,workDir:$.workDir,routing:$.conversationRouting(),launch:{kind:"fresh"},branchBase:{kind:"fresh"},seedAnchors:[]})}finally{AW(J)}if(!Y.ok){await E($.chatId,`❌ 建临时会话失败: ${Y.error??"未知"}`);return}await E($.chatId,`✅ 已创建 ${J}。临时群不会自动删除;在该群发送 bye 可停止并解散。`)}async function SW($){if(!U$($.sessionName)){await E($.chatId,"❌ bye 只能在带 *MMDD-HHMM 后缀的临时会话群里使用。");return}if(!$.opts.onDisbandTempSession){await E($.chatId,"❌ 解散能力未就绪(daemon 未注入回调)。");return}await E($.chatId,`\uD83D\uDC4B 正在停止会话并解散 ${$.sessionName}…`);let Z=await $.opts.onDisbandTempSession($.sessionName,$.chatId);if(!Z.ok)await E($.chatId,`❌ 解散失败: ${Z.error??"未知"}`)}async function bW($,Z,J,Y){let Q=MJ($,"fork",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;try{if(H.kind!=="fork")return{ok:!1,message:"选择项类型不匹配"};if(!$.opts.onCreateTempSession)return{ok:!1,message:"临时群能力未就绪"};let X=UW(V.baseName);K(`session-temp: fork ${$.sessionName} → ${X} (${H.launch.kind})`),await E($.chatId,`\uD83D\uDD31 正在分叉到 ${X}…`);let z;try{z=await $.opts.onCreateTempSession({chatName:X,userOpenId:Y,workDir:V.workDir,routing:V.routing,launch:H.launch,branchBase:H.branchBase,seedAnchors:H.seedAnchors})}finally{AW(X)}if(!z.ok)return{ok:!1,message:`分叉失败: ${z.error??"未知"}`};return{ok:!0,message:`已分叉到 ${X};原会话和磁盘文件未回滚`}}catch(X){return{ok:!1,message:`分叉失败: ${X instanceof Error?X.message:X}`}}finally{l6(V)}}async function CW($,Z,J,Y){let Q=MJ($,"back",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;try{if(H.kind!=="back")return{ok:!1,message:"选择项类型不匹配"};let X="";try{if(!await c($.chatId,ZZ({projectName:V.baseName,entries:H.writes})))X=";文件变更记录卡发送失败"}catch(G){X=`;文件变更记录卡发送失败: ${G instanceof Error?G.message:G}`}if(K(`session-temp: back ${$.sessionName} (${H.launch.kind}, writes=${H.writes.length})`),!await $.rollbackTo(H.launch,{anchors:H.seedAnchors,base:H.branchBase}))return{ok:!1,message:`回退失败;原会话绑定未改,请检查日志后重试${X}`};if(V.routing.provider==="claude")return{ok:!0,message:`本群已准备 Claude 新分支;发送下一条消息时生成并接入,旧会话未删除,磁盘文件未回滚${X}`};return{ok:!0,message:`本群已改接新会话${$.lastSessionId?` ${U0($.lastSessionId)}`:""};旧会话未删除,磁盘文件未回滚${X}`}}catch(X){return{ok:!1,message:`回退失败: ${X instanceof Error?X.message:X}`}}finally{l6(V)}}async function kW($,Z,J,Y){let Q=MJ($,"resume",Z,J,Y);if("error"in Q)return{ok:!1,message:Q.error,replaceCard:!1};let{panel:V,choice:H}=Q;if(H.kind!=="resume")throw l6(V),Error("resume panel contained a non-resume choice");let X=H.launch.source.sessionId,z=$.lastSessionId,W=(B,_)=>({projectName:V.baseName,provider:H.launch.source.provider,selectedPreview:H.sourcePreview,selectedTs:H.sourceTs,sourceSessionId:X,...H.sourceStatus?{sourceStatus:H.sourceStatus}:{},previousSessionId:z,newSessionId:B,bindingState:_}),G=(B,_,j,q=null)=>({ok:B,message:_,resumePresentation:W(q,j)});try{if($.isRunning())return G(!1,"当前群已经启动了新进程;为避免误杀,请先停止后重新发送 rs","unchanged");if(H.sourceStatus==="active")return G(!1,"所选 Codex 会话仍在运行;请先在原位置停止后再创建完整分支","unchanged");if(K(`session-temp: history fork ${$.sessionName} ← ${H.launch.source.provider} ${X}`),!await $.rollbackTo(H.launch,{anchors:[],base:H.launch,pendingLaunch:H.launch.source.provider==="claude"?{launch:H.launch,previousSessionId:z}:null}))return G(!1,"历史分支创建失败;原会话绑定未改,请检查日志后重试","unchanged");if(H.launch.source.provider==="claude")return G(!0,"Claude 独立分支已准备;首条消息时生成并接入新会话","prepared");let _=$.lastSessionId;if(!_)return G(!1,"历史分支已启动,但后端没有返回新会话 id","unknown");if(_===X||z&&_===z)return G(!1,"后端没有返回独立的新会话 id;为避免误判,本次不标记为恢复成功","unknown",_);return G(!0,"已创建并接入独立分支;源会话未修改","changed",_)}catch(B){return G(!1,`历史分支创建失败: ${B instanceof Error?B.message:B}`,"unknown")}finally{l6(V)}}var cF=86400000,uF=1800000,lF=3600000,dF=40,MW,DJ;var yW=R(()=>{t();Y$();I();x4();L4();A1();MW=new WeakMap,DJ=new Set});import{existsSync as wW}from"node:fs";import{randomBytes as ZM,timingSafeEqual as JM}from"node:crypto";import{isAbsolute as YM}from"node:path";function AJ($,Z=new Set){if($ instanceof B2)return $;if(!$||typeof $!=="object"&&typeof $!=="function"||Z.has($))return null;if(Z.add($),$ instanceof AggregateError)for(let J of $.errors){let Y=AJ(J,Z);if(Y)return Y}if($ instanceof Error&&$.cause!==void 0)return AJ($.cause,Z);return null}function QM($){return $.itemId||$.turnId||"__latest__"}function vW($){let Z=[];if($.itemId)Z.push(`item:${$.itemId}`);if($.turnId)Z.push(`turn:${$.threadId??$.sessionId??"-"}:${$.turnId}`);return Z}function VM($){let Z=null;for(let J of $.contextCompactionPending.keys())Z=J;return Z}function HM($,Z){if(!$)return Z;return{...$,...Z,phase:"end"}}function s1(){return f.runtime?.live_elapsed??"bucket"}function IW($,Z){return`${$} (${t$(Date.now()-Z,s1()).label})`}var fW="Thinking...",XM="Writing...",zM="Working...",UJ=1e4,i6=720000,WM=50,GM=256,n6=1e4,hW=250,G$;var YJ=R(()=>{L4();P4();D0();O1();B3();D0();y0();k3();V0();p0();T2();x4();v$();Y$();t();I();Q0();u5();w$();q9();PZ();YX();qX();CX();R6();wX();jz();qz();Nz();Cz();mz();iz();az();m6();FW();yW();A1();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;currentTurn=null;contextCompactionReceipts=new Map;contextCompactionOwnerIds=new WeakMap;contextCompactionOwnerSequence=0;lastManualContextCompactionCompletedAt=0;lastManualContextCompactionWasAnonymous=!1;backgroundTasks=[];pendingBgTasks=[];backgroundCard=null;settlingBackgroundCard=!1;migratingBackgroundCard=null;backgroundRefreshTimer=null;backgroundRefreshTick=null;openingBackground=!1;openingBackgroundOwner=null;backgroundOpenSequence=0;backgroundGeneration=0;backgroundDetailAdded=new Set;backgroundDetailAdding=new Set;lastMainTaskToolUseId=null;pendingRebuildBackgroundCard=!1;bgResumePending=!1;orphanAssistantSegments=[];orphanAssistantCurrent="";bgResumeCardless=!1;pendingPermissions=new Map;pendingAsks=new Map;currentGoal=null;status="stopped";pendingUserMessageCount=0;pendingMidTurnMsgs=[];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;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;G$.all.add(this);let Y=V5($);this.selectedProvider=Y?.provider??"claude",this.selectedModel=Y?.model??null,this.selectedEffort=Y?.effort??null,this.selectedTokenSourceId=this.deriveTokenSourceId(Y);let Q=q$(this.selectedTokenSourceId);if(Q){if(this.selectedProvider=Q.agent,Q.id==="glm"&&this.selectedModel==="claude:glm")this.selectedModel=Q.defaultModel,this.selectedEffort="max"}if(this.selectedModel)K(`session "${$}": restored selected provider=${this.selectedProvider} model=${this.selectedModel} effort=${this.selectedEffort??"unset"}`);if(this.lastSessionRef=Z1($,this.selectedProvider),this.lastSessionId=this.lastSessionRef?.sessionId??null,this.lastSessionId)K(`session "${$}": restored ${this.selectedProvider} lastSessionId=${this.lastSessionId}`);let V=i4($);if(V)if(this.selectedProvider!=="claude")e0($,[],null,null),K(`session "${$}": cleared pending Claude fork after provider changed`);else{_0(V.launch,"claude",this.workDir);let H=this.lastSessionId===V.previousSessionId,X=this.lastSessionRef,z=!H&&X?.provider==="claude"&&X.cwd===this.workDir&&X.sessionId!==V.launch.source.sessionId&&X.sessionId!==V.previousSessionId;if(!H&&!z)throw Error(`pending Claude fork has inconsistent resume binding for session "${$}"`);this.pendingConversationMaterialization=V,K(`session "${$}": restored ${z?"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.proc.codexAccountSelectionMode?.()!==null&&!(this.proc.turnRetry?.reason==="quota"&&this.proc.turnRetry.phase==="waiting")?{codexAccountName:k.get(r0(this.proc)).name}:{}}}get workDir(){return BW(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 P8(J)[0]?.id??null}currentTokenSource(){return this.tokenSource(this.selectedTokenSourceId)}codexStartAccountOverride;codexAccountId(){return this.proc?.isAlive()&&this.proc.provider==="codex"?r0(this.proc):this.codexStartAccountOverride??k.selected(this.sessionName)}tokenSource($){let Z=q$($);return Z?.forAccount?H0($,this.codexAccountId()):Z}currentProvider(){return this.selectedProvider}conversationRouting(){return{provider:this.selectedProvider,tokenSourceId:this.selectedTokenSourceId,model:this.selectedModel,effort:this.selectedEffort,...this.codexAccountId()===u?{}:{codexAccountId:this.codexAccountId()},...k.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");if($.codexAccountId)k.get($.codexAccountId);let Z=q$($.tokenSourceId);if(Z&&Z.agent!==$.provider)throw Error(`token source "${Z.id}" belongs to ${Z.agent}, not ${$.provider}`);if(this.selectedProvider!==$.provider)e0(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;this.selectedProvider=$.provider,this.selectedTokenSourceId=$.tokenSourceId,this.selectedModel=$.model,this.selectedEffort=$.effort,this.lastSessionRef=Z1(this.sessionName,$.provider),this.lastSessionId=this.lastSessionRef?.sessionId??null,b1(this.sessionName,$.provider,$.model,$.effort,$.tokenSourceId);let J=$.codexAccountId??u;if($.codexAccountAutomatic)k.selectAuto(this.sessionName);else if(k.selected(this.sessionName)!==J)k.select(this.sessionName,J)}dshEffortForSpawn(){if(B0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource(),Z=$&&L$($,this.selectedModel??$.defaultModel);if(!Z||!B0(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 X2({cwd:this.workDir,env:$.spawnEnv(process.env),profile:{loadProjectMcp:!1}},"session/list",{cwd:this.workDir})).filter((J)=>!H2("dsh",J.sessionId))}async listCodexConversations(){if(this.selectedProvider!=="codex")throw Error("Codex history requested for a non-Codex session");if(!r4(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");let $=this.currentTokenSource();if(this.selectedTokenSourceId&&(!$||!$.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Z=$?.enabled?$:void 0,J=Z?(X)=>Z.spawnEnv(X):void 0,Y=new _2({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Z?.id??null,transformEnv:J}),Q=null,V=null;try{Q=await Y.listConversations()}catch(X){V=X}let H=null;try{await Y.kill(2000)}catch(X){H=X}if(V&&H)throw AggregateError([V,H],`Codex history query and cleanup failed: ${O(V)}; ${O(H)}`);if(V)throw V;if(H)throw H;return Q??[]}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=j8(this.workDir,$.sessionId);if(!wW(J))throw Error(`旧 Claude 会话不属于当前 cwd,或 transcript 不存在: ${U0($.sessionId)}`);Z={...$,cwd:this.workDir}}else{if(!r4(this.codexAccountId()))throw Error("Codex 未登录 ChatGPT 账号");let J=this.currentTokenSource();if(this.selectedTokenSourceId&&(!J||!J.enabled))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或选择其他账号`);let Y=J?.enabled?J:void 0,Q=new _2({workDir:this.workDir,codexAccountId:this.codexAccountId(),launch:{kind:"fresh"},tokenSourceId:Y?.id??null,transformEnv:Y?(X)=>Y.spawnEnv(X):void 0}),V=null;try{Z=await Q.readConversationRef($.sessionId)}catch(X){V=X,Z=$}let H=null;try{await Q.kill(2000)}catch(X){H=X}if(V&&H)throw AggregateError([V,H],`Codex legacy resume lookup and cleanup failed: read=${O(V)}; cleanup=${O(H)}`);if(V)throw V;if(H)throw H}return _0({kind:"resume",source:Z},this.selectedProvider,this.workDir),u4(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 s0(this.selectedEffort)?this.selectedEffort:O4}return O4}claudeEffortForSpawn(){if(this.selectedProvider==="claude"&&E0(this.selectedEffort))return this.selectedEffort;let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude"){let Z=L$($,this.selectedModel??$.defaultModel);if(!E0(Z?.defaultEffort))throw Error("Claude 默认 effort MISS,请通过 model 面板明确选择");return Z.defaultEffort}return a$}currentModelLabel(){return(this.selectedModel??this.currentTokenSource()?.defaultModel??this.proc?.lastModel??null)?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null}currentEffortLabel(){let $=this.currentTokenSource();if(this.selectedProvider==="claude"&&$?.agent==="claude")return this.selectedEffort??L$($,this.selectedModel??$.defaultModel)?.defaultEffort??null;return this.selectedEffort??(this.selectedProvider==="dsh"?this.dshEffortForSpawn():void 0)??this.proc?.lastEffort??(this.selectedProvider==="claude"?a$:O4)}runtimeModelSelection(){let $=this.proc?.isAlive()?this.proc:null,Z=$?.provider??this.selectedProvider,J=!$||$.provider===this.selectedProvider,Y=($?.lastModel??(J?this.currentModelLabel():null))?.replace(/^claude:/i,"").replace(/\[1m\]$/i,"")??null,Q=$?.lastEffort??(J?this.currentEffortLabel():Z==="claude"?a$:O4);return{provider:Z,model:Y,effort:Q}}withModel($,Z){let J=this.modelLine(Z);return $.includes(J)?$:`${$} · ${J}`}replaceFooterContent($,Z){return J0($,N.footer,this.footerElement(Z),void 0,!1)}footerElement($){return{tag:"markdown",element_id:N.footer,content:$.trim()||" "}}modelLine($=this.currentTurn??this.runtimeModelSelection()){return O5($.provider,$.model,$.effort)}backendLabel($=this.selectedProvider){return _$($)}pendingConversationLaunch=null;pendingConversationMaterialization=null;lastTurnUserPreview="";pendingCodexTurnAnchors=[];pendingMaterializationLaunch(){let $=this.pendingConversationMaterialization;if(!$)return null;if(_0($.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($){this.agentCapability=ZM(32).toString("base64url");let Z={LODESTAR_AGENT_URL:R8(f.notify.bind,f.notify.port),LODESTAR_AGENT_CAPABILITY:this.agentCapability,LODESTAR_AGENT_SESSION:this.sessionName,LODESTAR_AGENT_ROLE:"main"},J=this.pendingConversationLaunch??this.pendingMaterializationLaunch()??($?{kind:"resume",source:$}:{kind:"fresh"});_0(J,this.selectedProvider,this.workDir);let Y=this.currentTokenSource(),Q=this.selectedProvider==="codex"&&this.selectedTokenSourceId==="codex-sub";if(this.selectedTokenSourceId&&(!Y||!Y.enabled&&!Q))throw Error(`token source "${this.selectedTokenSourceId}" 不可用,请重新配置或在 model 面板选择其他账号`);let V=Y?.enabled||Q?Y:void 0,H=this.currentTurn?.fileDeliveryMode??this.getFileDeliveryMode(),X=v4({provider:this.selectedProvider,workDir:this.workDir,tokenSourceId:V?.id??null,...this.selectedProvider==="codex"?{codexAccountId:k.selected(this.sessionName)}:{},...Q?{codexAccountPreference:this.codexStartAccountOverride??k.preferred(this.sessionName)}:{},model:V?this.selectedModel??V.defaultModel:this.modelForSpawn(),effort:this.selectedProvider==="dsh"?this.dshEffortForSpawn():this.selectedProvider==="claude"?this.claudeEffortForSpawn():this.effortForSpawn(),launch:J,developerInstructions:this.spawnDeveloperInstructions(H),profile:b2(this.worktreeProjectName()),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:D1},hostEnv:Z});return this.procSourceRevisions.set(X.process,X.sourceRevision),this.procFileDeliveryModes.set(X.process,H),X.process}async applyModelSelection($,Z,J,Y){await this.runLifecycle("apply-model-selection",()=>this.applyModelSelectionUnlocked($,Z,J,Y))}async applyModelSelectionUnlocked($,Z,J,Y){if(this.selectedProvider!==$)e0(this.sessionName,[],null,null),this.pendingConversationMaterialization=null;this.selectedProvider=$,this.selectedTokenSourceId=Y??this.selectedTokenSourceId;let V=q$(this.selectedTokenSourceId);if(V)this.selectedModel=Z||null,this.selectedEffort=J??L$(V,Z||V.defaultModel)?.defaultEffort??null;else this.selectedModel=$==="codex"?null:Z,this.selectedEffort=$==="codex"?null:J;this.lastSessionRef=Z1(this.sessionName,$),this.lastSessionId=this.lastSessionRef?.sessionId??null,Q5(this.sessionName,$,this.selectedModel,this.selectedEffort,this.selectedTokenSourceId),await this.stopIdleMismatchedProcessUnlocked()}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()===F2($,Z);return!this.proc||!this.procSourceRevisions.has(this.proc)||this.procSourceRevisions.get(this.proc)===F2($,Z)}async stopIdleMismatchedProcessUnlocked(){if(!this.proc?.isAlive())return;let $=this.currentTokenSource(),Z=this.processSourceMatches($,this.selectedModel);if(this.proc.provider===this.selectedProvider&&this.proc.tokenSourceId===this.selectedTokenSourceId&&Z)return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0)return;let J=this.proc;K(`session "${this.sessionName}": stop idle ${J.provider} process after switching to ${this.selectedProvider}`),this.beginProcStop(J),this.initCount=0,this.bgResumePending=!1,this.discardOrphanAssistant(),this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1,this.usageTotalsSeedUnknown=!1,this.status="stopped";let Y=await this.settleProcResumableState(J),Q=null;try{await J.kill(1000)}catch(X){Q=X}Y=await this.settleProcResumableState(J);let V=this.finishProcStop(J,Q);this.opts.onLifecycleChange?.();let H=[...!V?[Q??Error(this.blockedProcReason??"process stop unconfirmed")]:[],...Y?[Error(Y)]:[]];if(H.length===1)throw H[0];if(H.length>1)throw AggregateError(H,`idle process stop failed: ${H.map(O).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;K(`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),Y=null;try{await Z.kill(1000)}catch(H){Y=H}J=await this.settleProcResumableState(Z);let Q=this.finishProcStop(Z,Y);this.opts.onLifecycleChange?.();let V=[...!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(O).join("; ")}`);return!0}startFooterTimer($,Z,J=(Y)=>Y){let Y=Date.now(),Q=Z,V=!1,H=()=>{if(V)return;this.replaceFooterContent($,J(IW(Q,Y)))},X=null,z=()=>{if(V)return;let{nextDelayMs:W}=t$(Date.now()-Y,s1());X=setTimeout(()=>{H(),z()},Math.max(1,Math.ceil(W)))};return H(),z(),{setStatus(W){Q=W,H()},stop(){if(V=!0,X)clearTimeout(X)},elapsedSec(){return(Date.now()-Y)/1000}}}async openStatusCard($,Z,J="blue"){let Y=Date.now(),Q=l5({sessionName:this.sessionName,title:$,status:IW(Z,Y),template:J}),V=await c(this.chatId,Q);if(!V)return K(`session "${this.sessionName}": status card send failed title=${$}`),await w(this.chatId,`❌ 创建状态卡片失败: ${$}`),null;let H;try{H=await Z$(V)}catch(X){return K(`session "${this.sessionName}": status card id_convert failed title=${$}: ${X}`),await w(this.chatId,`❌ 状态卡片初始化失败: ${$}`),null}return d0(H,1),{cardId:H,title:$,timer:this.startFooterTimer(H,Z,(X)=>G9($,X))}}setStatusCard($,Z){$?.timer.setStatus(Z)}async closeStatusCard($,Z){if(!$)return;$.timer.stop();let J=$.timer.elapsedSec(),Y=G9($.title,`${Z} (${G0(J)})`);await O$($.cardId);let Q=await M0($.cardId,N.footer,this.footerElement(Y));A0($.cardId);let V=await P0($.cardId,h$({durationSec:J,suffix:Z}));if(Q&&V)await v0($.cardId);else{let H=`footer=${Q?"ok":"MISS"}, settings=${V?"ok":"MISS"}`;K(`session "${this.sessionName}": status card terminal transaction incomplete card=${$.cardId.slice(0,12)} ${H}`),await w(this.chatId,`⚠️ 状态卡片终态写入失败 (${H}):${Z}`)}}async runLifecycle($,Z){let J=this.lifecycleTail,Y;this.lifecycleTail=new Promise((V)=>{Y=V}),await J;let Q=++this.lifecycleSequence;K(`session "${this.sessionName}": lifecycle#${Q} ${$} begin`);try{return await Z()}finally{Y(),K(`session "${this.sessionName}": lifecycle#${Q} ${$} 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 Y,Q=new Promise((H)=>{Y=H}),V={token:++this.turnOpenSequence,proc:$,procEpoch:Z,sawResult:!1,terminalForcePush:!1,pendingCompactions:[],backendTurnStarted:J,done:Q,resolveDone:Y};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()}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()}beginBackgroundOpen(){if(this.backgroundCard||this.openingBackgroundOwner)return null;let $={token:++this.backgroundOpenSequence,proc:this.proc,procEpoch:this.procEpoch,generation:this.backgroundGeneration};return this.openingBackgroundOwner=$,this.openingBackground=!0,$}ownsBackgroundOpen($){return this.openingBackgroundOwner===$&&this.backgroundGeneration===$.generation&&this.proc===$.proc&&this.procEpoch===$.procEpoch}releaseBackgroundOpen($){if(this.openingBackgroundOwner!==$)return;this.openingBackgroundOwner=null,this.openingBackground=!1}invalidateBackgroundOpen(){this.backgroundGeneration++,this.openingBackgroundOwner=null,this.openingBackground=!1}attachProc($){this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),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.invalidateTurnOpen(),this.invalidateBackgroundOpen(),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($){this.stoppingProc=$,this.agentCapability=null}acceptsAgentCapability($){let Z=this.agentCapability;if(!Z||!$||!this.proc?.isAlive())return!1;let J=Buffer.from(Z),Y=Buffer.from($);return J.length===Y.length&&JM(J,Y)}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?O(Z):"kill returned while process still reports alive",K(`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(Y){J=Y}return this.finishProcStop($,J)}async settleProcResumableState($){let Z=null,J=$.conversationMaterializationBarrier?.();if(J)try{await J}catch(V){Z=`Codex 会话落盘确认失败: ${O(V)}`}let Y=$.conversationMaterializationFailure?.();if(Y&&$.isConversationResumable?.()!==!0)Z=`Codex 会话落盘确认失败: ${O(Y)}`;let Q=this.persistResumableSessionId(!1,$,!1);return[Z,Q].filter(Boolean).join(";")||null}resetFreshConversationState(){this.daemonRestoreRequired=!1,this.turnCounter=0,this.pendingConversationMaterialization=null,e0(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(k.get($),this.selectedProvider!=="codex"){if(this.proc?.isAlive())await this.stopUnlocked("切换到 Codex",{...Z,announce:!1});let Y=H0("codex-sub",$)?.defaultModel||null;e0(this.sessionName,[],null,null),b1(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=Z1(this.sessionName,"codex"),this.lastSessionId=this.lastSessionRef?.sessionId??null}if(this.selectedTokenSourceId!=="codex-sub")b1(this.sessionName,"codex",this.selectedModel,this.selectedEffort,"codex-sub"),this.selectedTokenSourceId="codex-sub";this.codexStartAccountOverride=$;try{if(this.proc?.isAlive()&&this.proc.provider==="codex"&&r0(this.proc)===$&&this.proc.turnRetry?.reason!=="quota")return Z.onStatus?.(`✅ 正在使用「${k.get($).name}」`),!0;return this.proc?.isAlive()?await this.restartUnlocked(!0,Z):await this.startUnlocked(Z)}finally{this.codexStartAccountOverride=void 0}})}async startUnlocked($={}){let Z=$.announce??!0,J=$.onStatus,Y=this.blockedProcessMessage();if(Y){if(this.status="stopped",J?.(`❌ ${Y}`),Z)await E(this.chatId,`❌ ${Y}。请重试 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?.("\uD83D\uDD0E 检查 Codex 登录");else J?.("\uD83D\uDD0E 检查 Claude Code");if(this.selectedProvider==="codex"&&this.selectedTokenSourceId!=="codex-sub"&&!r4(this.codexAccountId())){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.("❌ Codex 未登录 ChatGPT 账号"),Z){if(!await c(this.chatId,V$({phase:"warning",title:"需要登录",hint:"默认:codex-login · 额外:codex-login 备注"})))throw Error("Codex 登录引导卡片发送失败")}return!1}if(!wW(this.workDir)){if(J?.(`\uD83C\uDD95 创建项目目录 ~/${this.sessionName}`),Z)await E(this.chatId,`\uD83C\uDD95 目录 ~/${this.sessionName} 不存在,正在创建…`);try{q5(this.workDir)}catch(G){if(this.status="stopped",this.opts.onLifecycleChange?.(),J?.(`❌ 创建项目失败: ${G}`),Z)await E(this.chatId,`❌ 创建项目失败: ${G}`);return!1}}if(!$.freshConversationStateAlreadyReset&&!this.pendingConversationMaterialization)this.resetFreshConversationState();this.status="starting",J?.(this.withModel(`\uD83D\uDE80 启动 ${this.backendLabel()}`));let Q;try{if(this.selectedProvider!=="codex"||!this.codexStartAccountOverride&&k.preferred(this.sessionName)===null)await A2();Q=this.spawnAgent()}catch(G){let B=`${this.backendLabel()} 启动失败: ${O(G)}`;if(K(`session "${this.sessionName}": ${B}`),J?.(`❌ ${B}`),Z)await E(this.chatId,`❌ ${B}`);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}this.attachProc(Q);let V=this.backendLabel(),H=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(Q,hW):null;J?.(this.selectedProvider==="claude"?`⏳ 检查 ${V} 启动`:`⏳ 等待 ${V} init`);let X,z=null;try{Q.sendInitialize(),X=Q.initializationPromise?.()}catch(G){X=void 0,z=G}let W=z?{state:"error",error:z}:this.selectedProvider==="claude"?await H:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(X),()=>{K(`session "${this.sessionName}": codex init still pending after ${UJ/1000}s`),J?.(this.withModel(`⏳ 仍在等待 ${V} init 确认`))});if(W.state==="error"||W.state==="exit"){let G=W.error?O(W.error):W.state;K(`session "${this.sessionName}": ${this.selectedProvider} init failed: ${G}`);let _=await this.stopOwnedProc(Q,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,j=`❌ ${V} 启动失败: ${G}${_}`;if(J?.(j),Z)await E(this.chatId,j);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(W.state==="timeout"){K(`session "${this.sessionName}": ${this.selectedProvider} init wait timeout (${i6/1000}s)`);let B=await this.stopOwnedProc(Q,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,_=`❌ ${V} 启动超时: ${i6/1000} 秒内初始化事务未完成${B}`;if(J?.(_),Z)await E(this.chatId,_);return this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(this.proc!==Q||!Q.isAlive()){let G=`${V} 启动期间已退出`;if(K(`session "${this.sessionName}": ${G}`),J?.(`❌ ${G}`),Z)await E(this.chatId,`❌ ${G}`);return this.detachProc(Q),this.status="stopped",this.opts.onLifecycleChange?.(),!1}if(W.state==="waiting_quota"){if(this.status="starting",this.startedAt=Date.now(),this.opts.onLifecycleChange?.(),J?.("⏳ 账号额度用尽 · 自动等待恢复,可用后继续"),Z)await c(this.chatId,V$({phase:"checking",title:"等待额度恢复",message:"额度恢复后自动继续",hint:"stop 可取消等待"}));return!0}if(Z){let G=this.modelLine();await E(this.chatId,[this.withWorktreeInstructionNotice(`✅ Lodestar session "${this.sessionName}" 已就绪,发消息开始对话。`),G].filter(Boolean).join(`
|
|
255
|
+
`))}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 Y=!1,Q=(X,z)=>{if(Y)return;Y=!0,clearTimeout(V),clearTimeout(H),J({state:X,error:z})},V=setTimeout(()=>{if(Y)return;try{Z?.()}catch(X){Q("error",X)}},UJ),H=setTimeout(()=>{Q("timeout",Error(`codex init timed out after ${i6/1000}s`))},i6);$.then(()=>Q("init"),(X)=>Q("error",X)),this.proc?.quotaWaitPromise?.().then(()=>Q("waiting_quota"),(X)=>Q("error",X))})}async waitForProcEarlyFailure($,Z){return await new Promise((J)=>{let Y=!1,Q=(W,G)=>{if(Y)return;Y=!0,clearTimeout(V),$.off("init",H),$.off("error",X),$.off("exit",z),J({state:W,error:G})},V=setTimeout(()=>Q("ready"),Z),H=()=>Q("init"),X=(W)=>Q("error",W),z=(W)=>Q("exit",W);$.once("init",H),$.once("error",X),$.once("exit",z)})}releaseAllReactions(){for(let[$,Z]of[...this.pendingReactionIds.entries(),...this.currentBatchReactionIds.entries()])if(Z)C0($,Z);this.pendingReactionIds=new Map,this.currentBatchReactionIds=new Map}clearStaleIdleQueueState($){if(this.initCount<1||this.currentTurn||this.openingTurn||this.pendingUserMessageCount===0)return;K(`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)C0(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,Y=Z.onStatus;if(this.daemonRestoreRequired=!1,await this.cancelAgentRuns($),!this.proc){if(this.status="stopped",this.opts.onLifecycleChange?.(),Y?.("⚪ session 当前未运行"),J)await E(this.chatId,`⚪ session "${this.sessionName}" 当前未运行`);return}let Q=this.proc,V=this.persistResumableSessionId(!1,Q,!1),H=null;if(Y?.(`\uD83D\uDED1 停止 ${this.backendLabel(this.proc.provider)}`),K(`session "${this.sessionName}": stop (${$})`),this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),this.currentTurn)this.closeTurnCard(`\uD83D\uDED1 ${$}`).catch((D)=>{K(`session "${this.sessionName}": stop current main-card close failed: ${O(D)}`)});let X=this.waitForTurnCloses().catch((D)=>K(`session "${this.sessionName}": stop main-card close failed: ${O(D)}`));this.beginProcStop(Q),this.status="stopped";let z=[];try{this.opts.onLifecycleChange?.()}catch(D){z.push(D),K(`session "${this.sessionName}": stop intent lifecycle write failed: ${O(D)}`)}let W=Q.conversationMaterializationBarrier?.();if(W){try{await W}catch(D){H=`Codex 会话落盘确认失败: ${O(D)}`}V=this.persistResumableSessionId(!1,Q,!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 G=null;try{await Q.kill()}catch(D){G=D}let B=Q.conversationMaterializationFailure?.();if(B&&Q.isConversationResumable?.()!==!0)H=`Codex 会话落盘确认失败: ${O(B)}`;V=this.persistResumableSessionId(!1,Q,!1);let j=(await Promise.allSettled([this.resetBackgroundTasks(),X])).filter((D)=>D.status==="rejected").map((D)=>D.reason);for(let D of j)K(`session "${this.sessionName}": stop terminal cleanup failed: ${O(D)}`);let q=this.finishProcStop(Q,G);try{this.opts.onLifecycleChange?.()}catch(D){z.push(D),K(`session "${this.sessionName}": stop final lifecycle write failed: ${O(D)}`)}let P=[...G?[G]:[],...!q&&!G?[Error(this.blockedProcReason??"process stop unconfirmed")]:[],...j,...z,...V?[Error(V)]:[],...H&&Q.isConversationResumable?.()!==!0?[Error(H)]:[]];if(P.length===1)throw P[0];if(P.length>1)throw AggregateError(P,`stop failed: ${P.map(O).join("; ")}`);if(Y?.(`✅ ${$}`),J)await E(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 E(this.chatId,"❌ daemon 重启后没有可用的恢复点。请发送 rs 选择历史会话,或 hi 明确启动新会话。"),!1;return await this.restartUnlocked(!0)})}async restartUnlocked($=!1,Z={},J){let Y=Z.announce??!0,Q=Z.onStatus,V=this.status,H=null;if(!$&&!this.pendingConversationLaunch&&this.pendingConversationMaterialization)H=this.pendingConversationMaterialization,J1(this.sessionName,null),this.pendingConversationMaterialization=null;let X=this.pendingConversationLaunch??this.pendingMaterializationLaunch(),z=this.lastSessionRef;if($&&!X&&z?.cwd===null)try{z=await this.resolveLegacyResumeRef(z),this.lastSessionRef=z,this.lastSessionId=z.sessionId}catch(x){let h=this.invalidateMissingCodexResume(z.sessionId,x,J),p=h?`❌ 旧会话不可恢复: ${O(x)};${h}`:`❌ 旧会话 cwd 校验失败: ${O(x)};请在进程已停时发送 rs 重新选择历史会话`;if(this.status=this.proc?.isAlive()?V:"stopped",Q?.(p),Y)await E(this.chatId,p);return!1}let W=z?.sessionId??null,G=X&&X.kind!=="fresh"?X.source.sessionId:W,B=G?U0(G):"",_=null,j=(x=this.proc)=>{if(!$||X||x?.provider!=="codex"||x.isConversationResumable?.()!==!0)return;_=this.persistResumableSessionId(!1,x,!1),z=this.lastSessionRef,W=z?.sessionId??null,G=W,B=G?U0(G):""},q=null;if(!Q&&Y&&$&&W){let x=this.proc?this.withModel(`\uD83D\uDD01 重启 ${this.backendLabel(this.proc.provider)}`):this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${B}`);if(q=await this.openStatusCard("restart",x),q)Q=(h)=>this.setStatusCard(q,h)}let P=Y&&!q,D=async(x)=>{if(q)await this.closeStatusCard(q,x)},T=Boolean(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0||this.pendingTurnInputs.length>0||this.backgroundTasks.length>0||this.pendingBgTasks.length>0||this.openingBackground);this.bgResumePending=!1,this.invalidateTurnOpen(),this.invalidateBackgroundOpen(),this.discardOrphanAssistant();for(let x of this.fileDeliveries)x.cancel("会话正在重启");if(this.currentTurn)this.closeTurnCard("\uD83D\uDD01 已中止,正在重启").catch((x)=>{K(`session "${this.sessionName}": restart current main-card close failed: ${O(x)}`)});let M=this.waitForTurnCloses().catch((x)=>K(`session "${this.sessionName}": restart main-card close failed: ${O(x)}`)),A=null,U=null;if(this.proc){let x=this.proc;Q?.(`\uD83D\uDED1 停止当前 ${this.backendLabel(x.provider)}`),U=x,this.beginProcStop(x);let h=x.conversationMaterializationBarrier?.();if(h)try{await h}catch(l){_=`Codex 会话落盘确认失败: ${O(l)}`}if(j(x),$&&!X&&_&&!T&&x.isAlive()){if(this.stoppingProc===x)this.stoppingProc=null;this.status=V;let l=`❌ ${this.backendLabel(x.provider)} 恢复点尚未安全落盘,已保留当前进程: ${_}`;if(K(`session "${this.sessionName}": abort restart before kill: ${_}`),Q?.(l),P)await E(this.chatId,l);return await D(l),!1}try{await x.kill()}catch(l){A=l}let p=x.conversationMaterializationFailure?.();if(p&&x.isConversationResumable?.()!==!0)_=`Codex 会话落盘确认失败: ${O(p)}`;j(x)}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 b=(await Promise.allSettled([this.resetBackgroundTasks(),M])).filter((x)=>x.status==="rejected").map((x)=>x.reason);for(let x of b)K(`session "${this.sessionName}": restart terminal cleanup failed: ${O(x)}`);let v=U?this.finishProcStop(U,A):!0,y=[...A?[`kill=${O(A)}`]:[],...!v&&!A?[`kill=${this.blockedProcReason??"process stop unconfirmed"}`]:[],...b.map((x)=>`cleanup=${O(x)}`),..._?[`resume=${_}`]:[]];if(y.length>0&&H)try{J1(this.sessionName,H),this.pendingConversationMaterialization=H}catch(x){y.push(`pendingRestore=${O(x)}`)}if(y.length>0){let x=`❌ 旧 ${this.backendLabel()} 进程停止/清理失败: ${y.join("; ")}`;if(this.status="stopped",this.opts.onLifecycleChange?.(),Q?.(x),P)await E(this.chatId,x);return await D(x),!1}let g=X?.kind==="resume"||X?.kind==="fork";if($&&z||g){this.status="starting",this.usageTotalsSeedUnknown=!0,Q?.(this.withModel(`\uD83D\uDD01 恢复上一会话 thread=${B}`));let x;try{if(this.selectedProvider!=="codex"||!this.codexStartAccountOverride&&k.preferred(this.sessionName)===null)await A2();x=this.spawnAgent(z??void 0)}catch(o){let K0=`❌ ${this.backendLabel()} 恢复失败: ${O(o)}`;if(K(`session "${this.sessionName}": ${this.selectedProvider} resume failed before spawn: ${O(o)}`),Q?.(K0),P)await E(this.chatId,K0);return this.status="stopped",this.opts.onLifecycleChange?.(),await D(K0),!1}this.attachProc(x);let h=this.backendLabel(),p=this.selectedProvider==="claude"?this.waitForProcEarlyFailure(x,hW):null;Q?.(this.selectedProvider==="claude"?`⏳ 检查 ${h} 恢复启动`:`⏳ 等待 ${h} init 确认`);let l,F=null;try{x.sendInitialize(),l=x.initializationPromise?.()}catch(o){l=void 0,F=o}let C=F?{state:"error",error:F}:this.selectedProvider==="claude"?await p:await this.waitForCodexInitialization(this.requireCodexInitializationPromise(l),()=>{K(`session "${this.sessionName}": codex resume init still pending after ${UJ/1000}s`),Q?.(this.withModel(`⏳ 仍在等待 ${h} init 确认 thread=${B}`))});if(C.state==="error"||C.state==="exit"||C.state==="timeout"){let o=C.state==="error"?this.invalidateMissingCodexResume(G,C.error,J):null,K0=[C.error?O(C.error):C.state,o].filter(Boolean).join(";");K(`session "${this.sessionName}": ${this.selectedProvider} resume failed: ${K0}`);let S9=await this.stopOwnedProc(x,1000)?"":`;进程终止未确认: ${this.blockedProcReason??"未知原因"}`,Z2=C.state==="timeout"?`❌ ${h} 恢复超时${S9}`:`❌ ${h} 恢复失败: ${K0}${S9}`;if(Q?.(Z2),P)await E(this.chatId,Z2);return this.status="stopped",this.opts.onLifecycleChange?.(),await D(Z2),!1}if(this.proc!==x||!x.isAlive()){let o=`❌ ${h} 恢复期间已退出`;if(K(`session "${this.sessionName}": ${this.selectedProvider} resume process exited before ready`),Q?.(o),P)await E(this.chatId,o);return this.detachProc(x),this.status="stopped",this.opts.onLifecycleChange?.(),await D(o),!1}let d=this.withModel(this.withWorktreeInstructionNotice(C.state==="waiting_quota"?"⏳ 账号额度用尽 · 等待后自动恢复原会话":this.selectedProvider==="claude"&&C.state==="ready"?`✅ 已准备恢复上一会话 thread=${B}`:`✅ 已恢复上一会话 thread=${B}`));if(Q?.(d),P)await E(this.chatId,d);if(this.status=C.state==="waiting_quota"?"starting":"idle",this.startedAt=Date.now(),C.state!=="waiting_quota")this.daemonRestoreRequired=!1;this.opts.onLifecycleChange?.();try{await D(d)}catch(o){K(`session "${this.sessionName}": restart succeeded but status-card close failed: ${O(o)}`),await w(this.chatId,`⚠️ ${d}
|
|
256
|
+
状态卡收尾失败: ${O(o)}`)}return!0}else{if($&&!X){if(Q?.("⚠️ 没有可恢复的上一会话,将以新会话启动"),P)await E(this.chatId,"⚠️ 没有可恢复的上一会话,将以新会话启动")}return this.resetFreshConversationState(),await this.startUnlocked({...Z,freshConversationStateAlreadyReset:!0})}}async startForked($,Z={}){return await this.runLifecycle("start-forked",async()=>{_0($,this.selectedProvider,this.workDir);let J=i4(this.sessionName),Y=this.selectedProvider==="claude"?{launch:$,previousSessionId:this.lastSessionId}:null;if(Y)J1(this.sessionName,Y),this.pendingConversationMaterialization=Y;this.pendingConversationLaunch=$;try{let Q=await this.startUnlocked(Z);if(!Q&&Y)J1(this.sessionName,J),this.pendingConversationMaterialization=J;return Q}catch(Q){if(!Y)throw Q;try{J1(this.sessionName,J),this.pendingConversationMaterialization=J}catch(V){throw AggregateError([Q,V],`fork start and pending-intent restore failed: ${O(Q)}; ${O(V)}`)}throw Q}finally{this.pendingConversationLaunch=null}})}async rollbackTo($,Z,J={}){return await this.runLifecycle("rollback",async()=>{_0($,this.selectedProvider,this.workDir);let Y=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,Q=this.proc,V=this.lastSessionId,H=this.lastSessionRef,X=l4(this.sessionName).slice(),z=d4(this.sessionName),W=i4(this.sessionName),G={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},B=!1,_=()=>{if(B)this.lastSessionId=null,this.lastSessionRef=null,C2(this.sessionName,"codex");else if(this.lastSessionId=V,this.lastSessionRef=H,H)u4(this.sessionName,H);else C2(this.sessionName,this.selectedProvider);e0(this.sessionName,X,z,W),this.pendingConversationMaterialization=W,this.turnCounter=G.turnCounter,this.currentGoal=G.currentGoal,this.cumStats=G.cumStats,this.lastTurnDelta=G.lastTurnDelta,this.currentTurnUsageBaseline=G.currentTurnUsageBaseline,this.currentTurnUsageBaselineKnown=G.currentTurnUsageBaselineKnown,this.lastTurnUsage=G.lastTurnUsage,this.usageTotalsSeedUnknown=G.usageTotalsSeedUnknown},j=!1;if(Y?.pendingLaunch)e0(this.sessionName,Y.anchors,Y.base,Y.pendingLaunch),this.pendingConversationMaterialization=Y.pendingLaunch,j=!0;this.pendingConversationLaunch=$;let q=(P)=>{B=H?.provider==="codex"&&H.sessionId===P};try{let P;try{P=$.kind==="fresh"?await this.restartUnlocked(!1,J,q):await this.restartUnlocked(!0,J,q)}catch(D){let T=null,M=this.proc&&this.proc!==Q?this.proc:null;if(M)try{await this.stopUnlocked("回滚启动事务失败",{announce:!1})}catch(b){T=b}let A=!M||this.proc!==M&&!M.isAlive();if(!A&&!T)T=Error("replacement process stop was not confirmed");let U=null;if(A)try{_()}catch(b){U=b}let S=[D,...T?[T]:[],...U?[U]:[]];if(S.length===1)throw D;throw AggregateError(S,`rollback launch and cleanup failed: ${S.map(O).join("; ")}`)}if(!P)return _(),!1;if(Y)try{if(!j)e0(this.sessionName,Y.anchors,Y.base,Y.pendingLaunch);this.pendingConversationMaterialization=Y.pendingLaunch}catch(D){let T=null,M=this.proc;try{await this.stopUnlocked("回滚分支状态持久化失败",{announce:!1})}catch(b){T=b}let A=!M||this.proc!==M&&!M.isAlive();if(!A&&!T)T=Error("replacement process stop was not confirmed");let U=null;if(A)try{_()}catch(b){U=b}let S=[D,...T?[T]:[],...U?[U]:[]];if(S.length===1)throw D;throw AggregateError(S,`rollback branch commit failed: ${S.map(O).join("; ")}`)}return P}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 Y=`拒绝了与当前会话不匹配的 checkpoint provider=${$.provider} source=${$.source.sessionId}`;return K(`session "${this.sessionName}": ${Y}`),this.lastTurnUserPreview="",Y}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((Q)=>Q.proc===Z).length>=64)return K(`session "${this.sessionName}": ${"Codex rollout 长期未确认,延迟 checkpoint 队列已满"} thread=${Z.sessionId}`),"Codex rollout 长期未确认,延迟 checkpoint 队列已满";return this.pendingCodexTurnAnchors.push({proc:Z,anchor:J}),K(`session "${this.sessionName}": defer Codex turn checkpoint until rollout confirmation thread=${Z.sessionId} checkpoint=${$.id}`),null}return this.appendTurnAnchor(J)}appendTurnAnchor($){try{return Z5(this.sessionName,$),null}catch(Z){let J=`分叉 checkpoint 持久化失败: ${O(Z)}`;return K(`session "${this.sessionName}": ${J}`),J}}flushPendingCodexTurnAnchors($){let Z=null,J=[];for(let Y of this.pendingCodexTurnAnchors){if(Y.proc!==$||Z){J.push(Y);continue}if(Z=this.appendTurnAnchor(Y.anchor),Z)J.push(Y)}return this.pendingCodexTurnAnchors=J,Z}discardPendingCodexTurnAnchors($,Z){if($.provider!=="codex")return;let J=this.pendingCodexTurnAnchors.length;this.pendingCodexTurnAnchors=this.pendingCodexTurnAnchors.filter((Q)=>Q.proc!==$);let Y=J-this.pendingCodexTurnAnchors.length;if(Y>0)K(`session "${this.sessionName}": dropped ${Y} unmaterialized Codex checkpoint(s): ${Z}`)}collectTurnWrites(){let $=this.currentTurn;if(!$)return[];let Z=[];for(let J of $.toolByUseId.values())Z.push(...QZ(J.name,J.input));return Z}worktreeProjectName(){return B1(this)}worktreeProjectDir(){return $4(this)}spawnDeveloperInstructions($=this.getFileDeliveryMode()){return _W(this,$)}delegatedAgentDeveloperInstructions($){return jW(this,$)}worktreeInstructionLoadedNotice(){return qJ(this)}withWorktreeInstructionNotice($){return LW(this,$)}worktreeExtraInstruction(){return T9(this)}runWorktreeCommand($,Z){return qW(this,$,Z)}showWorktrees(){return PJ(this)}showTasklistPanel(){return fz(this)}showAgentIdentityPanel($=""){return Ez(this,$)}onAgentIdentityPage($,Z,J){return xz($,Z,J)}onTasklistEnable(){return hz(this)}onTasklistDeletePrompt($){return Iz(this,$)}onTasklistDeleteConfirm($){return gz(this,$)}runCompactCommand(){return Lz(this)}showModelPanel(){return Pz(this)}onModelSelect($,Z="",J="",Y=null){return this.runLifecycle("model-select",()=>Rz(this,$,Z,J,Y))}onModelEffortSelect($,Z,J="",Y="",Q=""){return this.runLifecycle("model-effort-select",()=>JJ(this,$,Z,J,Y,Q))}onProviderSelect($,Z=""){return ZJ(this,$,Z)}onModelPage($,Z,J){return y6(this,$,Z,J)}onModelAddOpen($,Z){return Dz(this,$,Z)}onModelListEdit($,Z,J,Y){return this.runLifecycle("model-list-edit",()=>Fz(this,$,Z,J,Y))}onModelPanelCancel($=""){return Az(this,$)}onModelCustomPrompt($,Z,J=""){return Mz(this,$,Z,J)}consumeModelCustomMessage($,Z){return Uz(this,$,Z)}onWorktreeDisband($){return DW(this,$)}showForkList($=""){return NW(this,$)}showBackList($=""){return TW(this,$)}showResumeList($=""){return EW(this,$)}runBtwCommand($){return xW(this,$)}runByeCommand(){return SW(this)}onForkSelect($,Z,J=""){return bW(this,$,Z,J)}onBackSelect($,Z,J=""){return CW(this,$,Z,J)}onResumeSelect($,Z,J=""){return kW(this,$,Z,J)}runCommand($,Z="",J){return _z(this,$,Z,J)}getFileDeliveryMode(){return r2.mode(this.chatId)}runFileDeliveryCommand($,Z){return nz(this.chatId,this.sessionName,Z,$,{get:(J)=>r2.get(J),enable:(J,Y)=>r2.enable(J,Y),disable:(J)=>r2.disable(J),sendCard:(J)=>c(this.chatId,J),reportError:async(J)=>{if(K(`session "${this.sessionName}": ${J}`),!await E(this.chatId,J))throw Error(J)}})}async buildConsoleOpts($,Z){let J=await AH(),Y=this.runtimeModelSelection();return{sessionName:this.sessionName,status:this.status,provider:Y.provider,model:Y.model??void 0,effort:Y.effort??"MISS",worktreeInstructionNotice:this.worktreeInstructionLoadedNotice(),peers:[...G$.all].filter((Q)=>Q.isRunning()).map((Q)=>({...Q.peerSnapshot(),isCurrent:Q===this})),usage:$,glmUsage:Z,sysinfo:J}}async buildConsoleCard($){return d5(await this.buildConsoleOpts($))}async patchConsoleUsage($){let Z=await this.buildConsoleOpts(void 0),J=Z.provider??this.currentProvider(),Y=this.currentTokenSource(),Q=Y&&Y.agent===J&&Y.enabled?Y:this.selectedTokenSourceId?void 0:P8(J)[0];if(Q)Z.unifiedUsage=await Q.readUsage();else if(this.selectedTokenSourceId)Z.unifiedUsage={state:"no_credentials",windows:[],reason:`token source ${this.selectedTokenSourceId} unavailable`};else if(Z.provider==="claude")Z.glmUsage=await rH();else Z.usage=await E1(this.codexAccountId());if(!await M0($,N.consoleUsage,K9(Z),{notifyCardFailure:!1}))throw Error("console usage element replace rejected")}async mutateStaticCard($,Z,J){let Y=!0;try{await J()}catch(V){Y=!1,K(`session "${this.sessionName}": ${Z} mutation failed: ${O(V)}`)}let Q=!1;try{Q=await P0($,{config:{streaming_mode:!1}})}catch(V){K(`session "${this.sessionName}": ${Z} streaming-off failed: ${O(V)}`)}if(!Y||!Q)return K(`session "${this.sessionName}": ${Z} state retained after checked MISS mutation=${Y} streamingOff=${Q} card=${$.slice(0,12)}`),!1;try{await v0($)}catch(V){return K(`session "${this.sessionName}": ${Z} dispose failed: ${O(V)}`),!1}return Y}patchConsoleUsageLater($){this.mutateStaticCard($,"console usage",()=>this.patchConsoleUsage($))}async replaceStatusCardWithConsole($,Z){$.timer.stop();let J=$.timer.elapsedSec(),Y=await this.buildConsoleOpts(void 0);await O$($.cardId);let Q=await M0($.cardId,N.footer,z6(Y,N.footer)),V=await Y1($.cardId,X6(Y),{type:"insert_after",targetElementId:N.footer}),H=await Y1($.cardId,W6(Y.sysinfo),{type:"insert_after",targetElementId:N.consoleProjects}),X=await Y1($.cardId,K9(Y),{type:"insert_after",targetElementId:N.consoleHost});if(!Q||!V||!H||!X){await w(this.chatId,"⚠️ 控制台卡片结构写入失败,请重新发送 hi。"),await this.mutateStaticCard($.cardId,"console structure",async()=>{});return}A0($.cardId),await P0($.cardId,h$({durationSec:J,suffix:Z})),this.patchConsoleUsageLater($.cardId)}async showConsole(){let $=await this.buildConsoleCard(void 0),Z=await c(this.chatId,$);if(!Z)return;(async()=>{let J="";try{J=await Z$(Z),d0(J,4)}catch(Y){K(`session "${this.sessionName}": console card conversion failed: ${O(Y)}`);return}await this.mutateStaticCard(J,"console usage",()=>this.patchConsoleUsage(J))})().catch((J)=>K(`session "${this.sessionName}": console async update rejected: ${O(J)}`))}interrupt(){if(!this.proc)return;K(`session "${this.sessionName}": interrupt`),this.proc.sendInterrupt()}sendClaimedUserText($,Z){let J=this.currentTurn,Y=J?J.fileDeliveryMode??=this.getFileDeliveryMode():this.getFileDeliveryMode(),Q=this.procFileDeliveryModes.get($),V=Q===Y?"":`${tz(Y)}
|
|
257
257
|
|
|
258
258
|
`;this.procFileDeliveryModes.set($,Y),this.pendingUserMessageCount++;try{$.sendUserText(V+Z,[])}catch(H){if(this.pendingUserMessageCount=Math.max(0,this.pendingUserMessageCount-1),Q===void 0)this.procFileDeliveryModes.delete($);else this.procFileDeliveryModes.set($,Q);throw H}}async startColdUserTurn($,Z,J){if(!this.pendingConversationMaterialization)this.resetFreshConversationState();this.pendingTurnInputs.push($);let Y=this.beginTurnOpen();try{let V=await this.openTurnCard(Y,J,"user_message",{initialFooter:"Waiting...(0s)",startThinking:!1,directStart:!0});if(!V||this.currentTurn!==V)return;let H=this.startFooterTimer(V.cardId,`\uD83D\uDE80 启动 ${this.backendLabel()}`,(G)=>this.withModel(G)),X=`\uD83D\uDE80 启动 ${this.backendLabel()}`,z=await this.startUnlocked({announce:!1,freshConversationStateAlreadyReset:!0,onStatus:(G)=>{X=G,H.setStatus(G)}});if(H.stop(),await O$(V.cardId),!z){this.pendingUserMessageCount=0,this.pendingMidTurnMsgs=[],this.pendingTurnInputs=[],this.lastUserOpenId="",this.releaseAllReactions(),await this.closeTurnCard(X.startsWith("❌")?X:"❌ 启动失败",{forcePush:!0});return}let W=this.proc;if(!W?.isAlive()){await this.closeTurnCard(`❌ ${this.backendLabel()} 启动后已退出`,{forcePush:!0});return}this.startThinkingFooter(V),this.sendClaimedUserText(W,Z),this.status="working"}finally{this.releaseTurnOpen(Y)}}async onUserMessage($,Z=[],J="",Y=""){await this.runLifecycle("user-message",()=>this.onUserMessageUnlocked($,Z,J,Y))}async onUserMessageUnlocked($,Z,J,Y){let Q=this.blockedProcessMessage();if(Q){await E(this.chatId,`❌ ${Q}。请重试 stop/restart,或等待旧进程退出。`);return}if(this.daemonRestoreRequired){await E(this.chatId,"❌ daemon 重启后的会话恢复尚未成功,这条消息未送给 Agent。请发送 rs 选择历史会话,或 hi 明确启动新会话,然后重发消息。");return}if(this.clearStaleIdleQueueState("user_message"),this.proc?.isAlive()&&!this.currentTurn&&!this.openingTurn&&this.pendingUserMessageCount===0&&this.pendingMidTurnMsgs.length===0)await this.stopIdleMismatchedProcessUnlocked();let V=this.currentTurn!==null||this.openingTurn||this.pendingUserMessageCount>0||this.pendingMidTurnMsgs.length>0;this.lastUserOpenId=J;let X=(Z.length?Z.map((W)=>`[file: ${W}]`).join(" ")+`
|
|
259
|
-
`:"")+$,z=(W)=>{this.pendingReactionIds.set(W,""),(async()=>{let G=await l0(W,"OneSecond");if(!G)return;if(this.pendingReactionIds.has(W))this.pendingReactionIds.set(W,G);else if(this.currentBatchReactionIds.has(W))this.currentBatchReactionIds.set(W,G);else C0(W,G)})().catch((G)=>{K(`session "${this.sessionName}": reaction tracking failed: ${O(G)}`)})};if(!this.isRunning()){if(this.openingTurn||this.currentTurn){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}await this.startColdUserTurn($,X,J);return}if(this.currentTurn!==null){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}if(!this.openingTurn&&this.initCount>=1){let W=this.proc,G=this.procEpoch,B=this.beginTurnOpen(W,G);try{this.pendingTurnInputs.push($);let _=await this.openTurnCard(B,J,"user_message");if(!_||this.currentTurn!==_)return;if(this.proc!==W||this.procEpoch!==G||!W.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel(W.provider)} 已退出`);return}this.sendClaimedUserText(W,X),this.status="working"}finally{this.releaseTurnOpen(B)}return}if(this.openingTurn||this.pendingUserMessageCount>0){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}if(this.pendingTurnInputs.push($),this.sendClaimedUserText(this.proc,X),V&&Y)z(Y)}hasPendingAsk(){return NX(this)}refreshPendingAsks(){R6(this)}askBlockReason($){return l2(this,$)}onMultiMessageInbound($,Z,J,Y){return YX(this,$,Z,J,Y)}clearMultiMsgBuffer($){MZ(this,$)}onAskMessageAnswer($,Z,J){return TX(this,$,Z,J)}onAskAnswer($,Z,J,Y){return EX(this,$,Z,J,Y)}onAskCustomAnswer($,Z,J,Y){return CZ(this,$,Z,J,Y)}onPermissionDecision($,Z,J){return yX(this,$,Z,J)}clearResumeBindingForFreshCodex($){if($.isConversationResumable?.())throw Error("fresh Codex thread was unexpectedly marked resumable during init");let Z=Z1(this.sessionName,"codex");if(C2(this.sessionName,"codex"),this.selectedProvider==="codex")this.lastSessionRef=null,this.lastSessionId=null;if(Z)K(`session "${this.sessionName}": cleared pre-fresh Codex resume binding thread=${Z.sessionId}`)}invalidateMissingCodexResume($,Z,J){if(!$||this.selectedProvider!=="codex")return null;let Y=OJ(Z);if(!Y||!["thread/read","thread/resume","thread/fork"].includes(Y.method)||Y.serverCode!==-32600||Y.serverMessage!==`no rollout found for thread id ${$}`)return null;let Q=Z1(this.sessionName,"codex");if(!Q||Q.sessionId!==$)return null;try{C2(this.sessionName,"codex")}catch(H){let X=`已确认恢复点无 rollout,但作废失败: ${O(H)}`;return K(`session "${this.sessionName}": ${X} thread=${$}`),X}if(this.lastSessionRef?.provider==="codex"&&this.lastSessionRef.sessionId===$)this.lastSessionRef=null,this.lastSessionId=null;J?.($);let V=`已作废无 rollout 的恢复点 thread=${U0($)}`;return K(`session "${this.sessionName}": ${V} fullThread=${$}`),V}persistResumableSessionId($=!1,Z=this.proc,J=!0){let Y=Z?.provider==="claude"?this.pendingConversationMaterialization:null,Q=Z?.sessionId;if(!Z)return null;if(Z.provider==="codex"&&Z.isConversationResumable?.()!==!0)return null;if(!Q){if(!Y)return null;let X=Error("Claude pending fork did not provide a materialized session id");if(K(`session "${this.sessionName}": ${X.message}`),$)throw X;return X.message}let V={provider:Z.provider,sessionId:Q,cwd:this.workDir};if(Y&&(Q===Y.launch.source.sessionId||Y.previousSessionId!==null&&Q===Y.previousSessionId)){let X=Error(`Claude fork did not materialize an independent session id (${Q})`);if(K(`session "${this.sessionName}": ${X.message}`),$)throw X;return X.message}try{u4(this.sessionName,V)}catch(X){let z=`会话恢复点持久化失败: ${O(X)}`,W=this.resumePersistenceError!==z;if(this.resumePersistenceError=z,Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Q;if(K(`session "${this.sessionName}": ${z}`),$)throw X;if(W&&J)w(this.chatId,`⚠️ ${z};当前进程可继续,但 daemon 重启前请先解决本机状态目录写入问题。`);return z}if(Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Q;let H=Z.provider==="codex"?this.flushPendingCodexTurnAnchors(Z):null;if(H){let X=this.resumePersistenceError!==H;if(this.resumePersistenceError=H,$)throw Error(H);if(X&&J)w(this.chatId,`⚠️ ${H}`);return H}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 K(`session "${this.sessionName}": ${"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker"}`),"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker";try{return J1(this.sessionName,null),this.pendingConversationMaterialization=null,null}catch(J){let Y=`Claude 待生成分支标记清除失败: ${O(J)}`;return K(`session "${this.sessionName}": ${Y}`),Y}}bgStore(){return{active:this.backgroundTasks,pending:this.pendingBgTasks}}applyBgStore($){this.backgroundTasks=$.active,this.pendingBgTasks=$.pending}onMainThreadAdvance(){if(this.pendingBgTasks.length===0)return;this.applyBgStore(H3(this.bgStore())),this.onBackgroundTaskChanged()}bgTaskOwns($){return this.backgroundTasks.some((Z)=>Z.toolUseId===$)||this.pendingBgTasks.some((Z)=>Z.toolUseId===$)}onBackgroundTaskChanged(){if(this.migratingBackgroundCard){this.pendingRebuildBackgroundCard=!0;return}if(!R1(this.backgroundTasks)){if(this.backgroundCard)this.settleBackgroundCard().catch((Z)=>{K(`session "${this.sessionName}": background settle failed: ${O(Z)}`)});return}if(!this.backgroundCard&&!this.openingBackground){this.openBackgroundCard().catch((Z)=>{K(`session "${this.sessionName}": background open failed: ${O(Z)}`)});return}this.scheduleBackgroundRefresh()}async openBackgroundCard(){let $=this.beginBackgroundOpen();if(!$)return;let Z=this.backgroundTasks.slice();try{let J=K3(Z,Date.now(),s1()),Y=await c(this.chatId,J);if(!Y){if(this.ownsBackgroundOpen($))K(`session "${this.sessionName}": background card send failed`);return}let Q;try{Q=await Z$(Y)}catch(V){K(`session "${this.sessionName}": background card id_convert failed: ${V}`);return}if(d0(Q,Z.length),!this.ownsBackgroundOpen($)){await this.terminalizeSupersededCard(Q,"⚠️ 后台任务世代已切换,本卡已作废",!1);return}if(this.backgroundCard={messageId:Y,cardId:Q},this.backgroundDetailAdded=new Set(Z.map((V)=>V.id)),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card opened cardId=${Q.slice(0,12)} tasks=${Z.length}`),!R1(this.backgroundTasks)){this.settleBackgroundCard().catch((V)=>{K(`session "${this.sessionName}": background settle-after-open failed: ${O(V)}`)});return}this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}finally{this.releaseBackgroundOpen($)}}startBackgroundRefreshTick(){if(this.backgroundRefreshTick)return;let $=()=>{if(this.migratingBackgroundCard||!this.backgroundCard||!R1(this.backgroundTasks))return;let Z=s1(),J=Date.now(),Y=1/0;for(let Q of this.backgroundTasks){if(t0(Q))continue;let V=t$(J-Q.startedAt,Z).nextDelayMs;if(V<Y)Y=V}if(!isFinite(Y))return;this.backgroundRefreshTick=setTimeout(()=>{this.refreshBackgroundCardFull(),$()},Math.max(1,Math.ceil(Y)))};$()}stopBackgroundRefreshTick(){if(this.backgroundRefreshTick)clearTimeout(this.backgroundRefreshTick),this.backgroundRefreshTick=null}scheduleBackgroundRefresh(){if(!this.backgroundCard||this.settlingBackgroundCard||this.migratingBackgroundCard)return;if(this.backgroundRefreshTimer)return;this.backgroundRefreshTimer=setTimeout(()=>{this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull()},1500)}refreshBackgroundCardFull(){if(this.migratingBackgroundCard)return;let $=this.backgroundCard;if(!$)return;let Z=Date.now(),J=s1();for(let Y of this.backgroundTasks)if(!this.backgroundDetailAdded.has(Y.id)){if(this.backgroundDetailAdding.has(Y.id))continue;this.backgroundDetailAdding.add(Y.id),Y1($.cardId,j2(Y,Z,J)).then((Q)=>{if(Q)this.backgroundDetailAdded.add(Y.id);else K(`session "${this.sessionName}": background panel add MISS task=${Y.id}`)}).finally(()=>{this.backgroundDetailAdding.delete(Y.id)})}else J0($.cardId,R4.panel(Y.id),j2(Y,Z,J));w1($.cardId,z8(this.backgroundTasks))}async resetBackgroundTasks(){if(this.invalidateBackgroundOpen(),this.backgroundTasks.some(($)=>!t0($))){let $=Date.now();this.backgroundTasks=this.backgroundTasks.map((Z)=>t0(Z)?Z:{...Z,status:"killed",endTime:Z.endTime??$})}if(this.pendingBgTasks=[],this.backgroundCard)await this.settleBackgroundCard();if(this.stopBackgroundRefreshTick(),this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;this.backgroundTasks=[],this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear()}async settleBackgroundCard(){if(this.migratingBackgroundCard)try{await this.migratingBackgroundCard}catch(J){K(`session "${this.sessionName}": background migration failed before settle; retry terminal snapshot: ${O(J)}`)}let $=this.backgroundCard;if(!$||this.settlingBackgroundCard)return;this.settlingBackgroundCard=!0;let Z=[...this.backgroundTasks];if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;this.stopBackgroundRefreshTick();try{if(await O$($.cardId),await A$($.messageId,W8(Z)),A0($.cardId),!await P0($.cardId,h$({suffix:"\uD83E\uDDED 后台任务已结束"})))throw Error("background history streaming-off rejected");if(await v0($.cardId),this.backgroundCard===$)this.backgroundCard=null;this.backgroundTasks=this.backgroundTasks.filter((Y)=>!t0(Y)),this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card settled cardId=${$.cardId.slice(0,12)} remaining=${this.backgroundTasks.length}`)}finally{if(this.settlingBackgroundCard=!1,this.backgroundCard===$&&R1(this.backgroundTasks))this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}if(this.backgroundTasks.length>0)this.onBackgroundTaskChanged()}migrateBackgroundCard(){if(this.migratingBackgroundCard)return this.migratingBackgroundCard;let $=this.backgroundCard;if(!$)return Promise.resolve();let Z=this.performBackgroundCardMigration($),J;return J=Z.finally(()=>{if(this.migratingBackgroundCard===J)this.migratingBackgroundCard=null}),this.migratingBackgroundCard=J,J}async performBackgroundCardMigration($){if(this.backgroundCard!==$)return;if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;if(this.stopBackgroundRefreshTick(),await O$($.cardId),this.backgroundCard!==$)return;let Z=[...this.backgroundTasks],J=new Set(Z.filter(t0).map((V)=>V.id)),Y=J.size;if(Y>0)await A$($.messageId,W8(Z));else await A$($.messageId,B3());if(A0($.cardId),!await P0($.cardId,h$({suffix:"\uD83E\uDDED 已迁移至新卡"})))throw Error("background migration streaming-off rejected");if(await v0($.cardId),this.backgroundCard===$)this.backgroundCard=null;this.backgroundTasks=this.backgroundTasks.filter((V)=>!J.has(V.id)||!t0(V)),this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card migrated cardId=${$.cardId.slice(0,12)} terminal=${Y} active=${this.backgroundTasks.length}`)}startScheduledTurnCard($,Z,J,Y){if(this.proc!==$||this.procEpoch!==Z||!$.isAlive())return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.bgResumePending)return;let Q;try{Q=this.beginTurnOpen($,Z,!0)}catch(H){K(`session "${this.sessionName}": scheduled turn-open ownership conflict: ${O(H)}`);return}let V=J.replace(/\s+/g," ").trim();this.lastTurnUserPreview=`⏰ ${V.slice(0,78)}`,K(`session "${this.sessionName}": scheduled wakeup prompt=${Y??"MISS"}`),(async()=>{try{let H=await this.openTurnCard(Q,"","scheduled_wakeup");if(this.proc!==$||this.procEpoch!==Z){if(K(`session "${this.sessionName}": scheduled ${$.provider} turn became stale while opening epoch=${Z}`),H&&this.currentTurn===H)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);return}if(!H||this.currentTurn!==H){if(!this.ownsTurnOpen(Q))return;if(this.bgResumeCardless=!0,Q.sawResult)Q.sawResult=!1,K(`session "${this.sessionName}": scheduled open failed after result — flushing orphan now`),this.flushOrphanAssistantToChat("scheduled open failed, result already arrived");else K(`session "${this.sessionName}": scheduled open failed — orphan text flush will cover the output`)}else if(Q.sawResult)Q.sawResult=!1,K(`session "${this.sessionName}": scheduled result raced card-open — closing freshly-opened card`),await this.closeTurnCard(Q.terminalSuffix,{forcePush:Q.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(Q)}})().catch((H)=>{K(`session "${this.sessionName}": scheduled turn-open handler failed: ${O(H)}`)})}wireProc($,Z){if(Z===void 0)this.invalidateTurnOpen(),this.invalidateBackgroundOpen();let J=Z??++this.procEpoch;if(Z===void 0&&this.proc!==$)this.proc=$;let Y=()=>this.proc===$&&this.procEpoch===J,Q=!1,V=!1,H=(X,z)=>{$.on(X,(W)=>{if(!Y()){if(!Q)Q=!0,K(`session "${this.sessionName}": ignore stale ${$.provider} event=${String(X)} epoch=${J} currentEpoch=${this.procEpoch}`);return}if(X!=="exit"&&(this.stoppingProc===$||this.blockedProc===$)){if(!V)V=!0,K(`session "${this.sessionName}": ignore ${$.provider} event=${String(X)} while process stop is pending`);return}z(W)})};H("error",(X)=>{K(`session "${this.sessionName}": ${$.provider} process error: ${X}`)}),H("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++,K(`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)K(`session "${this.sessionName}": SDK init claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;return}let X=this.pendingUserMessageCount>0,z=!X&&this.bgResumePending;if(!X&&!z)return;let W=this.lastUserOpenId,G;try{G=this.beginTurnOpen($,J,!0)}catch(j){K(`session "${this.sessionName}": init turn-open ownership conflict: ${O(j)}`);return}if(this.bgResumePending=!1,X)this.pendingUserMessageCount=0,this.currentBatchReactionIds=this.pendingReactionIds,this.pendingReactionIds=new Map;let B=X?[...this.currentBatchReactionIds.keys()]:[],_=()=>{for(let j of B){let q=this.currentBatchReactionIds.get(j);if(this.currentBatchReactionIds.delete(j),q)C0(j,q)}};(async()=>{try{let j=await this.openTurnCard(G,W,X?"user_message":"bg_task_resume");if(!Y()){if(K(`session "${this.sessionName}": ${$.provider} became stale while opening turn card epoch=${J}`),j&&this.currentTurn===j)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);_();return}if(!j||this.currentTurn!==j){if(!this.ownsTurnOpen(G)){_();return}if(G.sawResult&&G.terminalSuffix)w(this.chatId,G.terminalSuffix);if(X)K(`session "${this.sessionName}": init-path openTurnCard failed — sendInterrupt + release reactions`),this.proc?.sendInterrupt(),_();else if(this.bgResumeCardless=!0,G.sawResult)G.sawResult=!1,K(`session "${this.sessionName}": bg-resume openTurnCard failed, result already arrived — flushing orphan now`),this.flushOrphanAssistantToChat("bg-resume open failed, result already arrived");else K(`session "${this.sessionName}": bg-resume openTurnCard failed — orphan text flush will cover the output`)}else if(G.sawResult)G.sawResult=!1,K(`session "${this.sessionName}": result raced card-open — closing freshly-opened turn card now`),await this.closeTurnCard(G.terminalSuffix,{forcePush:G.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(G)}})().catch((j)=>{K(`session "${this.sessionName}": init turn-open handler failed: ${O(j)}`)})}),H("scheduled_turn_input",({text:X,promptId:z})=>{if($.provider!=="claude"&&$.provider!=="dsh")return;this.startScheduledTurnCard($,J,X,z)}),H("conversation_materialized",({session_id:X,source:z})=>{if($.provider!=="codex")return;if($.sessionId!==X){K(`session "${this.sessionName}": ignore mismatched Codex materialization session=${X} current=${$.sessionId??"MISS"} source=${z}`);return}K(`session "${this.sessionName}": Codex resume point materialized thread=${X} source=${z}`),this.persistResumableSessionId()}),H("conversation_materialization_failed",({session_id:X,source:z,error:W})=>{if($.provider!=="codex"||$.sessionId!==X)return;let G=`Codex 会话落盘确认失败,未写恢复点: ${O(W)}`,B=this.resumePersistenceError!==G;if(this.resumePersistenceError=G,K(`session "${this.sessionName}": ${G} thread=${X} source=${z}`),B)w(this.chatId,`⚠️ ${G}`)}),H("turn_retry",()=>{if(this.currentTurn)this.startThinkingFooter(this.currentTurn)}),H("codex_account_changed",({accountId:X,diagnostics:z})=>{if(K(`session "${this.sessionName}": Codex account=${X}`),this.pendingAsks.clear(),this.pendingPermissions.clear(),z.length)c(this.chatId,V$({phase:"warning",title:"部分账号 MISS",message:`${z.length} 个账号未参与选择`,details:z.join(`
|
|
260
|
-
`),hint:"详情:codex-accounts"})).catch((W)=>{K(`session "${this.sessionName}": 账号诊断卡失败: ${O(W)}`)})}),H("turn_started",({retry:X})=>{if((this.currentTurn||this.openingTurn)&&this.pendingUserMessageCount>0)K(`session "${this.sessionName}": turn_started claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;if(this.persistResumableSessionId(),X){if(this.currentTurn)this.startThinkingFooter(this.currentTurn);return}let z=this.proc?.lastTotalUsage;if(this.usageTotalsSeedUnknown&&!z){this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;return}this.currentTurnUsageBaseline=z?{...z}:null,this.currentTurnUsageBaselineKnown=!0}),H("token_usage",({totalUsage:X})=>{if(this.persistResumableSessionId(),X)this.usageTotalsSeedUnknown=!1}),H("turn_plan_updated",(X)=>{this.handleTurnPlanUpdated(X)}),H("plan_delta",(X)=>{this.handlePlanDelta(X)}),H("context_compacted",(X)=>{this.handleContextCompacted(X)}),H("rate_limits_updated",(X)=>{if($.provider==="codex")
|
|
259
|
+
`:"")+$,z=(W)=>{this.pendingReactionIds.set(W,""),(async()=>{let G=await l0(W,"OneSecond");if(!G)return;if(this.pendingReactionIds.has(W))this.pendingReactionIds.set(W,G);else if(this.currentBatchReactionIds.has(W))this.currentBatchReactionIds.set(W,G);else C0(W,G)})().catch((G)=>{K(`session "${this.sessionName}": reaction tracking failed: ${O(G)}`)})};if(!this.isRunning()){if(this.openingTurn||this.currentTurn){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}await this.startColdUserTurn($,X,J);return}if(this.currentTurn!==null){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}if(!this.openingTurn&&this.initCount>=1){let W=this.proc,G=this.procEpoch,B=this.beginTurnOpen(W,G);try{this.pendingTurnInputs.push($);let _=await this.openTurnCard(B,J,"user_message");if(!_||this.currentTurn!==_)return;if(this.proc!==W||this.procEpoch!==G||!W.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel(W.provider)} 已退出`);return}this.sendClaimedUserText(W,X),this.status="working"}finally{this.releaseTurnOpen(B)}return}if(this.openingTurn||this.pendingUserMessageCount>0){if(this.pendingMidTurnMsgs.push({text:$,wireText:X,userOpenId:J,msgId:Y}),Y)z(Y);return}if(this.pendingTurnInputs.push($),this.sendClaimedUserText(this.proc,X),V&&Y)z(Y)}hasPendingAsk(){return RX(this)}refreshPendingAsks(){O6(this)}askBlockReason($){return l2(this,$)}onMultiMessageInbound($,Z,J,Y){return JX(this,$,Z,J,Y)}clearMultiMsgBuffer($){FZ(this,$)}onAskMessageAnswer($,Z,J){return NX(this,$,Z,J)}onAskAnswer($,Z,J,Y){return TX(this,$,Z,J,Y)}onAskCustomAnswer($,Z,J,Y){return bZ(this,$,Z,J,Y)}onPermissionDecision($,Z,J){return kX(this,$,Z,J)}clearResumeBindingForFreshCodex($){if($.isConversationResumable?.())throw Error("fresh Codex thread was unexpectedly marked resumable during init");let Z=Z1(this.sessionName,"codex");if(C2(this.sessionName,"codex"),this.selectedProvider==="codex")this.lastSessionRef=null,this.lastSessionId=null;if(Z)K(`session "${this.sessionName}": cleared pre-fresh Codex resume binding thread=${Z.sessionId}`)}invalidateMissingCodexResume($,Z,J){if(!$||this.selectedProvider!=="codex")return null;let Y=AJ(Z);if(!Y||!["thread/read","thread/resume","thread/fork"].includes(Y.method)||Y.serverCode!==-32600||Y.serverMessage!==`no rollout found for thread id ${$}`)return null;let Q=Z1(this.sessionName,"codex");if(!Q||Q.sessionId!==$)return null;try{C2(this.sessionName,"codex")}catch(H){let X=`已确认恢复点无 rollout,但作废失败: ${O(H)}`;return K(`session "${this.sessionName}": ${X} thread=${$}`),X}if(this.lastSessionRef?.provider==="codex"&&this.lastSessionRef.sessionId===$)this.lastSessionRef=null,this.lastSessionId=null;J?.($);let V=`已作废无 rollout 的恢复点 thread=${U0($)}`;return K(`session "${this.sessionName}": ${V} fullThread=${$}`),V}persistResumableSessionId($=!1,Z=this.proc,J=!0){let Y=Z?.provider==="claude"?this.pendingConversationMaterialization:null,Q=Z?.sessionId;if(!Z)return null;if(Z.provider==="codex"&&Z.isConversationResumable?.()!==!0)return null;if(!Q){if(!Y)return null;let X=Error("Claude pending fork did not provide a materialized session id");if(K(`session "${this.sessionName}": ${X.message}`),$)throw X;return X.message}let V={provider:Z.provider,sessionId:Q,cwd:this.workDir};if(Y&&(Q===Y.launch.source.sessionId||Y.previousSessionId!==null&&Q===Y.previousSessionId)){let X=Error(`Claude fork did not materialize an independent session id (${Q})`);if(K(`session "${this.sessionName}": ${X.message}`),$)throw X;return X.message}try{u4(this.sessionName,V)}catch(X){let z=`会话恢复点持久化失败: ${O(X)}`,W=this.resumePersistenceError!==z;if(this.resumePersistenceError=z,Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Q;if(K(`session "${this.sessionName}": ${z}`),$)throw X;if(W&&J)w(this.chatId,`⚠️ ${z};当前进程可继续,但 daemon 重启前请先解决本机状态目录写入问题。`);return z}if(Z.provider===this.selectedProvider)this.lastSessionRef=V,this.lastSessionId=Q;let H=Z.provider==="codex"?this.flushPendingCodexTurnAnchors(Z):null;if(H){let X=this.resumePersistenceError!==H;if(this.resumePersistenceError=H,$)throw Error(H);if(X&&J)w(this.chatId,`⚠️ ${H}`);return H}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 K(`session "${this.sessionName}": ${"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker"}`),"Claude 待生成分支没有可验证的新会话恢复点,保留 pending marker";try{return J1(this.sessionName,null),this.pendingConversationMaterialization=null,null}catch(J){let Y=`Claude 待生成分支标记清除失败: ${O(J)}`;return K(`session "${this.sessionName}": ${Y}`),Y}}bgStore(){return{active:this.backgroundTasks,pending:this.pendingBgTasks}}applyBgStore($){this.backgroundTasks=$.active,this.pendingBgTasks=$.pending}onMainThreadAdvance(){if(this.pendingBgTasks.length===0)return;this.applyBgStore(V3(this.bgStore())),this.onBackgroundTaskChanged()}bgTaskOwns($){return this.backgroundTasks.some((Z)=>Z.toolUseId===$)||this.pendingBgTasks.some((Z)=>Z.toolUseId===$)}onBackgroundTaskChanged(){if(this.migratingBackgroundCard){this.pendingRebuildBackgroundCard=!0;return}if(!R1(this.backgroundTasks)){if(this.backgroundCard)this.settleBackgroundCard().catch((Z)=>{K(`session "${this.sessionName}": background settle failed: ${O(Z)}`)});return}if(!this.backgroundCard&&!this.openingBackground){this.openBackgroundCard().catch((Z)=>{K(`session "${this.sessionName}": background open failed: ${O(Z)}`)});return}this.scheduleBackgroundRefresh()}async openBackgroundCard(){let $=this.beginBackgroundOpen();if(!$)return;let Z=this.backgroundTasks.slice();try{let J=G3(Z,Date.now(),s1()),Y=await c(this.chatId,J);if(!Y){if(this.ownsBackgroundOpen($))K(`session "${this.sessionName}": background card send failed`);return}let Q;try{Q=await Z$(Y)}catch(V){K(`session "${this.sessionName}": background card id_convert failed: ${V}`);return}if(d0(Q,Z.length),!this.ownsBackgroundOpen($)){await this.terminalizeSupersededCard(Q,"⚠️ 后台任务世代已切换,本卡已作废",!1);return}if(this.backgroundCard={messageId:Y,cardId:Q},this.backgroundDetailAdded=new Set(Z.map((V)=>V.id)),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card opened cardId=${Q.slice(0,12)} tasks=${Z.length}`),!R1(this.backgroundTasks)){this.settleBackgroundCard().catch((V)=>{K(`session "${this.sessionName}": background settle-after-open failed: ${O(V)}`)});return}this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}finally{this.releaseBackgroundOpen($)}}startBackgroundRefreshTick(){if(this.backgroundRefreshTick)return;let $=()=>{if(this.migratingBackgroundCard||!this.backgroundCard||!R1(this.backgroundTasks))return;let Z=s1(),J=Date.now(),Y=1/0;for(let Q of this.backgroundTasks){if(t0(Q))continue;let V=t$(J-Q.startedAt,Z).nextDelayMs;if(V<Y)Y=V}if(!isFinite(Y))return;this.backgroundRefreshTick=setTimeout(()=>{this.refreshBackgroundCardFull(),$()},Math.max(1,Math.ceil(Y)))};$()}stopBackgroundRefreshTick(){if(this.backgroundRefreshTick)clearTimeout(this.backgroundRefreshTick),this.backgroundRefreshTick=null}scheduleBackgroundRefresh(){if(!this.backgroundCard||this.settlingBackgroundCard||this.migratingBackgroundCard)return;if(this.backgroundRefreshTimer)return;this.backgroundRefreshTimer=setTimeout(()=>{this.backgroundRefreshTimer=null,this.refreshBackgroundCardFull()},1500)}refreshBackgroundCardFull(){if(this.migratingBackgroundCard)return;let $=this.backgroundCard;if(!$)return;let Z=Date.now(),J=s1();for(let Y of this.backgroundTasks)if(!this.backgroundDetailAdded.has(Y.id)){if(this.backgroundDetailAdding.has(Y.id))continue;this.backgroundDetailAdding.add(Y.id),Y1($.cardId,j2(Y,Z,J)).then((Q)=>{if(Q)this.backgroundDetailAdded.add(Y.id);else K(`session "${this.sessionName}": background panel add MISS task=${Y.id}`)}).finally(()=>{this.backgroundDetailAdding.delete(Y.id)})}else J0($.cardId,R4.panel(Y.id),j2(Y,Z,J));w1($.cardId,X8(this.backgroundTasks))}async resetBackgroundTasks(){if(this.invalidateBackgroundOpen(),this.backgroundTasks.some(($)=>!t0($))){let $=Date.now();this.backgroundTasks=this.backgroundTasks.map((Z)=>t0(Z)?Z:{...Z,status:"killed",endTime:Z.endTime??$})}if(this.pendingBgTasks=[],this.backgroundCard)await this.settleBackgroundCard();if(this.stopBackgroundRefreshTick(),this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;this.backgroundTasks=[],this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear()}async settleBackgroundCard(){if(this.migratingBackgroundCard)try{await this.migratingBackgroundCard}catch(J){K(`session "${this.sessionName}": background migration failed before settle; retry terminal snapshot: ${O(J)}`)}let $=this.backgroundCard;if(!$||this.settlingBackgroundCard)return;this.settlingBackgroundCard=!0;let Z=[...this.backgroundTasks];if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;this.stopBackgroundRefreshTick();try{if(await O$($.cardId),await A$($.messageId,z8(Z)),A0($.cardId),!await P0($.cardId,h$({suffix:"\uD83E\uDDED 后台任务已结束"})))throw Error("background history streaming-off rejected");if(await v0($.cardId),this.backgroundCard===$)this.backgroundCard=null;this.backgroundTasks=this.backgroundTasks.filter((Y)=>!t0(Y)),this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card settled cardId=${$.cardId.slice(0,12)} remaining=${this.backgroundTasks.length}`)}finally{if(this.settlingBackgroundCard=!1,this.backgroundCard===$&&R1(this.backgroundTasks))this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}if(this.backgroundTasks.length>0)this.onBackgroundTaskChanged()}migrateBackgroundCard(){if(this.migratingBackgroundCard)return this.migratingBackgroundCard;let $=this.backgroundCard;if(!$)return Promise.resolve();let Z=this.performBackgroundCardMigration($),J;return J=Z.finally(()=>{if(this.migratingBackgroundCard===J)this.migratingBackgroundCard=null}),this.migratingBackgroundCard=J,J}async performBackgroundCardMigration($){if(this.backgroundCard!==$)return;if(this.backgroundRefreshTimer)clearTimeout(this.backgroundRefreshTimer),this.backgroundRefreshTimer=null;if(this.stopBackgroundRefreshTick(),await O$($.cardId),this.backgroundCard!==$)return;let Z=[...this.backgroundTasks],J=new Set(Z.filter(t0).map((V)=>V.id)),Y=J.size;if(Y>0)await A$($.messageId,z8(Z));else await A$($.messageId,K3());if(A0($.cardId),!await P0($.cardId,h$({suffix:"\uD83E\uDDED 已迁移至新卡"})))throw Error("background migration streaming-off rejected");if(await v0($.cardId),this.backgroundCard===$)this.backgroundCard=null;this.backgroundTasks=this.backgroundTasks.filter((V)=>!J.has(V.id)||!t0(V)),this.backgroundDetailAdded.clear(),this.backgroundDetailAdding.clear(),K(`session "${this.sessionName}": background card migrated cardId=${$.cardId.slice(0,12)} terminal=${Y} active=${this.backgroundTasks.length}`)}startScheduledTurnCard($,Z,J,Y){if(this.proc!==$||this.procEpoch!==Z||!$.isAlive())return;if(this.currentTurn||this.openingTurn||this.pendingUserMessageCount>0||this.bgResumePending)return;let Q;try{Q=this.beginTurnOpen($,Z,!0)}catch(H){K(`session "${this.sessionName}": scheduled turn-open ownership conflict: ${O(H)}`);return}let V=J.replace(/\s+/g," ").trim();this.lastTurnUserPreview=`⏰ ${V.slice(0,78)}`,K(`session "${this.sessionName}": scheduled wakeup prompt=${Y??"MISS"}`),(async()=>{try{let H=await this.openTurnCard(Q,"","scheduled_wakeup");if(this.proc!==$||this.procEpoch!==Z){if(K(`session "${this.sessionName}": scheduled ${$.provider} turn became stale while opening epoch=${Z}`),H&&this.currentTurn===H)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);return}if(!H||this.currentTurn!==H){if(!this.ownsTurnOpen(Q))return;if(this.bgResumeCardless=!0,Q.sawResult)Q.sawResult=!1,K(`session "${this.sessionName}": scheduled open failed after result — flushing orphan now`),this.flushOrphanAssistantToChat("scheduled open failed, result already arrived");else K(`session "${this.sessionName}": scheduled open failed — orphan text flush will cover the output`)}else if(Q.sawResult)Q.sawResult=!1,K(`session "${this.sessionName}": scheduled result raced card-open — closing freshly-opened card`),await this.closeTurnCard(Q.terminalSuffix,{forcePush:Q.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(Q)}})().catch((H)=>{K(`session "${this.sessionName}": scheduled turn-open handler failed: ${O(H)}`)})}wireProc($,Z){if(Z===void 0)this.invalidateTurnOpen(),this.invalidateBackgroundOpen();let J=Z??++this.procEpoch;if(Z===void 0&&this.proc!==$)this.proc=$;let Y=()=>this.proc===$&&this.procEpoch===J,Q=!1,V=!1,H=(X,z)=>{$.on(X,(W)=>{if(!Y()){if(!Q)Q=!0,K(`session "${this.sessionName}": ignore stale ${$.provider} event=${String(X)} epoch=${J} currentEpoch=${this.procEpoch}`);return}if(X!=="exit"&&(this.stoppingProc===$||this.blockedProc===$)){if(!V)V=!0,K(`session "${this.sessionName}": ignore ${$.provider} event=${String(X)} while process stop is pending`);return}z(W)})};H("error",(X)=>{K(`session "${this.sessionName}": ${$.provider} process error: ${X}`)}),H("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++,K(`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)K(`session "${this.sessionName}": SDK init claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;return}let X=this.pendingUserMessageCount>0,z=!X&&this.bgResumePending;if(!X&&!z)return;let W=this.lastUserOpenId,G;try{G=this.beginTurnOpen($,J,!0)}catch(j){K(`session "${this.sessionName}": init turn-open ownership conflict: ${O(j)}`);return}if(this.bgResumePending=!1,X)this.pendingUserMessageCount=0,this.currentBatchReactionIds=this.pendingReactionIds,this.pendingReactionIds=new Map;let B=X?[...this.currentBatchReactionIds.keys()]:[],_=()=>{for(let j of B){let q=this.currentBatchReactionIds.get(j);if(this.currentBatchReactionIds.delete(j),q)C0(j,q)}};(async()=>{try{let j=await this.openTurnCard(G,W,X?"user_message":"bg_task_resume");if(!Y()){if(K(`session "${this.sessionName}": ${$.provider} became stale while opening turn card epoch=${J}`),j&&this.currentTurn===j)await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);_();return}if(!j||this.currentTurn!==j){if(!this.ownsTurnOpen(G)){_();return}if(G.sawResult&&G.terminalSuffix)w(this.chatId,G.terminalSuffix);if(X)K(`session "${this.sessionName}": init-path openTurnCard failed — sendInterrupt + release reactions`),this.proc?.sendInterrupt(),_();else if(this.bgResumeCardless=!0,G.sawResult)G.sawResult=!1,K(`session "${this.sessionName}": bg-resume openTurnCard failed, result already arrived — flushing orphan now`),this.flushOrphanAssistantToChat("bg-resume open failed, result already arrived");else K(`session "${this.sessionName}": bg-resume openTurnCard failed — orphan text flush will cover the output`)}else if(G.sawResult)G.sawResult=!1,K(`session "${this.sessionName}": result raced card-open — closing freshly-opened turn card now`),await this.closeTurnCard(G.terminalSuffix,{forcePush:G.terminalForcePush,hasFreshResult:!0}),this.status="idle";else this.status="working"}finally{this.releaseTurnOpen(G)}})().catch((j)=>{K(`session "${this.sessionName}": init turn-open handler failed: ${O(j)}`)})}),H("scheduled_turn_input",({text:X,promptId:z})=>{if($.provider!=="claude"&&$.provider!=="dsh")return;this.startScheduledTurnCard($,J,X,z)}),H("conversation_materialized",({session_id:X,source:z})=>{if($.provider!=="codex")return;if($.sessionId!==X){K(`session "${this.sessionName}": ignore mismatched Codex materialization session=${X} current=${$.sessionId??"MISS"} source=${z}`);return}K(`session "${this.sessionName}": Codex resume point materialized thread=${X} source=${z}`),this.persistResumableSessionId()}),H("conversation_materialization_failed",({session_id:X,source:z,error:W})=>{if($.provider!=="codex"||$.sessionId!==X)return;let G=`Codex 会话落盘确认失败,未写恢复点: ${O(W)}`,B=this.resumePersistenceError!==G;if(this.resumePersistenceError=G,K(`session "${this.sessionName}": ${G} thread=${X} source=${z}`),B)w(this.chatId,`⚠️ ${G}`)}),H("turn_retry",()=>{if(this.currentTurn)this.startThinkingFooter(this.currentTurn)}),H("codex_account_changed",({accountId:X,diagnostics:z})=>{if(K(`session "${this.sessionName}": Codex account=${X}`),this.pendingAsks.clear(),this.pendingPermissions.clear(),z.length)c(this.chatId,V$({phase:"warning",title:"部分账号 MISS",message:`${z.length} 个账号未参与选择`,details:z.join(`
|
|
260
|
+
`),hint:"详情:codex-accounts"})).catch((W)=>{K(`session "${this.sessionName}": 账号诊断卡失败: ${O(W)}`)})}),H("turn_started",({retry:X})=>{if((this.currentTurn||this.openingTurn)&&this.pendingUserMessageCount>0)K(`session "${this.sessionName}": turn_started claimed eager input pendingCount=${this.pendingUserMessageCount}`),this.pendingUserMessageCount=0;if(this.persistResumableSessionId(),X){if(this.currentTurn)this.startThinkingFooter(this.currentTurn);return}let z=this.proc?.lastTotalUsage;if(this.usageTotalsSeedUnknown&&!z){this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;return}this.currentTurnUsageBaseline=z?{...z}:null,this.currentTurnUsageBaselineKnown=!0}),H("token_usage",({totalUsage:X})=>{if(this.persistResumableSessionId(),X)this.usageTotalsSeedUnknown=!1}),H("turn_plan_updated",(X)=>{this.handleTurnPlanUpdated(X)}),H("plan_delta",(X)=>{this.handlePlanDelta(X)}),H("context_compacted",(X)=>{this.handleContextCompacted(X)}),H("rate_limits_updated",(X)=>{if($.provider==="codex")nQ(X,r0($))}),H("thread_goal_updated",(X)=>{this.handleThreadGoalUpdated(X)}),H("thread_goal_cleared",()=>{this.handleThreadGoalCleared()}),H("assistant_text",({text:X,parentToolUseId:z})=>{if(z)return;this.appendAssistant(X)}),H("assistant_block_stop",({parentToolUseId:X})=>{if(X)return;this.finalizeCurrentAssistantSegment(),this.onMainThreadAdvance()}),H("tool_use",({id:X,name:z,input:W,parentToolUseId:G})=>{if(G&&this.bgTaskOwns(G)){this.applyBgStore(X3({active:this.backgroundTasks,pending:this.pendingBgTasks},G,X,z,W)),this.onBackgroundTaskChanged();return}if(SX(this,X,z,W),!G)this.onMainThreadAdvance();if(!G&&(z==="Task"||z==="Agent"))this.lastMainTaskToolUseId=X}),H("tool_result",({tool_use_id:X,content:z,is_error:W,parentToolUseId:G,input:B})=>{if(G&&this.bgTaskOwns(G)){this.applyBgStore(W3({active:this.backgroundTasks,pending:this.pendingBgTasks},G,X,z,W)),this.onBackgroundTaskChanged();return}bX(this,X,z,W,B)}),H("can_use_tool",(X)=>{yX(this,X)}),H("hook_callback",(X)=>{this.proc?.sendHookResponse(X.request_id,{})}),H("result",(X)=>{let z=this.persistResumableSessionId(),W=z?null:this.consumePendingConversationMaterialization(),G=[z,W].filter(Boolean).join(";")||null;if(this.accumulateResultStats(),this.openingTurnOwner)this.openingTurnOwner.sawResult=!0;if(this.userInterrupted){this.userInterrupted=!1,this.discardOrphanAssistant(),this.bgResumePending=!1;let U=this.proc?.lastResult.subtype??"unknown",S=this.proc?.lastResult.is_error===!0;K(`session "${this.sessionName}": SDK result after user stop subtype=${U} isError=${S} — ignored`),this.status="idle";return}let B=X?.is_error!==!0?this.recordTurnAnchor(X?.checkpoint):null;if(X?.is_error===!0)this.lastTurnUserPreview="";if(!this.currentTurn&&!this.openingTurn)this.flushOrphanAssistantToChat("result with no turn card");let _=this.pendingMidTurnMsgs.length>0,j=this.proc?.lastResult.is_error===!0,q=this.proc?.lastResult.subtype??"success",P=typeof X?.error==="string"&&X.error.trim()?X.error.trim():q,D,T=!1,M=this.proc?this.backendLabel(this.proc.provider):this.backendLabel(),A=[G,B].filter(Boolean).join(";")||null;if(A)D=`⚠️ ${A}`,T=!0;else if(_)D=j?`⚠️ ${M} ${P},用户已介入`:"\uD83D\uDCE8 转交新卡";else if(j)D=`⚠️ ${M} ${P}`,T=!0;if(this.openingTurnOwner)this.openingTurnOwner.terminalSuffix=D,this.openingTurnOwner.terminalForcePush=T;if(A&&!this.currentTurn&&!this.openingTurn)w(this.chatId,`⚠️ ${A}`);if(K(`session "${this.sessionName}": SDK result subtype=${q} isError=${j} midBuffer=${this.pendingMidTurnMsgs.length} forcePush=${T}`),this.closeTurnCard(D,{forcePush:T,hasFreshResult:!0}).catch((U)=>{K(`session "${this.sessionName}": result card close failed: ${O(U)}`)}),this.status="idle",_)this.drainMidTurnAndOpen().catch((U)=>{K(`session "${this.sessionName}": mid-turn drain failed: ${O(U)}`)})}),H("bg_task_started",(X)=>{let z=X.tool_use_id??this.lastMainTaskToolUseId??void 0;K(`session "${this.sessionName}": bg_task_started task=${X.task_id} type=${X.task_type??"-"} subagent=${X.subagent_type??"-"} toolUseId=${z?.slice(0,8)??"-"} desc=${(X.description??"").slice(0,40)}`),this.applyBgStore(J3(this.bgStore(),{...X,tool_use_id:z})),this.onBackgroundTaskChanged()}),H("bg_task_progress",(X)=>{this.applyBgStore(Y3(this.bgStore(),X)),this.onBackgroundTaskChanged()}),H("bg_task_updated",(X)=>{this.applyBgStore(Q3(this.bgStore(),X)),this.onBackgroundTaskChanged()}),H("bg_task_settled",(X)=>{if(K(`session "${this.sessionName}": bg_task_settled task=${X.task_id} status=${X.status}`),this.applyBgStore(H3(this.bgStore(),X)),this.onBackgroundTaskChanged(),$.provider==="claude"&&!this.currentTurn&&!this.openingTurn&&this.initCount>=1)this.bgResumePending=!0}),H("subagent_step",(X)=>{this.applyBgStore(z3(this.bgStore(),X.thread_id,X.item_id,X.tool,X.phase,X.brief)),this.onBackgroundTaskChanged()}),H("exit",({code:X,signal:z,expected:W})=>{if(K(`session "${this.sessionName}": ${$.provider} exited code=${X} signal=${z} expected=${W}`),this.stoppingProc===$||this.blockedProc===$){if(this.blockedProc===$){let q=$.conversationMaterializationFailure?.(),P=this.persistResumableSessionId(!1,$,!1),D=[q&&$.isConversationResumable?.()!==!0?`Codex 会话落盘确认失败: ${O(q)}`:null,P].filter(Boolean).join(";");if(D)w(this.chatId,`⚠️ 旧进程退出后的恢复状态收尾失败: ${D}`);this.discardPendingCodexTurnAnchors($,"blocked process finally exited")}K(`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((q)=>{K(`session "${this.sessionName}": cancel Agent runs after process exit failed: ${O(q)}`)});let G=this.backendLabel($.provider),B=`code=${X??"null"}, signal=${z??"null"}`,_=W?`\uD83D\uDED1 ${G} 已退出`:`⚠️ ${G} 异常退出 (${B})`;if(this.currentTurn)this.closeTurnCard(_).catch((q)=>{K(`session "${this.sessionName}": process-exit current main-card close failed: ${O(q)}`)});let j=this.waitForTurnCloses().catch((q)=>{K(`session "${this.sessionName}": process-exit main-card close failed: ${O(q)}`)});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 q=await Promise.allSettled([j,this.resetBackgroundTasks()]);for(let P of q)if(P.status==="rejected")K(`session "${this.sessionName}": process-exit terminal cleanup failed: ${O(P.reason)}`);if(!W)await E(this.chatId,`⚠️ ${G} 异常退出 (${B})。回复任意消息将重新启动。`)}).catch((q)=>{K(`session "${this.sessionName}": process-exit cleanup rejected: ${O(q)}`)})})}accumulateResultStats(){let $=this.proc?.lastResult;if(!$)return;let Z=this.currentTurnUsageBaselineKnown?g7(this.proc?.lastTotalUsage,this.currentTurnUsageBaseline):this.proc?.provider==="claude"&&$.usage?{...$.usage}:null;this.lastTurnUsage=Z,this.currentTurnUsageBaseline=null,this.currentTurnUsageBaselineKnown=!1;let J=m7(Z),Y=this.proc?.provider==="claude"?0:$.cost_delta_usd??0,Q=$.duration_ms??0;if(J!=null)this.cumStats.tokens+=J;this.cumStats.costUsd+=Y,this.cumStats.turns+=$.num_turns??1,this.lastTurnDelta={tokens:J,costUsd:Y,durationMs:Q}}currentContextTokens($=this.proc){if($?.provider==="claude"||$?.provider==="dsh")return $.lastContextTokens??null;let Z=$?.lastUsage;return u8(Z)}contextLimitForDisplay($=this.proc){return l8($?.lastContextWindow)}async drainMidTurnAndOpen(){if(this.pendingMidTurnMsgs.length===0)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)return;let J;try{J=this.beginTurnOpen($,Z)}catch(Q){K(`session "${this.sessionName}": mid-turn open ownership conflict: ${O(Q)}`);return}let Y=this.pendingMidTurnMsgs;this.pendingMidTurnMsgs=[];try{for(let z of Y)if(this.pendingTurnInputs.push(z.text),z.msgId){let W=this.pendingReactionIds.get(z.msgId)??"";this.currentBatchReactionIds.set(z.msgId,W),this.pendingReactionIds.delete(z.msgId)}let Q=Y.map((z)=>z.wireText).join(`
|
|
261
261
|
|
|
262
|
-
`),H=Y[Y.length-1]?.userOpenId??this.lastUserOpenId,X=await this.openTurnCard(J,H,"user_message");if(!X||this.currentTurn!==X){for(let z of Y){if(!z.msgId)continue;let W=this.currentBatchReactionIds.get(z.msgId);if(this.currentBatchReactionIds.delete(z.msgId),W)C0(z.msgId,W)}this.status="idle";return}if(this.proc!==$||this.procEpoch!==Z||!$.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);for(let z of Y){if(!z.msgId)continue;let W=this.currentBatchReactionIds.get(z.msgId);if(this.currentBatchReactionIds.delete(z.msgId),W)C0(z.msgId,W)}this.status="stopped";return}try{this.sendClaimedUserText($,Q)}catch(z){K(`session "${this.sessionName}": mid-turn sendUserText failed after card open: ${z}`),await this.closeTurnCard(`❌ ${this.backendLabel($.provider)} 接收消息失败`),await w(this.chatId,`❌ ${this.backendLabel($.provider)} 接收消息失败: ${O(z)}。这批消息未开始处理,请重发。`),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 Y=J?await M0($,N.footer,this.footerElement(Z)):!0;A0($);let Q=await P0($,h$({suffix:Z}));if(Y&&Q){await v0($);return}let V=`footer=${Y?"ok":"MISS"}, settings=${Q?"ok":"MISS"}`;K(`session "${this.sessionName}": superseded card terminal transaction incomplete card=${$.slice(0,12)} ${V}`),await w(this.chatId,`⚠️ 已作废卡片未能正常关闭 (${V})。`)}rebuildBackgroundAfterTurnOpenFailure(){if(!this.pendingRebuildBackgroundCard)return;if(this.pendingRebuildBackgroundCard=!1,this.backgroundTasks.length===0)return;this.openBackgroundCard().catch(($)=>{K(`session "${this.sessionName}": background rebuild after turn-open failure failed: ${O($)}`)})}async openTurnCard($,Z,J,Y={}){if(!this.ownsTurnOpen($))return null;if(this.bgResumePending=!1,this.backgroundCard&&R1(this.backgroundTasks))try{await this.migrateBackgroundCard(),this.pendingRebuildBackgroundCard=!0}catch(q){K(`session "${this.sessionName}": background migrate failed (non-blocking): ${q}`),this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}if(!this.ownsTurnOpen($))return null;let Q=++this.turnCounter,V=this.pendingTurnInputs;this.pendingTurnInputs=[],this.lastTurnUserPreview=V[0]?.slice(0,80)??this.lastTurnUserPreview,K(`session "${this.sessionName}": openTurnCard turn=${Q} trigger=${J} inputs=${V.length}`);let H=this.runtimeModelSelection(),X=this.withModel(Y.initialFooter??"Waiting...(0s)",H),z=o8({sessionName:this.sessionName,turn:Q,provider:H.provider,model:H.model??void 0,effort:H.effort??"MISS",kind:J,userInputs:V,initialFooter:X,directStart:Y.directStart}),W=await c(this.chatId,z);if(!W){if(!this.ownsTurnOpen($))return null;if(K(`session "${this.sessionName}": openTurnCard sendCard EXHAUSTED retries — surfacing via raw text`),J==="user_message")await w(this.chatId,`❌ 创建对话卡片失败 (Feishu SDK 重试 3 次后仍连不上)。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。`);return this.rebuildBackgroundAfterTurnOpenFailure(),null}let G;try{G=await Z$(W)}catch(q){if(K(`session "${this.sessionName}": id_convert failed: ${q}`),J==="user_message"&&this.ownsTurnOpen($))await w(this.chatId,`❌ 对话卡片初始化失败。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。`);if(this.ownsTurnOpen($))this.rebuildBackgroundAfterTurnOpenFailure();return null}let B=(J==="bg_task_resume"||J==="scheduled_wakeup"?1:0)+(V.length>0?1:0)+1;if(!this.ownsTurnOpen($))return d0(G,B),await this.terminalizeSupersededCard(G,"⚠️ 会话已切换,本卡已作废",!0),null;let _={cardId:G,...H,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(d0(G,B,(q,P)=>{this.onCardWriteFailure(_,G,q,P)}),this.currentTurn=_,Y.startThinking!==!1)this.startThinkingFooter(_);if($.pendingCompactions.length>0){let q=$.pendingCompactions.splice(0);K(`session "${this.sessionName}": replay ${q.length} context compaction event(s) buffered during card open`);for(let P of q)this.handleContextCompacted(P)}let j=this.takeOrphanAssistantText();if(j)this.appendAssistant(j),this.finalizeCurrentAssistantSegment();if(this.pendingRebuildBackgroundCard){if(this.pendingRebuildBackgroundCard=!1,this.backgroundTasks.length>0)this.openBackgroundCard().catch((q)=>{K(`session "${this.sessionName}": background rebuild failed: ${O(q)}`)})}return _}maybeMidTurnRotate(){let $=this.currentTurn;if(!$)return;if($.rotating)return;if(!$.cardRotationFailed&&t4($.cardId)<zM)return;this.startMidTurnRotate($)}onCardWriteFailure($,Z,J,Y){let Q=this.currentTurn;if(Q!==$){K(`session "${this.sessionName}": ignore stale card failure card=${Z.slice(0,12)} code=${J??"n/a"} (turn owner changed)`);return}if(Q.cardId!==Z){K(`session "${this.sessionName}": ignore retired-card failure card=${Z.slice(0,12)} current=${Q.cardId.slice(0,12)} code=${J??"n/a"}`);return}if(Q.rotating)return;if(Q.cardRotationFailed)return;if(!s4(J,Y)){let H=Y?.operation??"unknown operation",X=Y?.elementId?` element=${Y.elementId}`:"";K(`session "${this.sessionName}": non-capacity card write failure card=${Z.slice(0,12)} operation=${H}${X} code=${J??"n/a"} — not rotating`);let z=`${Z}:${H}:${Y?.elementId??""}:${J??"MISS"}`;if(!Q.cardWriteFailureNotices.has(z))Q.cardWriteFailureNotices.add(z),w(this.chatId,`⚠️ 对话卡片有一项写入失败(code=${J??"MISS"}, ${H}${X})。未识别为卡片容量超限,未自动换卡;其余输出继续处理。`);return}let V=Y?.capacityFingerprint;if(V){let H=Q.cardCapacityFailures.get(V);if(H!==void 0){if(K(`session "${this.sessionName}": unchanged content still exceeds card capacity card=${Z} operation=${Y.operation} element=${Y.elementId??"MISS"} code=${J??"MISS"}`),!H)Q.cardCapacityFailures.set(V,!0),w(this.chatId,`⚠️ 有一项内容换卡后仍超出飞书容量,写入失败(code=${J??"MISS"}, ${Y.operation}, element=${Y.elementId??"MISS"});其余输出继续处理。`);return}Q.cardCapacityFailures.set(V,!1)}K(`session "${this.sessionName}": confirmed card capacity limit (${J}) on card=${Q.cardId.slice(0,8)}… — rotating to fresh card`),Q.failureRotateCount++,this.startMidTurnRotate(Q)}startMidTurnRotate($){if($.rotating)return;$.rotateCount++;let{cardId:Z,toolByUseId:J,toolBatches:Y}=$,Q={value:null},V=(H,X)=>{if(!Q.value)Q.value={code:H,failure:X}};$.rotating=(async()=>{try{K(`session "${this.sessionName}": mid-turn rotate triggered card=${Z.slice(0,8)}… elementCount=${t4(Z)}`);let H=o8({sessionName:this.sessionName,turn:this.turnCounter,provider:$.provider,model:$.model??void 0,effort:$.effort??"MISS",kind:"card_full",userInputs:[]}),X=await c(this.chatId,H);if(!X){if(K(`session "${this.sessionName}": mid-turn rotate sendCard failed — retry on the next content event`),this.currentTurn===$)$.cardRotationFailed=!0,this.stopFooterStatus($);await w(this.chatId,"⚠️ 续卡发送失败,后续内容到达时会再次尝试。");return}let z;try{z=await Z$(X)}catch(P){if(K(`session "${this.sessionName}": mid-turn rotate id_convert failed: ${P}`),this.currentTurn===$)$.cardRotationFailed=!0,this.stopFooterStatus($),await w(this.chatId,"⚠️ 续卡已发送,但 Card Kit 初始化失败;后续内容到达时会再次尝试。");return}d0(z,2,(P,F)=>{if($.rotating){V(P,F);return}this.onCardWriteFailure($,z,P,F)});let W=$.assistantWriteInflight?.get(Z);if(W?.size)await Promise.allSettled([...W]);this.stopFooterStatus($),$.cardId=z,$.cardRotationFailed=!1,$.messageId=X,$.toolCount=0,$.toolByUseId=new Map,$.toolBatches=new Map,$.openBatchI=null,$.planUpdateCount=0,$.goalUpdateCount=0;let G=$.currentAssistantSegmentId,B=$.currentAssistantText??"",_=$.segmentTexts;if($.assistantSegmentCount=0,$.currentAssistantSegmentId=null,$.currentAssistantText="",$.segmentTexts=new Map,G&&B){let P=N.assistant($.assistantSegmentCount++);$.currentAssistantSegmentId=P,$.currentAssistantText=B,$.segmentTexts.set(P,B)}if(B)this.startWritingFooter($);else this.startThinkingFooter($);if($.taskLiveInserted)D0($.cardId,m1(this.taskBoard),{type:"insert_before",targetElementId:N.footer});if($.planLiveInserted)D0($.cardId,Z9($.planSteps,$.planExplanation,N.planLive),{type:"insert_before",targetElementId:$.taskLiveInserted?N.taskBoardLive:N.footer});for(let P of $.contextCompactionPending.values()){if(P.cardId!==Z)continue;P.cardId=z,P.created=!1,P.createFailure=void 0;let F=N.contextCompact(P.i);P.createPromise=y2(z,$9(P.i,P.notice,F),{type:"insert_before",targetElementId:O0($)}).then((T)=>{if(P.cardId===z)P.created=T.landed,P.createFailure=T.failure;return T.landed})}for(let[P,F]of _){if(G&&B&&P===G)continue;if(!k2(Z,P))continue;let T=$.assistantSegmentCount++,M=N.assistant(T);$.segmentTexts.set(M,F),await this.addCompletedAssistantSegment($,M,F)}wZ(this,Z,z,J,Y,$),await O$(Z),wZ(this,Z,z,J,Y,$);let j=new Set([N.taskBoardLive,N.planLive,...[...$.contextCompactionPending.values()].map((P)=>N.contextCompact(P.i))]);if(G)j.add(G);for(let P of J.values())if(P.output==null)j.add(N.tool(P.i));if(kV(Z).some((P)=>!j.has(P)))$.cardCapacityFailures.clear();await O$(z);try{await yZ($,Z);let P=$.mathRenderInflight?.get(Z);if(P?.size)await Promise.allSettled([...P]);await O$(Z);let F=$.mathRendered?.get(Z);for(let[U,S]of _){if(G&&B&&U===G)continue;if(k2(Z,U))continue;if(F?.has(U))continue;await J0(Z,U,this.completedAssistantElement(U,S))}let T=$.contextCompactCount>0?` · \uD83D\uDEA8 压缩×${$.contextCompactCount}`:"",M=await M0(Z,N.footer,this.footerElement(this.withModel(`\uD83D\uDCE8 已续至下一张卡 ↓${T}`)),{notifyCardFailure:!1});A0(Z);let A=await P0(Z,h$({suffix:"\uD83D\uDCE8 转下一张"}));if(M&&A)await v0(Z);else K(`session "${this.sessionName}": rotate old-card terminal MISS footer=${M} settings=${A}`),await w(this.chatId,`⚠️ 上一张对话卡未能正常关闭 (footer=${M?"ok":"MISS"}, settings=${A?"ok":"MISS"}),本轮输出已续到新卡。`)}catch(P){K(`session "${this.sessionName}": mid-turn rotate close-old failed: ${P}`)}K(`session "${this.sessionName}": mid-turn rotate done old=${Z.slice(0,8)}… new=${z.slice(0,8)}…`)}finally{$.rotating=null;let H=Q.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=N.planUpdate($.planUpdateCount++);D0(Z,E5($.planSteps,$.planExplanation,"",J),{type:"insert_before",targetElementId:O0($)})}addGoalUpdateOnCurrentTurn($){let Z=this.currentTurn;if(!Z)return;this.maybeMidTurnRotate();let J=N.goalUpdate(Z.goalUpdateCount++);D0(Z.cardId,x5($,J),{type:"insert_before",targetElementId:O0(Z)})}addGoalClearedOnCurrentTurn(){let $=this.currentTurn;if(!$)return;this.maybeMidTurnRotate();let Z=N.goalUpdate($.goalUpdateCount++);D0($.cardId,{tag:"markdown",element_id:Z,content:`**\uD83C\uDFAF 当前目标**
|
|
262
|
+
`),H=Y[Y.length-1]?.userOpenId??this.lastUserOpenId,X=await this.openTurnCard(J,H,"user_message");if(!X||this.currentTurn!==X){for(let z of Y){if(!z.msgId)continue;let W=this.currentBatchReactionIds.get(z.msgId);if(this.currentBatchReactionIds.delete(z.msgId),W)C0(z.msgId,W)}this.status="idle";return}if(this.proc!==$||this.procEpoch!==Z||!$.isAlive()){await this.closeTurnCard(`⚠️ ${this.backendLabel($.provider)} 已退出`);for(let z of Y){if(!z.msgId)continue;let W=this.currentBatchReactionIds.get(z.msgId);if(this.currentBatchReactionIds.delete(z.msgId),W)C0(z.msgId,W)}this.status="stopped";return}try{this.sendClaimedUserText($,Q)}catch(z){K(`session "${this.sessionName}": mid-turn sendUserText failed after card open: ${z}`),await this.closeTurnCard(`❌ ${this.backendLabel($.provider)} 接收消息失败`),await w(this.chatId,`❌ ${this.backendLabel($.provider)} 接收消息失败: ${O(z)}。这批消息未开始处理,请重发。`),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 Y=J?await M0($,N.footer,this.footerElement(Z)):!0;A0($);let Q=await P0($,h$({suffix:Z}));if(Y&&Q){await v0($);return}let V=`footer=${Y?"ok":"MISS"}, settings=${Q?"ok":"MISS"}`;K(`session "${this.sessionName}": superseded card terminal transaction incomplete card=${$.slice(0,12)} ${V}`),await w(this.chatId,`⚠️ 已作废卡片未能正常关闭 (${V})。`)}rebuildBackgroundAfterTurnOpenFailure(){if(!this.pendingRebuildBackgroundCard)return;if(this.pendingRebuildBackgroundCard=!1,this.backgroundTasks.length===0)return;this.openBackgroundCard().catch(($)=>{K(`session "${this.sessionName}": background rebuild after turn-open failure failed: ${O($)}`)})}async openTurnCard($,Z,J,Y={}){if(!this.ownsTurnOpen($))return null;if(this.bgResumePending=!1,this.backgroundCard&&R1(this.backgroundTasks))try{await this.migrateBackgroundCard(),this.pendingRebuildBackgroundCard=!0}catch(q){K(`session "${this.sessionName}": background migrate failed (non-blocking): ${q}`),this.startBackgroundRefreshTick(),this.scheduleBackgroundRefresh()}if(!this.ownsTurnOpen($))return null;let Q=++this.turnCounter,V=this.pendingTurnInputs;this.pendingTurnInputs=[],this.lastTurnUserPreview=V[0]?.slice(0,80)??this.lastTurnUserPreview,K(`session "${this.sessionName}": openTurnCard turn=${Q} trigger=${J} inputs=${V.length}`);let H=this.runtimeModelSelection(),X=this.withModel(Y.initialFooter??"Waiting...(0s)",H),z=a8({sessionName:this.sessionName,turn:Q,provider:H.provider,model:H.model??void 0,effort:H.effort??"MISS",kind:J,userInputs:V,initialFooter:X,directStart:Y.directStart}),W=await c(this.chatId,z);if(!W){if(!this.ownsTurnOpen($))return null;if(K(`session "${this.sessionName}": openTurnCard sendCard EXHAUSTED retries — surfacing via raw text`),J==="user_message")await w(this.chatId,`❌ 创建对话卡片失败 (Feishu SDK 重试 3 次后仍连不上)。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。`);return this.rebuildBackgroundAfterTurnOpenFailure(),null}let G;try{G=await Z$(W)}catch(q){if(K(`session "${this.sessionName}": id_convert failed: ${q}`),J==="user_message"&&this.ownsTurnOpen($))await w(this.chatId,`❌ 对话卡片初始化失败。你这条消息尚未送给 ${this.backendLabel()},请稍后重发。`);if(this.ownsTurnOpen($))this.rebuildBackgroundAfterTurnOpenFailure();return null}let B=(J==="bg_task_resume"||J==="scheduled_wakeup"?1:0)+(V.length>0?1:0)+1;if(!this.ownsTurnOpen($))return d0(G,B),await this.terminalizeSupersededCard(G,"⚠️ 会话已切换,本卡已作废",!0),null;let _={cardId:G,...H,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(d0(G,B,(q,P)=>{this.onCardWriteFailure(_,G,q,P)}),this.currentTurn=_,Y.startThinking!==!1)this.startThinkingFooter(_);if($.pendingCompactions.length>0){let q=$.pendingCompactions.splice(0);K(`session "${this.sessionName}": replay ${q.length} context compaction event(s) buffered during card open`);for(let P of q)this.handleContextCompacted(P)}let j=this.takeOrphanAssistantText();if(j)this.appendAssistant(j),this.finalizeCurrentAssistantSegment();if(this.pendingRebuildBackgroundCard){if(this.pendingRebuildBackgroundCard=!1,this.backgroundTasks.length>0)this.openBackgroundCard().catch((q)=>{K(`session "${this.sessionName}": background rebuild failed: ${O(q)}`)})}return _}maybeMidTurnRotate(){let $=this.currentTurn;if(!$)return;if($.rotating)return;if(!$.cardRotationFailed&&t4($.cardId)<WM)return;this.startMidTurnRotate($)}onCardWriteFailure($,Z,J,Y){let Q=this.currentTurn;if(Q!==$){K(`session "${this.sessionName}": ignore stale card failure card=${Z.slice(0,12)} code=${J??"n/a"} (turn owner changed)`);return}if(Q.cardId!==Z){K(`session "${this.sessionName}": ignore retired-card failure card=${Z.slice(0,12)} current=${Q.cardId.slice(0,12)} code=${J??"n/a"}`);return}if(Q.rotating)return;if(Q.cardRotationFailed)return;if(!s4(J,Y)){let H=Y?.operation??"unknown operation",X=Y?.elementId?` element=${Y.elementId}`:"";K(`session "${this.sessionName}": non-capacity card write failure card=${Z.slice(0,12)} operation=${H}${X} code=${J??"n/a"} — not rotating`);let z=`${Z}:${H}:${Y?.elementId??""}:${J??"MISS"}`;if(!Q.cardWriteFailureNotices.has(z))Q.cardWriteFailureNotices.add(z),w(this.chatId,`⚠️ 对话卡片有一项写入失败(code=${J??"MISS"}, ${H}${X})。未识别为卡片容量超限,未自动换卡;其余输出继续处理。`);return}let V=Y?.capacityFingerprint;if(V){let H=Q.cardCapacityFailures.get(V);if(H!==void 0){if(K(`session "${this.sessionName}": unchanged content still exceeds card capacity card=${Z} operation=${Y.operation} element=${Y.elementId??"MISS"} code=${J??"MISS"}`),!H)Q.cardCapacityFailures.set(V,!0),w(this.chatId,`⚠️ 有一项内容换卡后仍超出飞书容量,写入失败(code=${J??"MISS"}, ${Y.operation}, element=${Y.elementId??"MISS"});其余输出继续处理。`);return}Q.cardCapacityFailures.set(V,!1)}K(`session "${this.sessionName}": confirmed card capacity limit (${J}) on card=${Q.cardId.slice(0,8)}… — rotating to fresh card`),Q.failureRotateCount++,this.startMidTurnRotate(Q)}startMidTurnRotate($){if($.rotating)return;$.rotateCount++;let{cardId:Z,toolByUseId:J,toolBatches:Y}=$,Q={value:null},V=(H,X)=>{if(!Q.value)Q.value={code:H,failure:X}};$.rotating=(async()=>{try{K(`session "${this.sessionName}": mid-turn rotate triggered card=${Z.slice(0,8)}… elementCount=${t4(Z)}`);let H=a8({sessionName:this.sessionName,turn:this.turnCounter,provider:$.provider,model:$.model??void 0,effort:$.effort??"MISS",kind:"card_full",userInputs:[]}),X=await c(this.chatId,H);if(!X){if(K(`session "${this.sessionName}": mid-turn rotate sendCard failed — retry on the next content event`),this.currentTurn===$)$.cardRotationFailed=!0,this.stopFooterStatus($);await w(this.chatId,"⚠️ 续卡发送失败,后续内容到达时会再次尝试。");return}let z;try{z=await Z$(X)}catch(P){if(K(`session "${this.sessionName}": mid-turn rotate id_convert failed: ${P}`),this.currentTurn===$)$.cardRotationFailed=!0,this.stopFooterStatus($),await w(this.chatId,"⚠️ 续卡已发送,但 Card Kit 初始化失败;后续内容到达时会再次尝试。");return}d0(z,2,(P,D)=>{if($.rotating){V(P,D);return}this.onCardWriteFailure($,z,P,D)});let W=$.assistantWriteInflight?.get(Z);if(W?.size)await Promise.allSettled([...W]);this.stopFooterStatus($),$.cardId=z,$.cardRotationFailed=!1,$.messageId=X,$.toolCount=0,$.toolByUseId=new Map,$.toolBatches=new Map,$.openBatchI=null,$.planUpdateCount=0,$.goalUpdateCount=0;let G=$.currentAssistantSegmentId,B=$.currentAssistantText??"",_=$.segmentTexts;if($.assistantSegmentCount=0,$.currentAssistantSegmentId=null,$.currentAssistantText="",$.segmentTexts=new Map,G&&B){let P=N.assistant($.assistantSegmentCount++);$.currentAssistantSegmentId=P,$.currentAssistantText=B,$.segmentTexts.set(P,B)}if(B)this.startWritingFooter($);else this.startThinkingFooter($);if($.taskLiveInserted)F0($.cardId,m1(this.taskBoard),{type:"insert_before",targetElementId:N.footer});if($.planLiveInserted)F0($.cardId,Z9($.planSteps,$.planExplanation,N.planLive),{type:"insert_before",targetElementId:$.taskLiveInserted?N.taskBoardLive:N.footer});for(let P of $.contextCompactionPending.values()){if(P.cardId!==Z)continue;P.cardId=z,P.created=!1,P.createFailure=void 0;let D=N.contextCompact(P.i);P.createPromise=y2(z,$9(P.i,P.notice,D),{type:"insert_before",targetElementId:O0($)}).then((T)=>{if(P.cardId===z)P.created=T.landed,P.createFailure=T.failure;return T.landed})}for(let[P,D]of _){if(G&&B&&P===G)continue;if(!k2(Z,P))continue;let T=$.assistantSegmentCount++,M=N.assistant(T);$.segmentTexts.set(M,D),await this.addCompletedAssistantSegment($,M,D)}yZ(this,Z,z,J,Y,$),await O$(Z),yZ(this,Z,z,J,Y,$);let j=new Set([N.taskBoardLive,N.planLive,...[...$.contextCompactionPending.values()].map((P)=>N.contextCompact(P.i))]);if(G)j.add(G);for(let P of J.values())if(P.output==null)j.add(N.tool(P.i));if(CV(Z).some((P)=>!j.has(P)))$.cardCapacityFailures.clear();await O$(z);try{await kZ($,Z);let P=$.mathRenderInflight?.get(Z);if(P?.size)await Promise.allSettled([...P]);await O$(Z);let D=$.mathRendered?.get(Z);for(let[U,S]of _){if(G&&B&&U===G)continue;if(k2(Z,U))continue;if(D?.has(U))continue;await J0(Z,U,this.completedAssistantElement(U,S))}let T=$.contextCompactCount>0?` · \uD83D\uDEA8 压缩×${$.contextCompactCount}`:"",M=await M0(Z,N.footer,this.footerElement(this.withModel(`\uD83D\uDCE8 已续至下一张卡 ↓${T}`)),{notifyCardFailure:!1});A0(Z);let A=await P0(Z,h$({suffix:"\uD83D\uDCE8 转下一张"}));if(M&&A)await v0(Z);else K(`session "${this.sessionName}": rotate old-card terminal MISS footer=${M} settings=${A}`),await w(this.chatId,`⚠️ 上一张对话卡未能正常关闭 (footer=${M?"ok":"MISS"}, settings=${A?"ok":"MISS"}),本轮输出已续到新卡。`)}catch(P){K(`session "${this.sessionName}": mid-turn rotate close-old failed: ${P}`)}K(`session "${this.sessionName}": mid-turn rotate done old=${Z.slice(0,8)}… new=${z.slice(0,8)}…`)}finally{$.rotating=null;let H=Q.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=N.planUpdate($.planUpdateCount++);F0(Z,T5($.planSteps,$.planExplanation,"",J),{type:"insert_before",targetElementId:O0($)})}addGoalUpdateOnCurrentTurn($){let Z=this.currentTurn;if(!Z)return;this.maybeMidTurnRotate();let J=N.goalUpdate(Z.goalUpdateCount++);F0(Z.cardId,E5($,J),{type:"insert_before",targetElementId:O0(Z)})}addGoalClearedOnCurrentTurn(){let $=this.currentTurn;if(!$)return;this.maybeMidTurnRotate();let Z=N.goalUpdate($.goalUpdateCount++);F0($.cardId,{tag:"markdown",element_id:Z,content:`**\uD83C\uDFAF 当前目标**
|
|
263
263
|
|
|
264
|
-
已清除`},{type:"insert_before",targetElementId:O0($)})}handleContextCompacted($){let Z=fW($);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;K(`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<a6){K(`session "${this.sessionName}": late anonymous manual compaction duplicate ignored`);return}let J=this.currentTurn,Y=$.itemId?`item:${$.itemId}`:void 0,Q=Z.find((M)=>M.startsWith("turn:")),V=Y??Q,H=V?this.contextCompactionReceipts.get(V):void 0;if(Y&&!H&&$.phase!=="start"&&Q){let M=this.contextCompactionReceipts.get(Q);if(!M?.hasItemAlias&&M?.completed&&Date.now()-M.completedAt<a6||!M?.hasItemAlias&&M?.completionKey&&J?.contextCompactionCompleting.has(M.completionKey))V=Q,H=M,M.hasItemAlias=!0,this.contextCompactionReceipts.delete(Y),this.contextCompactionReceipts.set(Y,M)}if(!J){if(this.openingTurnOwner?.backendTurnStarted){this.openingTurnOwner.pendingCompactions.push($),K(`session "${this.sessionName}": buffer context compaction ${$.phase??"event"} while turn card opens`);return}if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");K(`session "${this.sessionName}": context compaction ${$.phase??"event"} with no current turn thread=${$.threadId??"-"} turn=${$.turnId??"-"} item=${$.itemId??"-"}`);return}if(V&&H?.completed){K(`session "${this.sessionName}": duplicate context compaction ${$.phase??"event"} ignored receipt=${V}`);return}let X=this.contextCompactionOwnerId(J);if(V&&H&&H.ownerId!==X){this.rememberContextCompactionReceipt(Z,null,!0),K(`session "${this.sessionName}": late context compaction ${$.phase??"event"} ignored receipt=${V} (turn owner changed)`);return}if(V&&H?.completionKey&&J.contextCompactionCompleting.has(H.completionKey)){K(`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__")){K(`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<a6){K(`session "${this.sessionName}": identified context compaction duplicate ignored after anonymous completion`);return}if($.phase==="start"){let M=YM($);if(J.contextCompactionPending.has(M)||J.contextCompactionCompleted.has(M)){K(`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,X,!1);let A=J.contextCompactCount++,U=J.cardId,S=N.contextCompact(A),b={i:A,cardId:U,notice:$,created:!1,createFailure:void 0,createPromise:Promise.resolve(!1)};b.createPromise=y2(U,$9(A,$,S),{type:"insert_before",targetElementId:O0(J)}).then((v)=>{if(b.cardId===U)b.created=v.landed,b.createFailure=v.failure;return v.landed}),J.contextCompactionPending.set(M,b),K(`session "${this.sessionName}": context compaction start #${A+1} key=${M}`),w1(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionCompleting.size>0){K(`session "${this.sessionName}": anonymous context compaction duplicate ignored while completion writes`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionPending.size===0&&Date.now()-J.lastContextCompactionCompletedAt<a6){K(`session "${this.sessionName}": immediate anonymous context compaction duplicate ignored`);return}let z=$.itemId||$.turnId;if(z&&J.contextCompactionCompleted.has(z)){K(`session "${this.sessionName}": duplicate context compaction completion ignored key=${z}`);return}let W=$.itemId?J.contextCompactionPending.has($.itemId)?$.itemId:null:QM(J),G=W?J.contextCompactionPending.get(W):void 0,B=W??z??"__anonymous__";if(J.contextCompactionCompleting.has(B)){K(`session "${this.sessionName}": context compaction completion already writing key=${B}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();J.openBatchI=null,this.maybeMidTurnRotate();let _=VM(G?.notice,$),j=J.contextCompactionEndOnly.get(B),q=G?.i??j??J.contextCompactCount++;if(!G&&j===void 0)J.contextCompactionEndOnly.set(B,q);J.contextCompactionCompleting.add(B);let P=[...new Set([...fW(G?.notice??{}),...Z])];if(P.length>0)this.rememberContextCompactionReceipt(P,X,!1,B);let F=N.contextCompact(q),T=$9(q,_,F);K(`session "${this.sessionName}": context compaction completion write #${q+1} key=${B}`),(async()=>{let M=!1;if(!G)while(!0){let A=J.cardId;if(M=await Y1(A,T,{type:"insert_before",targetElementId:O0(J)}),M)break;let U=J.rotating;if(U){await U;continue}if(J.cardId!==A)continue;break}else while(!0){let A=G.cardId;if(await G.createPromise,G.cardId!==A)continue;if(G.created)M=await M0(A,F,T);else{if(CV(G.createFailure?.code,G.createFailure))yV(A,F),M=await M0(A,F,T,{notifyCardFailure:!1});if(!M)M=await Y1(A,T,{type:"insert_before",targetElementId:O0(J)})}if(G.cardId!==A)continue;if(M){G.created=!0;break}let U=J.rotating;if(U){await U;continue}if(G.cardId!==A)continue;break}if(J.contextCompactionCompleting.delete(B),!M){K(`session "${this.sessionName}": context compaction completion write MISS #${q+1} key=${B}`);return}if(W&&J.contextCompactionPending.get(W)===G)J.contextCompactionPending.delete(W);if(J.contextCompactionEndOnly.delete(B),B!=="__anonymous__")J.contextCompactionCompleted.add(B);if(J.lastContextCompactionCompletedAt=Date.now(),J.lastContextCompactionWasAnonymous=B==="__anonymous__",P.length>0){let A=[...this.contextCompactionReceipts.entries()].filter(([,U])=>U.completionKey===B).map(([U])=>U);this.rememberContextCompactionReceipt([...new Set([...P,...A])],null,!0)}K(`session "${this.sessionName}": context compaction completed #${q+1} key=${B}`)})().catch((M)=>{J.contextCompactionCompleting.delete(B),K(`session "${this.sessionName}": context compaction completion transaction failed: ${O(M)}`)}),w1(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,Y){let Q={ownerId:J?null:Z,completed:J,completedAt:J?Date.now():0,...J||!Y?{}:{completionKey:Y},hasItemAlias:$.some((V)=>V.startsWith("item:"))};for(let V of $)this.contextCompactionReceipts.delete(V),this.contextCompactionReceipts.set(V,Q);while(this.contextCompactionReceipts.size>WM){let V;for(let H of this.contextCompactionReceipts.values()){if(H.completed){V=H;break}V??=H}if(!V)break;for(let[H,X]of this.contextCompactionReceipts)if(X===V)this.contextCompactionReceipts.delete(H)}}handleTurnPlanUpdated($){let Z=this.currentTurn;if(!Z){K(`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))K(`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?N.taskBoardLive:N.footer;Z.planLiveInserted=!0,D0(Z.cardId,Z9(Z.planSteps,Z.planExplanation,N.planLive),{type:"insert_before",targetElementId:J})}else J0(Z.cardId,N.planLive,Z9(Z.planSteps,Z.planExplanation,N.planLive));this.addPlanSnapshotOnCurrentTurn()}handlePlanDelta($){if(typeof $.delta!=="string"||!$.delta){K(`session "${this.sessionName}": item/plan/delta missing delta text`);return}if(typeof $.itemId!=="string"||!$.itemId)K(`session "${this.sessionName}": item/plan/delta missing itemId`)}handleThreadGoalUpdated($){if(!$||typeof $.objective!=="string"){K(`session "${this.sessionName}": thread/goal/updated missing objective`);return}if($.tokenBudget!=null&&typeof $.tokenBudget!=="number")K(`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&&a8(Z)===a8(J))return;let Y=this.currentTurn;if(Y){if(this.startWorkingFooter(Y),Y.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();Y.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++,H=N.assistant(V);Z.currentAssistantSegmentId=H,Z.currentAssistantText=""}Z.currentAssistantText+=$;let J=Z.currentAssistantSegmentId;if(!J)return;Z.segmentTexts.set(J,Z.currentAssistantText),this.processOutboundMarkers(Z.currentAssistantText);let Q=this.cleanAssistantTextForDisplay(Z.currentAssistantText).slice(0,40);w1(Z.cardId,Q)}takeOrphanAssistantText(){let $=[...this.orphanAssistantSegments];if(this.orphanAssistantCurrent.trim())$.push(this.orphanAssistantCurrent);return this.orphanAssistantSegments=[],this.orphanAssistantCurrent="",$.join(`
|
|
264
|
+
已清除`},{type:"insert_before",targetElementId:O0($)})}handleContextCompacted($){let Z=vW($);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;K(`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<n6){K(`session "${this.sessionName}": late anonymous manual compaction duplicate ignored`);return}let J=this.currentTurn,Y=$.itemId?`item:${$.itemId}`:void 0,Q=Z.find((M)=>M.startsWith("turn:")),V=Y??Q,H=V?this.contextCompactionReceipts.get(V):void 0;if(Y&&!H&&$.phase!=="start"&&Q){let M=this.contextCompactionReceipts.get(Q);if(!M?.hasItemAlias&&M?.completed&&Date.now()-M.completedAt<n6||!M?.hasItemAlias&&M?.completionKey&&J?.contextCompactionCompleting.has(M.completionKey))V=Q,H=M,M.hasItemAlias=!0,this.contextCompactionReceipts.delete(Y),this.contextCompactionReceipts.set(Y,M)}if(!J){if(this.openingTurnOwner?.backendTurnStarted){this.openingTurnOwner.pendingCompactions.push($),K(`session "${this.sessionName}": buffer context compaction ${$.phase??"event"} while turn card opens`);return}if(Z.length>0)this.rememberContextCompactionReceipt(Z,null,$.phase!=="start");K(`session "${this.sessionName}": context compaction ${$.phase??"event"} with no current turn thread=${$.threadId??"-"} turn=${$.turnId??"-"} item=${$.itemId??"-"}`);return}if(V&&H?.completed){K(`session "${this.sessionName}": duplicate context compaction ${$.phase??"event"} ignored receipt=${V}`);return}let X=this.contextCompactionOwnerId(J);if(V&&H&&H.ownerId!==X){this.rememberContextCompactionReceipt(Z,null,!0),K(`session "${this.sessionName}": late context compaction ${$.phase??"event"} ignored receipt=${V} (turn owner changed)`);return}if(V&&H?.completionKey&&J.contextCompactionCompleting.has(H.completionKey)){K(`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__")){K(`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<n6){K(`session "${this.sessionName}": identified context compaction duplicate ignored after anonymous completion`);return}if($.phase==="start"){let M=QM($);if(J.contextCompactionPending.has(M)||J.contextCompactionCompleted.has(M)){K(`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,X,!1);let A=J.contextCompactCount++,U=J.cardId,S=N.contextCompact(A),b={i:A,cardId:U,notice:$,created:!1,createFailure:void 0,createPromise:Promise.resolve(!1)};b.createPromise=y2(U,$9(A,$,S),{type:"insert_before",targetElementId:O0(J)}).then((v)=>{if(b.cardId===U)b.created=v.landed,b.createFailure=v.failure;return v.landed}),J.contextCompactionPending.set(M,b),K(`session "${this.sessionName}": context compaction start #${A+1} key=${M}`),w1(J.cardId,`\uD83D\uDEA8 压缩×${J.contextCompactCount}`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionCompleting.size>0){K(`session "${this.sessionName}": anonymous context compaction duplicate ignored while completion writes`);return}if(!$.itemId&&!$.turnId&&J.contextCompactionPending.size===0&&Date.now()-J.lastContextCompactionCompletedAt<n6){K(`session "${this.sessionName}": immediate anonymous context compaction duplicate ignored`);return}let z=$.itemId||$.turnId;if(z&&J.contextCompactionCompleted.has(z)){K(`session "${this.sessionName}": duplicate context compaction completion ignored key=${z}`);return}let W=$.itemId?J.contextCompactionPending.has($.itemId)?$.itemId:null:VM(J),G=W?J.contextCompactionPending.get(W):void 0,B=W??z??"__anonymous__";if(J.contextCompactionCompleting.has(B)){K(`session "${this.sessionName}": context compaction completion already writing key=${B}`);return}if(this.startWorkingFooter(J),J.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();J.openBatchI=null,this.maybeMidTurnRotate();let _=HM(G?.notice,$),j=J.contextCompactionEndOnly.get(B),q=G?.i??j??J.contextCompactCount++;if(!G&&j===void 0)J.contextCompactionEndOnly.set(B,q);J.contextCompactionCompleting.add(B);let P=[...new Set([...vW(G?.notice??{}),...Z])];if(P.length>0)this.rememberContextCompactionReceipt(P,X,!1,B);let D=N.contextCompact(q),T=$9(q,_,D);K(`session "${this.sessionName}": context compaction completion write #${q+1} key=${B}`),(async()=>{let M=!1;if(!G)while(!0){let A=J.cardId;if(M=await Y1(A,T,{type:"insert_before",targetElementId:O0(J)}),M)break;let U=J.rotating;if(U){await U;continue}if(J.cardId!==A)continue;break}else while(!0){let A=G.cardId;if(await G.createPromise,G.cardId!==A)continue;if(G.created)M=await M0(A,D,T);else{if(bV(G.createFailure?.code,G.createFailure))kV(A,D),M=await M0(A,D,T,{notifyCardFailure:!1});if(!M)M=await Y1(A,T,{type:"insert_before",targetElementId:O0(J)})}if(G.cardId!==A)continue;if(M){G.created=!0;break}let U=J.rotating;if(U){await U;continue}if(G.cardId!==A)continue;break}if(J.contextCompactionCompleting.delete(B),!M){K(`session "${this.sessionName}": context compaction completion write MISS #${q+1} key=${B}`);return}if(W&&J.contextCompactionPending.get(W)===G)J.contextCompactionPending.delete(W);if(J.contextCompactionEndOnly.delete(B),B!=="__anonymous__")J.contextCompactionCompleted.add(B);if(J.lastContextCompactionCompletedAt=Date.now(),J.lastContextCompactionWasAnonymous=B==="__anonymous__",P.length>0){let A=[...this.contextCompactionReceipts.entries()].filter(([,U])=>U.completionKey===B).map(([U])=>U);this.rememberContextCompactionReceipt([...new Set([...P,...A])],null,!0)}K(`session "${this.sessionName}": context compaction completed #${q+1} key=${B}`)})().catch((M)=>{J.contextCompactionCompleting.delete(B),K(`session "${this.sessionName}": context compaction completion transaction failed: ${O(M)}`)}),w1(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,Y){let Q={ownerId:J?null:Z,completed:J,completedAt:J?Date.now():0,...J||!Y?{}:{completionKey:Y},hasItemAlias:$.some((V)=>V.startsWith("item:"))};for(let V of $)this.contextCompactionReceipts.delete(V),this.contextCompactionReceipts.set(V,Q);while(this.contextCompactionReceipts.size>GM){let V;for(let H of this.contextCompactionReceipts.values()){if(H.completed){V=H;break}V??=H}if(!V)break;for(let[H,X]of this.contextCompactionReceipts)if(X===V)this.contextCompactionReceipts.delete(H)}}handleTurnPlanUpdated($){let Z=this.currentTurn;if(!Z){K(`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))K(`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?N.taskBoardLive:N.footer;Z.planLiveInserted=!0,F0(Z.cardId,Z9(Z.planSteps,Z.planExplanation,N.planLive),{type:"insert_before",targetElementId:J})}else J0(Z.cardId,N.planLive,Z9(Z.planSteps,Z.planExplanation,N.planLive));this.addPlanSnapshotOnCurrentTurn()}handlePlanDelta($){if(typeof $.delta!=="string"||!$.delta){K(`session "${this.sessionName}": item/plan/delta missing delta text`);return}if(typeof $.itemId!=="string"||!$.itemId)K(`session "${this.sessionName}": item/plan/delta missing itemId`)}handleThreadGoalUpdated($){if(!$||typeof $.objective!=="string"){K(`session "${this.sessionName}": thread/goal/updated missing objective`);return}if($.tokenBudget!=null&&typeof $.tokenBudget!=="number")K(`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&&n8(Z)===n8(J))return;let Y=this.currentTurn;if(Y){if(this.startWorkingFooter(Y),Y.currentAssistantSegmentId)this.finalizeCurrentAssistantSegment();Y.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++,H=N.assistant(V);Z.currentAssistantSegmentId=H,Z.currentAssistantText=""}Z.currentAssistantText+=$;let J=Z.currentAssistantSegmentId;if(!J)return;Z.segmentTexts.set(J,Z.currentAssistantText),this.processOutboundMarkers(Z.currentAssistantText);let Q=this.cleanAssistantTextForDisplay(Z.currentAssistantText).slice(0,40);w1(Z.cardId,Q)}takeOrphanAssistantText(){let $=[...this.orphanAssistantSegments];if(this.orphanAssistantCurrent.trim())$.push(this.orphanAssistantCurrent);return this.orphanAssistantSegments=[],this.orphanAssistantCurrent="",$.join(`
|
|
265
265
|
|
|
266
266
|
`).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;K(`session "${this.sessionName}": flushing ${J.length} chars of orphan assistant text (${$})`),E(this.chatId,`\uD83D\uDCC4 后台轮输出(未能建卡,纯文本兜底):
|
|
267
267
|
|
|
268
|
-
${J}`)}completedAssistantElement($,Z){if(
|
|
268
|
+
${J}`)}completedAssistantElement($,Z){if(OZ(Z))return this.mathAssistantContainer($,[{type:"markdown",text:Z}]);return{tag:"markdown",element_id:$,content:this.cleanAssistantTextForDisplay(Z).trim()||" "}}mathAssistantContainer($,Z){let J=Z.map((Y)=>Y.type==="markdown"?{tag:"markdown",content:this.cleanAssistantTextForDisplay(Y.text).trim()||" "}:{...Y.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,Y){let Q=await LX(Y);if(!await M0(Z,J,this.mathAssistantContainer(J,Q.blocks),{notifyCardFailure:!1})){K(`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),K(`session "${this.sessionName}": math rendered ${J} (${Q.renderedImageCount} img, ${Q.blocks.length} blocks)`)}addCompletedAssistantSegment($,Z,J){let Y=$.cardId,Q=O0($),V=(async()=>{if(!await Y1(Y,this.completedAssistantElement(Z,J),{type:"insert_before",targetElementId:Q}))return K(`session "${this.sessionName}": assistant segment ${Z} raw write failed on card=${Y}`),!1;if(OZ(J)){let X=this.replaceSegmentWithMathImgs($,Y,Z,J).catch((z)=>K(`session "${this.sessionName}": math render ${Z} failed: ${z}`));$.mathRenderInflight??=new Map,$.mathRenderInflight.get(Y)??$.mathRenderInflight.set(Y,new Set),$.mathRenderInflight.get(Y).add(X),X.finally(()=>$.mathRenderInflight?.get(Y)?.delete(X))}return!0})();return $.assistantWriteInflight??=new Map,$.assistantWriteInflight.get(Y)??$.assistantWriteInflight.set(Y,new Set),$.assistantWriteInflight.get(Y).add(V),V.finally(()=>$.assistantWriteInflight?.get(Y)?.delete(V)),V}async sendAssistantTextFallback($,Z){let J=$.trim();if(!J)return;let Y=`⚠️ 对话卡片正文写入失败(${Z}),以下为 agent 原始回复:
|
|
269
269
|
|
|
270
|
-
${J}`;if(!await E(this.chatId,Y))K(`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
|
|
271
|
-
${P}`:q,T=await M0(V,N.footer,this.footerElement(
|
|
272
|
-
你的下一条文字优先用于这条通知,完成后再回答 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(Y==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let H=J?.detail??Z.error;if(H)V.push({tag:"markdown",content:`<font color='red'>${Z0(H)}</font>`});if(Y==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Y==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:Z0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Q[Y]},template:Y==="failed"||Y==="unknown"?"red":Y==="delivered"||Y==="done"?"green":"blue"},body:{elements:V}}}function FM($){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 Y of $){if(!Y||typeof Y!=="object")return{error:"each button must be an object"};let Q=String(Y.id??"").trim(),V=String(Y.text??"").trim();if(!
|
|
270
|
+
${J}`;if(!await E(this.chatId,Y))K(`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 sH($))this.sendOutboundPath(Z,"send marker")}cleanAssistantTextForDisplay($){return Z0($)}sendOutboundPath($,Z){let J=F6($.trim());if(!J)return;let Y=this.currentTurn;if(Y?.outboundSeenPaths.has(J))return;if(Y?.outboundSeenPaths.add(J),!YM(J)){K(`session "${this.sessionName}": ignore non-absolute outbound path from ${Z}: ${J}`);return}K(`session "${this.sessionName}": outbound send from ${Z}: ${J}`);try{let Q=Y?.fileDeliveryMode??(this.proc?this.procFileDeliveryModes.get(this.proc):void 0)??this.getFileDeliveryMode();if(Y)Y.fileDeliveryMode=Q;if(Q==="chat"){Y?.outboundSentPaths.add(J),o4(this.chatId,J);return}if(!Y)throw Error("当前没有可关联的交付轮次");if(!Y.fileDelivery)Y.fileDelivery=this.createFileDeliveryForTurn(Y),this.fileDeliveries.add(Y.fileDelivery);Y.fileDelivery.add(J)}catch(Q){K(`session "${this.sessionName}": file delivery rejected: ${O(Q)}`),E(this.chatId,`❌ 文件交付失败:${O(Q)}`)}}createFileDeliveryForTurn($){return dz({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)Z=J.reason==="quota"?`⏳ ${J.message}`:J.phase==="waiting"?`⏳ 模型满载 · ${J.delayMs/1000}s 后重试 #${J.attempt}`:`⏳ 模型满载 · 正在重试 #${J.attempt}`;if($.footerStatusHandle&&$.footerStatusLabel===Z)return;this.stopFooterStatus($),$.footerStatusLabel=Z,$.footerStatusStartedAt=Date.now();let Y=()=>{if($.footerStatusLabel!==Z)return;let{label:V}=t$(Date.now()-$.footerStatusStartedAt,s1()),H=Z===fW?this.proc?.lastThinkingTokens:null,X=typeof H==="number"?` · 约 ${H} tokens`:"";this.replaceFooterContent($.cardId,this.withModel(`${Z}${X} (${V})`))},Q=()=>{if($.footerStatusLabel!==Z)return;let{nextDelayMs:V}=t$(Date.now()-$.footerStatusStartedAt,s1());$.footerStatusHandle=setTimeout(()=>{Y(),Q()},Math.max(1,Math.ceil(V)))};Y(),Q()}startThinkingFooter($){this.startFooterStatus($,fW)}startWritingFooter($){this.startFooterStatus($,XM)}startWorkingFooter($){this.startFooterStatus($,zM)}stopFooterStatus($){if(!$)return;if($.footerStatusHandle)clearTimeout($.footerStatusHandle);$.footerStatusHandle=null,$.footerStatusStartedAt=0,$.footerStatusLabel=null}async footerUsageSuffix($,Z,J,Y,Q){if(J&&(!Y||!Y.enabled||Y.agent!==$))return" | 额度 MISS";if(Y?.agent===$&&Y.enabled&&($==="claude"||$==="dsh")){let V=await Y.readUsage();if(V.state==="ok"&&V.kind!=="balance"){let H=V.windows.find((z)=>z.kind==="fiveHour"),X=V.windows.find((z)=>z.kind==="weekly");if(H||X)return this.fmtDualWindowSuffix(H??null,X??null)}return` | ${G6(V)}`}if($==="codex"){let V=Z?.isAlive()&&Z.provider==="codex"&&Z.readRateLimits?Z:null,H=V?await A8(()=>V.readRateLimits(),r0(V)):null,X=V?H:Q;return X?.state==="ok"?this.fmtDualWindowSuffix(X.fiveHour??null,X.weekly??null):" | 额度 MISS"}return" | 额度 MISS"}fmtDualWindowSuffix($,Z){let J=(V)=>{if(!V)return null;if(V.percent==null)return"MISS";let H=V.resetsAt&&V.resetsAt.getTime()>Date.now()?R2(V.resetsAt):"",X=`${Math.round(V.percent)}%`;return H?`${H}·${X}`:X},Y=J($),Q=J(Z);if(Y&&Q)return` | ${Y}·[${Q}]`;if(Y)return` | ${Y}`;if(Q)return` | [${Q}]`;return" | 额度 MISS"}waitForTurnCloses(){let $=[...this.turnCloseInflight];if($.length===0)return Promise.resolve();return Promise.allSettled($).then((Z)=>{let J=Z.filter((Y)=>Y.status==="rejected").map((Y)=>Y.reason);if(J.length===1)throw J[0];if(J.length>1)throw AggregateError(J,`turn close failed: ${J.map(O).join("; ")}`)})}releaseTurnCloseReactions($){for(let[Z,J]of[...$.currentBatchReactionIds.entries(),...$.pendingReactionIds.entries()])if(J)C0(Z,J)}closeTurnCard($,Z={}){let J=this.currentTurn;if(!J)return this.waitForTurnCloses();if(!$&&J.cardRotationFailed)this.maybeMidTurnRotate();this.currentTurn=null,this.stopFooterStatus(J);let Y=this.proc,Q={turn:J,proc:Y,procEpoch:this.procEpoch,contextTokens:this.currentContextTokens(Y),contextLimit:this.contextLimitForDisplay(Y),lastTurnDelta:this.lastTurnDelta?{...this.lastTurnDelta}:null,lastTurnUsage:this.lastTurnUsage?{...this.lastTurnUsage}:null,tokenSourceId:this.selectedTokenSourceId,tokenSource:Y?.provider==="codex"?H0(Y.tokenSourceId??this.selectedTokenSourceId,r0(Y)):this.currentTokenSource(),codexUsage:aQ(r0(Y)),currentBatchReactionIds:this.currentBatchReactionIds,pendingReactionIds:this.pendingReactionIds};this.currentBatchReactionIds=new Map,this.pendingReactionIds=new Map;let V=this.finishTurnCardClose(Q,$,Z).finally(()=>this.releaseTurnCloseReactions(Q));return this.turnCloseInflight.add(V),V.then(()=>{this.turnCloseInflight.delete(V)},()=>{this.turnCloseInflight.delete(V)}),V}async finishTurnCardClose($,Z,J={}){let{turn:Y}=$;if(Y.rotating)await Y.rotating;if(await kZ(Y),Y.fileDelivery)try{for(let A of await Y.fileDelivery.finish())Y.outboundSentPaths.add(A)}catch(A){K(`session "${this.sessionName}": file delivery close failed: ${O(A)}`),await w(this.chatId,`❌ 文件交付收尾失败:${O(A)}`)}finally{this.fileDeliveries.delete(Y.fileDelivery)}this.stopFooterStatus(Y);let Q=(Date.now()-Y.startedAt)/1000,V=Y.cardId,H=Y.segmentTexts;await O$(V);let X=new Map;if(Y.currentAssistantSegmentId&&Y.currentAssistantText.trim()){let{currentAssistantSegmentId:A,currentAssistantText:U}=Y;if(!await this.addCompletedAssistantSegment(Y,A,U))X.set(A,U);Y.currentAssistantSegmentId=null,Y.currentAssistantText=""}let z=Y.assistantWriteInflight?.get(V);if(z?.size)await Promise.allSettled([...z]);let W=Y.mathRenderInflight?.get(V);if(W?.size)await Promise.allSettled([...W]);let G=Y.mathRendered?.get(V);for(let[A,U]of H){if(k2(V,A)){X.set(A,U);continue}if(G?.has(A))continue;await J0(V,A,this.completedAssistantElement(A,U))}if(Y.cardRotationFailed)for(let[A,U]of H)X.set(A,U);let B=Z?Z:"✅",_=[`${B} ⏱ ${G0(Q)}`];if(J.hasFreshResult){let{contextTokens:A,contextLimit:U}=$,S=Y.provider==="claude",b=R5(A,U,S?0:void 0);if(b)_.push(`\uD83E\uDDE0 ${b}`);let v=$.lastTurnDelta?.costUsd??0;if(v>0)_.push(`\uD83D\uDCB0 $${v.toFixed(3)}`)}if(Y.contextCompactCount>0)_.push(`\uD83D\uDEA8 压缩×${Y.contextCompactCount}`);if(Y.outboundSentPaths.size>0)_.push(`\uD83D\uDCCE ${Y.outboundSentPaths.size}`);let j=this.modelLine(Y);if(j)_.push(j);let q=_.join(" | "),P=J.hasFreshResult?N5($.lastTurnUsage)+(Y.cardRotationFailed?"":await this.footerUsageSuffix(Y.provider,$.proc,$.tokenSourceId,$.tokenSource,$.codexUsage)):"",D=P?`${q}
|
|
271
|
+
${P}`:q,T=await M0(V,N.footer,this.footerElement(D));A0(V);let M=await P0(V,h$({durationSec:Q,outputTokens:J.hasFreshResult?$.lastTurnUsage?.output_tokens:void 0,suffix:Z}));if(T&&M)await v0(V);else{let A=`footer=${T?"ok":"MISS"}, settings=${M?"ok":"MISS"}`;K(`session "${this.sessionName}": terminal card transaction incomplete card=${V.slice(0,12)} ${A}`),await w(this.chatId,`⚠️ 对话卡片终态写入失败 (${A})。本轮已结束: ${B}`)}for(let A of X.values())await this.sendAssistantTextFallback(A,"CardKit 元素未落地");if((J.forcePush||!Z)&&Y.userOpenId&&Y.messageId&&!Y.cardRotationFailed)C1(Y.messageId,[Y.userOpenId])}}});function Q$($){return{card:{type:"raw",data:$}}}import{randomUUID as KM}from"node:crypto";function OJ($){return{session_name:$.sessionName,chat_id:$.chatId,status:$.status,running:$.isRunning(),native_session_id:$.proc?.sessionId??null,codex_account:$.proc?.provider==="codex"&&$.proc.isAlive()?{name:k.get(r0($.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((Y)=>({model:Y.model,provider:Y.provider,source_id:Y.sourceId,efforts:Y.efforts.map((Q)=>Q.effort),origin:Y.origin}))})),sources:y$().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 gW($,Z,J,Y,Q){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(!Q||V.message_id!==Q)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!==Y)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 H={};for(let[X,z]of Object.entries(V.value)){if(!_M.has(X))throw Error(`unsupported model action field: ${X}`);if(X==="page"){if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)throw Error("invalid page");H.page=z}else{if(typeof z!=="string"||!z.trim()||z.length>1024)throw Error(`invalid ${X}`);H[X]=z.trim()}}if(!BM.has(String(H.kind)))throw Error("only model panel actions are supported");for(let X of["panel_id","source_id"])if(!H[X])throw Error(`${X} required`);if(["model_select","model_effort_select","model_add","model_remove","model_custom_remove"].includes(String(H.kind))&&!H.model)throw Error("model required");if(H.kind==="model_effort_select"&&!H.effort)throw Error("effort required");if(H.kind==="model_page"&&H.page===void 0)throw Error("page required");if(H.kind==="model_list_open"&&H.mode!=="select"&&H.mode!=="add")throw Error("invalid model list mode");if(H.provider!==void 0&&!B$(H.provider))throw Error("invalid provider");return{event_id:`debug-model-${KM()}`,operator:{open_id:Z.sender_open_id},context:{open_chat_id:Z.chat_id,open_message_id:V.message_id},action:{tag:"button",value:H}}}var BM,_M;var mW=R(()=>{D0();V0();p0();BM=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"]),_M=new Set(["kind","panel_id","source_id","model","effort","provider","page","mode"])});import{createServer as jM}from"node:http";import{randomUUID as LM}from"node:crypto";function lW($){if($.allowReply&&$.buttons?.length)throw Error(uW);let Z=$.level==="error"?"red":$.level==="warn"?"yellow":"blue",J=$.level==="error"?"❌":$.level==="warn"?"⚠️":"\uD83D\uDD14",Y=!!(($.buttons?.length||$.allowReply)&&$.notifyId),Q=new Date,V=`${String(Q.getHours()).padStart(2,"0")}:${String(Q.getMinutes()).padStart(2,"0")}`,H=[];for(let z of $.images??[])if(z.key)H.push({tag:"img",img_key:z.key,alt:{tag:"plain_text",content:"screenshot"}});else H.push({tag:"markdown",content:`<font color='red'>\uD83D\uDCF7 图片上传失败: ${z.src}</font>`});if(H.push({tag:"markdown",content:e7($.text??"")||"_(空消息)_"}),$.resolution){let z=$.resolution,W=z.kind==="text"?"已回复":`已选择:${z.text}`,G;if(z.status==="processing")G=`<font color='blue'>⏳ ${W} · 推送中…</font>`;else if(z.status==="failed")G=`<font color='red'>⚠️ ${z.kind==="text"?W:`已选:${z.text}`} · 回调失败:${Z0(z.detail??"未知")} · ${V}</font>`;else if(z.status==="delivered")G=`<font color='green'>✅ ${W} · 反馈已送达 · ${V}</font>`;else if(z.status==="unknown")G=`<font color='red'>⚠️ ${W} · ${z.kind==="text"?"送达状态未知,禁止自动重试":"外部回调已成功,但本地确认状态未知,禁止自动重试"} · ${V}</font>`;else G=`<font color='green'>✅ ${W} · ${V}</font>`;if(H.push({tag:"markdown",content:G}),z.status==="delivered"&&z.reply)H.push({tag:"markdown",content:Z0(z.reply)})}let X=Y&&(!$.resolution||$.resolution.status==="failed");if(X&&$.buttons?.length)H.push({tag:"column_set",columns:[{tag:"column",width:"weighted",weight:1,elements:$.buttons.map((z)=>({tag:"button",text:{tag:"plain_text",content:z.text},type:z.type,behaviors:[{type:"callback",value:{kind:"notify_callback",notify_id:$.notifyId,button_id:z.id}}]}))}]});if(H.push({tag:"hr"}),H.push({tag:"markdown",content:`<font color='grey'>via notify · ${V}</font>`}),X&&$.allowReply)H.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:Y?{update_multi:!0}:{},header:{title:{tag:"plain_text",content:`${J} ${$.title}`},template:Z},body:{elements:H}}}function _1($,Z,J){let Y=J?.status??Z.status,Q={waiting:"等待用户输入",sending:"正在发送回复",processing:"正在发送回复",delivered:"回复已送达",done:"回复已记录",failed:"回复发送失败",cancelled:"已取消回复",unknown:"回复送达状态未知"},V=[{tag:"markdown",content:`通知:${Z0($.title)}`}];if(Z.response)V.push({tag:"markdown",content:Z0(Z.response.text)});if(Y==="waiting")V.push({tag:"markdown",content:`<at id=${Z.openId}></at> 请在群里发送一条文字消息作为回复。
|
|
272
|
+
你的下一条文字优先用于这条通知,完成后再回答 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(Y==="cancelled"&&Z.cancelReason==="switched")V.push({tag:"markdown",content:"已切换到另一条通知,本次回复已放弃。"});let H=J?.detail??Z.error;if(H)V.push({tag:"markdown",content:`<font color='red'>${Z0(H)}</font>`});if(Y==="failed")V.push({tag:"markdown",content:"请点击原通知的「回复」按钮后重新输入。"});if(Y==="unknown")V.push({tag:"markdown",content:"无法确认是否已送达,请联系通知发起方核实;已禁止自动重试。"});if(J?.reply)V.push({tag:"markdown",content:Z0(J.reply)});return{schema:"2.0",config:{update_multi:!0},header:{title:{tag:"plain_text",content:Q[Y]},template:Y==="failed"||Y==="unknown"?"red":Y==="delivered"||Y==="done"?"green":"blue"},body:{elements:V}}}function FM($){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 Y of $){if(!Y||typeof Y!=="object")return{error:"each button must be an object"};let Q=String(Y.id??"").trim(),V=String(Y.text??"").trim();if(!DM.test(Q))return{error:`button id "${Q.slice(0,32)}" invalid (need ^[A-Za-z0-9_-]{1,64}$)`};if(!V)return{error:`button "${Q}" missing text`};if(V.length>pW)return{error:`button "${Q}" text > ${pW} chars`};if(Z.has(Q))return{error:`button id "${Q}" duplicated`};Z.add(Q);let H=String(Y.type??"default").toLowerCase(),X=PM.has(H)?H:"default";J.push({id:Q,text:V,type:X})}return{buttons:J}}function MM($){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 Y=J.hostname.replace(/^\[|]$/g,"");if(Y!=="127.0.0.1"&&Y!=="localhost"&&Y!=="::1")return{error:`"callback" must be loopback (本机内), got "${J.hostname}"`};return{url:Z}}function dW($){try{let Z=jM((J,Y)=>{let Q=new URL(J.url??"/",`http://${J.headers.host??"localhost"}`);($.extraHandler?$.extraHandler(J,Y,Q).then((H)=>H?void 0:cW(J,Y)):cW(J,Y)).catch((H)=>{if(K(`notify: handler crash: ${H?.message??H}`),!Y.headersSent)Y.statusCode=500,Y.setHeader("content-type","text/plain; charset=utf-8"),Y.end("internal error");else try{Y.end()}catch{}})});Z.on("error",(J)=>{K(`notify: server bind failed (${$.bind}:${$.port}): ${J.message}`)}),Z.listen($.port,$.bind,()=>{K(`notify: HTTP listening at http://${$.bind}:${$.port}/notify`)})}catch(Z){K(`notify: server bind failed (${$.bind}:${$.port}): ${Z}`)}}async function cW($,Z,J=Y0){let Y=new URL($.url??"/",`http://${$.headers.host??"localhost"}`),Q=(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"&&Y.pathname==="/")return Q(200,`lodestar notify
|
|
273
273
|
`+`POST /notify body={project,text,title?,level?,images?,buttons?,allow_reply?,callback?} → push card to group
|
|
274
274
|
`+`GET /notify/result/<notify_id> → poll a button choice or text reply (pull mode, no callback server)
|
|
275
275
|
`+`GET /agents/identities; POST/GET/DELETE /agents/runs[/<id>] → capability-protected delegated Agents
|
|
276
276
|
`+`levels: info|warn|error (default info); images=[/abs/*.png] uploaded + embedded
|
|
277
277
|
card types: plain (neither field), selection (buttons), text reply (allow_reply:true); do not combine buttons and allow_reply:true
|
|
278
278
|
`+`all types support text + images; callback=http://127.0.0.1:PORT/path optional for selection/reply (push) — omit to poll
|
|
279
|
-
`);if($.method==="GET"&&Y.pathname.startsWith("/notify/result/")){let l=decodeURIComponent(Y.pathname.slice(15)).trim();if(!l)return Q(400,"missing notify_id in path");let
|
|
280
|
-
`;for(let[V,H]of[[J,Q],[Y,$.body]])try{let X=
|
|
281
|
-
name: ${
|
|
279
|
+
`);if($.method==="GET"&&Y.pathname.startsWith("/notify/result/")){let l=decodeURIComponent(Y.pathname.slice(15)).trim();if(!l)return Q(400,"missing notify_id in path");let F=I$(l);if(!F)return V(404,{error:"unknown notify_id",notify_id:l});return V(200,OX(F))}if($.method!=="POST"||Y.pathname!=="/notify")return Q(405,"use POST /notify");let H="";for await(let l of $)H+=l.toString();let X={};try{X=JSON.parse(H)}catch{return Q(400,"bad json")}if(!X||typeof X!=="object"||Array.isArray(X))return Q(400,"body must be an object");if(X.allow_reply!==void 0&&typeof X.allow_reply!=="boolean")return Q(400,'"allow_reply" must be a boolean');let z=X.allow_reply===!0,W=String(X.project??"").trim(),G=String(X.text??""),B=String(X.title??"").trim(),_=String(X.level??"info").toLowerCase();if(!W)return Q(400,'missing "project"');if(!G)return Q(400,'missing "text"');let{buttons:j,error:q}=FM(X.buttons);if(q)return Q(400,q);let{url:P,error:D}=MM(X.callback);if(D)return Q(400,D);let T=!!(j&&j.length);if(T&&z)return Q(400,uW);let M=T||z,A=P??"",U=qM.has(_)?_:"info",S=B||W,b=J.sanitizeSessionName(W),v=J.chatIdForSession(b);if(!v)return K(`notify: project "${W}" (sanitized "${b}") has no chat binding → 404`),Q(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(X.images)?X.images:[],g=[];for(let l of y){let F=String(l??"").trim();if(!F)continue;let C=await J.uploadImageKey(F);g.push({key:C??"",src:F})}let x=M?`nf_${LM()}`:"",h=lW({title:S,text:G,level:U,images:g,buttons:j,allowReply:z,notifyId:x}),p=await J.sendCard(v,h);if(!p)return K(`notify: sendCard failed → 502 (project="${W}" chat=${v.slice(0,8)}…)`),Q(502,"feishu sendCard failed (see daemon log)");if(M&&x){let l={notifyId:x,callbackUrl:A,chatId:v,messageId:p,project:W,title:S,text:G,level:U,imageKeys:g,buttons:j,allowReply:z,createdAt:Date.now()};UX(l)}K(`notify: → ${W} (${v.slice(0,8)}…) level=${U} bytes=${G.length} images=${g.length} buttons=${j?.length??0} allowReply=${z} push=${M&&!!A?1:0} msg=${p}`),V(200,{ok:!0,chat_id:v,message_id:p,...x?{notify_id:x}:{}})}function t1($,Z){return lW({title:$.title,text:$.text,level:$.level,images:$.imageKeys,buttons:$.buttons,allowReply:$.allowReply,notifyId:$.notifyId,resolution:Z})}var qM,PM,DM,pW=64,uW='"buttons" and "allow_reply":true are mutually exclusive; choose button selection or text reply';var a6=R(()=>{I();t();x0();U9();qM=new Set(["info","warn","error"]),PM=new Set(["default","primary","danger"]),DM=/^[A-Za-z0-9_-]{1,64}$/});import{existsSync as RJ,readFileSync as NJ,rmSync as UM}from"node:fs";import{homedir as o6}from"node:os";import{join as T$}from"node:path";function J4($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){K(`skill: sync disabled, skip ${$.name}`);return}let J=Z??[T$(o6(),".codex","skills"),T$(o6(),".claude","skills")];for(let Y of J){let Q=T$(Y,$.name,"SKILL.md");try{let V=RJ(Q)?NJ(Q,"utf8"):null;if(V===$.body)continue;I0(Q,$.body),K(`skill: ${V===null?"installed":"updated"} ${Q}`)}catch(V){K(`skill: sync failed (${Q}): ${V}`)}}if(!Z)AM($,D1)}function AM($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){K(`skill: sync disabled, skip Claude plugin ${$.name}`);return}let J=T$(Z,".claude-plugin","plugin.json"),Y=T$(Z,"skills",$.name,"SKILL.md"),Q=JSON.stringify({name:"lodestar-managed",description:"Lodestar daemon-managed Skills for Claude Agent SDK sessions",version:"1.0.0",author:{name:"Lodestar"}},null,2)+`
|
|
280
|
+
`;for(let[V,H]of[[J,Q],[Y,$.body]])try{let X=RJ(V)?NJ(V,"utf8"):null;if(X===H)continue;I0(V,H),K(`skill: ${X===null?"installed":"updated"} ${V}`)}catch(X){K(`skill: Claude plugin sync failed (${V}): ${X}`)}}function iW($,Z){if(process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"){K(`skill: sync disabled, skip removal ${$}`);return}let Y=(Z??[T$(o6(),".codex","skills"),T$(o6(),".claude","skills")]).map((Q)=>T$(Q,$));if(!Z)Y.push(T$(D1,"skills",$));for(let Q of Y){let V=T$(Q,"SKILL.md");if(!RJ(V))continue;try{let H=NJ(V,"utf8");if(!(H.includes(`name: ${$}`)||H.includes(`name: "${$}"`))){K(`skill: obsolete path preserved because ownership is unclear ${V}`);continue}UM(Q,{recursive:!0,force:!1}),K(`skill: removed obsolete ${Q}`)}catch(H){K(`skill: obsolete removal failed (${Q}): ${H}`)}}}var r6=R(()=>{I();T0();Q0()});function OM($){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`---
|
|
281
|
+
name: ${nW}
|
|
282
282
|
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.")}
|
|
283
283
|
---
|
|
284
284
|
|
|
@@ -535,13 +535,13 @@ is the script's acknowledgement, distinct from the user's response.
|
|
|
535
535
|
Hand-edits will be overwritten — set
|
|
536
536
|
\`LODESTAR_DISABLE_SKILL_SYNC=1\` and restart the daemon if you want
|
|
537
537
|
to maintain the file yourself.
|
|
538
|
-
`}function oW(){J4({name:aW,body:AM(f.notify.port)})}var aW="feishu-notify";var rW=R(()=>{y0();s6()});import{randomUUID as OM}from"node:crypto";function sW($){let Z=(V)=>V instanceof Error?V.message:String(V),J=(V,H,X)=>{if(!V)return"通知已过期或已移除";if(!X)return"无法识别回复人,操作未执行";if(H&&H!==V.chatId)return"通知不属于当前群,操作未执行";if(!V.allowReply)return"此通知未开启文字回复";if(V.unknownAt)return`回复送达状态未知,禁止自动重试:${V.unknownReason}`;if(V.resolvedAt)return"此通知已处理";if(p2(V.notifyId))return"通知正在处理中";return null},Y=async(V,H)=>{if($.log(`notify-reply: ${H}`),!await $.sendText(V,`❌ ${H}`))throw Error(`通知回复错误提示发送失败: ${H}`)},Q=async(V,H,X,z)=>{try{await $.updateCard(H,X)}catch(W){await Y(V.chatId,`${z},卡片更新失败:${Z(W)}`)}};return{async recover(V){let H=V.replyState;if(!H||!V.unknownAt)return;let X={kind:"text",status:"unknown",text:H.response?.text??"",operatorOpenId:H.openId,detail:V.unknownReason};await Q(V,H.promptMessageId,_1(V,H,X),"回复送达状态未知"),await Q(V,V.messageId,t1(V,X),"回复送达状态未知")},async open(V,H,X){let z=I$(V),W=J(z,H,X);if(W||!z)return{ok:!1,message:W};if(z.replyState?.status==="waiting"||z.replyState?.status==="sending")return{ok:!1,message:"此通知正在等待回复,请先在群里输入或由回复人取消"};let G=TZ(z.chatId);if(G.some((B)=>B.replyState?.status==="sending"||p2(B.notifyId)))return{ok:!1,message:"上一条通知回复正在发送,请稍后切换"};P9(V);try{for(let j of G){let q={...j.replyState,status:"cancelled",cancelReason:"switched"};u2(j.notifyId,q),await Q(j,q.promptMessageId,_1(j,q),"已放弃上一条回复并切换通知")}let B={id:OM(),openId:X,promptMessageId:"",openedAt:Date.now(),status:"waiting"},_=await $.sendCard(z.chatId,_1(z,B));if(!_)return{ok:!1,message:"等待输入卡片发送失败,未开始接收回复,请重新点击「回复」"};B.promptMessageId=_;try{u2(V,B)}catch(j){let q=`等待输入状态保存失败,未开始接收回复:${Z(j)}`;return await Q(z,_,_1(z,B,{status:"failed",detail:q}),q),{ok:!1,message:q,presented:!0}}return{ok:!0,message:"等待输入卡片已发送,请在群里回复一条文字",presented:!0}}finally{F9(V),$.onWaitingChanged(z.chatId)}},async cancel(V,H,X,z){let W=I$(V),G=J(W,X,z);if(G||!W)return{ok:!1,message:G};let B=W.replyState;if(!B||B.id!==H||B.status!=="waiting")return{ok:!1,message:"此回复已结束或正在发送,无法取消"};if(B.openId!==z)return{ok:!1,message:"仅点击「回复」的人可以取消"};let _={...B,status:"cancelled"};return u2(V,_),$.onWaitingChanged(W.chatId),await Q(W,B.promptMessageId,_1(W,_),"回复已取消"),{ok:!0,message:"已取消回复",presented:!0}},async consume(V){let{chatId:H,openId:X,messageId:z,text:W,createTime:G}=V;if(!X||!z||!W.trim())return!1;if(OX(H,z))return!0;let B=D9(H,X);if(!B?.replyState)return!1;let _=B.replyState;if(G>0&&G<_.openedAt)return!1;if(_.status!=="waiting"||p2(B.notifyId))return await Y(H,"上一条通知回复正在发送,这条文字未提交,请稍后重发"),!0;let j={text:W,message_id:z,prompt_message_id:_.promptMessageId},q={..._,status:"sending",response:j};P9(B.notifyId);try{try{u2(B.notifyId,q)}catch(M){return await Y(H,`回复保存失败,尚未回传,请重新输入:${Z(M)}`),!0}let P;try{if(await $.updateCard(_.promptMessageId,_1(B,q)),B.callbackUrl)P=await $.dispatch(B,j,X);else M9(B.notifyId,void 0,X),P={ok:!0,detail:"已记录"}}catch(M){P={ok:!1,detail:Z(M)}}let F;if(P.ok){let M=B.callbackUrl?A6(B.notifyId,void 0,X):{state:"complete"};F={kind:"text",text:W,operatorOpenId:X,status:M.state==="unknown"?"unknown":B.callbackUrl?"delivered":"done",...M.state==="unknown"?{detail:M.detail}:{reply:P.reply}}}else{F={kind:"text",text:W,operatorOpenId:X,status:"failed",detail:P.detail};try{u2(B.notifyId,{...q,status:"failed",error:P.detail})}catch(M){let A=`${P.detail};失败状态保存失败:${Z(M)}`;try{EZ(B.notifyId,void 0,X,A)}catch(U){$.log(`notify-reply: UNKNOWN persistence failed: ${Z(U)}`)}F={...F,status:"unknown",detail:A}}}let T=F.status==="delivered"?"回复已送达":F.status==="done"?"回复已记录":F.status==="unknown"?`回复送达状态未知:${F.detail}`:`回复未送达:${F.detail}`;return await Q(B,_.promptMessageId,_1(B,q,F),T),await Q(B,B.messageId,t1(B,F),T),$.log(`notify-reply: notify_id=${B.notifyId} status=${F.status}`),!0}finally{F9(B.notifyId),$.onWaitingChanged(B.chatId)}}}}var tW=R(()=>{U9();o6()});class EJ{deps;tails=new Map;byRun=new Map;constructor($){this.deps=$}add($){return D$($.chatId,async()=>{let Z=this.tails.get($.chatId);if(Z){if(await this.deps.getChatTailMessageId($.chatId)===Z.messageId&&this.deps.getElementCount(Z.cardId)<RM){let Y=await this.deps.addElementResult(Z.cardId,_9($));if(Y.landed){this.attach(Z,$),await this.settings(Z);return}if(!eW(Y))throw $G("agent card append",Y)}await this.seal(Z)}await this.create($)})}update($,Z=!1){return D$($.chatId,async()=>{let J=this.byRun.get($.runId);if(!J)return;if(J.settled.has($.runId)){if(Z)await this.settings(J);return}let Y=[],Q=await this.deps.replaceElementResult(J.cardId,j9($.runId),_9($));if(!Q.landed){if(!eW(Q)||J.runs.size===1)throw $G("agent task row update",Q);let V=J;await this.seal(V);let H=this.tails.get($.chatId);if(H)await this.seal(H);J=await this.create($),V.runs.delete($.runId),V.settled.delete($.runId);try{if(!await this.deps.deleteElementChecked(V.cardId,j9($.runId)))throw Error("agent moved task row deletion MISS; the previous card may still show its earlier state")}catch(X){Y.push(String(X))}try{await this.settings(V)}catch(X){Y.push(String(X))}}if(Z)J.settled.add($.runId);try{await this.settings(J)}catch(V){Y.push(String(V))}if(Y.length)throw Error(Y.join("; "))})}closeChat($){return D$($,async()=>{let Z=this.tails.get($);if(Z)await this.seal(Z)})}attach($,Z){$.runs.set(Z.runId,Z),this.byRun.set(Z.runId,$),Z.cardMessageId=$.messageId}async create($){let Z=await this.deps.sendCard($.chatId,GZ($));if(!Z)throw Error("agent card creation failed");let J=await this.deps.convertMessageToCard(Z);this.deps.recordCardCreated(J,1);let Y={cardId:J,messageId:Z,chatId:$.chatId,runs:new Map,settled:new Set,sealed:!1};return this.attach(Y,$),this.tails.set($.chatId,Y),Y}async seal($){if($.sealed=!0,this.tails.get($.chatId)===$)this.tails.delete($.chatId);await this.settings($)}async settings($){this.deps.cancelSummary($.cardId);let Z=$.settled.size===$.runs.size,J={config:{streaming_mode:!Z,summary:{content:KZ([...$.runs.values()])}}},Y=JSON.stringify(J);if(Y!==$.settingsJson){if(!await this.deps.patchSettingsChecked($.cardId,J))throw Error("agent card settings update MISS");$.settingsJson=Y}if(Z&&$.sealed){await this.deps.dispose($.cardId);for(let Q of $.runs.keys())if(this.byRun.get(Q)===$)this.byRun.delete(Q)}}}function eW($){return s4($.failure?.code,$.failure)}function $G($,Z){return Error(`${$} MISS${Z.failure?`: ${Z.failure.message} (code=${Z.failure.code??"MISS"})`:""}`)}var RM=50;var ZG=R(()=>{Y$();v$();g3()});function JG($){let Z=xJ($,"agent run request"),J=Array.isArray(Z.identity_ids)?Z.identity_ids.map(String):Array.isArray(Z.identityIds)?Z.identityIds.map(String):[],Y=[...new Set(J.map((z)=>z.trim()).filter(Boolean))],Q=Z.session_id!==void 0?Z.session_id:Z.sessionId,V=Y4(Q);if(Q!==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&&Y.length>1)throw Error("agent session continuation accepts at most one identity_id");if(!V&&Y.length===0)throw Error("agent run requires at least one identity_id");if(Y.length>64)throw Error("agent run supports at most 64 identities");let H=VG(Z.prompt,'agent run requires "prompt"'),X=Y4(Z.effort);return{identityIds:Y,description:Q4(Z.description),prompt:H,...X?{effort:X}:{},...V?{sessionId:V}:{}}}function YG($){let Z=xJ($,"agent follow-up request"),J=VG(Z.prompt,'agent follow-up requires "prompt"'),Y=Y4(Z.identity_id??Z.identityId),Q=Y4(Z.effort);return{description:Q4(Z.description),prompt:J,...Y?{identityId:Y}:{},...Q?{effort:Q}:{}}}function Q4($){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 QG($){let Z=xJ($,"agent answer request"),J=Y4(Z.identity_id??Z.identityId),Y=Y4(Z.request_id??Z.requestId);if(!Y)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 Q={};for(let[V,H]of Object.entries(Z.answers)){if(!V.trim())throw Error("agent answer contains an empty question key");Q[V]=String(H)}if(Object.keys(Q).length===0)throw Error("agent answer requires at least one answer");return{requestId:Y,answers:Q,...J?{identityId:J}:{}}}function xJ($,Z){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${Z} must be an object`);return $}function VG($,Z){let J=String($??"");if(!J.trim())throw Error(Z);if(J.length>800000)throw Error("agent prompt exceeds 800000 chars");return J}function Y4($){return(typeof $==="string"?$.trim():"")||void 0}function NM(){return["---",`name: ${HG}`,`description: ${JSON.stringify("Main Agents can delegate a task to a different configured model or Agent through Lodestar and continue the same work across multiple turns. Delegated Agents and subagents must not use this Skill or delegate further. Main-Agent self-calls use native delegation capabilities.")}`,"---","","# 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.","","## Single-level delegation","","- Only the main Agent may delegate work. If you are already a delegated"," Agent or subagent, complete your assigned task yourself: do not delegate further.","- This prohibition covers this Skill, `lodestar-agent run` / `follow-up`,"," native Agent/subagent tools, and delegation through provider CLIs or HTTP APIs.","- `LODESTAR_AGENT_ROLE=worker` identifies a Lodestar delegated process."," Native subagents are also delegated Agents even when they inherit a main role environment.","- Return additional work requests to the main Agent. It can assign separate"," tasks, continue your session, or answer your questions.","","## Hard rule: native Agent capabilities for self-calls","","- For the main Agent only: when calling yourself or your own model/Agent, use your current"," Agent's native Agent/subagent capabilities. You MUST NOT use this Skill"," or the `lodestar-agent` command for self-calls.","- For example, Codex calling Codex uses Codex native subagents; Claude"," calling Claude uses Claude native Agent capabilities.","- This does not exempt delegated Agents from the single-level rule above.","- If native delegation is unavailable, report that limitation. It does not"," permit routing a self-call through this Skill.","","## Required workflow","","1. For another model/Agent, 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."," Explicitly tell it to complete the work itself without further delegation."," 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 other models, pass every identity to one run"," with repeated `--identity`; the daemon schedules them within concurrency limits."," OpenRouter allows at most 2 delegated tasks at once across projects and models"," in the same daemon; additional tasks queue. This is a local limit, not an API quota."," Wait for queued tasks instead of submitting duplicates. If rate-limited, report"," the error 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","```","","## 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; the delegated Agent still must not delegate further.","","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 and inherits its identity and","last effort. An optional `--identity` must match the original worker;","`--effort` explicitly changes the effort for this turn. The run returns a new","`run_id` and the same native `session_id`; repeat to continue further turns.","The session must belong to this Lodestar Session and workspace, with its","delegated run history still available. Saved history supports continuation","after a daemon restart. Unknown sessions, unavailable identities and native","resume failures are errors. Wait for the current run to finish before resuming;","concurrent turns on the same 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.","An empty, unknown or out-of-scope session id is rejected before execution;","native resume 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","","When a 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.","- 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.",""].join(`
|
|
539
|
-
`)}function
|
|
540
|
-
`)});function
|
|
538
|
+
`}function aW(){J4({name:nW,body:OM(f.notify.port)})}var nW="feishu-notify";var oW=R(()=>{y0();r6()});import{randomUUID as RM}from"node:crypto";function rW($){let Z=(V)=>V instanceof Error?V.message:String(V),J=(V,H,X)=>{if(!V)return"通知已过期或已移除";if(!X)return"无法识别回复人,操作未执行";if(H&&H!==V.chatId)return"通知不属于当前群,操作未执行";if(!V.allowReply)return"此通知未开启文字回复";if(V.unknownAt)return`回复送达状态未知,禁止自动重试:${V.unknownReason}`;if(V.resolvedAt)return"此通知已处理";if(p2(V.notifyId))return"通知正在处理中";return null},Y=async(V,H)=>{if($.log(`notify-reply: ${H}`),!await $.sendText(V,`❌ ${H}`))throw Error(`通知回复错误提示发送失败: ${H}`)},Q=async(V,H,X,z)=>{try{await $.updateCard(H,X)}catch(W){await Y(V.chatId,`${z},卡片更新失败:${Z(W)}`)}};return{async recover(V){let H=V.replyState;if(!H||!V.unknownAt)return;let X={kind:"text",status:"unknown",text:H.response?.text??"",operatorOpenId:H.openId,detail:V.unknownReason};await Q(V,H.promptMessageId,_1(V,H,X),"回复送达状态未知"),await Q(V,V.messageId,t1(V,X),"回复送达状态未知")},async open(V,H,X){let z=I$(V),W=J(z,H,X);if(W||!z)return{ok:!1,message:W};if(z.replyState?.status==="waiting"||z.replyState?.status==="sending")return{ok:!1,message:"此通知正在等待回复,请先在群里输入或由回复人取消"};let G=NZ(z.chatId);if(G.some((B)=>B.replyState?.status==="sending"||p2(B.notifyId)))return{ok:!1,message:"上一条通知回复正在发送,请稍后切换"};P9(V);try{for(let j of G){let q={...j.replyState,status:"cancelled",cancelReason:"switched"};u2(j.notifyId,q),await Q(j,q.promptMessageId,_1(j,q),"已放弃上一条回复并切换通知")}let B={id:RM(),openId:X,promptMessageId:"",openedAt:Date.now(),status:"waiting"},_=await $.sendCard(z.chatId,_1(z,B));if(!_)return{ok:!1,message:"等待输入卡片发送失败,未开始接收回复,请重新点击「回复」"};B.promptMessageId=_;try{u2(V,B)}catch(j){let q=`等待输入状态保存失败,未开始接收回复:${Z(j)}`;return await Q(z,_,_1(z,B,{status:"failed",detail:q}),q),{ok:!1,message:q,presented:!0}}return{ok:!0,message:"等待输入卡片已发送,请在群里回复一条文字",presented:!0}}finally{D9(V),$.onWaitingChanged(z.chatId)}},async cancel(V,H,X,z){let W=I$(V),G=J(W,X,z);if(G||!W)return{ok:!1,message:G};let B=W.replyState;if(!B||B.id!==H||B.status!=="waiting")return{ok:!1,message:"此回复已结束或正在发送,无法取消"};if(B.openId!==z)return{ok:!1,message:"仅点击「回复」的人可以取消"};let _={...B,status:"cancelled"};return u2(V,_),$.onWaitingChanged(W.chatId),await Q(W,B.promptMessageId,_1(W,_),"回复已取消"),{ok:!0,message:"已取消回复",presented:!0}},async consume(V){let{chatId:H,openId:X,messageId:z,text:W,createTime:G}=V;if(!X||!z||!W.trim())return!1;if(AX(H,z))return!0;let B=F9(H,X);if(!B?.replyState)return!1;let _=B.replyState;if(G>0&&G<_.openedAt)return!1;if(_.status!=="waiting"||p2(B.notifyId))return await Y(H,"上一条通知回复正在发送,这条文字未提交,请稍后重发"),!0;let j={text:W,message_id:z,prompt_message_id:_.promptMessageId},q={..._,status:"sending",response:j};P9(B.notifyId);try{try{u2(B.notifyId,q)}catch(M){return await Y(H,`回复保存失败,尚未回传,请重新输入:${Z(M)}`),!0}let P;try{if(await $.updateCard(_.promptMessageId,_1(B,q)),B.callbackUrl)P=await $.dispatch(B,j,X);else M9(B.notifyId,void 0,X),P={ok:!0,detail:"已记录"}}catch(M){P={ok:!1,detail:Z(M)}}let D;if(P.ok){let M=B.callbackUrl?U6(B.notifyId,void 0,X):{state:"complete"};D={kind:"text",text:W,operatorOpenId:X,status:M.state==="unknown"?"unknown":B.callbackUrl?"delivered":"done",...M.state==="unknown"?{detail:M.detail}:{reply:P.reply}}}else{D={kind:"text",text:W,operatorOpenId:X,status:"failed",detail:P.detail};try{u2(B.notifyId,{...q,status:"failed",error:P.detail})}catch(M){let A=`${P.detail};失败状态保存失败:${Z(M)}`;try{TZ(B.notifyId,void 0,X,A)}catch(U){$.log(`notify-reply: UNKNOWN persistence failed: ${Z(U)}`)}D={...D,status:"unknown",detail:A}}}let T=D.status==="delivered"?"回复已送达":D.status==="done"?"回复已记录":D.status==="unknown"?`回复送达状态未知:${D.detail}`:`回复未送达:${D.detail}`;return await Q(B,_.promptMessageId,_1(B,q,D),T),await Q(B,B.messageId,t1(B,D),T),$.log(`notify-reply: notify_id=${B.notifyId} status=${D.status}`),!0}finally{D9(B.notifyId),$.onWaitingChanged(B.chatId)}}}}var sW=R(()=>{U9();a6()});class TJ{deps;tails=new Map;byRun=new Map;constructor($){this.deps=$}add($){return F$($.chatId,async()=>{let Z=this.tails.get($.chatId);if(Z){if(await this.deps.getChatTailMessageId($.chatId)===Z.messageId&&this.deps.getElementCount(Z.cardId)<NM){let Y=await this.deps.addElementResult(Z.cardId,_9($));if(Y.landed){this.attach(Z,$),await this.settings(Z);return}if(!tW(Y))throw eW("agent card append",Y)}await this.seal(Z)}await this.create($)})}update($,Z=!1){return F$($.chatId,async()=>{let J=this.byRun.get($.runId);if(!J)return;if(J.settled.has($.runId)){if(Z)await this.settings(J);return}let Y=[],Q=await this.deps.replaceElementResult(J.cardId,j9($.runId),_9($));if(!Q.landed){if(!tW(Q)||J.runs.size===1)throw eW("agent task row update",Q);let V=J;await this.seal(V);let H=this.tails.get($.chatId);if(H)await this.seal(H);J=await this.create($),V.runs.delete($.runId),V.settled.delete($.runId);try{if(!await this.deps.deleteElementChecked(V.cardId,j9($.runId)))throw Error("agent moved task row deletion MISS; the previous card may still show its earlier state")}catch(X){Y.push(String(X))}try{await this.settings(V)}catch(X){Y.push(String(X))}}if(Z)J.settled.add($.runId);try{await this.settings(J)}catch(V){Y.push(String(V))}if(Y.length)throw Error(Y.join("; "))})}closeChat($){return F$($,async()=>{let Z=this.tails.get($);if(Z)await this.seal(Z)})}attach($,Z){$.runs.set(Z.runId,Z),this.byRun.set(Z.runId,$),Z.cardMessageId=$.messageId}async create($){let Z=await this.deps.sendCard($.chatId,WZ($));if(!Z)throw Error("agent card creation failed");let J=await this.deps.convertMessageToCard(Z);this.deps.recordCardCreated(J,1);let Y={cardId:J,messageId:Z,chatId:$.chatId,runs:new Map,settled:new Set,sealed:!1};return this.attach(Y,$),this.tails.set($.chatId,Y),Y}async seal($){if($.sealed=!0,this.tails.get($.chatId)===$)this.tails.delete($.chatId);await this.settings($)}async settings($){this.deps.cancelSummary($.cardId);let Z=$.settled.size===$.runs.size,J={config:{streaming_mode:!Z,summary:{content:GZ([...$.runs.values()])}}},Y=JSON.stringify(J);if(Y!==$.settingsJson){if(!await this.deps.patchSettingsChecked($.cardId,J))throw Error("agent card settings update MISS");$.settingsJson=Y}if(Z&&$.sealed){await this.deps.dispose($.cardId);for(let Q of $.runs.keys())if(this.byRun.get(Q)===$)this.byRun.delete(Q)}}}function tW($){return s4($.failure?.code,$.failure)}function eW($,Z){return Error(`${$} MISS${Z.failure?`: ${Z.failure.message} (code=${Z.failure.code??"MISS"})`:""}`)}var NM=50;var $G=R(()=>{Y$();v$();I3()});function ZG($){let Z=EJ($,"agent run request"),J=Array.isArray(Z.identity_ids)?Z.identity_ids.map(String):Array.isArray(Z.identityIds)?Z.identityIds.map(String):[],Y=[...new Set(J.map((z)=>z.trim()).filter(Boolean))],Q=Z.session_id!==void 0?Z.session_id:Z.sessionId,V=Y4(Q);if(Q!==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&&Y.length>1)throw Error("agent session continuation accepts at most one identity_id");if(!V&&Y.length===0)throw Error("agent run requires at least one identity_id");if(Y.length>64)throw Error("agent run supports at most 64 identities");let H=QG(Z.prompt,'agent run requires "prompt"'),X=Y4(Z.effort);return{identityIds:Y,description:Q4(Z.description),prompt:H,...X?{effort:X}:{},...V?{sessionId:V}:{}}}function JG($){let Z=EJ($,"agent follow-up request"),J=QG(Z.prompt,'agent follow-up requires "prompt"'),Y=Y4(Z.identity_id??Z.identityId),Q=Y4(Z.effort);return{description:Q4(Z.description),prompt:J,...Y?{identityId:Y}:{},...Q?{effort:Q}:{}}}function Q4($){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 YG($){let Z=EJ($,"agent answer request"),J=Y4(Z.identity_id??Z.identityId),Y=Y4(Z.request_id??Z.requestId);if(!Y)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 Q={};for(let[V,H]of Object.entries(Z.answers)){if(!V.trim())throw Error("agent answer contains an empty question key");Q[V]=String(H)}if(Object.keys(Q).length===0)throw Error("agent answer requires at least one answer");return{requestId:Y,answers:Q,...J?{identityId:J}:{}}}function EJ($,Z){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${Z} must be an object`);return $}function QG($,Z){let J=String($??"");if(!J.trim())throw Error(Z);if(J.length>800000)throw Error("agent prompt exceeds 800000 chars");return J}function Y4($){return(typeof $==="string"?$.trim():"")||void 0}function TM(){return["---",`name: ${VG}`,`description: ${JSON.stringify("Main Agents can delegate a task to a different configured model or Agent through Lodestar and continue the same work across multiple turns. Delegated Agents and subagents must not use this Skill or delegate further. Main-Agent self-calls use native delegation capabilities.")}`,"---","","# 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.","","## Single-level delegation","","- Only the main Agent may delegate work. If you are already a delegated"," Agent or subagent, complete your assigned task yourself: do not delegate further.","- This prohibition covers this Skill, `lodestar-agent run` / `follow-up`,"," native Agent/subagent tools, and delegation through provider CLIs or HTTP APIs.","- `LODESTAR_AGENT_ROLE=worker` identifies a Lodestar delegated process."," Native subagents are also delegated Agents even when they inherit a main role environment.","- Return additional work requests to the main Agent. It can assign separate"," tasks, continue your session, or answer your questions.","","## Hard rule: native Agent capabilities for self-calls","","- For the main Agent only: when calling yourself or your own model/Agent, use your current"," Agent's native Agent/subagent capabilities. You MUST NOT use this Skill"," or the `lodestar-agent` command for self-calls.","- For example, Codex calling Codex uses Codex native subagents; Claude"," calling Claude uses Claude native Agent capabilities.","- This does not exempt delegated Agents from the single-level rule above.","- If native delegation is unavailable, report that limitation. It does not"," permit routing a self-call through this Skill.","","## Required workflow","","1. For another model/Agent, 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."," Explicitly tell it to complete the work itself without further delegation."," 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 other models, pass every identity to one run"," with repeated `--identity`; the daemon schedules them within concurrency limits."," OpenRouter allows at most 2 delegated tasks at once across projects and models"," in the same daemon; additional tasks queue. This is a local limit, not an API quota."," Wait for queued tasks instead of submitting duplicates. If rate-limited, report"," the error 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","```","","## 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; the delegated Agent still must not delegate further.","","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 and inherits its identity and","last effort. An optional `--identity` must match the original worker;","`--effort` explicitly changes the effort for this turn. The run returns a new","`run_id` and the same native `session_id`; repeat to continue further turns.","The session must belong to this Lodestar Session and workspace, with its","delegated run history still available. Saved history supports continuation","after a daemon restart. Unknown sessions, unavailable identities and native","resume failures are errors. Wait for the current run to finish before resuming;","concurrent turns on the same 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.","An empty, unknown or out-of-scope session id is rejected before execution;","native resume 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","","When a 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.","- 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.",""].join(`
|
|
539
|
+
`)}function XG(){iW("lodestar-consult"),J4({name:VG,body:TM()})}var VG="lodestar-agent",HG;var xJ=R(()=>{r6();HG=["You are a delegated Agent working on a task assigned by the main Agent.","Complete this task yourself. You must not create or invoke any further Agents or subagents.","This includes Lodestar delegation, provider-native Agent/subagent tools, and delegation through CLIs or HTTP APIs.","If additional Agent work is needed, report the need to the main Agent so it can assign that work."].join(`
|
|
540
|
+
`)});function zG($){let Z=H0($.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:Y}=v4({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,HG].filter(Boolean).join(`
|
|
541
541
|
|
|
542
|
-
`),allowDelegation:!1,profile:$.profile,managedSkillPluginPath:$.managedSkillPluginPath,hostEnv:{...$.hostEnv,LODESTAR_AGENT_ROLE:"worker"},serviceName:"lodestar-agent"});return TM(Y,$.prompt,$.callbacks)}function TM($,Z,J={},Y=bY){let Q=[],V=null,H=!1,X=null,z=null,W=[],G,B,_=Date.now(),j=new Promise((D,C)=>{G=D,B=C}),q=(D)=>{if(!D)return null;try{return Y($.provider,D),J.onSession?.(D),null}catch(C){return C instanceof Error?C:Error(String(C))}},P=()=>{if($.off("assistant_text",T),$.off("tool_use",A),$.off("tool_result",U),$.off("subagent_step",S),$.off("can_use_tool",b),$.off("hook_callback",v),$.off("init",y),!$.isAlive())$.off("error",g);$.off("turn_retry",h),$.off("codex_account_changed",x),$.off("result",p),$.off("exit",l)},F=(D,C)=>{if(X)return X;return H=!0,W.length=0,X=Promise.resolve().then(async()=>{let d=q($.sessionId);try{await $.kill(3000)}catch(q1){z=q1 instanceof Error?q1:Error(String(q1))}P();let o=[D,d,z].filter((q1)=>!!q1),K0=o.length>1?AggregateError(o,o.map((q1)=>q1.message).join("; ")):o[0];if(K0){B(new E9(K0,Q.join("").trim(),$.sessionId));return}let W4=$.sessionId;if(!W4){B(new E9(Error("delegated agent completed without a native session id"),Q.join("").trim(),null));return}let b9=Q.join("").trim(),Z2=SM(C?.checkpoint,$);G({output:b9,outputTruncated:!1,sessionId:W4,...Z2?{checkpointId:Z2}:{},durationMs:Date.now()-_,usage:$.lastUsage?{...$.lastUsage}:null})}),X},T=(D)=>{if(H||D?.parentToolUseId||typeof D?.text!=="string")return;Q.push(D.text)},M=(D)=>{if(H)return;try{J.onProgress?.(D)}catch(C){F(C instanceof Error?C:Error(String(C)))}},A=(D)=>M({at:new Date().toISOString(),phase:"started",tool:String(D?.name??"tool"),detail:""}),U=(D)=>M({at:new Date().toISOString(),phase:"completed",tool:D?.is_error?"tool error":"tool result",detail:""}),S=(D)=>M({at:new Date().toISOString(),phase:D?.phase??"info",tool:String(D?.tool??"subagent"),detail:""}),b=(D)=>{if(H)return;if(D.tool_name!=="AskUserQuestion"){try{$.sendPermissionResponse(D.request_id,"allow",{updatedInput:D.input??{}})}catch(d){F(d instanceof Error?d:Error(String(d)))}return}let C;try{C=EM(D)}catch(d){F(d instanceof Error?d:Error(String(d)));return}if(W.some((d)=>d.request.requestId===C.requestId))return;W.push({request:C,originalInput:D.input??{}});try{if(W.length===1)J.onNeedsInput?.(C)}catch(d){F(d instanceof Error?d:Error(String(d)))}},v=(D)=>{if(H)return;try{$.sendHookResponse(String(D.request_id),{})}catch(C){F(C instanceof Error?C:Error(String(C)))}},y=(D)=>{let C=q(D?.session_id??$.sessionId);if(C)F(C)},g=(D)=>{V=D instanceof Error?D:Error(String(D))},x=(D)=>{if(H)return;try{J.onCodexAccount?.(D.accountId)}catch(C){F(C instanceof Error?C:Error(String(C)))}if(D.diagnostics.length)M({at:new Date().toISOString(),phase:"info",tool:"账号 MISS",detail:D.diagnostics.join(";")})},h=(D)=>{M({at:new Date().toISOString(),phase:"info",tool:D.reason==="quota"?"Codex 额度换号":"Codex 容量重试",detail:D.phase==="waiting"?`${D.message} · ${D.delayMs/1000}s 后重试 #${D.attempt}`:`正在重试 #${D.attempt}`})},p=(D)=>{let C=D?.is_error?Error(String(D.error??D.subtype??$.lastResult.subtype??"delegated agent failed")):void 0;F(C,D)},l=(D)=>{if(H)return;let C=`code=${D?.code??"null"} signal=${D?.signal??"null"}`;F(V??Error(`delegated agent exited before result (${C})`))};$.on("assistant_text",T),$.on("tool_use",A),$.on("tool_result",U),$.on("subagent_step",S),$.on("can_use_tool",b),$.on("hook_callback",v),$.on("init",y),$.on("error",g),$.on("turn_retry",h),$.on("codex_account_changed",x),$.on("result",p),$.on("exit",l);try{$.sendInitialize(),$.sendUserText(Z)}catch(D){F(D instanceof Error?D:Error(String(D)))}return{done:j,isAlive:()=>$.isAlive(),pendingInput:()=>W[0]?.request??null,answer(D,C){let d=W[0];if(!d)throw Error("delegated agent is not waiting for input");if(d.request.requestId!==D)throw Error(`delegated agent input request mismatch: expected ${d.request.requestId}`);if($.sendPermissionResponse(D,"allow",{updatedInput:{...d.originalInput,answers:C}}),W.shift(),W[0])J.onNeedsInput?.(W[0].request)},async cancel(D="delegated agent cancelled"){let C=H;if(await F(Error(D)),await j.catch(()=>{}),C){if($.isAlive())await $.kill(3000);z=null,P()}if(z)throw z}}}function EM($){let Z=$.input??{},Y=(Array.isArray(Z.questions)?Z.questions:[Z]).map((Q,V)=>xM(Q,V));if(Y.length===0)throw Error("delegated agent input request contains no questions");return{requestId:String($.request_id),...$.tool_use_id?{toolUseId:$.tool_use_id}:{},questions:Y}}function xM($,Z){let J=$&&typeof $==="object"?$:{question:$},Y=String(J.question??J.prompt??J.title??"").trim();if(!Y)throw Error(`delegated agent input question ${Z+1} is empty`);let Q=String(J.id??Y),V=Array.isArray(J.options)?J.options.map((H)=>{if(typeof H==="string")return{label:H};let X=H&&typeof H==="object"?H:{};return{label:String(X.label??X.value??""),...X.description?{description:String(X.description)}:{}}}).filter((H)=>H.label):[];return{id:Q,...J.header?{header:String(J.header)}:{},question:Y,options:V}}function SM($,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 E9;var GG=R(()=>{y3();L4();V0();SJ();E9=class E9 extends Error{output;sessionId;constructor($,Z,J){super($.message,{cause:$});this.output=Z;this.sessionId=J;this.name="AgentWorkerFailure"}}});import{createHash as bM,randomBytes as CM,randomUUID as kM}from"node:crypto";import{existsSync as yM,readdirSync as wM,readFileSync as MG}from"node:fs";import{join as t6}from"node:path";class kJ{deps;presentation;runs=new Map;capabilities=new Map;activeTurns=0;activeTurnsBySource=new Map;slotWaiters=[];cancellationEpochBySession=new Map;startingWorkers=0;startingRunsBySession=new Map;startingNativeSessions=new Set;constructor($=vM){this.deps=$;this.presentation=new EJ($),this.loadDurableRuns()}rootPrincipal($){return{kind:"session",session:$,depth:-1}}principalForCapability($){return this.capabilities.get($)??null}async startRun($,Z){if($.kind!=="session")throw Error(BG);if(Q4(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{run:Y,worker:Q}=this.requireSessionRun($,Z.sessionId,Z.identityIds[0]);return this.followUp($,Y.snapshot.runId,{identityId:Q.identityId,description:Z.description,prompt:Z.prompt,effort:Z.effort})}let J=this.reserveCapacity($,Z.identityIds.length);try{return await this.createRun($.session,Z,{cancellationEpoch:this.currentCancellationEpoch($.session)})}finally{J()}}async followUp($,Z,J){if($.kind!=="session")throw Error(BG);Q4(J.description);let Y=this.requireMutableDescendant($,Z);if(!V4(Y.snapshot.status))throw Error("agent follow-up requires a terminal source run");let Q=PG(Y.snapshot,J.identityId);if(Y.handles.get(Q.identityId)?.isAlive?.())throw Error("Agent process has not stopped; cannot start follow-up yet");if(!Q.sessionId)throw Error(`${Q.identityName} has no resumable native session id`);let V=J.effort??Q.effort,H=this.reserveCapacity($,1),X;try{return X=this.reserveNativeSession(Q),await this.createRun($.session,{identityIds:[Q.identityId],description:J.description,prompt:J.prompt,effort:V},{parentRunId:Y.snapshot.runId,parentKind:"follow_up",cancellationEpoch:this.currentCancellationEpoch($.session),resumeWorker:Q})}finally{X?.(),H()}}async answer($,Z,J){let Y=this.requireMutableDescendant($,Z),Q=PG(Y.snapshot,J.identityId);if(Q.status!=="needs_input"||!Q.pendingInput)throw Error(`${Q.identityName} is not waiting for input`);if(Q.pendingInput.requestId!==J.requestId)throw Error(`input request mismatch: expected ${Q.pendingInput.requestId}`);let V=Y.handles.get(Q.identityId);if(!V)throw Error("waiting agent process is no longer alive; start a follow-up run");V.answer(J.requestId,J.answers);let H=V.pendingInput();if(Q.status=H?"needs_input":"running",H)Q.pendingInput=H;else delete Q.pendingInput;return delete Q.queuedReason,this.refreshNonterminalStatus(Y),this.persist(Y),await this.updateWorkerCard(Y,Q),S9(Y.snapshot)}getRun($,Z){return S9(this.requireAccessibleRun($,Z).snapshot)}async cancelRun($,Z,J="agent run cancelled"){let Y=this.requireMutableDescendant($,Z);if(!this.treeHasActiveRun(Y))return!1;return await this.cancelTree(Y,J),!0}async cancelSessionRuns($,Z,J){this.bumpCancellationEpoch($,Z);let Y=[...this.runs.values()].filter((V)=>V.snapshot.sessionName===$&&V.snapshot.chatId===Z&&!V.snapshot.parentRunId&&this.treeHasActiveRun(V)),Q=await Promise.allSettled(Y.map((V)=>this.cancelTree(V,J)));CJ(Q)}async shutdown($){let Z=new Set([...this.runs.values()].map((H)=>`${H.snapshot.sessionName}\x00${H.snapshot.chatId}`));for(let H of Z){let[X,z]=H.split("\x00");this.bumpCancellationEpoch(X,z)}let J=[...this.runs.values()].filter((H)=>!H.snapshot.parentRunId&&this.treeHasActiveRun(H)),Y=await Promise.allSettled(J.map((H)=>this.cancelTree(H,$))),Q=[...this.runs.values()].flatMap((H)=>[...H.handles.values()]),V=Y.some((H)=>H.status==="rejected")?[]:await Promise.allSettled(Q.map((H)=>H.cancel($)));CJ([...Y,...V]);for(let H of new Set([...this.runs.values()].map((X)=>X.snapshot.chatId)))await this.presentation.closeChat(H)}async createRun($,Z,J){this.pruneRuns(J.parentRunId);let Y;if(J.parentRunId){if(Y=this.runs.get(J.parentRunId),!Y)throw Error(`parent agent run not found: ${J.parentRunId}`);this.assertSameSession(Y,$)}let Q=$.codexAccountId(),V=this.deps.getCatalog(Q),H=Z.identityIds.map((_)=>{let j=V.identities.find((P)=>P.id===_);if(!j)throw Error(`agent identity not found: ${_}`);if(j.status!=="ready")throw Error(`${j.displayName}: ${j.reason??j.status}`);let q=J.resumeWorker;if(q&&(j.id!==q.identityId||j.provider!==q.provider||j.tokenSourceId!==q.tokenSourceId||j.model!==q.model))throw Error("agent session identity changed; cannot resume with a different provider, source or model");return j}),X=H.map((_)=>fM(_,hM(_,Z.effort),J.resumeWorker?.sessionId)),z=`agent_${kM()}`,W={runId:z,codexAccountId:Q,sessionName:$.sessionName,chatId:$.chatId,workDir:$.workDir,prompt:Z.prompt,description:Q4(Z.description),...J.parentRunId?{parentRunId:J.parentRunId}:{},...J.parentKind?{parentKind:J.parentKind}:{},depth:0,status:"queued",workers:X,createdAt:new Date().toISOString()},G={snapshot:W,session:$,handles:new Map,slotOwners:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,cancelled:!1,finalizing:!1,finalized:!1,persistedArtifacts:new Set};try{await this.presentation.add(W)}catch(_){if(this.runs.set(z,G),J.parentRunId)Y?.children.add(z);let j=`Agent 卡片初始化失败,Agent 未启动: ${f0(_)}`;for(let q of X)q.status="failed",q.error=j;throw await this.finalizeRun(G,"failed",j),await this.deps.sendTextRaw($.chatId,`❌ ${j}`),_}if(this.runs.set(z,G),J.parentRunId)Y?.children.add(z);if(this.currentCancellationEpoch($)!==J.cancellationEpoch){G.cancelled=!0;let _="任务已在启动前取消";for(let j of G.snapshot.workers)j.status="cancelled",j.error=_,j.finishedAt=new Date().toISOString();return this.persist(G),await Promise.all(G.snapshot.workers.map((j)=>this.updateWorkerCard(G,j))),await this.finalizeRun(G,"cancelled",_),S9(G.snapshot)}this.persist(G);for(let _ of H){let j=J.resumeWorker?.sessionId;this.executeWorker(G,_,Z.prompt,j).catch((q)=>{K(`agent: run=${z} worker=${_.id} crashed: ${f0(q)}`)})}return S9(W)}async executeWorker($,Z,J,Y){let Q=$.snapshot.workers.find((H)=>H.identityId===Z.id);if(await this.acquireSlot(Z,(H)=>{Q.queuedReason=H,this.persist($),this.updateWorkerCard($,Q)}),$.slotOwners.set(Z.id,Z.tokenSourceId),$.cancelled){this.releaseWorkerSlot($,Z.id);return}let V="";try{if(V=CM(32).toString("base64url"),this.capabilities.set(V,{kind:"worker",session:$.session,runId:$.snapshot.runId,identityId:Z.id,depth:$.snapshot.depth}),$.capabilityByIdentity.set(Z.id,V),Q.status="running",Q.startedAt=new Date().toISOString(),delete Q.queuedReason,this.refreshNonterminalStatus($),this.persist($),await this.updateWorkerCard($,Q),$.cancelled)return;let H=this.deps.startWorker({identity:Z,codexAccountId:$.snapshot.codexAccountId,effort:Q.effort,workDir:$.snapshot.workDir,prompt:J,resumeSessionId:Y,developerInstructions:$.session.delegatedAgentDeveloperInstructions(Z.provider),profile:mM(b2($.session.worktreeProjectName())),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:F1},hostEnv:{LODESTAR_AGENT_URL:N8(f.notify.bind,f.notify.port),LODESTAR_AGENT_CAPABILITY:V,LODESTAR_AGENT_SESSION:$.snapshot.sessionName},callbacks:{onNeedsInput:(z)=>{if($.cancelled)return;Q.status="needs_input",Q.pendingInput=z,this.refreshNonterminalStatus($),this.persist($),this.updateWorkerCard($,Q)},onProgress:(z)=>this.recordStep($,Q,z),onCodexAccount:(z)=>{if($.cancelled)return;Q.codexAccountId=z,this.persist($)},onSession:(z)=>{if(Q.sessionId===z)return;Q.sessionId=z,this.persist($)}}});$.handles.set(Z.id,H);let X=await H.done;if($.cancelled)return;this.clearProgressTimer($,Z.id),Q.status="completed",Q.output=X.output,Q.outputTruncated=X.outputTruncated,Q.sessionId=X.sessionId,Q.checkpointId=X.checkpointId,Q.durationMs=X.durationMs,Q.usage=X.usage,Q.finishedAt=new Date().toISOString(),delete Q.pendingInput,this.persist($),await this.updateWorkerCard($,Q)}catch(H){if(H instanceof E9){if(Q.output=H.output,Q.outputTruncated=!1,H.sessionId)Q.sessionId=H.sessionId;this.persist($)}if(!$.cancelled){if(this.clearProgressTimer($,Z.id),Q.status="failed",Q.error=f0(H),Q.finishedAt=new Date().toISOString(),Q.startedAt)Q.durationMs=Date.now()-Date.parse(Q.startedAt);delete Q.pendingInput,this.persist($),await this.updateWorkerCard($,Q)}}finally{if(!$.handles.get(Z.id)?.isAlive?.())$.handles.delete(Z.id),this.releaseWorkerSlot($,Z.id);if(V)this.capabilities.delete(V);$.capabilityByIdentity.delete(Z.id),this.recomputeRun($)}}recordStep($,Z,J){if($.cancelled||$.finalizing||$.finalized||x9(Z.status))return;if(Z.steps.push(J),Z.steps.length>jG)Z.steps.splice(0,Z.steps.length-jG);if($.progressTimers.has(Z.identityId))return;let Y=setTimeout(()=>{$.progressTimers.delete(Z.identityId),this.updateWorkerCard($,Z)},250);$.progressTimers.set(Z.identityId,Y)}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((Y)=>Y.status==="needs_input"||Y.status==="running"||Y.status==="queued")){this.refreshNonterminalStatus($),this.persist($);return}let J=Z.some((Y)=>Y.status==="failed")?"failed":"completed";this.finalizeRun($,J,J==="failed"?"一个或多个 Agent 失败":void 0).catch((Y)=>{$.finalizing=!1,$.finalized=!1,$.snapshot.status="failed",$.snapshot.error=`Agent terminal persistence failed: ${f0(Y)}`,K(`agent: terminal finalization failed run=${$.snapshot.runId}: ${f0(Y)}`),this.deps.sendTextRaw($.snapshot.chatId,`❌ agent ${$.snapshot.runId} 收尾失败: ${f0(Y)}`).catch((Q)=>K(`agent: terminal failure delivery failed: ${f0(Q)}`))})}async cancelTree($,Z){let J=!V4($.snapshot.status)&&!$.cancelled||$.handles.size>0,Y=[];if(J){$.cancelled=!0;for(let V of[...$.progressTimers.keys()])this.clearProgressTimer($,V);for(let V of $.capabilityByIdentity.values())this.capabilities.delete(V);$.capabilityByIdentity.clear()}while(!0){let V=[...$.children].map((X)=>this.runs.get(X)).filter((X)=>!!X&&this.treeHasActiveRun(X));if(V.length===0)break;let H=await Promise.allSettled(V.map((X)=>this.cancelTree(X,Z)));if(Y.push(...H),H.some((X)=>X.status==="rejected"))break}if(!J){CJ(Y);return}if(Y.push(...await Promise.allSettled([...$.handles].map(async([V,H])=>{if(await H.cancel(Z),H.isAlive?.())throw Error(`${V}: Agent process is still alive after cancellation`);$.handles.delete(V),this.releaseWorkerSlot($,V)}))),Y.some((V)=>V.status==="rejected")){let V=UG(Y);throw $.snapshot.status="failed",$.snapshot.error=V.message,this.persist($),await this.deps.sendTextRaw($.snapshot.chatId,`❌ Agent 取消未完成: ${V.message}`).catch((H)=>K(`agent: cancellation failure notice failed: ${f0(H)}`)),V}let Q=[];for(let V of $.snapshot.workers)if(!x9(V.status))V.status="cancelled",V.error=Z,V.finishedAt=new Date().toISOString(),delete V.pendingInput,Q.push(V);await Promise.all(Q.map((V)=>this.updateWorkerCard($,V))),await this.finalizeRun($,"cancelled",Z)}async finalizeRun($,Z,J){if($.finalized||$.finalizing)return;$.finalizing=!0;for(let Y of[...$.progressTimers.keys()])this.clearProgressTimer($,Y);if($.snapshot.status=Z,$.snapshot.finishedAt=new Date().toISOString(),J)$.snapshot.error=J;try{await this.presentation.update($.snapshot,!0)}catch(Y){this.recordPresentationError($,`agent card finalization failed: ${f0(Y)}`)}if($.finalizing=!1,this.persist($),$.finalized=!0,$.snapshot.presentationErrors?.length)await this.deps.sendTextRaw($.snapshot.chatId,`⚠️ agent ${$.snapshot.runId} 结果已保存,但卡片有 ${$.snapshot.presentationErrors.length} 个呈现错误。`).catch((Y)=>K(`agent: warning delivery failed run=${$.snapshot.runId}: ${f0(Y)}`))}async updateWorkerCard($,Z){if($.finalized)return;let J=$.snapshot.cardMessageId;try{await this.presentation.update($.snapshot)}catch(Y){this.recordPresentationError($,`agent worker card update failed (${Z.identityName}): ${f0(Y)}`)}finally{if($.snapshot.cardMessageId!==J)this.persist($)}}recordPresentationError($,Z){let J=$.snapshot.presentationErrors??[];if(!J.includes(Z))J.push(Z);$.snapshot.presentationErrors=J,K(`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 Y=bM("sha256").update(J.identityId).digest("hex").slice(0,16);J.outputArtifact=`${$.snapshot.runId}.${Y}.output.txt`}this.persistTextArtifact($,J.outputArtifact,J.output)}let Z=S9($.snapshot);Z.prompt="";for(let J of Z.workers)J.output="";this.deps.writeArtifact(t6(P1,`${$.snapshot.runId}.json`),Z)}persistTextArtifact($,Z,J){if($.persistedArtifacts.has(Z))return;AG(Z),this.deps.writeTextArtifact(t6(P1,Z),J),$.persistedArtifacts.add(Z)}requireAccessibleRun($,Z){let J=this.runs.get(Z);if(!J||!this.canAccess($,J))throw Error(`agent run not found: ${Z}`);if(this.assertSameSession(J,$.session),!J.session)J.session=$.session;return J}requireSessionRun($,Z,J){let Y=[...this.runs.values()].flatMap((H)=>{if(!this.canAccess($,H)||H.snapshot.workDir!==$.session.workDir)return[];return H.snapshot.workers.filter((X)=>X.sessionId===Z&&(!J||X.identityId===J)).map((X)=>({run:H,worker:X}))});if(!Y.length)throw Error(`agent session not found in this Session${J?" for the requested identity":""}: ${Z}`);if(new Set(Y.map(({worker:H})=>H.identityId)).size>1)throw Error("agent session id matches multiple identities; specify identity_id");let Q=new Set(Y.map(({run:H})=>H.snapshot.parentRunId)),V=Y.filter(({run:H})=>!Q.has(H.snapshot.runId)).sort((H,X)=>Date.parse(X.run.snapshot.createdAt)-Date.parse(H.run.snapshot.createdAt))[0];if(!V)throw Error(`agent session history has no latest run: ${Z}`);return V}reserveNativeSession($){let Z=JSON.stringify([$.provider,$.sessionId]),J=[...this.runs.values()].some((Y)=>Y.snapshot.workers.some((Q)=>{if(Q.provider!==$.provider||Q.sessionId!==$.sessionId)return!1;let V=Y.handles.get(Q.identityId);return!x9(Q.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){if(Z.snapshot.sessionName!==$.session.sessionName||Z.snapshot.chatId!==$.session.chatId)return!1;if($.kind==="session")return!0;let J=Z;while(J){if(J.snapshot.runId===$.runId)return!0;J=J.snapshot.parentRunId?this.runs.get(J.snapshot.parentRunId):void 0}return!1}assertSameSession($,Z){if($.snapshot.sessionName!==Z.sessionName||$.snapshot.chatId!==Z.chatId||$.snapshot.workDir!==Z.workDir)throw Error("agent run belongs to a different Session")}treeHasActiveRun($){if($.handles.size>0)return!0;if(!V4($.snapshot.status))return!0;for(let Z of $.children){let J=this.runs.get(Z);if(J&&this.treeHasActiveRun(J))return!0}return!1}reserveCapacity($,Z){let J=this.sessionKey($.session.sessionName,$.session.chatId),Y=[...this.runs.values()].filter((X)=>this.sessionKey(X.snapshot.sessionName,X.snapshot.chatId)===J&&(!V4(X.snapshot.status)||X.handles.size>0)).length,Q=this.startingRunsBySession.get(J)??0;if(Y+Q>=LG)throw Error(`Session has reached ${LG} active Agent runs`);if([...this.runs.values()].reduce((X,z)=>X+z.snapshot.workers.filter((W)=>!x9(W.status)||z.handles.get(W.identityId)?.isAlive?.()).length,0)+this.startingWorkers+Z>qG)throw Error(`global Agent worker limit ${qG} would be exceeded`);this.startingWorkers+=Z,this.startingRunsBySession.set(J,Q+1);let H=!1;return()=>{if(H)return;H=!0,this.startingWorkers=Math.max(0,this.startingWorkers-Z),DG(this.startingRunsBySession,J)}}sessionKey($,Z){return`${$}\x00${Z}`}currentCancellationEpoch($){return this.cancellationEpochBySession.get(this.sessionKey($.sessionName,$.chatId))??0}bumpCancellationEpoch($,Z){let J=this.sessionKey($,Z);this.cancellationEpochBySession.set(J,(this.cancellationEpochBySession.get(J)??0)+1)}tryAcquireSlot($){let Z=KG.get($),J=this.activeTurnsBySource.get($)??0;if(this.activeTurns>=bJ||Z!==void 0&&J>=Z)return!1;return this.activeTurns++,this.activeTurnsBySource.set($,J+1),!0}acquireSlot($,Z){if(this.tryAcquireSlot($.tokenSourceId))return Promise.resolve();let J=KG.get($.tokenSourceId);return Z(J!==void 0?`等待 ${$.tokenSourceDisplay} 执行名额(同一来源最多同时运行 ${J} 个 Agent)`:`等待执行名额(最多同时运行 ${bJ} 个 Agent)`),new Promise((Y)=>this.slotWaiters.push({tokenSourceId:$.tokenSourceId,resolve:Y}))}releaseSlot($){this.activeTurns--,DG(this.activeTurnsBySource,$);for(let Z=0;Z<this.slotWaiters.length&&this.activeTurns<bJ;){let J=this.slotWaiters[Z];if(!this.tryAcquireSlot(J.tokenSourceId)){Z++;continue}this.slotWaiters.splice(Z,1),J.resolve()}}releaseWorkerSlot($,Z){let J=$.slotOwners.get(Z);if(J===void 0)return;$.slotOwners.delete(Z),this.releaseSlot(J)}loadDurableRuns(){for(let $ of this.deps.loadArtifacts()){if(!V4($.status)){$.status="failed",$.error="daemon restarted before this Agent run reached a terminal state",$.finishedAt=new Date().toISOString();for(let J of $.workers)if(!x9(J.status))J.status="failed",J.error=$.error,J.finishedAt=$.finishedAt,delete J.pendingInput}let Z={snapshot:$,session:null,handles:new Map,slotOwners:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,cancelled:$.status==="cancelled",finalizing:!1,finalized:!0,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.pruneRuns()}pruneRuns($){if(this.runs.size<=_G)return;let Z=[...this.runs.values()].filter((J)=>J.snapshot.runId!==$&&V4(J.snapshot.status)&&J.handles.size===0&&J.slotOwners.size===0&&J.children.size===0).sort((J,Y)=>Date.parse(J.snapshot.finishedAt??J.snapshot.createdAt)-Date.parse(Y.snapshot.finishedAt??Y.snapshot.createdAt));for(let J of Z){if(this.runs.size<=_G)break;if(this.runs.delete(J.snapshot.runId),J.snapshot.parentRunId)this.runs.get(J.snapshot.parentRunId)?.children.delete(J.snapshot.runId)}}}function fM($,Z,J){return{identityId:$.id,identityName:$.displayName,tokenSourceId:$.tokenSourceId,provider:$.provider,model:$.model,effort:Z,status:"queued",output:"",...J?{sessionId:J}:{},steps:[]}}function hM($,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 PG($,Z){if(Z){let J=$.workers.find((Y)=>Y.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 V4($){return $==="completed"||$==="failed"||$==="cancelled"}function x9($){return $==="completed"||$==="failed"||$==="cancelled"}function S9($){return JSON.parse(JSON.stringify($))}function IM(){if(!yM(P1))return[];let $=[];for(let Z of wM(P1).filter((J)=>J.endsWith(".json")).sort()){let J=t6(P1,Z),Y;try{Y=JSON.parse(MG(J,"utf8"))}catch(Q){throw Error(`agent run artifact is unreadable (${J}): ${f0(Q)}`)}if(!gM(Y))throw Error(`agent run artifact is invalid: ${J}`);pM(Y,J),$.push(Y)}return $}function gM($){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"&&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 UG($){let Z=$.flatMap((J)=>J.status==="rejected"?[J.reason]:[]);return AggregateError(Z,`Agent cancellation failed: ${Z.map(f0).join("; ")}`)}function CJ($){if($.some((Z)=>Z.status==="rejected"))throw UG($)}function f0($){return $ instanceof Error?$.message:String($)}function mM($){return $?{...$,tools:void 0,strictMcp:!1,loadProjectMcp:!0}:{strictMcp:!1,loadProjectMcp:!0}}function pM($,Z){if($.promptArtifact)$.prompt=FG($.promptArtifact,`prompt for ${Z}`);for(let J of $.workers)if(J.outputArtifact)J.output=FG(J.outputArtifact,`output for ${Z}`)}function FG($,Z){AG($);try{return MG(t6(P1,$),"utf8")}catch(J){throw Error(`${Z} is unreadable (${$}): ${f0(J)}`)}}function AG($){if(!/^[A-Za-z0-9._-]+$/.test($))throw Error(`invalid Agent artifact name: ${$}`)}function DG($,Z){let J=($.get(Z)??0)-1;if(J>0)$.set(Z,J);else $.delete(Z)}var bJ=8,KG,BG="Delegated Agents cannot delegate again; ask the main Agent to assign additional work.",_G=512,jG=50,LG=64,qG=128,vM;var OG=R(()=>{v$();ZG();t();y0();v6();GG();Q0();T0();I();KG=new Map([["openrouter",2]]),vM={getCatalog:n1,startWorker:WG,sendCard:c,getChatTailMessageId:L5,sendTextRaw:w,convertMessageToCard:Z$,recordCardCreated:d0,getElementCount:t4,addElementResult:y2,replaceElementResult:vV,deleteElementChecked:fV,cancelSummary:A0,patchSettingsChecked:P0,dispose:v0,writeArtifact:s,writeTextArtifact:I0,loadArtifacts:IM}});async function TG($,Z,J,Y){if(J.pathname!=="/agents"&&!J.pathname.startsWith("/agents/"))return!1;let Q=(G,B)=>{return Z.statusCode=G,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(B)),!0},V=lM($.headers.authorization);if(!V)return Q(401,{error:"missing bearer capability"});let H=cM(Y,V);if(!H)return Q(403,{error:"invalid or stale agent capability"});if($.method==="GET"&&J.pathname==="/agents/identities")return await U2(),Q(200,dM(n1(H.session.codexAccountId())));if($.method==="POST"&&J.pathname==="/agents/runs")try{let G=await Y.service.startRun(H,JG(await yJ($)));return Q(202,e6(G))}catch(G){return Q(409,{error:NG(G)})}let X=J.pathname.match(/^\/agents\/runs\/([^/]+)(?:\/(follow-up|answer))?$/);if(!X)return Q(405,{error:"unsupported agent endpoint"});let z=uM(X[1]);if(!z)return Q(400,{error:"invalid agent run id encoding"});let W=X[2];try{if(!W&&$.method==="GET")return Q(200,e6(Y.service.getRun(H,z)));if(!W&&$.method==="DELETE"){let G=await Y.service.cancelRun(H,z,"cancelled by agent client");return Q(G?200:409,G?{ok:!0,run_id:z}:{error:"agent run is already terminal",run_id:z})}if(W==="follow-up"&&$.method==="POST"){let G=await Y.service.followUp(H,z,YG(await yJ($)));return Q(202,e6(G))}if(W==="answer"&&$.method==="POST"){let G=await Y.service.answer(H,z,QG(await yJ($)));return Q(200,e6(G))}}catch(G){return Q(409,{error:NG(G)})}return Q(405,{error:"unsupported agent endpoint"})}function cM($,Z){let J=$.authorizeSession(Z);if(J)return $.service.rootPrincipal(J);return $.service.principalForCapability(Z)}function uM($){try{return decodeURIComponent($)}catch{return null}}function lM($){return $?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()??""}async function yJ($){let Z="";for await(let J of $)if(Z+=J.toString(),Buffer.byteLength(Z)>RG)throw Error(`request body exceeds ${RG} bytes`);try{return JSON.parse(Z||"{}")}catch{throw Error("bad json")}}function dM($){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 e6($){return{run_id:$.runId,session_name:$.sessionName,prompt:$.prompt,description:$.description,parent_run_id:$.parentRunId,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 NG($){return $ instanceof Error?$.message:String($)}var RG=4194304;var EG=R(()=>{v6();V0()});function xG($){J4({name:rz,body:$W()},$)}var SG=R(()=>{s6();p6()});import{chmodSync as iM,existsSync as wJ,readFileSync as kG,realpathSync as nM,unlinkSync as aM}from"node:fs";import{homedir as oM}from"node:os";import{basename as rM,dirname as sM,join as j1,resolve as tM}from"node:path";function eM($={}){let Z=nM(tM($.daemonEntry??process.argv[1]??"")),J=$.runtime??process.execPath,Y=$.exists??wJ,Q=sM(Z),V=j1(Q,"src","agent-cli.ts"),H=j1(Q,"lodestar-agent.js"),X=j1(Q,"dist","lodestar-agent.js"),W=/^bun(?:\.exe)?$/i.test(rM(J))?[V,H,X]:[H,X],G=W.find(Y);if(!G)throw Error(`lodestar-agent entry not found beside daemon: ${W.join(", ")}`);return{runtime:J,entry:G}}function yG($={}){let Z=$.platform??process.platform,J=$.env??process.env,Y=$.targetDir??ZU(Z,$.homeDir??oM(),$.localAppData??process.env.LOCALAPPDATA),Q=$.launch??eM(),V=j1(Y,Z==="win32"?"lodestar-agent.cmd":"lodestar-agent"),H=Z==="win32"?`@"${CG(Q.runtime)}" "${CG(Q.entry)}" %*\r
|
|
542
|
+
`),allowDelegation:!1,profile:$.profile,managedSkillPluginPath:$.managedSkillPluginPath,hostEnv:{...$.hostEnv,LODESTAR_AGENT_ROLE:"worker"},serviceName:"lodestar-agent"});return EM(Y,$.prompt,$.callbacks)}function EM($,Z,J={},Y=SY){let Q=[],V=null,H=!1,X=null,z=null,W=[],G,B,_=Date.now(),j=new Promise((F,C)=>{G=F,B=C}),q=(F)=>{if(!F)return null;try{return Y($.provider,F),J.onSession?.(F),null}catch(C){return C instanceof Error?C:Error(String(C))}},P=()=>{if($.off("assistant_text",T),$.off("tool_use",A),$.off("tool_result",U),$.off("subagent_step",S),$.off("can_use_tool",b),$.off("hook_callback",v),$.off("init",y),!$.isAlive())$.off("error",g);$.off("turn_retry",h),$.off("codex_account_changed",x),$.off("result",p),$.off("exit",l)},D=(F,C)=>{if(X)return X;return H=!0,W.length=0,X=Promise.resolve().then(async()=>{let d=q($.sessionId);try{await $.kill(3000)}catch(q1){z=q1 instanceof Error?q1:Error(String(q1))}P();let o=[F,d,z].filter((q1)=>!!q1),K0=o.length>1?AggregateError(o,o.map((q1)=>q1.message).join("; ")):o[0];if(K0){B(new E9(K0,Q.join("").trim(),$.sessionId));return}let W4=$.sessionId;if(!W4){B(new E9(Error("delegated agent completed without a native session id"),Q.join("").trim(),null));return}let S9=Q.join("").trim(),Z2=bM(C?.checkpoint,$);G({output:S9,outputTruncated:!1,sessionId:W4,...Z2?{checkpointId:Z2}:{},durationMs:Date.now()-_,usage:$.lastUsage?{...$.lastUsage}:null})}),X},T=(F)=>{if(H||F?.parentToolUseId||typeof F?.text!=="string")return;Q.push(F.text)},M=(F)=>{if(H)return;try{J.onProgress?.(F)}catch(C){D(C instanceof Error?C:Error(String(C)))}},A=(F)=>M({at:new Date().toISOString(),phase:"started",tool:String(F?.name??"tool"),detail:""}),U=(F)=>M({at:new Date().toISOString(),phase:"completed",tool:F?.is_error?"tool error":"tool result",detail:""}),S=(F)=>M({at:new Date().toISOString(),phase:F?.phase??"info",tool:String(F?.tool??"subagent"),detail:""}),b=(F)=>{if(H)return;if(F.tool_name!=="AskUserQuestion"){try{$.sendPermissionResponse(F.request_id,"allow",{updatedInput:F.input??{}})}catch(d){D(d instanceof Error?d:Error(String(d)))}return}let C;try{C=xM(F)}catch(d){D(d instanceof Error?d:Error(String(d)));return}if(W.some((d)=>d.request.requestId===C.requestId))return;W.push({request:C,originalInput:F.input??{}});try{if(W.length===1)J.onNeedsInput?.(C)}catch(d){D(d instanceof Error?d:Error(String(d)))}},v=(F)=>{if(H)return;try{$.sendHookResponse(String(F.request_id),{})}catch(C){D(C instanceof Error?C:Error(String(C)))}},y=(F)=>{let C=q(F?.session_id??$.sessionId);if(C)D(C)},g=(F)=>{V=F instanceof Error?F:Error(String(F))},x=(F)=>{if(H)return;try{J.onCodexAccount?.(F.accountId)}catch(C){D(C instanceof Error?C:Error(String(C)))}if(F.diagnostics.length)M({at:new Date().toISOString(),phase:"info",tool:"账号 MISS",detail:F.diagnostics.join(";")})},h=(F)=>{M({at:new Date().toISOString(),phase:"info",tool:F.reason==="quota"?"Codex 额度换号":"Codex 容量重试",detail:F.phase==="waiting"?`${F.message} · ${F.delayMs/1000}s 后重试 #${F.attempt}`:`正在重试 #${F.attempt}`})},p=(F)=>{let C=F?.is_error?Error(String(F.error??F.subtype??$.lastResult.subtype??"delegated agent failed")):void 0;D(C,F)},l=(F)=>{if(H)return;let C=`code=${F?.code??"null"} signal=${F?.signal??"null"}`;D(V??Error(`delegated agent exited before result (${C})`))};$.on("assistant_text",T),$.on("tool_use",A),$.on("tool_result",U),$.on("subagent_step",S),$.on("can_use_tool",b),$.on("hook_callback",v),$.on("init",y),$.on("error",g),$.on("turn_retry",h),$.on("codex_account_changed",x),$.on("result",p),$.on("exit",l);try{$.sendInitialize(),$.sendUserText(Z)}catch(F){D(F instanceof Error?F:Error(String(F)))}return{done:j,isAlive:()=>$.isAlive(),pendingInput:()=>W[0]?.request??null,answer(F,C){let d=W[0];if(!d)throw Error("delegated agent is not waiting for input");if(d.request.requestId!==F)throw Error(`delegated agent input request mismatch: expected ${d.request.requestId}`);if($.sendPermissionResponse(F,"allow",{updatedInput:{...d.originalInput,answers:C}}),W.shift(),W[0])J.onNeedsInput?.(W[0].request)},async cancel(F="delegated agent cancelled"){let C=H;if(await D(Error(F)),await j.catch(()=>{}),C){if($.isAlive())await $.kill(3000);z=null,P()}if(z)throw z}}}function xM($){let Z=$.input??{},Y=(Array.isArray(Z.questions)?Z.questions:[Z]).map((Q,V)=>SM(Q,V));if(Y.length===0)throw Error("delegated agent input request contains no questions");return{requestId:String($.request_id),...$.tool_use_id?{toolUseId:$.tool_use_id}:{},questions:Y}}function SM($,Z){let J=$&&typeof $==="object"?$:{question:$},Y=String(J.question??J.prompt??J.title??"").trim();if(!Y)throw Error(`delegated agent input question ${Z+1} is empty`);let Q=String(J.id??Y),V=Array.isArray(J.options)?J.options.map((H)=>{if(typeof H==="string")return{label:H};let X=H&&typeof H==="object"?H:{};return{label:String(X.label??X.value??""),...X.description?{description:String(X.description)}:{}}}).filter((H)=>H.label):[];return{id:Q,...J.header?{header:String(J.header)}:{},question:Y,options:V}}function bM($,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 E9;var WG=R(()=>{k3();L4();V0();xJ();E9=class E9 extends Error{output;sessionId;constructor($,Z,J){super($.message,{cause:$});this.output=Z;this.sessionId=J;this.name="AgentWorkerFailure"}}});import{createHash as CM,randomBytes as kM,randomUUID as yM}from"node:crypto";import{existsSync as wM,readdirSync as vM,readFileSync as FG}from"node:fs";import{join as s6}from"node:path";class CJ{deps;presentation;runs=new Map;capabilities=new Map;activeTurns=0;activeTurnsBySource=new Map;slotWaiters=[];cancellationEpochBySession=new Map;startingWorkers=0;startingRunsBySession=new Map;startingNativeSessions=new Set;constructor($=fM){this.deps=$;this.presentation=new TJ($),this.loadDurableRuns()}rootPrincipal($){return{kind:"session",session:$,depth:-1}}principalForCapability($){return this.capabilities.get($)??null}async startRun($,Z){if($.kind!=="session")throw Error(KG);if(Q4(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{run:Y,worker:Q}=this.requireSessionRun($,Z.sessionId,Z.identityIds[0]);return this.followUp($,Y.snapshot.runId,{identityId:Q.identityId,description:Z.description,prompt:Z.prompt,effort:Z.effort})}let J=this.reserveCapacity($,Z.identityIds.length);try{return await this.createRun($.session,Z,{cancellationEpoch:this.currentCancellationEpoch($.session)})}finally{J()}}async followUp($,Z,J){if($.kind!=="session")throw Error(KG);Q4(J.description);let Y=this.requireMutableDescendant($,Z);if(!V4(Y.snapshot.status))throw Error("agent follow-up requires a terminal source run");let Q=qG(Y.snapshot,J.identityId);if(Y.handles.get(Q.identityId)?.isAlive?.())throw Error("Agent process has not stopped; cannot start follow-up yet");if(!Q.sessionId)throw Error(`${Q.identityName} has no resumable native session id`);let V=J.effort??Q.effort,H=this.reserveCapacity($,1),X;try{return X=this.reserveNativeSession(Q),await this.createRun($.session,{identityIds:[Q.identityId],description:J.description,prompt:J.prompt,effort:V},{parentRunId:Y.snapshot.runId,parentKind:"follow_up",cancellationEpoch:this.currentCancellationEpoch($.session),resumeWorker:Q})}finally{X?.(),H()}}async answer($,Z,J){let Y=this.requireMutableDescendant($,Z),Q=qG(Y.snapshot,J.identityId);if(Q.status!=="needs_input"||!Q.pendingInput)throw Error(`${Q.identityName} is not waiting for input`);if(Q.pendingInput.requestId!==J.requestId)throw Error(`input request mismatch: expected ${Q.pendingInput.requestId}`);let V=Y.handles.get(Q.identityId);if(!V)throw Error("waiting agent process is no longer alive; start a follow-up run");V.answer(J.requestId,J.answers);let H=V.pendingInput();if(Q.status=H?"needs_input":"running",H)Q.pendingInput=H;else delete Q.pendingInput;return delete Q.queuedReason,this.refreshNonterminalStatus(Y),this.persist(Y),await this.updateWorkerCard(Y,Q),this.readSnapshot(Y)}getRun($,Z){return this.readSnapshot(this.requireAccessibleRun($,Z))}async cancelRun($,Z,J="agent run cancelled"){let Y=this.requireMutableDescendant($,Z);if(!this.treeHasActiveRun(Y))return!1;return await this.cancelTree(Y,J),!0}async cancelSessionRuns($,Z,J){this.bumpCancellationEpoch($,Z);let Y=[...this.runs.values()].filter((V)=>V.snapshot.sessionName===$&&V.snapshot.chatId===Z&&!V.snapshot.parentRunId&&this.treeHasActiveRun(V)),Q=await Promise.allSettled(Y.map((V)=>this.cancelTree(V,J)));bJ(Q)}async shutdown($){let Z=new Set([...this.runs.values()].map((H)=>`${H.snapshot.sessionName}\x00${H.snapshot.chatId}`));for(let H of Z){let[X,z]=H.split("\x00");this.bumpCancellationEpoch(X,z)}let J=[...this.runs.values()].filter((H)=>!H.snapshot.parentRunId&&this.treeHasActiveRun(H)),Y=await Promise.allSettled(J.map((H)=>this.cancelTree(H,$))),Q=[...this.runs.values()].flatMap((H)=>[...H.handles.values()]),V=Y.some((H)=>H.status==="rejected")?[]:await Promise.allSettled(Q.map((H)=>H.cancel($)));bJ([...Y,...V]);for(let H of new Set([...this.runs.values()].map((X)=>X.snapshot.chatId)))await this.presentation.closeChat(H)}async createRun($,Z,J){let Y;if(J.parentRunId){if(Y=this.runs.get(J.parentRunId),!Y)throw Error(`parent agent run not found: ${J.parentRunId}`);this.assertSameSession(Y,$)}let Q=$.codexAccountId(),V=this.deps.getCatalog(Q),H=Z.identityIds.map((_)=>{let j=V.identities.find((P)=>P.id===_);if(!j)throw Error(`agent identity not found: ${_}`);if(j.status!=="ready")throw Error(`${j.displayName}: ${j.reason??j.status}`);let q=J.resumeWorker;if(q&&(j.id!==q.identityId||j.provider!==q.provider||j.tokenSourceId!==q.tokenSourceId||j.model!==q.model))throw Error("agent session identity changed; cannot resume with a different provider, source or model");return j}),X=H.map((_)=>hM(_,IM(_,Z.effort),J.resumeWorker?.sessionId)),z=`agent_${yM()}`,W={runId:z,codexAccountId:Q,sessionName:$.sessionName,chatId:$.chatId,workDir:$.workDir,prompt:Z.prompt,description:Q4(Z.description),...J.parentRunId?{parentRunId:J.parentRunId}:{},...J.parentKind?{parentKind:J.parentKind}:{},depth:0,status:"queued",workers:X,createdAt:new Date().toISOString()},G={snapshot:W,session:$,handles:new Map,slotOwners:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,cancelled:!1,finalizing:!1,finalized:!1,persistedArtifacts:new Set,artifactsUnloaded:!1};try{await this.presentation.add(W)}catch(_){if(this.runs.set(z,G),J.parentRunId)Y?.children.add(z);let j=`Agent 卡片初始化失败,Agent 未启动: ${f0(_)}`;for(let q of X)q.status="failed",q.error=j;throw await this.finalizeRun(G,"failed",j),await this.deps.sendTextRaw($.chatId,`❌ ${j}`),_}if(this.runs.set(z,G),J.parentRunId)Y?.children.add(z);if(this.currentCancellationEpoch($)!==J.cancellationEpoch){G.cancelled=!0;let _="任务已在启动前取消";for(let j of G.snapshot.workers)j.status="cancelled",j.error=_,j.finishedAt=new Date().toISOString();return this.persist(G),await Promise.all(G.snapshot.workers.map((j)=>this.updateWorkerCard(G,j))),await this.finalizeRun(G,"cancelled",_),this.readSnapshot(G)}this.persist(G);for(let _ of H){let j=J.resumeWorker?.sessionId;this.executeWorker(G,_,Z.prompt,j).catch((q)=>{K(`agent: run=${z} worker=${_.id} crashed: ${f0(q)}`)})}return this.readSnapshot(G)}async executeWorker($,Z,J,Y){let Q=$.snapshot.workers.find((H)=>H.identityId===Z.id);if(await this.acquireSlot(Z,(H)=>{Q.queuedReason=H,this.persist($),this.updateWorkerCard($,Q)}),$.slotOwners.set(Z.id,Z.tokenSourceId),$.cancelled){this.releaseWorkerSlot($,Z.id);return}let V="";try{if(V=kM(32).toString("base64url"),this.capabilities.set(V,{kind:"worker",session:$.session,runId:$.snapshot.runId,identityId:Z.id,depth:$.snapshot.depth}),$.capabilityByIdentity.set(Z.id,V),Q.status="running",Q.startedAt=new Date().toISOString(),delete Q.queuedReason,this.refreshNonterminalStatus($),this.persist($),await this.updateWorkerCard($,Q),$.cancelled)return;let H=this.deps.startWorker({identity:Z,codexAccountId:$.snapshot.codexAccountId,effort:Q.effort,workDir:$.snapshot.workDir,prompt:J,resumeSessionId:Y,developerInstructions:$.session.delegatedAgentDeveloperInstructions(Z.provider),profile:pM(b2($.session.worktreeProjectName())),...process.env.LODESTAR_DISABLE_SKILL_SYNC==="1"?{}:{managedSkillPluginPath:D1},hostEnv:{LODESTAR_AGENT_URL:R8(f.notify.bind,f.notify.port),LODESTAR_AGENT_CAPABILITY:V,LODESTAR_AGENT_SESSION:$.snapshot.sessionName},callbacks:{onNeedsInput:(z)=>{if($.cancelled)return;Q.status="needs_input",Q.pendingInput=z,this.refreshNonterminalStatus($),this.persist($),this.updateWorkerCard($,Q)},onProgress:(z)=>this.recordStep($,Q,z),onCodexAccount:(z)=>{if($.cancelled)return;Q.codexAccountId=z,this.persist($)},onSession:(z)=>{if(Q.sessionId===z)return;Q.sessionId=z,this.persist($)}}});$.handles.set(Z.id,H);let X=await H.done;if($.cancelled)return;this.clearProgressTimer($,Z.id),Q.status="completed",Q.output=X.output,Q.outputTruncated=X.outputTruncated,Q.sessionId=X.sessionId,Q.checkpointId=X.checkpointId,Q.durationMs=X.durationMs,Q.usage=X.usage,Q.finishedAt=new Date().toISOString(),delete Q.pendingInput,this.persist($),await this.updateWorkerCard($,Q)}catch(H){if(H instanceof E9){if(Q.output=H.output,Q.outputTruncated=!1,H.sessionId)Q.sessionId=H.sessionId;this.persist($)}if(!$.cancelled){if(this.clearProgressTimer($,Z.id),Q.status="failed",Q.error=f0(H),Q.finishedAt=new Date().toISOString(),Q.startedAt)Q.durationMs=Date.now()-Date.parse(Q.startedAt);delete Q.pendingInput,this.persist($),await this.updateWorkerCard($,Q)}}finally{if(!$.handles.get(Z.id)?.isAlive?.())$.handles.delete(Z.id),this.releaseWorkerSlot($,Z.id);if(V)this.capabilities.delete(V);$.capabilityByIdentity.delete(Z.id),this.recomputeRun($)}}recordStep($,Z,J){if($.cancelled||$.finalizing||$.finalized||x9(Z.status))return;if(Z.steps.push(J),Z.steps.length>_G)Z.steps.splice(0,Z.steps.length-_G);if($.progressTimers.has(Z.identityId))return;let Y=setTimeout(()=>{$.progressTimers.delete(Z.identityId),this.updateWorkerCard($,Z)},250);$.progressTimers.set(Z.identityId,Y)}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((Y)=>Y.status==="needs_input"||Y.status==="running"||Y.status==="queued")){this.refreshNonterminalStatus($),this.persist($);return}let J=Z.some((Y)=>Y.status==="failed")?"failed":"completed";this.finalizeRun($,J,J==="failed"?"一个或多个 Agent 失败":void 0).catch((Y)=>{$.finalizing=!1,$.finalized=!1,$.snapshot.status="failed",$.snapshot.error=`Agent terminal persistence failed: ${f0(Y)}`,K(`agent: terminal finalization failed run=${$.snapshot.runId}: ${f0(Y)}`),this.deps.sendTextRaw($.snapshot.chatId,`❌ agent ${$.snapshot.runId} 收尾失败: ${f0(Y)}`).catch((Q)=>K(`agent: terminal failure delivery failed: ${f0(Q)}`))})}async cancelTree($,Z){let J=!V4($.snapshot.status)&&!$.cancelled||$.handles.size>0,Y=[];if(J){$.cancelled=!0;for(let V of[...$.progressTimers.keys()])this.clearProgressTimer($,V);for(let V of $.capabilityByIdentity.values())this.capabilities.delete(V);$.capabilityByIdentity.clear()}while(!0){let V=[...$.children].map((X)=>this.runs.get(X)).filter((X)=>!!X&&this.treeHasActiveRun(X));if(V.length===0)break;let H=await Promise.allSettled(V.map((X)=>this.cancelTree(X,Z)));if(Y.push(...H),H.some((X)=>X.status==="rejected"))break}if(!J){bJ(Y);return}if(Y.push(...await Promise.allSettled([...$.handles].map(async([V,H])=>{if(await H.cancel(Z),H.isAlive?.())throw Error(`${V}: Agent process is still alive after cancellation`);$.handles.delete(V),this.releaseWorkerSlot($,V)}))),Y.some((V)=>V.status==="rejected")){let V=MG(Y);throw $.snapshot.status="failed",$.snapshot.error=V.message,this.persist($),await this.deps.sendTextRaw($.snapshot.chatId,`❌ Agent 取消未完成: ${V.message}`).catch((H)=>K(`agent: cancellation failure notice failed: ${f0(H)}`)),V}let Q=[];for(let V of $.snapshot.workers)if(!x9(V.status))V.status="cancelled",V.error=Z,V.finishedAt=new Date().toISOString(),delete V.pendingInput,Q.push(V);await Promise.all(Q.map((V)=>this.updateWorkerCard($,V))),await this.finalizeRun($,"cancelled",Z)}async finalizeRun($,Z,J){if($.finalized||$.finalizing)return;$.finalizing=!0;for(let Y of[...$.progressTimers.keys()])this.clearProgressTimer($,Y);if($.snapshot.status=Z,$.snapshot.finishedAt=new Date().toISOString(),J)$.snapshot.error=J;try{await this.presentation.update($.snapshot,!0)}catch(Y){this.recordPresentationError($,`agent card finalization failed: ${f0(Y)}`)}if($.finalizing=!1,this.persist($),$.finalized=!0,this.pruneRunArtifacts(),$.snapshot.presentationErrors?.length)await this.deps.sendTextRaw($.snapshot.chatId,`⚠️ agent ${$.snapshot.runId} 结果已保存,但卡片有 ${$.snapshot.presentationErrors.length} 个呈现错误。`).catch((Y)=>K(`agent: warning delivery failed run=${$.snapshot.runId}: ${f0(Y)}`))}async updateWorkerCard($,Z){if($.finalized)return;let J=$.snapshot.cardMessageId;try{await this.presentation.update($.snapshot)}catch(Y){this.recordPresentationError($,`agent worker card update failed (${Z.identityName}): ${f0(Y)}`)}finally{if($.snapshot.cardMessageId!==J)this.persist($)}}recordPresentationError($,Z){let J=$.snapshot.presentationErrors??[];if(!J.includes(Z))J.push(Z);$.snapshot.presentationErrors=J,K(`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 Y=CM("sha256").update(J.identityId).digest("hex").slice(0,16);J.outputArtifact=`${$.snapshot.runId}.${Y}.output.txt`}this.persistTextArtifact($,J.outputArtifact,J.output)}let Z=PG($.snapshot);Z.prompt="";for(let J of Z.workers)J.output="";this.deps.writeArtifact(s6(P1,`${$.snapshot.runId}.json`),Z)}persistTextArtifact($,Z,J){if($.persistedArtifacts.has(Z))return;OG(Z),this.deps.writeTextArtifact(s6(P1,Z),J),$.persistedArtifacts.add(Z)}readSnapshot($){let Z=PG($.snapshot);if($.artifactsUnloaded)UG(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.assertSameSession(J,$.session),!J.session)J.session=$.session;return J}requireSessionRun($,Z,J){let Y=[...this.runs.values()].flatMap((H)=>{if(!this.canAccess($,H)||H.snapshot.workDir!==$.session.workDir)return[];return H.snapshot.workers.filter((X)=>X.sessionId===Z&&(!J||X.identityId===J)).map((X)=>({run:H,worker:X}))});if(!Y.length)throw Error(`agent session not found in this Session${J?" for the requested identity":""}: ${Z}`);if(new Set(Y.map(({worker:H})=>H.identityId)).size>1)throw Error("agent session id matches multiple identities; specify identity_id");let Q=new Set(Y.map(({run:H})=>H.snapshot.parentRunId)),V=Y.filter(({run:H})=>!Q.has(H.snapshot.runId)).sort((H,X)=>Date.parse(X.run.snapshot.createdAt)-Date.parse(H.run.snapshot.createdAt))[0];if(!V)throw Error(`agent session history has no latest run: ${Z}`);return V}reserveNativeSession($){let Z=JSON.stringify([$.provider,$.sessionId]),J=[...this.runs.values()].some((Y)=>Y.snapshot.workers.some((Q)=>{if(Q.provider!==$.provider||Q.sessionId!==$.sessionId)return!1;let V=Y.handles.get(Q.identityId);return!x9(Q.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){if(Z.snapshot.sessionName!==$.session.sessionName||Z.snapshot.chatId!==$.session.chatId)return!1;if($.kind==="session")return!0;let J=Z;while(J){if(J.snapshot.runId===$.runId)return!0;J=J.snapshot.parentRunId?this.runs.get(J.snapshot.parentRunId):void 0}return!1}assertSameSession($,Z){if($.snapshot.sessionName!==Z.sessionName||$.snapshot.chatId!==Z.chatId||$.snapshot.workDir!==Z.workDir)throw Error("agent run belongs to a different Session")}treeHasActiveRun($){if($.handles.size>0)return!0;if(!V4($.snapshot.status))return!0;for(let Z of $.children){let J=this.runs.get(Z);if(J&&this.treeHasActiveRun(J))return!0}return!1}reserveCapacity($,Z){let J=this.sessionKey($.session.sessionName,$.session.chatId),Y=[...this.runs.values()].filter((X)=>this.sessionKey(X.snapshot.sessionName,X.snapshot.chatId)===J&&(!V4(X.snapshot.status)||X.handles.size>0)).length,Q=this.startingRunsBySession.get(J)??0;if(Y+Q>=jG)throw Error(`Session has reached ${jG} active Agent runs`);if([...this.runs.values()].reduce((X,z)=>X+z.snapshot.workers.filter((W)=>!x9(W.status)||z.handles.get(W.identityId)?.isAlive?.()).length,0)+this.startingWorkers+Z>LG)throw Error(`global Agent worker limit ${LG} would be exceeded`);this.startingWorkers+=Z,this.startingRunsBySession.set(J,Q+1);let H=!1;return()=>{if(H)return;H=!0,this.startingWorkers=Math.max(0,this.startingWorkers-Z),DG(this.startingRunsBySession,J)}}sessionKey($,Z){return`${$}\x00${Z}`}currentCancellationEpoch($){return this.cancellationEpochBySession.get(this.sessionKey($.sessionName,$.chatId))??0}bumpCancellationEpoch($,Z){let J=this.sessionKey($,Z);this.cancellationEpochBySession.set(J,(this.cancellationEpochBySession.get(J)??0)+1)}tryAcquireSlot($){let Z=GG.get($),J=this.activeTurnsBySource.get($)??0;if(this.activeTurns>=SJ||Z!==void 0&&J>=Z)return!1;return this.activeTurns++,this.activeTurnsBySource.set($,J+1),!0}acquireSlot($,Z){if(this.tryAcquireSlot($.tokenSourceId))return Promise.resolve();let J=GG.get($.tokenSourceId);return Z(J!==void 0?`等待 ${$.tokenSourceDisplay} 执行名额(同一来源最多同时运行 ${J} 个 Agent)`:`等待执行名额(最多同时运行 ${SJ} 个 Agent)`),new Promise((Y)=>this.slotWaiters.push({tokenSourceId:$.tokenSourceId,resolve:Y}))}releaseSlot($){this.activeTurns--,DG(this.activeTurnsBySource,$);for(let Z=0;Z<this.slotWaiters.length&&this.activeTurns<SJ;){let J=this.slotWaiters[Z];if(!this.tryAcquireSlot(J.tokenSourceId)){Z++;continue}this.slotWaiters.splice(Z,1),J.resolve()}}releaseWorkerSlot($,Z){let J=$.slotOwners.get(Z);if(J===void 0)return;$.slotOwners.delete(Z),this.releaseSlot(J)}loadDurableRuns(){for(let $ of this.deps.loadArtifacts()){if(!V4($.status)){$.status="failed",$.error="daemon restarted before this Agent run reached a terminal state",$.finishedAt=new Date().toISOString();for(let J of $.workers)if(!x9(J.status))J.status="failed",J.error=$.error,J.finishedAt=$.finishedAt,delete J.pendingInput}let Z={snapshot:$,session:null,handles:new Map,slotOwners:new Map,capabilityByIdentity:new Map,progressTimers:new Map,children:new Set,cancelled:$.status==="cancelled",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<=BG)return;let $=[...this.runs.values()].filter((Z)=>!Z.artifactsUnloaded&&Z.finalized&&!Z.finalizing&&V4(Z.snapshot.status)&&Z.handles.size===0&&Z.slotOwners.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-BG))){Z.snapshot.prompt="";for(let J of Z.snapshot.workers)J.output="";Z.artifactsUnloaded=!0}}}function hM($,Z,J){return{identityId:$.id,identityName:$.displayName,tokenSourceId:$.tokenSourceId,provider:$.provider,model:$.model,effort:Z,status:"queued",output:"",...J?{sessionId:J}:{},steps:[]}}function IM($,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 qG($,Z){if(Z){let J=$.workers.find((Y)=>Y.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 V4($){return $==="completed"||$==="failed"||$==="cancelled"}function x9($){return $==="completed"||$==="failed"||$==="cancelled"}function PG($){return JSON.parse(JSON.stringify($))}function gM(){if(!wM(P1))return[];let $=[];for(let Z of vM(P1).filter((J)=>J.endsWith(".json")).sort()){let J=s6(P1,Z),Y;try{Y=JSON.parse(FG(J,"utf8"))}catch(Q){throw Error(`agent run artifact is unreadable (${J}): ${f0(Q)}`)}if(!mM(Y))throw Error(`agent run artifact is invalid: ${J}`);UG(Y,J),$.push(Y)}return $}function mM($){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"&&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 MG($){let Z=$.flatMap((J)=>J.status==="rejected"?[J.reason]:[]);return AggregateError(Z,`Agent cancellation failed: ${Z.map(f0).join("; ")}`)}function bJ($){if($.some((Z)=>Z.status==="rejected"))throw MG($)}function f0($){return $ instanceof Error?$.message:String($)}function pM($){return $?{...$,tools:void 0,strictMcp:!1,loadProjectMcp:!0}:{strictMcp:!1,loadProjectMcp:!0}}function UG($,Z,J=AG){if($.promptArtifact)$.prompt=J($.promptArtifact,`prompt for ${Z}`);for(let Y of $.workers)if(Y.outputArtifact)Y.output=J(Y.outputArtifact,`output for ${Z}`)}function AG($,Z){OG($);try{return FG(s6(P1,$),"utf8")}catch(J){throw Error(`${Z} is unreadable (${$}): ${f0(J)}`)}}function OG($){if(!/^[A-Za-z0-9._-]+$/.test($))throw Error(`invalid Agent artifact name: ${$}`)}function DG($,Z){let J=($.get(Z)??0)-1;if(J>0)$.set(Z,J);else $.delete(Z)}var SJ=8,GG,KG="Delegated Agents cannot delegate again; ask the main Agent to assign additional work.",BG=512,_G=50,jG=64,LG=128,fM;var RG=R(()=>{v$();$G();t();y0();w6();WG();Q0();T0();I();GG=new Map([["openrouter",2]]),fM={getCatalog:n1,startWorker:zG,sendCard:c,getChatTailMessageId:j5,sendTextRaw:w,convertMessageToCard:Z$,recordCardCreated:d0,getElementCount:t4,addElementResult:y2,replaceElementResult:wV,deleteElementChecked:vV,cancelSummary:A0,patchSettingsChecked:P0,dispose:v0,writeArtifact:s,writeTextArtifact:I0,readTextArtifact:AG,loadArtifacts:gM}});async function EG($,Z,J,Y){if(J.pathname!=="/agents"&&!J.pathname.startsWith("/agents/"))return!1;let Q=(G,B)=>{return Z.statusCode=G,Z.setHeader("content-type","application/json"),Z.end(JSON.stringify(B)),!0},V=lM($.headers.authorization);if(!V)return Q(401,{error:"missing bearer capability"});let H=cM(Y,V);if(!H)return Q(403,{error:"invalid or stale agent capability"});if($.method==="GET"&&J.pathname==="/agents/identities")return await U2(),Q(200,dM(n1(H.session.codexAccountId())));if($.method==="POST"&&J.pathname==="/agents/runs")try{let G=await Y.service.startRun(H,ZG(await kJ($)));return Q(202,t6(G))}catch(G){return Q(409,{error:TG(G)})}let X=J.pathname.match(/^\/agents\/runs\/([^/]+)(?:\/(follow-up|answer))?$/);if(!X)return Q(405,{error:"unsupported agent endpoint"});let z=uM(X[1]);if(!z)return Q(400,{error:"invalid agent run id encoding"});let W=X[2];try{if(!W&&$.method==="GET")return Q(200,t6(Y.service.getRun(H,z)));if(!W&&$.method==="DELETE"){let G=await Y.service.cancelRun(H,z,"cancelled by agent client");return Q(G?200:409,G?{ok:!0,run_id:z}:{error:"agent run is already terminal",run_id:z})}if(W==="follow-up"&&$.method==="POST"){let G=await Y.service.followUp(H,z,JG(await kJ($)));return Q(202,t6(G))}if(W==="answer"&&$.method==="POST"){let G=await Y.service.answer(H,z,YG(await kJ($)));return Q(200,t6(G))}}catch(G){return Q(409,{error:TG(G)})}return Q(405,{error:"unsupported agent endpoint"})}function cM($,Z){let J=$.authorizeSession(Z);if(J)return $.service.rootPrincipal(J);return $.service.principalForCapability(Z)}function uM($){try{return decodeURIComponent($)}catch{return null}}function lM($){return $?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()??""}async function kJ($){let Z="";for await(let J of $)if(Z+=J.toString(),Buffer.byteLength(Z)>NG)throw Error(`request body exceeds ${NG} bytes`);try{return JSON.parse(Z||"{}")}catch{throw Error("bad json")}}function dM($){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 t6($){return{run_id:$.runId,session_name:$.sessionName,prompt:$.prompt,description:$.description,parent_run_id:$.parentRunId,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 TG($){return $ instanceof Error?$.message:String($)}var NG=4194304;var xG=R(()=>{w6();V0()});function SG($){J4({name:oz,body:ez()},$)}var bG=R(()=>{r6();m6()});import{chmodSync as iM,existsSync as yJ,readFileSync as yG,realpathSync as nM,unlinkSync as aM}from"node:fs";import{homedir as oM}from"node:os";import{basename as rM,dirname as sM,join as j1,resolve as tM}from"node:path";function eM($={}){let Z=nM(tM($.daemonEntry??process.argv[1]??"")),J=$.runtime??process.execPath,Y=$.exists??yJ,Q=sM(Z),V=j1(Q,"src","agent-cli.ts"),H=j1(Q,"lodestar-agent.js"),X=j1(Q,"dist","lodestar-agent.js"),W=/^bun(?:\.exe)?$/i.test(rM(J))?[V,H,X]:[H,X],G=W.find(Y);if(!G)throw Error(`lodestar-agent entry not found beside daemon: ${W.join(", ")}`);return{runtime:J,entry:G}}function wG($={}){let Z=$.platform??process.platform,J=$.env??process.env,Y=$.targetDir??ZU(Z,$.homeDir??oM(),$.localAppData??process.env.LOCALAPPDATA),Q=$.launch??eM(),V=j1(Y,Z==="win32"?"lodestar-agent.cmd":"lodestar-agent"),H=Z==="win32"?`@"${kG(Q.runtime)}" "${kG(Q.entry)}" %*\r
|
|
543
543
|
`:`#!/bin/sh
|
|
544
|
-
exec ${
|
|
545
|
-
`,X=
|
|
544
|
+
exec ${CG(Q.runtime)} ${CG(Q.entry)} "$@"
|
|
545
|
+
`,X=yJ(V)?yG(V,"utf8"):null;if(X!==H)KY(V,H),K(`command: ${X===null?"installed":"updated"} ${V}`);else iM(V,448);return JU(J,Y,Z),$U(Y,Z),V}function $U($,Z){let J=j1($,Z==="win32"?"lodestar-consult.cmd":"lodestar-consult");if(!yJ(J))return;try{let Y=yG(J,"utf8");if(!Y.includes("lodestar-consult")&&!Y.includes("consult-cli")){K(`command: obsolete path preserved because ownership is unclear ${J}`);return}aM(J),K(`command: removed obsolete ${J}`)}catch(Y){K(`command: obsolete removal failed (${J}): ${Y}`)}}function ZU($,Z,J){if($==="win32")return j1(J??j1(Z,"AppData","Local"),"Lodestar","bin");return j1(Z,".local","bin")}function JU($,Z,J){let Y=J==="win32"?Object.keys($).find((X)=>X.toLowerCase()==="path")??"Path":"PATH",Q=J==="win32"?";":":",V=$[Y]??"",H=(X)=>J==="win32"?X.toLowerCase():X;if(V.split(Q).some((X)=>H(X)===H(Z)))return;$[Y]=V?`${Z}${Q}${V}`:Z}function CG($){return`'${$.replaceAll("'",`'"'"'`)}'`}function kG($){return $.replaceAll('"','""')}var vG=R(()=>{I();T0()});function fG($,Z,J){return $>0&&Z-$>J}async function hG($){if(await $.reply())return!0;if(!$.hasQuestion())return!1;return await $.answerQuestion(),!0}function IG($){let Z=$==="media"?"视频":$==="image"?"图片":"文件";return`❌ 收到的${Z}下载失败,未转交给 Agent。备注:可能是${Z}超过飞书消息资源 100 MB 下载上限。`}function wJ($){return typeof $==="string"&&$.length>0?$:void 0}function gG($,Z){if(!Z||typeof Z!=="object")return null;let J=Z;if($==="image"){let H=wJ(J.image_key);return H?{key:H,type:"image",displayText:""}:null}if($!=="file"&&$!=="media")return null;let Y=wJ(J.file_key);if(!Y)return null;let Q=wJ(J.file_name);return{key:Y,type:"file",...Q?{name:Q}:{},displayText:Q?`(${$==="media"?"video":"file"}: ${Q})`:""}}function mG($,Z){return $.add(Z),Z.then(()=>{$.delete(Z)},()=>{$.delete(Z)}),Z}async function pG($){while(!0){let Z=[...$()];if(Z.length===0)return;await Promise.allSettled(Z)}}class vJ{deps;pending=null;shutdownSnapshot=null;revival=null;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 Y;try{Y=this.deps.sessionFor(J,Z);let Q=await Y.restoreAfterDaemonRestart();this.deps.log(`revive: "${Z}" ${Q?"restored":"did not start"}`)}catch(Q){this.deps.log(`revive: restore "${Z}" failed: ${Q}`)}finally{if(Y)this.pending.delete(Z);this.persist()}})})).then(()=>{}),this.revival}}function c$($){return $ instanceof Error?$.message:String($)}function cG($,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 uG($){let Z=(Q,V)=>{let H=$.registry.get(Q);if(H&&H.sessionName!==V)throw Error(`chat ${Q} is already owned by session "${H.sessionName}", not "${V}"`);if(!H)H=$.createSession(V,Q),$.registry.set(Q,H);return H};return{sessionFor:Z,createTempSession:async(Q)=>{let V;try{if(_0(Q.launch,Q.routing.provider,Q.workDir),Q.launch.kind==="resume")throw Error("temporary groups must start fresh or fork; resume is not allowed");if(V=await $.ensureChatForSession(Q.chatName,Q.userOpenId),!V.created)return{ok:!1,chatId:V.chatId,error:"临时会话必须使用新群;既有群保留,未执行加入、启动或删除"}}catch(X){let z=c$(X);return $.log(`temp-session: create "${Q.chatName}" failed: ${z}`),{ok:!1,error:z}}let H=async()=>{let X=null;try{if($.registerTempSessionLease(Q.chatName,V.chatId),X=Z(V.chatId,Q.chatName),X.isRunning())return{ok:!1,error:`${Q.chatName} 已有会话在跑,先 bye 解散再重试`};if(X.workDir!==Q.workDir)throw Error(`临时群 cwd 不匹配: source=${Q.workDir} target=${X.workDir}`);if(X.applyConversationRouting(Q.routing),!(Q.launch.kind==="fork"?await X.startForked(Q.launch,{announce:!1}):await X.start({announce:!1})))throw Error(`${X.backendLabel()} 启动失败`);return $.replaceTurnAnchors(Q.chatName,Q.seedAnchors??[],Q.branchBase),{ok:!0,chatId:V.chatId}}catch(z){let W=c$(z);if($.log(`temp-session: initialize "${Q.chatName}" failed: ${W}`),X)try{await X.stop("临时群启动失败清理",{announce:!1})}catch(B){let _=c$(B);return $.log(`temp-session: failed-create stop "${Q.chatName}" failed: ${_}`),{ok:!1,chatId:V.chatId,error:`${W};无法确认 Session 已停止,临时群/session 仍保留: ${_}`}}if(!V.created)return{ok:!1,error:`${W};既有群保留,未执行删除`};let G;try{let B=await $.disbandChatForSessionExact(Q.chatName,V.chatId);G=cG(Q.chatName,V.chatId,B)}catch(B){let _=c$(B);return $.log(`temp-session: create cleanup "${Q.chatName}" failed: ${_}`),{ok:!1,chatId:V.chatId,error:`${W};自动解散失败,临时群/session 仍保留: ${_}`}}try{$.registry.delete(G),X?.dispose(),$.clearSessionConversationState(Q.chatName)}catch(B){let _=c$(B);return $.log(`temp-session: local cleanup "${Q.chatName}" failed: ${_}`),{ok:!1,error:`${W};临时群已确认解散,但本地状态清理失败: ${_}`}}return{ok:!1,error:`${W};本次新建的临时群已确认解散`}}};try{return $.runExclusive?await $.runExclusive(V.chatId,H):await H()}catch(X){let z=c$(X);return $.log(`temp-session: target actor "${Q.chatName}" failed: ${z}`),{ok:!1,chatId:V.chatId,error:`${z};临时群/session 仍保留`}}},disbandTempSession:async(Q,V)=>{let H=$.chatIdForSession(Q);if(!V||H!==V){let W=`临时群 chat_id 已变化: expected=${V||"-"} bound=${H??"-"}`;return $.log(`temp-session: disband identity rejected "${Q}": ${W}`),{ok:!1,error:`${W};未执行停止或删群`}}if(!$.hasTempSessionLease(Q,V)){let W=`群 ${V} 没有 Lodestar 临时会话 lease,拒绝解散`;return $.log(`temp-session: disband lease rejected "${Q}": ${W}`),{ok:!1,error:`${W};未执行停止或删群`}}let X=$.registry.get(H);try{if(X)await X.stop("bye 解散",{announce:!1})}catch(W){let G=c$(W);return $.log(`temp-session: stop before disband "${Q}" failed: ${G}`),{ok:!1,error:`${G};无法确认 Session 已停止,未执行删群`}}let z;try{let W=await $.disbandChatForSessionExact(Q,H);z=cG(Q,H,W)}catch(W){let G=c$(W);return $.log(`temp-session: disband "${Q}" failed: ${G}`),{ok:!1,error:`${G};临时群/session 仍保留`}}try{return $.registry.delete(z),X?.dispose(),$.clearSessionConversationState(Q),{ok:!0}}catch(W){let G=c$(W);return $.log(`temp-session: local cleanup after disband "${Q}" failed: ${G}`),{ok:!1,error:`临时群已确认解散,但本地状态清理失败: ${G}`}}}}}var lG=R(()=>{A1()});var NU={};import*as X4 from"@larksuiteoapi/node-sdk";import{chmodSync as YU,existsSync as hJ,mkdirSync as QU,readFileSync as VU,unlinkSync as $7,writeFileSync as HU}from"node:fs";import{dirname as XU}from"node:path";function z4($,Z){if(L1=Math.max(L1,Z),e6)return e6;a0=!0,nG?.(),i$.close();try{aG?.()}catch(J){L1=1,K(`shutdown WebSocket close failed: ${J}`)}try{$2.persist()}catch(J){K(`shutdown alive marker write failed: ${J}`),L1=1}return e6=(async()=>{K(`${$}: staged shutdown begin sessions=${d$.size}`);try{let J=(async()=>{await pG(()=>[...i$.pending(),...rG]),$2.freezeForShutdown();let H=await Promise.allSettled([IJ.shutdown(`daemon ${$}`),l1.shutdown()]),X=await Promise.allSettled([vZ()]),z=await Promise.allSettled([...d$.values()].map((W)=>W.stop(`daemon ${$}`,{announce:!1})));return[...H,...X,...z]})(),Y=null,Q=new Promise((H)=>{Y=setTimeout(()=>H("deadline"),iG)}),V=await Promise.race([J.then((H)=>{for(let X of H)if(X.status==="rejected")L1=1,K(`shutdown session stop failed: ${X.reason}`);return"stopped"}),Q]);if(Y)clearTimeout(Y);if(V==="deadline")L1=1,K(`${$}: shutdown deadline ${iG}ms reached; forcing exit`);else K(`${$}: all sessions stopped`)}catch(J){K(`${$}: staged shutdown failed: ${J}`),L1=1}finally{oG(),process.exit(L1)}})(),e6}function gJ($){return mG(rG,$)}function sG($,Z="ws"){if(a0)return K(`${Z}: reject inbound message: daemon shutdown in progress`),!1;let J=String($?.message?.chat_id??""),Y=WU.accept($);if(!Y.accepted)return K(`${Z}: reject inbound message${J?"":" without chat_id"}: actor ${Y.reason}`),!1;return Y.completion.catch((Q)=>{K(`${Z}: handleMessage rejected chat=${J.slice(0,8)}…: ${Q}`)}),!0}function GU(){$2.persist()}function tG($,Z){return mJ.sessionFor($,Z)}async function KU($){return await mJ.createTempSession($)}async function BU($,Z){return await mJ.disbandTempSession($,Z)}function _U($){let Z=[],J=[],Y=[],Q=typeof $?.title==="string"?$.title.trim():"";if(Q)Y.push(`# ${Q}`);let V=Array.isArray($?.content)?$.content:[];for(let H of V){if(!Array.isArray(H))continue;let X=[];for(let W of H){if(!W||typeof W!=="object")continue;switch(W.tag){case"text":{let G=String(W.text??""),B=Array.isArray(W.style)?W.style:[];if(B.includes("bold"))G=`**${G}**`;if(B.includes("italic"))G=`*${G}*`;if(B.includes("lineThrough")||B.includes("strikethrough"))G=`~~${G}~~`;X.push(G);break}case"a":{let G=String(W.href??""),B=String(W.text??G);X.push(`[${B}](${G})`);break}case"at":{let G=String(W.user_name??W.user_id??"");X.push(`@${G}`);break}case"code_inline":X.push(`\`${String(W.text??"")}\``);break;case"hr":X.push("---");break;case"img":if(W.image_key)Z.push(String(W.image_key));break;case"media":if(W.file_key)J.push({key:String(W.file_key),name:W.file_name});break;case"emotion":break;default:if(typeof W.text==="string")X.push(W.text)}}let z=X.join("");if(z.trim())Y.push(z)}return{markdown:Y.join(`
|
|
546
546
|
|
|
547
|
-
`),imageKeys:Z,fileKeys:J}}async function LU($,Z=Date.now()){let J=$?.message;if(!J)return;let Q=($?.sender?.sender_id??$?.event?.sender?.sender_id??J?.sender?.sender_id)?.open_id??"",V=J.message_id;if(V&&H4.has(V))return;if(V){if(H4.add(V),H4.size>200){let A=[...H4];H4.clear();for(let U of A.slice(-100))H4.add(U)}}let H=Number(J.create_time??0);if(vG(H,Z,jU)){if(K(`drop stale message ${V} ageAtReceipt=${Math.round((Z-H)/1000)}s`),V)l0(V,"CrossMark");return}let X=J.chat_id,z={};try{z=JSON.parse(J.content??"{}")}catch{}let W=J.message_type==="text"?z.text??"":"";if(typeof W==="string"&&W.startsWith("[DEBUG]")){try{HU(w9,JSON.stringify({chat_id:X,sender_open_id:Q,seeded_at:new Date().toISOString(),seeded_msg_id:V??""},null,2)),K(`debug: seeded inject context chat=${X.slice(0,8)}… sender=${Q.slice(0,8)}…`)}catch(U){K(`debug: seed context failed: ${U}`)}let A=W.slice(7);z.text=A,J.content=JSON.stringify(z)}let G=q0.get(X);if(!G)await n4(),G=q0.get(X);if(!G)G=await j5(X)??void 0;if(!G){K(`unknown chat ${X}, dropping message`),await E(X,"❌ 无法识别群名。请确认:① 机器人已被拉进本群;② 群已设置名称(未命名群拿不到群名,无法映射项目目录)。设置后再发一条消息即可。");return}let B=F5(G);S2(B,X);let _=sG(X,B),j={};try{j=JSON.parse(J.content??"{}")}catch{}let q=J.message_type,P="",F=!1,T=[];if(q==="text")P=(j.text??"").trim();else if(q==="post"){let A=_U(j);F=A.imageKeys.length>0||A.fileKeys.length>0,P=A.markdown.trim();for(let U of A.imageKeys){let S=await a4(J.message_id,U,"image");if(S)T.push(S)}for(let U of A.fileKeys){let S=await a4(J.message_id,U.key,"file",U.name);if(S)T.push(S)}}if(q==="text"&&P){if(await _.runCommand(P,Q,V))return}if((q==="text"||q==="post")&&P&&!F&&await fG({reply:()=>J7.consume({chatId:X,openId:Q,messageId:V??"",text:P,createTime:H,parentId:J.parent_id}),hasQuestion:()=>_.hasPendingAsk(),answerQuestion:()=>_.onAskMessageAnswer(P,Q,V??"")}))return;if(q==="text"&&P&&await _.consumeModelCustomMessage(P,Q))return;let M=IG(q,j);if(M){let A=await a4(J.message_id,M.key,M.type,M.name);if(!A){await E(X,hG(q));return}if(T.push(A),!P&&M.displayText)P=M.displayText}if(!P&&T.length===0){K(`drop empty message ${V} type=${q}`);return}if(await _.onMultiMessageInbound(P,T,Q,V??""))return;await _.onUserMessage(P||"(empty)",T,Q,V??"")}function Y7($){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:"取消通知回复"}[$]??$}function qU($){return $?.card?.type==="raw"&&$.card.data&&typeof $.card.data==="object"?$.card.data:null}function z0($,Z,J){return{...$,__businessOk:Z,...J?{__businessMessage:J}:{}}}function l$($,Z){return{...Z,__cardActionMessageId:$.messageId,__cardActionChatId:$.chatId}}function u$($){return z0($.card?Q$($.card):{toast:{type:$.ok?"success":"error",content:$.message}},$.ok)}async function e1($,Z){if(!$){K(`card-action: cannot send receipt without chat_id: ${Z}`);return}if(!await w($,Z))K(`card-action: visible receipt MISS chat=${$.slice(0,8)}… text=${Z.slice(0,120)}`)}async function PU($,Z){if(Z?.__cardActionPresented)return;let J=String($?.action?.value?.kind??"unknown"),Y=Y7(J),Q=String(Z?.__cardActionChatId??$?.__cardActionChatId??$?.context?.open_chat_id??""),V=String(Z?.__cardActionMessageId??$?.context?.open_message_id??""),H=qU(Z),X=Z?.__businessOk===!1&&typeof Z?.__businessMessage==="string"?` 业务失败: ${Z.__businessMessage.replace(/\s+/g," ").trim().slice(0,300)}。`:"";if(H&&V)try{await A$(V,H);return}catch(j){K(`card-action: ${J} original-card update failed: ${j instanceof Error?j.message:j}`),await e1(Q,`⚠️ ${Y}已处理,但原卡更新失败。${X}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":"请重新打开操作面板。"}`);return}if(H){await e1(Q,`⚠️ ${Y}已处理,但回调缺少原卡 message_id,无法更新。${X}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":""}`);return}if(J==="notify_callback"&&Z?.__cardActionCompletion)return;let z=Z?.toast,W=typeof z?.content==="string"&&z.content.trim()?z.content.trim():`${Y}已完成`,G=J==="permission"&&String($?.action?.value?.decision??"")==="deny",B=Z?.__businessOk===!1||z?.type==="error"&&!G;if(!B&&new Set(["permission","ask","token_source_enable"]).has(J))return;await e1(Q,`${B?"❌":"✅"} ${Y}: ${W}`)}async function FU($,Z){let J=String($?.action?.value?.kind??"unknown"),Y=Z instanceof Error?Z.message:String(Z);await e1(String($?.__cardActionChatId??$?.context?.open_chat_id??""),`❌ ${Y7(J)}失败: ${Y}`)}function tG($){return DU.accept($)}async function MU($){let Z=$?.action,J=Z?.value;if(!J?.kind)return;let Y=$?.context?.open_chat_id??"",Q=$?.operator?.open_id??"";if(J.kind==="notify_callback"||J.kind==="notify_reply"||J.kind==="notify_reply_cancel"){let H=String(J.notify_id??""),X=I$(H);if(X)$.__cardActionChatId=X.chatId;if(J.kind==="notify_callback")return await UU(J,Y,Q);let z=J.kind==="notify_reply"?await J7.open(H,Y,Q):await J7.cancel(H,String(J.reply_id??""),Y,Q),W=z0({toast:{type:z.ok?"success":"error",content:z.message},__cardActionPresented:z.presented===!0},z.ok);return X?l$(X,W):W}let V=d$.get(Y);if(!V)return z0({toast:{type:"error",content:"会话不存在,请先发消息启动"}},!1);switch(J.kind){case"permission":{let H=String(J.decision??"");if(!["allow","allow_always","deny"].includes(H))return{toast:{type:"error",content:"无效的权限决定"}};let X=await V.onPermissionDecision(J.request_id,H,Q);return z0({toast:{type:X.ok?H==="deny"?"error":"success":"error",content:X.message}},X.ok)}case"menu":{let H=Number(J.choice??-1);try{if(!Number.isInteger(H)||H<0)throw Error("无效的菜单选项");return await V.onUserMessage(`(menu choice ${H+1})`),z0(Q$(z1({title:"\uD83D\uDCCB 菜单选择",message:`已选择第 ${H+1} 项`,ok:!0})),!0)}catch(X){let z=X instanceof Error?X.message:String(X);return z0(Q$(z1({title:"\uD83D\uDCCB 菜单选择",message:z,ok:!1})),!1)}}case"provider_select":{let H=await V.onProviderSelect(String(J.source_id??""),String(J.panel_id??""));return u$(H)}case"model_page":{let H=await V.onModelPage(String(J.panel_id??""),String(J.source_id??""),Number(J.page));return u$(H)}case"model_list_open":{let H=String(J.panel_id??""),X=String(J.source_id??"");if(J.mode!=="add"&&J.mode!=="select")throw Error("模型管理模式无效");return u$(await(J.mode==="add"?V.onModelAddOpen(H,X):V.onProviderSelect(X,H)))}case"model_add":case"model_remove":case"model_custom_remove":return u$(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 H=await V.onModelSelect(String(J.model??""),String(J.panel_id??""),Q,J);return u$(H)}case"model_custom_prompt":{let H=await V.onModelCustomPrompt(String(J.source_id??""),String(J.panel_id??""),String($?.context?.open_message_id??""));return u$(H)}case"model_panel_cancel":{let H=await V.onModelPanelCancel(String(J.panel_id??""));return u$(H)}case"model_effort_select":{let H=await V.onModelEffortSelect(String(J.model??""),String(J.effort??""),String(J.panel_id??""),Q,String(J.provider??""));return u$(H)}case"ask":{let H=V.askBlockReason(String(J.tool_use_id??""));if(H)return z0({toast:{type:"error",content:H}},!1);if(J.custom){let W=(Z?.form_value??Z?.input??{})?.custom_answer??Z?.input_value??"",G=await V.onAskCustomAnswer(J.tool_use_id,J.question_idx??0,W,Q);return z0({toast:{type:G?"success":"error",content:G?"已回答":W.trim()?"问题已失效或答案未被接受":"请输入答案"}},G)}let X=await V.onAskAnswer(J.tool_use_id,J.question_idx??0,J.option_idx,Q);return z0({toast:{type:X?"success":"error",content:X?"已回答":"问题已失效或选项无效"}},X)}case"worktree_disband":{let H=await V.onWorktreeDisband(String(J.slug??""));return z0(Q$(H.card),H.ok)}case"temp_fork_select":{let H=await V.onForkSelect(String(J.panel_id??""),String(J.choice_id??""),Q);return z0(H.replaceCard===!1?{toast:{type:"error",content:H.message}}:Q$(z1({title:"\uD83D\uDD31 会话分叉",message:H.message,ok:H.ok})),H.ok)}case"temp_back_select":{let H=await V.onBackSelect(String(J.panel_id??""),String(J.choice_id??""),Q);return z0(H.replaceCard===!1?{toast:{type:"error",content:H.message}}:Q$(z1({title:"⏪ 会话回滚",message:H.message,ok:H.ok})),H.ok)}case"temp_resume_select":{let H=await V.onResumeSelect(String(J.panel_id??""),String(J.choice_id??""),Q);if(H.replaceCard===!1)return z0({toast:{type:"error",content:H.message}},H.ok);if(!H.resumePresentation)throw Error("rs selection result missing trusted presentation snapshot");return z0(Q$(YZ({...H.resumePresentation,message:H.message,ok:H.ok})),H.ok,H.message)}case"tasklist_enable":{let H=await V.onTasklistEnable();return z0(Q$(H.card),H.ok)}case"tasklist_delete_prompt":{let H=V.onTasklistDeletePrompt(String(J.guid??""));return z0(Q$(H.card),H.ok)}case"tasklist_delete_confirm":{let H=await V.onTasklistDeleteConfirm(String(J.guid??""));return z0(Q$(H.card),H.ok)}case"token_source_enable":{let{onTokenSourceEnable:H}=await Promise.resolve().then(() => (eZ(),tZ));return await H(V,String(J.source_id??"")),{toast:{type:"info",content:"已处理"}}}case"agent_identity_page":return u$(V.onAgentIdentityPage(String(J.panel_id??""),J.page,Q))}return{toast:{type:"info",content:"unknown action"}}}async function UU($,Z,J){let Y=String($?.notify_id??""),Q=String($?.button_id??"");if(!Y)return{toast:{type:"error",content:"回调缺少 notify_id"}};let V=I$(Y);if(!V)return K(`notify-callback: notify_id=${Y.slice(0,12)}… not found (expired or pre-restart)`),{toast:{type:"error",content:"通知已过期或已移除"}};if(V.unknownAt)return l$(V,z0({toast:{type:"error",content:`外部回调可能已成功,但本地确认状态未知,已禁止自动重试${V.unknownReason?`: ${V.unknownReason}`:""}`}},!0));if(V.resolvedAt)return l$(V,{toast:{type:"info",content:"已处理过"}});if(p2(Y))return l$(V,{toast:{type:"info",content:"处理中…"}});if(V.replyState?.status==="waiting"||V.replyState?.status==="sending")return l$(V,z0({toast:{type:"error",content:"正在等待文字回复,请先发送或取消回复,再选择按钮"}},!1));let H=V.buttons.find((W)=>W.id===Q);if(!H)return K(`notify-callback: notify_id=${Y.slice(0,12)}… unknown button_id="${Q}"`),l$(V,z0({toast:{type:"error",content:"未知按钮"}},!1));if(!V.callbackUrl){try{M9(V.notifyId,H.id,J)}catch(W){return l$(V,z0({toast:{type:"error",content:`保存反馈结果失败: ${W instanceof Error?W.message:W}`}},!1))}return K(`notify-callback: notify_id=${Y.slice(0,12)}… resolved button="${Q}" by=${J.slice(0,8)}… (no callback, pull/display)`),l$(V,{...Q$(t1(V,{status:"done",buttonId:H.id,text:H.text,operatorOpenId:J}))})}P9(V.notifyId);let X=mJ(AU(V,H,J));X.catch((W)=>{K(`notify-callback: notify_id=${V.notifyId.slice(0,12)}… phase-2 rejected: ${W instanceof Error?W.message:W}`)});let z=X.then((W)=>W==="retry"?"retry":"complete").catch(()=>"retry");return l$(V,{toast:{type:"info",content:`⏳ 已选择:${H.text} · 推送中…`},__cardActionCompletion:z})}async function AU($,Z,J){try{let Y=t1($,{status:"processing",buttonId:Z.id,text:Z.text,operatorOpenId:J});try{await A$($.messageId,Y)}catch(X){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-1 (processing) updateCard failed: ${X instanceof Error?X.message:X}`)}let Q=await xZ($,Z,J),V=Q.ok?"complete":"retry",H;if(Q.ok){let X=A6($.notifyId,Z.id,J);if(X.state==="complete")H={status:"delivered",buttonId:Z.id,text:Z.text,operatorOpenId:J,reply:Q.reply};else{V="unknown",H={status:"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:X.detail},K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… callback succeeded but tombstone is UNKNOWN: ${X.detail}`);try{await e1($.chatId,`⚠️ 通知反馈的外部回调已成功,但本地确认状态未知;为避免重复副作用,已禁止自动重试。${X.detail}`)}catch(z){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… UNKNOWN warning receipt failed: ${z instanceof Error?z.message:z}`)}}}else H={status:"failed",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:Q.detail};try{let X=t1($,H);await A$($.messageId,X)}catch(X){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-2 (final) presentation failed: ${X instanceof Error?X.message:X}`);try{await e1($.chatId,`⚠️ 通知反馈${V==="retry"?"失败且结果卡更新失败,可重新点击":"已执行,但结果卡更新失败"}: ${X instanceof Error?X.message:X}`)}catch(z){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… final fallback receipt failed: ${z instanceof Error?z.message:z}`)}}return K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… button="${Z.id}" ${V==="complete"?"delivered":V==="unknown"?"unknown/non-retryable":`failed: ${Q.detail}`} by=${J.slice(0,8)}…`),V}finally{F9($.notifyId)}}function hJ($){return $.map((Z)=>typeof Z==="string"?Z:JSON.stringify(Z)).join(" ")}function OU(){if(process.platform==="win32"){K("debug: inject socket skipped on Windows (dev-only feature)");return}if(typeof Bun>"u"){K("debug: inject socket skipped (Bun runtime only — npm/Node build does not include it)");return}try{if(IJ(D1))Z7(D1)}catch{}try{Bun.serve({unix:D1,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(a0)return new Response("daemon shutdown in progress",{status:503});let Y={};if($.method==="POST")try{Y=await $.json()}catch{return new Response("bad json",{status:400})}if(!IJ(w9))return new Response("no debug context yet — send `[DEBUG]hi` from Feishu first",{status:412});let Q={};try{Q=JSON.parse(VU(w9,"utf8"))}catch(G){return new Response(`ctx read failed: ${G}`,{status:500})}let V=J?Z.searchParams.get("chat_id"):Y.chat_id;if(V!==void 0&&V!==Q.chat_id||Z.pathname!=="/"&&!V)return new Response("explicit debug chat_id must match the seeded context",{status:409});if(J){let G=d$.get(Q.chat_id);return G?Response.json(RJ(G)):new Response("send md to open a model panel first",{status:404})}if(Z.pathname==="/model-action"){let G=d$.get(Q.chat_id);if(!G)return new Response("debug session not found",{status:404});try{if(typeof Y.message_id!=="string"||!Y.message_id.startsWith("om_"))throw Error("message_id required");let B=typeof Y.value?.panel_id==="string"?Y.value.panel_id.trim():"",_=G.modelPanels.get(B);if(!_?.messageId||_.messageId!==Y.message_id)throw Error("stale or mismatched model panel");let j=await X0.im.v1.message.get({path:{message_id:Y.message_id}});if(j.code!==0)throw Error(`message.get failed: ${j.code} ${j.msg}`);let q=mW(Y,Q,j.data?.items?.[0],f.feishu.app_id,_.messageId);K(`debug: model action ${Y.value.kind} chat=${Q.chat_id.slice(0,8)}…`);let P=tG(q);return await i$.enqueue(Q.chat_id,async()=>{}),Response.json({admission:P,state:RJ(G)})}catch(B){return new Response(B instanceof Error?B.message:String(B),{status:400})}}if(Z.pathname!=="/")return new Response("unknown debug endpoint",{status:404});let H=String(Y.text??"");if(!H)return new Response("text required",{status:400});let X=`【自动化测试】:${H}`,z=await E(Q.chat_id,X);if(!z)return new Response("sendText failed — see daemon log",{status:502});let W={sender:{sender_id:{open_id:Q.sender_open_id}},message:{message_id:z,chat_id:Q.chat_id,message_type:"text",content:JSON.stringify({text:H}),create_time:String(Date.now())}};if(K(`debug: inject text=${JSON.stringify(H).slice(0,80)} msg_id=${z}`),!rG(W,"debug"))return new Response("daemon shutdown in progress",{status:503});if(Y.wait_for_handling===!0)await i$.enqueue(Q.chat_id,async()=>{});return new Response(JSON.stringify({ok:!0,msg_id:z}),{headers:{"content-type":"application/json"}})}});try{YU(D1,384)}catch{}K(`debug: inject socket listening at ${D1}`)}catch($){K(`debug: socket bind failed: ${$}`)}}async function RU(){K(`lodestar-daemon: pid ${process.pid} starting`),$2.load();let{buildTokenSourcesFromConfig:$}=await Promise.resolve().then(() => (rZ(),zz));if(a0)return;$();let{refreshAllTokenSourceModels:Z}=await Promise.resolve().then(() => (V0(),lQ));if(a0)return;if(await Z(),a0)return;if(o3(),t3(),e3(),Z5(),Q5(),await n4(),a0)return;setInterval(()=>{n4()},1800000);let{reconcileTasklistDeletions:J}=await Promise.resolve().then(() => (zJ(),XJ));if(a0)return;try{await J()}catch(D){K(`tasklist deletion reconcile failed: ${D instanceof Error?D.message:D}`)}if(a0)return;let Y,Q=Date.now(),V=0,H=!1,X=null,z=1500,W=90000,G=600000,B=3,_=null,j=0,q="",P=!1,F=(D)=>{K(`[ws] rebuild requested before WS init — ${D}`)},T=(D,C=0,d=!1)=>{if(a0)return;let o=Date.now()+C;if(_){if(P||=d,o>=j){K(`[ws] rebuild already scheduled — ${D}`);return}clearTimeout(_)}j=o,q=D,P=d,_=setTimeout(()=>{let K0=q,W4=P;_=null,j=0,q="",P=!1,F(K0,W4)},C)},M={error:(D)=>K(`[ws-sdk error] ${hJ(D)}`),warn:(D)=>{let C=hJ(D);if(K(`[ws-sdk warn] ${C}`),C.includes("no pong/inbound"))T("ping-timeout: SDK liveness watchdog fired",2000,Date.now()-Q<G)},info:(D)=>K(`[ws-sdk] ${hJ(D)}`),debug:(D)=>{},trace:(D)=>{}},A=new X4.EventDispatcher({}),U=()=>{if(Q=Date.now(),V=0,X)clearTimeout(X),X=null};A.register({"im.message.receive_v1":async(D)=>{if(U(),!rG(D))throw Error("daemon shutdown in progress")}}),A.register({"card.action.trigger":async(D)=>{return U(),tG(D)}});let S=()=>new X4.WSClient({appId:f.feishu.app_id,appSecret:f.feishu.app_secret,loggerLevel:X4.LoggerLevel.info,logger:M,wsConfig:{pingTimeout:60},handshakeTimeoutMs:1e4,onReconnecting:()=>K("[ws] reconnecting — WS lost, SDK is retrying"),onReconnected:()=>v(),onError:(D)=>F(`SDK onError: ${D?.message??D}`)});F=(D,C=!1)=>{if(a0)return;if(H){K(`[ws] rebuild skipped (already rebuilding) — ${D}`);return}if(_)clearTimeout(_),_=null,j=0;H=!0,V++,K(`[ws] rebuild #${V} (fresh WSClient) — ${D}`);let d=Y;try{d?.close({force:!0})}catch(o){K(`[ws] rebuild: old close failed: ${o}`)}if(Y=S(),Y.start({eventDispatcher:A}).catch((o)=>{K(`[ws] rebuild start failed: ${o}`),T(`fresh client start failed: ${o}`,z,C)}),H=!1,C)b()};let b=()=>{if(X)clearTimeout(X);let D=Date.now();X=setTimeout(()=>{if(X=null,Q>=D){V=0;return}if(V>=B){K(`[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"),V=0;return}F(`verify: no event ${Math.round((Date.now()-D)/1000)}s after rebuild`,!0)},W)},v=()=>{let D=Date.now()-Q<G;K("[ws] reconnected — swapping in a fresh WSClient (cluster-routing precaution; "+`recentlyActive=${D})`),V=0,T("post-reconnect precaution",z,D)};Y=S();let y=15000,g=2,x=0,h=setInterval(()=>{if(a0)return;let{state:D}=Y.getConnectionStatus();if(D==="connected"){x=0;return}if(D==="failed"||D==="idle"){x=0,F(`watchdog: state=${D}`);return}if(x++,K(`[ws] watchdog: state=${D} (${x}/${g})`),x>=g)x=0,F(`watchdog: stuck in '${D}' ~${Math.round(y*g/1000)}s`)},y);nG=()=>{if(clearInterval(h),_)clearTimeout(_);if(X)clearTimeout(X);Y.close({force:!0})};let p=UX();iW({bind:f.notify.bind,port:f.notify.port,extraHandler:(D,C,d)=>TG(D,C,d,{service:gJ,authorizeSession:(o)=>{for(let K0 of d$.values())if(K0.acceptsAgentCapability(o))return K0;return null}})}),yG(),oW(),zG(),xG();let l=$2.enqueue();iG=UY(K,{enabled:f.runtime.agent_auto_update}),Y.start({eventDispatcher:A}).catch((D)=>{K(`[ws] initial start failed: ${D}`),T(`initial start failed: ${D}`,z,!1)}),K(`lodestar-daemon: WS start requested, watching ${q0.size} groups`),OU();for(let D of p)mJ(i$.enqueue(D.chatId,()=>J7.recover(D))).catch((C)=>K(`notify-reply recovery failed: ${C instanceof Error?C.message:C}`));await l}var lG=!1,a0=!1,$7=null,L1=0,iG,nG,dG=15000,aG=()=>{if(lG)return;lG=!0;try{$2.persist()}catch($){K(`alive marker write failed: ${$}`)}try{Z7(o0)}catch{}try{Z7(D1)}catch{}},d$,gJ,i$,$2,zU,oG,WU,pJ,jU=30000,H4,J7,DU;var eG=R(()=>{QJ();t();Y$();pW();U9();o6();o6();rW();tW();OG();vZ();x6();EG();SJ();SG();wG();y0();I();V2();Q0();j7();I3();uG();{let $=v9(o0);if($.state==="exit")console.error(`lodestar-daemon: already running (pid ${$.pid})`),process.exit(1);if(IJ(o0))try{Z7(o0)}catch{}}QU(XU(o0),{recursive:!0});tJ(o0);process.on("exit",aG);process.on("SIGTERM",()=>{z4("SIGTERM",0)});process.on("SIGINT",()=>{z4("SIGINT",0)});if(process.platform==="win32")process.on("SIGBREAK",()=>{z4("SIGBREAK",0)});process.on("unhandledRejection",($)=>{K(`unhandledRejection: ${$ instanceof Error?$.stack??$.message:$}`),z4("unhandledRejection",1)});process.on("uncaughtException",($)=>{K(`uncaughtException: ${$.stack??$.message}`),z4("uncaughtException",1)});d$=new Map,gJ=new kJ,i$=new g4,$2=new fJ({readMarker:W5,writeMarker:z5,sessions:()=>d$.values(),chatIdForSession:v8,sessionFor:sG,actor:i$,isShuttingDown:()=>a0,log:K}),zU=new h3(30000),oG=new Set,WU=JV({actor:i$,key:($)=>String($?.message?.chat_id??""),execute:($,Z)=>LU($,Z)});pJ=cG({registry:d$,createSession:($,Z)=>{let J=new G$($,Z,{onLifecycleChange:GU,onCreateTempSession:KU,onDisbandTempSession:BU,onCancelAgentRuns:(Y,Q,V)=>gJ.cancelSessionRuns(Y,Q,V)});return $2.transferPending(J),J},ensureChatForSession:K5,disbandChatForSessionExact:_5,chatIdForSession:v8,clearSessionConversationState:X5,registerTempSessionLease:r3,hasTempSessionLease:s3,replaceTurnAnchors:e0,runExclusive:($,Z)=>i$.enqueue($,Z),log:K});H4=new Set,J7=sW({sendCard:c,updateCard:A$,sendText:E,dispatch:xZ,onWaitingChanged:($)=>d$.get($)?.refreshPendingAsks(),log:K});DU=YV({actor:i$,deduper:zU,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=I$(String($?.action?.value?.notify_id??""));if(J)return J.chatId}return String($?.context?.open_chat_id??"")||"__notify_global__"},execute:MU,present:PU,presentExecutionFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");K(`handleCardAction ${J}: ${Z instanceof Error?Z.stack??Z.message:Z}`),await FU($,Z)},presentPresentationFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");K(`card-action presentation ${J}: ${Z instanceof Error?Z.message:Z}`),await e1(String($?.context?.open_chat_id??""),`⚠️ ${Y7(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?.__cardActionCompletion;return J&&typeof J.then==="function"?J:null},track:($)=>{mJ($)},onBackgroundError:($)=>{K(`card-action background: ${$ instanceof Error?$.stack??$.message:$}`)},responses:{accepted:($)=>({toast:{type:"info",content:`⏳ ${Y7(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}})}});RU().catch(($)=>{K(`boot fatal: ${$}`),z4("boot fatal",1)})});Q0();j7();import{existsSync as $K,unlinkSync as TU}from"node:fs";var K$={reset:"\x1B[0m",bold:"\x1B[1m",yellow:"\x1B[33m",green:"\x1B[32m",red:"\x1B[31m"};async function EU(){if(!$K(N0)){if(process.stdin.isTTY){console.log(),console.log(`${K$.bold}${K$.yellow}Lodestar: 未找到配置, 启动安装向导...${K$.reset}`);let{runSetup:Z}=await Promise.resolve().then(() => (EY(),TY));await Z();return}console.error(`${K$.red}Lodestar: 未找到配置 ${N0}${K$.reset}`),console.error(`请在交互式 cmd / PowerShell 里运行 ${K$.green}lodestar-setup${K$.reset} 完成首次配置 (或直接运行 ${K$.green}lodestar-daemon${K$.reset} 也会触发同一个向导)。`),process.exit(1)}let $=v9(o0);if($.state==="exit")console.error(`${K$.yellow}Lodestar: 已经有一个 daemon 在运行 (pid ${$.pid})${K$.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(` • 误判 / 已经死了: 手删 ${o0} 后再跑`),process.exit(1);if($K(o0))try{TU(o0)}catch{}await Promise.resolve().then(() => (eG(),NU))}EU().catch(($)=>{console.error("lodestar fatal:",$?.message??$),process.exit(1)});
|
|
547
|
+
`),imageKeys:Z,fileKeys:J}}async function LU($,Z=Date.now()){let J=$?.message;if(!J)return;let Q=($?.sender?.sender_id??$?.event?.sender?.sender_id??J?.sender?.sender_id)?.open_id??"",V=J.message_id;if(V&&H4.has(V))return;if(V){if(H4.add(V),H4.size>200){let A=[...H4];H4.clear();for(let U of A.slice(-100))H4.add(U)}}let H=Number(J.create_time??0);if(fG(H,Z,jU)){if(K(`drop stale message ${V} ageAtReceipt=${Math.round((Z-H)/1000)}s`),V)l0(V,"CrossMark");return}let X=J.chat_id,z={};try{z=JSON.parse(J.content??"{}")}catch{}let W=J.message_type==="text"?z.text??"":"";if(typeof W==="string"&&W.startsWith("[DEBUG]")){try{HU(y9,JSON.stringify({chat_id:X,sender_open_id:Q,seeded_at:new Date().toISOString(),seeded_msg_id:V??""},null,2)),K(`debug: seeded inject context chat=${X.slice(0,8)}… sender=${Q.slice(0,8)}…`)}catch(U){K(`debug: seed context failed: ${U}`)}let A=W.slice(7);z.text=A,J.content=JSON.stringify(z)}let G=q0.get(X);if(!G)await n4(),G=q0.get(X);if(!G)G=await _5(X)??void 0;if(!G){K(`unknown chat ${X}, dropping message`),await E(X,"❌ 无法识别群名。请确认:① 机器人已被拉进本群;② 群已设置名称(未命名群拿不到群名,无法映射项目目录)。设置后再发一条消息即可。");return}let B=P5(G);S2(B,X);let _=tG(X,B),j={};try{j=JSON.parse(J.content??"{}")}catch{}let q=J.message_type,P="",D=!1,T=[];if(q==="text")P=(j.text??"").trim();else if(q==="post"){let A=_U(j);D=A.imageKeys.length>0||A.fileKeys.length>0,P=A.markdown.trim();for(let U of A.imageKeys){let S=await a4(J.message_id,U,"image");if(S)T.push(S)}for(let U of A.fileKeys){let S=await a4(J.message_id,U.key,"file",U.name);if(S)T.push(S)}}if(q==="text"&&P){if(await _.runCommand(P,Q,V))return}if((q==="text"||q==="post")&&P&&!D&&await hG({reply:()=>Z7.consume({chatId:X,openId:Q,messageId:V??"",text:P,createTime:H,parentId:J.parent_id}),hasQuestion:()=>_.hasPendingAsk(),answerQuestion:()=>_.onAskMessageAnswer(P,Q,V??"")}))return;if(q==="text"&&P&&await _.consumeModelCustomMessage(P,Q))return;let M=gG(q,j);if(M){let A=await a4(J.message_id,M.key,M.type,M.name);if(!A){await E(X,IG(q));return}if(T.push(A),!P&&M.displayText)P=M.displayText}if(!P&&T.length===0){K(`drop empty message ${V} type=${q}`);return}if(await _.onMultiMessageInbound(P,T,Q,V??""))return;await _.onUserMessage(P||"(empty)",T,Q,V??"")}function J7($){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:"取消通知回复"}[$]??$}function qU($){return $?.card?.type==="raw"&&$.card.data&&typeof $.card.data==="object"?$.card.data:null}function z0($,Z,J){return{...$,__businessOk:Z,...J?{__businessMessage:J}:{}}}function l$($,Z){return{...Z,__cardActionMessageId:$.messageId,__cardActionChatId:$.chatId}}function u$($){return z0($.card?Q$($.card):{toast:{type:$.ok?"success":"error",content:$.message}},$.ok)}async function e1($,Z){if(!$){K(`card-action: cannot send receipt without chat_id: ${Z}`);return}if(!await w($,Z))K(`card-action: visible receipt MISS chat=${$.slice(0,8)}… text=${Z.slice(0,120)}`)}async function PU($,Z){if(Z?.__cardActionPresented)return;let J=String($?.action?.value?.kind??"unknown"),Y=J7(J),Q=String(Z?.__cardActionChatId??$?.__cardActionChatId??$?.context?.open_chat_id??""),V=String(Z?.__cardActionMessageId??$?.context?.open_message_id??""),H=qU(Z),X=Z?.__businessOk===!1&&typeof Z?.__businessMessage==="string"?` 业务失败: ${Z.__businessMessage.replace(/\s+/g," ").trim().slice(0,300)}。`:"";if(H&&V)try{await A$(V,H);return}catch(j){K(`card-action: ${J} original-card update failed: ${j instanceof Error?j.message:j}`),await e1(Q,`⚠️ ${Y}已处理,但原卡更新失败。${X}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":"请重新打开操作面板。"}`);return}if(H){await e1(Q,`⚠️ ${Y}已处理,但回调缺少原卡 message_id,无法更新。${X}${J==="temp_resume_select"?"请发送 rs 查看当前状态。":""}`);return}if(J==="notify_callback"&&Z?.__cardActionCompletion)return;let z=Z?.toast,W=typeof z?.content==="string"&&z.content.trim()?z.content.trim():`${Y}已完成`,G=J==="permission"&&String($?.action?.value?.decision??"")==="deny",B=Z?.__businessOk===!1||z?.type==="error"&&!G;if(!B&&new Set(["permission","ask","token_source_enable"]).has(J))return;await e1(Q,`${B?"❌":"✅"} ${Y}: ${W}`)}async function DU($,Z){let J=String($?.action?.value?.kind??"unknown"),Y=Z instanceof Error?Z.message:String(Z);await e1(String($?.__cardActionChatId??$?.context?.open_chat_id??""),`❌ ${J7(J)}失败: ${Y}`)}function eG($){return FU.accept($)}async function MU($){let Z=$?.action,J=Z?.value;if(!J?.kind)return;let Y=$?.context?.open_chat_id??"",Q=$?.operator?.open_id??"";if(J.kind==="notify_callback"||J.kind==="notify_reply"||J.kind==="notify_reply_cancel"){let H=String(J.notify_id??""),X=I$(H);if(X)$.__cardActionChatId=X.chatId;if(J.kind==="notify_callback")return await UU(J,Y,Q);let z=J.kind==="notify_reply"?await Z7.open(H,Y,Q):await Z7.cancel(H,String(J.reply_id??""),Y,Q),W=z0({toast:{type:z.ok?"success":"error",content:z.message},__cardActionPresented:z.presented===!0},z.ok);return X?l$(X,W):W}let V=d$.get(Y);if(!V)return z0({toast:{type:"error",content:"会话不存在,请先发消息启动"}},!1);switch(J.kind){case"permission":{let H=String(J.decision??"");if(!["allow","allow_always","deny"].includes(H))return{toast:{type:"error",content:"无效的权限决定"}};let X=await V.onPermissionDecision(J.request_id,H,Q);return z0({toast:{type:X.ok?H==="deny"?"error":"success":"error",content:X.message}},X.ok)}case"menu":{let H=Number(J.choice??-1);try{if(!Number.isInteger(H)||H<0)throw Error("无效的菜单选项");return await V.onUserMessage(`(menu choice ${H+1})`),z0(Q$(z1({title:"\uD83D\uDCCB 菜单选择",message:`已选择第 ${H+1} 项`,ok:!0})),!0)}catch(X){let z=X instanceof Error?X.message:String(X);return z0(Q$(z1({title:"\uD83D\uDCCB 菜单选择",message:z,ok:!1})),!1)}}case"provider_select":{let H=await V.onProviderSelect(String(J.source_id??""),String(J.panel_id??""));return u$(H)}case"model_page":{let H=await V.onModelPage(String(J.panel_id??""),String(J.source_id??""),Number(J.page));return u$(H)}case"model_list_open":{let H=String(J.panel_id??""),X=String(J.source_id??"");if(J.mode!=="add"&&J.mode!=="select")throw Error("模型管理模式无效");return u$(await(J.mode==="add"?V.onModelAddOpen(H,X):V.onProviderSelect(X,H)))}case"model_add":case"model_remove":case"model_custom_remove":return u$(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 H=await V.onModelSelect(String(J.model??""),String(J.panel_id??""),Q,J);return u$(H)}case"model_custom_prompt":{let H=await V.onModelCustomPrompt(String(J.source_id??""),String(J.panel_id??""),String($?.context?.open_message_id??""));return u$(H)}case"model_panel_cancel":{let H=await V.onModelPanelCancel(String(J.panel_id??""));return u$(H)}case"model_effort_select":{let H=await V.onModelEffortSelect(String(J.model??""),String(J.effort??""),String(J.panel_id??""),Q,String(J.provider??""));return u$(H)}case"ask":{let H=V.askBlockReason(String(J.tool_use_id??""));if(H)return z0({toast:{type:"error",content:H}},!1);if(J.custom){let W=(Z?.form_value??Z?.input??{})?.custom_answer??Z?.input_value??"",G=await V.onAskCustomAnswer(J.tool_use_id,J.question_idx??0,W,Q);return z0({toast:{type:G?"success":"error",content:G?"已回答":W.trim()?"问题已失效或答案未被接受":"请输入答案"}},G)}let X=await V.onAskAnswer(J.tool_use_id,J.question_idx??0,J.option_idx,Q);return z0({toast:{type:X?"success":"error",content:X?"已回答":"问题已失效或选项无效"}},X)}case"worktree_disband":{let H=await V.onWorktreeDisband(String(J.slug??""));return z0(Q$(H.card),H.ok)}case"temp_fork_select":{let H=await V.onForkSelect(String(J.panel_id??""),String(J.choice_id??""),Q);return z0(H.replaceCard===!1?{toast:{type:"error",content:H.message}}:Q$(z1({title:"\uD83D\uDD31 会话分叉",message:H.message,ok:H.ok})),H.ok)}case"temp_back_select":{let H=await V.onBackSelect(String(J.panel_id??""),String(J.choice_id??""),Q);return z0(H.replaceCard===!1?{toast:{type:"error",content:H.message}}:Q$(z1({title:"⏪ 会话回滚",message:H.message,ok:H.ok})),H.ok)}case"temp_resume_select":{let H=await V.onResumeSelect(String(J.panel_id??""),String(J.choice_id??""),Q);if(H.replaceCard===!1)return z0({toast:{type:"error",content:H.message}},H.ok);if(!H.resumePresentation)throw Error("rs selection result missing trusted presentation snapshot");return z0(Q$(JZ({...H.resumePresentation,message:H.message,ok:H.ok})),H.ok,H.message)}case"tasklist_enable":{let H=await V.onTasklistEnable();return z0(Q$(H.card),H.ok)}case"tasklist_delete_prompt":{let H=V.onTasklistDeletePrompt(String(J.guid??""));return z0(Q$(H.card),H.ok)}case"tasklist_delete_confirm":{let H=await V.onTasklistDeleteConfirm(String(J.guid??""));return z0(Q$(H.card),H.ok)}case"token_source_enable":{let{onTokenSourceEnable:H}=await Promise.resolve().then(() => (tZ(),sZ));return await H(V,String(J.source_id??"")),{toast:{type:"info",content:"已处理"}}}case"agent_identity_page":return u$(V.onAgentIdentityPage(String(J.panel_id??""),J.page,Q))}return{toast:{type:"info",content:"unknown action"}}}async function UU($,Z,J){let Y=String($?.notify_id??""),Q=String($?.button_id??"");if(!Y)return{toast:{type:"error",content:"回调缺少 notify_id"}};let V=I$(Y);if(!V)return K(`notify-callback: notify_id=${Y.slice(0,12)}… not found (expired or pre-restart)`),{toast:{type:"error",content:"通知已过期或已移除"}};if(V.unknownAt)return l$(V,z0({toast:{type:"error",content:`外部回调可能已成功,但本地确认状态未知,已禁止自动重试${V.unknownReason?`: ${V.unknownReason}`:""}`}},!0));if(V.resolvedAt)return l$(V,{toast:{type:"info",content:"已处理过"}});if(p2(Y))return l$(V,{toast:{type:"info",content:"处理中…"}});if(V.replyState?.status==="waiting"||V.replyState?.status==="sending")return l$(V,z0({toast:{type:"error",content:"正在等待文字回复,请先发送或取消回复,再选择按钮"}},!1));let H=V.buttons.find((W)=>W.id===Q);if(!H)return K(`notify-callback: notify_id=${Y.slice(0,12)}… unknown button_id="${Q}"`),l$(V,z0({toast:{type:"error",content:"未知按钮"}},!1));if(!V.callbackUrl){try{M9(V.notifyId,H.id,J)}catch(W){return l$(V,z0({toast:{type:"error",content:`保存反馈结果失败: ${W instanceof Error?W.message:W}`}},!1))}return K(`notify-callback: notify_id=${Y.slice(0,12)}… resolved button="${Q}" by=${J.slice(0,8)}… (no callback, pull/display)`),l$(V,{...Q$(t1(V,{status:"done",buttonId:H.id,text:H.text,operatorOpenId:J}))})}P9(V.notifyId);let X=gJ(AU(V,H,J));X.catch((W)=>{K(`notify-callback: notify_id=${V.notifyId.slice(0,12)}… phase-2 rejected: ${W instanceof Error?W.message:W}`)});let z=X.then((W)=>W==="retry"?"retry":"complete").catch(()=>"retry");return l$(V,{toast:{type:"info",content:`⏳ 已选择:${H.text} · 推送中…`},__cardActionCompletion:z})}async function AU($,Z,J){try{let Y=t1($,{status:"processing",buttonId:Z.id,text:Z.text,operatorOpenId:J});try{await A$($.messageId,Y)}catch(X){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-1 (processing) updateCard failed: ${X instanceof Error?X.message:X}`)}let Q=await EZ($,Z,J),V=Q.ok?"complete":"retry",H;if(Q.ok){let X=U6($.notifyId,Z.id,J);if(X.state==="complete")H={status:"delivered",buttonId:Z.id,text:Z.text,operatorOpenId:J,reply:Q.reply};else{V="unknown",H={status:"unknown",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:X.detail},K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… callback succeeded but tombstone is UNKNOWN: ${X.detail}`);try{await e1($.chatId,`⚠️ 通知反馈的外部回调已成功,但本地确认状态未知;为避免重复副作用,已禁止自动重试。${X.detail}`)}catch(z){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… UNKNOWN warning receipt failed: ${z instanceof Error?z.message:z}`)}}}else H={status:"failed",buttonId:Z.id,text:Z.text,operatorOpenId:J,detail:Q.detail};try{let X=t1($,H);await A$($.messageId,X)}catch(X){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… phase-2 (final) presentation failed: ${X instanceof Error?X.message:X}`);try{await e1($.chatId,`⚠️ 通知反馈${V==="retry"?"失败且结果卡更新失败,可重新点击":"已执行,但结果卡更新失败"}: ${X instanceof Error?X.message:X}`)}catch(z){K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… final fallback receipt failed: ${z instanceof Error?z.message:z}`)}}return K(`notify-callback: notify_id=${$.notifyId.slice(0,12)}… button="${Z.id}" ${V==="complete"?"delivered":V==="unknown"?"unknown/non-retryable":`failed: ${Q.detail}`} by=${J.slice(0,8)}…`),V}finally{D9($.notifyId)}}function fJ($){return $.map((Z)=>typeof Z==="string"?Z:JSON.stringify(Z)).join(" ")}function OU(){if(process.platform==="win32"){K("debug: inject socket skipped on Windows (dev-only feature)");return}if(typeof Bun>"u"){K("debug: inject socket skipped (Bun runtime only — npm/Node build does not include it)");return}try{if(hJ(F1))$7(F1)}catch{}try{Bun.serve({unix:F1,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(a0)return new Response("daemon shutdown in progress",{status:503});let Y={};if($.method==="POST")try{Y=await $.json()}catch{return new Response("bad json",{status:400})}if(!hJ(y9))return new Response("no debug context yet — send `[DEBUG]hi` from Feishu first",{status:412});let Q={};try{Q=JSON.parse(VU(y9,"utf8"))}catch(G){return new Response(`ctx read failed: ${G}`,{status:500})}let V=J?Z.searchParams.get("chat_id"):Y.chat_id;if(V!==void 0&&V!==Q.chat_id||Z.pathname!=="/"&&!V)return new Response("explicit debug chat_id must match the seeded context",{status:409});if(J){let G=d$.get(Q.chat_id);return G?Response.json(OJ(G)):new Response("send md to open a model panel first",{status:404})}if(Z.pathname==="/model-action"){let G=d$.get(Q.chat_id);if(!G)return new Response("debug session not found",{status:404});try{if(typeof Y.message_id!=="string"||!Y.message_id.startsWith("om_"))throw Error("message_id required");let B=typeof Y.value?.panel_id==="string"?Y.value.panel_id.trim():"",_=G.modelPanels.get(B);if(!_?.messageId||_.messageId!==Y.message_id)throw Error("stale or mismatched model panel");let j=await X0.im.v1.message.get({path:{message_id:Y.message_id}});if(j.code!==0)throw Error(`message.get failed: ${j.code} ${j.msg}`);let q=gW(Y,Q,j.data?.items?.[0],f.feishu.app_id,_.messageId);K(`debug: model action ${Y.value.kind} chat=${Q.chat_id.slice(0,8)}…`);let P=eG(q);return await i$.enqueue(Q.chat_id,async()=>{}),Response.json({admission:P,state:OJ(G)})}catch(B){return new Response(B instanceof Error?B.message:String(B),{status:400})}}if(Z.pathname!=="/")return new Response("unknown debug endpoint",{status:404});let H=String(Y.text??"");if(!H)return new Response("text required",{status:400});let X=`【自动化测试】:${H}`,z=await E(Q.chat_id,X);if(!z)return new Response("sendText failed — see daemon log",{status:502});let W={sender:{sender_id:{open_id:Q.sender_open_id}},message:{message_id:z,chat_id:Q.chat_id,message_type:"text",content:JSON.stringify({text:H}),create_time:String(Date.now())}};if(K(`debug: inject text=${JSON.stringify(H).slice(0,80)} msg_id=${z}`),!sG(W,"debug"))return new Response("daemon shutdown in progress",{status:503});if(Y.wait_for_handling===!0)await i$.enqueue(Q.chat_id,async()=>{});return new Response(JSON.stringify({ok:!0,msg_id:z}),{headers:{"content-type":"application/json"}})}});try{YU(F1,384)}catch{}K(`debug: inject socket listening at ${F1}`)}catch($){K(`debug: socket bind failed: ${$}`)}}async function RU(){K(`lodestar-daemon: pid ${process.pid} starting`),$2.load();let{buildTokenSourcesFromConfig:$}=await Promise.resolve().then(() => (oZ(),Xz));if(a0)return;$();let{refreshAllTokenSourceModels:Z}=await Promise.resolve().then(() => (V0(),uQ));if(a0)return;if(await Z(),a0)return;if(a3(),s3(),t3(),$5(),Y5(),await n4(),a0)return;setInterval(()=>{n4()},1800000);let{reconcileTasklistDeletions:J}=await Promise.resolve().then(() => (XJ(),HJ));if(a0)return;try{await J()}catch(F){K(`tasklist deletion reconcile failed: ${F instanceof Error?F.message:F}`)}if(a0)return;let Y,Q=Date.now(),V=0,H=!1,X=null,z=1500,W=90000,G=600000,B=3,_=null,j=0,q="",P=!1,D=(F)=>{K(`[ws] rebuild requested before WS init — ${F}`)},T=(F,C=0,d=!1)=>{if(a0)return;let o=Date.now()+C;if(_){if(P||=d,o>=j){K(`[ws] rebuild already scheduled — ${F}`);return}clearTimeout(_)}j=o,q=F,P=d,_=setTimeout(()=>{let K0=q,W4=P;_=null,j=0,q="",P=!1,D(K0,W4)},C)},M={error:(F)=>K(`[ws-sdk error] ${fJ(F)}`),warn:(F)=>{let C=fJ(F);if(K(`[ws-sdk warn] ${C}`),C.includes("no pong/inbound"))T("ping-timeout: SDK liveness watchdog fired",2000,Date.now()-Q<G)},info:(F)=>K(`[ws-sdk] ${fJ(F)}`),debug:(F)=>{},trace:(F)=>{}},A=new X4.EventDispatcher({}),U=()=>{if(Q=Date.now(),V=0,X)clearTimeout(X),X=null};A.register({"im.message.receive_v1":async(F)=>{if(U(),!sG(F))throw Error("daemon shutdown in progress")}}),A.register({"card.action.trigger":async(F)=>{return U(),eG(F)}});let S=()=>new X4.WSClient({appId:f.feishu.app_id,appSecret:f.feishu.app_secret,loggerLevel:X4.LoggerLevel.info,logger:M,wsConfig:{pingTimeout:60},handshakeTimeoutMs:1e4,onReconnecting:()=>K("[ws] reconnecting — WS lost, SDK is retrying"),onReconnected:()=>v(),onError:(F)=>D(`SDK onError: ${F?.message??F}`)});D=(F,C=!1)=>{if(a0)return;if(H){K(`[ws] rebuild skipped (already rebuilding) — ${F}`);return}if(_)clearTimeout(_),_=null,j=0;H=!0,V++,K(`[ws] rebuild #${V} (fresh WSClient) — ${F}`);let d=Y;try{d?.close({force:!0})}catch(o){K(`[ws] rebuild: old close failed: ${o}`)}if(Y=S(),Y.start({eventDispatcher:A}).catch((o)=>{K(`[ws] rebuild start failed: ${o}`),T(`fresh client start failed: ${o}`,z,C)}),H=!1,C)b()};let b=()=>{if(X)clearTimeout(X);let F=Date.now();X=setTimeout(()=>{if(X=null,Q>=F){V=0;return}if(V>=B){K(`[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"),V=0;return}D(`verify: no event ${Math.round((Date.now()-F)/1000)}s after rebuild`,!0)},W)},v=()=>{let F=Date.now()-Q<G;K("[ws] reconnected — swapping in a fresh WSClient (cluster-routing precaution; "+`recentlyActive=${F})`),V=0,T("post-reconnect precaution",z,F)};Y=S();let y=15000,g=2,x=0,h=setInterval(()=>{if(a0)return;let{state:F}=Y.getConnectionStatus();if(F==="connected"){x=0;return}if(F==="failed"||F==="idle"){x=0,D(`watchdog: state=${F}`);return}if(x++,K(`[ws] watchdog: state=${F} (${x}/${g})`),x>=g)x=0,D(`watchdog: stuck in '${F}' ~${Math.round(y*g/1000)}s`)},y);aG=()=>{if(clearInterval(h),_)clearTimeout(_);if(X)clearTimeout(X);Y.close({force:!0})};let p=MX();dW({bind:f.notify.bind,port:f.notify.port,extraHandler:(F,C,d)=>EG(F,C,d,{service:IJ,authorizeSession:(o)=>{for(let K0 of d$.values())if(K0.acceptsAgentCapability(o))return K0;return null}})}),wG(),aW(),XG(),SG();let l=$2.enqueue();nG=MY(K,{enabled:f.runtime.agent_auto_update}),Y.start({eventDispatcher:A}).catch((F)=>{K(`[ws] initial start failed: ${F}`),T(`initial start failed: ${F}`,z,!1)}),K(`lodestar-daemon: WS start requested, watching ${q0.size} groups`),OU();for(let F of p)gJ(i$.enqueue(F.chatId,()=>Z7.recover(F))).catch((C)=>K(`notify-reply recovery failed: ${C instanceof Error?C.message:C}`));await l}var dG=!1,a0=!1,e6=null,L1=0,nG,aG,iG=15000,oG=()=>{if(dG)return;dG=!0;try{$2.persist()}catch($){K(`alive marker write failed: ${$}`)}try{$7(o0)}catch{}try{$7(F1)}catch{}},d$,IJ,i$,$2,zU,rG,WU,mJ,jU=30000,H4,Z7,FU;var $K=R(()=>{YJ();t();Y$();mW();U9();a6();a6();oW();sW();RG();wZ();E6();xG();xJ();bG();vG();y0();I();V2();Q0();_7();h3();lG();{let $=w9(o0);if($.state==="exit")console.error(`lodestar-daemon: already running (pid ${$.pid})`),process.exit(1);if(hJ(o0))try{$7(o0)}catch{}}QU(XU(o0),{recursive:!0});sJ(o0);process.on("exit",oG);process.on("SIGTERM",()=>{z4("SIGTERM",0)});process.on("SIGINT",()=>{z4("SIGINT",0)});if(process.platform==="win32")process.on("SIGBREAK",()=>{z4("SIGBREAK",0)});process.on("unhandledRejection",($)=>{K(`unhandledRejection: ${$ instanceof Error?$.stack??$.message:$}`),z4("unhandledRejection",1)});process.on("uncaughtException",($)=>{K(`uncaughtException: ${$.stack??$.message}`),z4("uncaughtException",1)});d$=new Map,IJ=new CJ,i$=new g4,$2=new vJ({readMarker:z5,writeMarker:X5,sessions:()=>d$.values(),chatIdForSession:w8,sessionFor:tG,actor:i$,isShuttingDown:()=>a0,log:K}),zU=new f3(30000),rG=new Set,WU=ZV({actor:i$,key:($)=>String($?.message?.chat_id??""),execute:($,Z)=>LU($,Z)});mJ=uG({registry:d$,createSession:($,Z)=>{let J=new G$($,Z,{onLifecycleChange:GU,onCreateTempSession:KU,onDisbandTempSession:BU,onCancelAgentRuns:(Y,Q,V)=>IJ.cancelSessionRuns(Y,Q,V)});return $2.transferPending(J),J},ensureChatForSession:G5,disbandChatForSessionExact:B5,chatIdForSession:w8,clearSessionConversationState:H5,registerTempSessionLease:o3,hasTempSessionLease:r3,replaceTurnAnchors:e0,runExclusive:($,Z)=>i$.enqueue($,Z),log:K});H4=new Set,Z7=rW({sendCard:c,updateCard:A$,sendText:E,dispatch:EZ,onWaitingChanged:($)=>d$.get($)?.refreshPendingAsks(),log:K});FU=JV({actor:i$,deduper:zU,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=I$(String($?.action?.value?.notify_id??""));if(J)return J.chatId}return String($?.context?.open_chat_id??"")||"__notify_global__"},execute:MU,present:PU,presentExecutionFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");K(`handleCardAction ${J}: ${Z instanceof Error?Z.stack??Z.message:Z}`),await DU($,Z)},presentPresentationFailure:async($,Z)=>{let J=String($?.action?.value?.kind??"unknown");K(`card-action presentation ${J}: ${Z instanceof Error?Z.message:Z}`),await e1(String($?.context?.open_chat_id??""),`⚠️ ${J7(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?.__cardActionCompletion;return J&&typeof J.then==="function"?J:null},track:($)=>{gJ($)},onBackgroundError:($)=>{K(`card-action background: ${$ instanceof Error?$.stack??$.message:$}`)},responses:{accepted:($)=>({toast:{type:"info",content:`⏳ ${J7(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}})}});RU().catch(($)=>{K(`boot fatal: ${$}`),z4("boot fatal",1)})});Q0();_7();import{existsSync as ZK,unlinkSync as TU}from"node:fs";var K$={reset:"\x1B[0m",bold:"\x1B[1m",yellow:"\x1B[33m",green:"\x1B[32m",red:"\x1B[31m"};async function EU(){if(!ZK(N0)){if(process.stdin.isTTY){console.log(),console.log(`${K$.bold}${K$.yellow}Lodestar: 未找到配置, 启动安装向导...${K$.reset}`);let{runSetup:Z}=await Promise.resolve().then(() => (TY(),NY));await Z();return}console.error(`${K$.red}Lodestar: 未找到配置 ${N0}${K$.reset}`),console.error(`请在交互式 cmd / PowerShell 里运行 ${K$.green}lodestar-setup${K$.reset} 完成首次配置 (或直接运行 ${K$.green}lodestar-daemon${K$.reset} 也会触发同一个向导)。`),process.exit(1)}let $=w9(o0);if($.state==="exit")console.error(`${K$.yellow}Lodestar: 已经有一个 daemon 在运行 (pid ${$.pid})${K$.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(` • 误判 / 已经死了: 手删 ${o0} 后再跑`),process.exit(1);if(ZK(o0))try{TU(o0)}catch{}await Promise.resolve().then(() => ($K(),NU))}EU().catch(($)=>{console.error("lodestar fatal:",$?.message??$),process.exit(1)});
|