@sleep2agi/agent-node 2.5.0-preview.172 → 2.5.0-preview.173

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/build-info.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "commit": "46a936c91ed486453595c50484baeff34f12a34f",
3
+ "commit": "35a4ebc3b4b01533d2a3bff0d5eb981d8731b8de",
4
4
  "dirty": false,
5
- "built_at": "2026-11-01T07:23:34.707Z",
5
+ "built_at": "2026-11-01T07:33:02.316Z",
6
6
  "source": "git"
7
7
  }
package/dist/cli.js CHANGED
@@ -287,7 +287,7 @@ model_provider = "openai"
287
287
  `,{flag:"wx",mode:384}),this.sync(Q),GmA(A)}catch(B){if(B?.code!=="EEXIST")throw B;let I=this.read(Q);if(I.operationId!==A.operationId||I.fingerprint!==A.fingerprint||I.sideThreadId!==A.sideThreadId)throw Error("source thread already has an unresolved fork lease");return I}}put(A){RT(A);let Q=this.path(A.nodeId,A.sourceThreadHash),B=this.read(Q);if(B.operationId!==A.operationId||B.fingerprint!==A.fingerprint||B.sideThreadId!==A.sideThreadId)throw Error("fork lease ownership changed");if(A.updatedAt<B.updatedAt||B.state!==A.state&&!(B.state==="snapshot"&&A.state==="sent")&&!(B.state==="sent"&&A.state==="ambiguous"))throw Error(`invalid fork lease transition ${B.state}->${A.state}`);if(B.state!=="snapshot"&&JSON.stringify(B.snapshotThreadIdHashes)!==JSON.stringify(A.snapshotThreadIdHashes))throw Error("fork lease snapshot is immutable after send");let I=`${Q}.tmp.${process.pid}.${FmA()}`;FgA(I,`${JSON.stringify(A)}
288
288
  `,{flag:"wx",mode:384}),this.sync(I),JA(I,Q),ggA(Q,384),this.syncDir()}get(A,Q){let B=this.path(A,hQ(Q));return FN(B)?this.read(B):void 0}release(A,Q,B){let I=this.path(A,hQ(Q));if(!FN(I))return;if(this.read(I).operationId!==B)throw Error("fork lease release ownership mismatch");YmA(I),this.syncDir()}path(A,Q){if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(A))throw Error("invalid fork lease nodeId");if(!/^sha256:[0-9a-f]{64}$/.test(Q))throw Error("fork lease source hash required");return GgA(this.root,`${A}.${Q.slice(7)}.json`)}read(A){let Q=lW(A,YN.O_RDONLY|(YN.O_NOFOLLOW||0));try{let B=JgA(Q);if(!B.isFile()||B.nlink!==1)throw Error("fork lease must be a single-link regular file");UgA(Q,384);let I=JSON.parse(JmA(Q,"utf8"));return RT(I),I}finally{gG(Q)}}sync(A){let Q=lW(A,"r");try{YgA(Q)}finally{gG(Q)}this.syncDir()}syncDir(){let A=lW(this.root,"r");try{YgA(A)}finally{gG(A)}}}function RT(A){if(A?.version!==1||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(A.nodeId)||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(A.sideThreadId)||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(A.operationId)||!/^sha256:[0-9a-f]{64}$/.test(A.sourceThreadHash)||!/^sha256:[0-9a-f]{64}$/.test(A.fingerprint)||!/^(snapshot|sent|ambiguous)$/.test(A.state)||A.snapshotThreadIdHashes.some((Q)=>!/^sha256:[0-9a-f]{64}$/.test(Q)))throw Error("invalid fork lease")}function GmA(A){return{...A,snapshotThreadIdHashes:[...A.snapshotThreadIdHashes]}}var $gA=H(()=>{QQ();JN()});import{createHash as $mA,randomUUID as DmA}from"node:crypto";import{chmodSync as DgA,mkdirSync as NmA,writeFileSync as VmA}from"node:fs";import{join as ZmA}from"node:path";async function NgA(A,Q){if(!Q.nodeToken.startsWith("ntok_"))throw Error("bound node token required");let I=await(Q.fetchImpl??fetch)(`${Q.hubUrl.replace(/\/+$/,"")}/api/side-thread/attachment-grants/${encodeURIComponent(A.grantId)}`,{headers:{Authorization:`Bearer ${Q.nodeToken}`}});if(!I.ok)throw Error(`attachment grant refused: ${I.status}`);let C=I.headers.get("content-length");if(C!==null&&Number(C)!==A.size)throw Error("attachment grant size mismatch");if(A.size>52428800)throw Error("attachment grant exceeds node cap");let E=new Uint8Array(await I.arrayBuffer());if(E.byteLength!==A.size)throw Error("attachment grant size mismatch");let g=$mA("sha256").update(E).digest("hex");if(g!==A.sha256)throw Error("attachment grant digest mismatch");NmA(Q.cacheDir,{recursive:!0,mode:448}),DgA(Q.cacheDir,448);let U=ZmA(Q.cacheDir,`${A.fileId}-${A.sha256.slice(0,16)}`),J=`${U}.tmp.${process.pid}.${DmA()}`;return VmA(J,E,{flag:"wx",mode:384}),JA(J,U),DgA(U,384),{path:U,mediaType:A.mediaType,sha256:g,size:E.byteLength}}var VgA=H(()=>{QQ()});import{chmodSync as ZgA,closeSync as WgA,existsSync as XgA,fsyncSync as MgA,mkdirSync as WmA,openSync as zgA,readFileSync as LgA,readdirSync as XmA,unlinkSync as MmA,writeFileSync as zmA}from"node:fs";import{createHash as LmA,randomUUID as KmA}from"node:crypto";import{join as KgA}from"node:path";class wT{root;constructor(A){this.root=A;WmA(A,{recursive:!0,mode:448}),ZgA(A,448)}enqueue(A){let Q=this.path(A),B=`${JSON.stringify(A)}
289
289
  `;if(XgA(Q)){if(LgA(Q,"utf8")!==B)throw Error("terminal envelope is immutable");return}let I=`${Q}.tmp.${process.pid}.${KmA()}`;zmA(I,B,{flag:"wx",mode:384}),this.sync(I),JA(I,Q),ZgA(Q,384),this.syncDir()}list(){return XmA(this.root).filter((A)=>A.endsWith(".json")).sort().map((A)=>{let Q=JSON.parse(LgA(KgA(this.root,A),"utf8"));if(Q?.protocol!=="side_thread.terminal.v1")throw Error("invalid terminal outbox entry");return Q})}remove(A){let Q=this.path(A);if(XgA(Q))MmA(Q),this.syncDir()}path(A){let Q=JSON.stringify([A.sideThreadId,A.attemptId,A.threadId,A.turnId]);return KgA(this.root,`${LmA("sha256").update(Q).digest("hex")}.json`)}sync(A){let Q=zgA(A,"r");try{MgA(Q)}finally{WgA(Q)}}syncDir(){let A=zgA(this.root,"r");try{MgA(A)}finally{WgA(A)}}}var HgA=H(()=>{QQ()});var RgA={};GA(RgA,{startCliSideThreadConsumer:()=>RmA,detectCodexRuntimeVersion:()=>_mA,createProductionSideThreadNode:()=>_gA,SIDE_THREAD_EVIDENCE_REVISION:()=>qT,SIDE_THREAD_CODEX_VERSION:()=>jmA});import{execFileSync as HmA}from"node:child_process";import{join as $g}from"node:path";function _mA(A="codex"){try{return HmA(A,["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).match(/(?:codex(?:-cli)?\s+)?(\d+\.\d+\.\d+)/i)?.[1]??"unknown"}catch{return"unknown"}}function _gA(A){if(!A.enabled)return jgA("runtime");let Q=$g(A.codexHome,"agent-network-side-threads",A.nodeId),B=new pW($g(Q,"fork-leases")),I=new pW($g(Q,"command-claims")),C=new KT({client:A.client,runtimeVersion:A.runtimeVersion,topology:A.topology,evidenceRevision:qT,experimentalApi:A.experimentalApi,nodeId:A.nodeId,operationLedger:new MT($g(Q,"operations")),forkLeaseStore:B}),E=C.capability();if(!E.supported)return C.close(),jgA(E.reason??"runtime",E);let g=new wT($g(Q,"terminal-outbox")),U=new LT($g(Q,"bring-back"),async(D)=>{let N=await A.client.request("turn/start",{threadId:D.destinationThreadId,clientUserMessageId:`anet-btw-bring-back:${D.clientRequestId}`,input:[{type:"text",text:`[BTW bring-back]
290
- ${D.text}`}]}),V=N?.turn?.id??N?.turnId;if(!V)throw Error("Codex bring-back returned no turn identity");return{destinationTurnId:V}}),J=new _T({nodeId:A.nodeId,adapter:C,terminalOutbox:g,receipts:new jT($g(Q,"command-receipts")),claimExecution:({nodeId:D,sideThreadId:N,operationId:V})=>I.claimOperation(D,N,V),materializeAttachment:(D)=>NgA(D,{hubUrl:A.hubUrl,nodeToken:typeof A.token==="function"?A.token():A.token,cacheDir:$g(Q,"attachments"),fetchImpl:A.fetchImpl}),bringBack:(D)=>U.execute(D),onDroppedTerminal:(D)=>A.warn?.(`[side-thread] dropped terminal: ${D}`)}),Y=new HT({hubUrl:A.hubUrl,nodeId:A.nodeId,token:A.token,executor:J,terminalOutbox:g,fetchImpl:A.fetchImpl}),F=!1,G=()=>Y.trigger().catch((D)=>A.warn?.(`[side-thread] poll failed: ${D instanceof Error?D.message:String(D)}`)),$=setInterval(G,A.pollMs??1000);return $.unref?.(),G(),A.log?.(`[side-thread] dedicated consumer enabled (${E.runtimeVersion}, ${E.topology})`),{enabled:!0,capability:E,close(){if(F)return;F=!0,clearInterval($),Y.stop(),J.close(),C.close()}}}function jgA(A,Q){return{enabled:!1,capability:Q??{supported:!1,runtime:"codex-app-server",runtimeVersion:"unknown",topology:"unknown",evidenceRevision:qT,reason:A},close(){}}}var qT="test1190-wire-v2",jmA="0.148.0",RmA;var wgA=H(()=>{d0A();n0A();IgA();EgA();$gA();VgA();JN();HgA();RmA=_gA});var PgA={};GA(PgA,{sweepDeletedOnce:()=>OT,startDeletedSweeper:()=>PmA,_stopDeletedSweeperForTest:()=>SmA,SWEEP_INTERVAL_MS:()=>TgA,RETENTION_MS:()=>OgA});import{readdirSync as wmA,rmSync as qmA,statSync as OmA}from"node:fs";import{homedir as TmA}from"node:os";import{join as qgA}from"node:path";function OT(A={}){let Q=A.deletedRoot??qgA(TmA(),".anet","deleted"),B=A.now??Date.now(),I=A.log??(()=>{}),C=A.warn??((F)=>console.warn(F)),E=A.readdir??((F)=>wmA(F)),g=A.stat??((F)=>OmA(F)),U=A.rmDir??((F)=>qmA(F,{recursive:!0,force:!0})),J={purged:[],scanned:0,errors:0},Y;try{Y=E(Q)}catch{return J}for(let F of Y){J.scanned++;let G=F.match(/^(\d{10,})-/);if(!G)continue;let $=qgA(Q,F),D=!1;try{D=g($).isDirectory()}catch{continue}if(!D)continue;let N=Number(G[1]);if(!Number.isFinite(N)||N<=0)continue;let V=B-N;if(V<OgA)continue;try{U($);let Z=Math.floor(V/86400000);J.purged.push({name:F,age_days:Z}),I(`[deleted-sweeper] purged ${F} (age ${Z}d)`)}catch(Z){J.errors++,C(`[deleted-sweeper] failed to purge ${F}: ${Z?.message||Z}`)}}return J}function PmA(A={}){if(Q0)return Q0;try{OT(A)}catch{}if(Q0=setInterval(()=>{try{OT(A)}catch{}},TgA),typeof Q0.unref==="function")Q0.unref();return Q0}function SmA(){if(Q0)clearInterval(Q0),Q0=null}var OgA=2592000000,TgA=86400000,Q0=null;var SgA=()=>{};var xgA={};GA(xgA,{startLoopsHttpServer:()=>fmA});import{randomBytes as xmA}from"crypto";import{createServer as kmA}from"node:http";function TT(A,Q){return{jsonrpc:"2.0",id:A,result:Q}}function dW(A,Q,B,I){return{jsonrpc:"2.0",id:A,error:{code:Q,message:B,...I!==void 0?{data:I}:{}}}}function vmA(A){let Q={};if(A.name==="create_my_loop")Q.task={type:"string"},Q.interval={type:"string"},Q.schedule={type:"object"};else if(A.name==="edit_my_loop")Q.goal_id={type:"string"},Q.task={type:"string"},Q.interval={type:"string"},Q.schedule={type:"object"},Q.paused={type:"boolean"};else if(A.name==="reschedule_my_loop")Q.goal_id={type:"string"},Q.next_wake_in={type:"string"};else if(A.name==="complete_my_loop"||A.name==="cancel_my_loop"){if(Q.goal_id={type:"string"},A.name==="cancel_my_loop")Q.confirm_token={type:"string"}}return{name:A.name,description:A.description,inputSchema:{type:"object",properties:Q,required:A.name==="list_my_loops"?[]:["goal_id"].filter((B)=>(B in Q))}}}async function bmA(A,Q){let{id:B,method:I,params:C}=A||{};if(I==="initialize")return TT(B,{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"loops",version:"0.1.0"}});if(I==="tools/list")return TT(B,{tools:m2.map(vmA)});if(I==="tools/call"){let E=C?.name,g=C?.arguments??{},U=m2.find((Y)=>Y.name===E);if(!U)return dW(B,-32601,`Tool not found: ${E}`);let J=await U.handler(g,Q);return TT(B,{content:[{type:"text",text:JSON.stringify(J)}],isError:!J.ok})}return dW(B,-32601,`Method not found: ${I}`)}function ymA(A){return new Promise((Q,B)=>{let I=[];A.on("data",(C)=>I.push(C)),A.on("end",()=>Q(Buffer.concat(I).toString("utf8"))),A.on("error",B)})}function iW(A,Q,B){A.statusCode=Q,A.setHeader("content-type","application/json"),A.end(JSON.stringify(B))}async function fmA(A){let Q=A.token??xmA(16).toString("base64url"),B=kmA(async(E,g)=>{let U=E.url?.split("?")[0];if(!U||E.method!=="POST"||U!=="/mcp"){g.statusCode=404,g.end("not found");return}let J=E.headers.authorization||"";if(typeof J!=="string"||!J.startsWith("Bearer ")||J.slice(7)!==Q){iW(g,401,{error:"unauthorized"});return}let Y;try{let F=await ymA(E);Y=F?JSON.parse(F):null}catch{iW(g,400,dW(null,-32700,"Parse error"));return}try{let F=await bmA(Y,A.ctx);iW(g,200,F)}catch(F){iW(g,500,dW(Y?.id??null,-32603,`Internal error: ${F?.message??F}`))}});await new Promise((E,g)=>{B.once("error",g),B.listen(A.port??0,"127.0.0.1",()=>{B.removeListener("error",g),E()})});let I=B.address(),C=typeof I==="object"&&I?I.port:0;return{url:`http://127.0.0.1:${C}/mcp`,token:Q,port:C,close:()=>new Promise((E,g)=>B.close((U)=>U?g(U):E()))}}var kgA=H(()=>{Fq()});function LJA(A){return String(A.role??A.type??"")}function KJA(A){let Q=A.content??A.parts??[],B="";for(let I of Q)if(I&&typeof I.text==="string")B+=I.text;return B.trim()}function yP(A,Q){let B=A.findIndex((g)=>g.id===Q);if(B<0)return{state:"missing"};let E=A.slice(0,B).reverse().filter((g)=>LJA(g)==="assistant").map(KJA).filter((g)=>g.length>0).at(-1);if(E)return{state:"done",text:E};return{state:"pending"}}async function fP(A,Q,B,I=40){try{let E=(await AQ(A,Q,`/api/session/${B}/message?order=desc&limit=${I}`,{},8000))?.data;return Array.isArray(E)?E:null}catch{return null}}QQ();import{mkdirSync as jJA,readdirSync as _JA,readFileSync as RJA,rmSync as hP,writeFileSync as wJA}from"node:fs";import{join as xN}from"node:path";var qJA="pending-late-replies";function HX(A){return xN(A,qJA)}function mP(A){return`${A.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)||"unknown"}.json`}function uP(A,Q){let B=HX(A);try{jJA(B,{recursive:!0});let I=xN(B,mP(Q.taskId)),C=`${I}.tmp`;return wJA(C,JSON.stringify(Q,null,2),"utf8"),JA(C,I),!0}catch{return!1}}function jX(A,Q){try{return hP(xN(HX(A),mP(Q)),{force:!0}),!0}catch{return!1}}function cP(A){let Q=HX(A),B;try{B=_JA(Q)}catch{return{records:[],corrupted:0}}let I=[],C=0;for(let E of B){if(!E.endsWith(".json"))continue;let g=xN(Q,E);try{let U=JSON.parse(RJA(g,"utf8"));if(typeof U?.taskId!=="string"||!U.taskId||typeof U?.threadId!=="string"||!U.threadId||typeof U?.turnId!=="string"||!U.turnId)throw Error("incomplete record");I.push({taskId:U.taskId,threadId:U.threadId,turnId:U.turnId,sessionId:typeof U.sessionId==="string"?U.sessionId:U.threadId,armedAt:typeof U.armedAt==="string"?U.armedAt:"",deadlineAt:typeof U.deadlineAt==="string"?U.deadlineAt:""})}catch{C+=1;try{hP(g,{force:!0})}catch{}}}return{records:I,corrupted:C}}var lP=["【轮询纪律】","- 等子任务时不要连环调 get_task。实测(2026-10-29/30):一个节点在空闲等待里以约 13 次/分钟"," 连续拉了 8 小时 get_task(约 6000 次),每次都是一轮 LLM —— 成本全花在「看有没有好」。","- 间隔至少 60 秒;子任务要跑很久时,可以隔几分钟看一次。你不需要盯着它。","- 子任务的最终结果本来就会自动 chain 回上游(parent_task_id),所以「没盯着」不会丢结果。"],pP="- mcp__commhub__get_task(task_id) — 查子任务状态;**两次之间至少隔 60 秒**(见下方【轮询纪律】)。",iP=["3. 用 get_task 查子任务状态,直到 status=replied/failed —— **但两次之间至少隔 60 秒**,"," 见下方【轮询纪律】:每次 get_task 都是一整轮 LLM 调用,连续打等于把一个等待烧成几百轮推理。"],dP=["【不要反复确认自己】","- `org_whoami` 的答案在进程启动时就定了,同一次会话里反复调用不会有新信息。"," 实测(2026-11-01):90 个节点 6 小时里调了 6,474 次 whoami + 5,738 次 get_all_status = 全部调用的 56%。","- 有没有新活,Hub 会**推**给你;不需要靠轮询 `get_all_status` 去发现。","- 确实需要查时,两次之间至少隔 5 分钟,并且要有理由(例如刚派了任务、要看对方是否在线)。"];var _X=45000;async function nP(A,Q,B){let I;try{return await Promise.race([A,new Promise((C,E)=>{I=setTimeout(()=>E(Error(B)),Q),I?.unref?.()})])}finally{if(I)clearTimeout(I)}}QQ();RX();var wX="/api/node-session-control",TJA=new Set(["session_control_unavailable","session_control_changed","session_control_unsupported","session_control_invalid_response","session_control_request_invalid","session_control_request_expired","session_control_request_limit","session_background_outcome_unknown"]);function rP(A){let{token:Q,nodeId:B,networkId:I,epoch:C}=A,E=A.hubUrl.replace(/\/+$/,""),g=Object.freeze({node_id:B,network_id:I}),U=new AbortController,J=()=>{U.abort()};if(A.signal.aborted)J();else A.signal.addEventListener("abort",J,{once:!0});let Y=()=>{if(U.signal.aborted||!Q.startsWith("ntok_")||!B||!I||A.currentToken()!==Q||A.currentEpoch()!==C)throw J(),new hI("session_control_changed")};return{expected:g,signal:U.signal,checkpoint:Y,invalidate:J,async post(F,G){if(Y(),!/^\/api\/node-session-control\/(?:bridge|pull|(?:bg|sc)_[0-9]{13}_[A-Za-z0-9_-]{8,64}\/ack)$/.test(F))throw new hI("session_control_request_invalid");let $=await(A.fetch??globalThis.fetch)(`${E}${F}`,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"content-type":"application/json"},body:JSON.stringify(G),redirect:"error",signal:AbortSignal.any([U.signal,AbortSignal.timeout(5000)])});if(Y(),!$.ok)throw new hI("session_control_unavailable");let D=await $.json();return Y(),D}}}function sP(A){let Q=null,B=null,I=null,C=null,E=(G)=>{try{return A.identity.checkpoint(),A.session()===G.session&&G.session.isRunning}catch{return!1}};async function g(){A.identity.checkpoint();let G=A.session();if(!G?.isRunning||!G.backgroundControl)return Q=null,null;if(Q?.session===G)return Q;let $=await G.backgroundControl.state();if(A.identity.checkpoint(),A.session()!==G||!G.isRunning||$.session_id!==G.sessionId)return null;return Q={session:G,session_id:$.session_id,binding_id:$.binding_id}}let U=(G)=>({session_id:G.session_id,binding_id:G.binding_id});async function J(){try{let G=await g();if(!G||!E(G))return!1;let $=await A.identity.post(`${wX}/bridge`,{...U(G),expected:A.identity.expected});if(!E(G))return!1;let D=$?.identity;if($?.ok!==!0||D?.node_id!==A.identity.expected.node_id||D?.network_id!==A.identity.expected.network_id||typeof D?.token_id!=="string"||!D.token_id||D.token_id.length>200||D.token_id.trim()!==D.token_id||I!==null&&I!==D.token_id)return B=null,A.identity.invalidate(),!1;return I=D.token_id,B=G,!0}catch{return A.warn("[session-control] registration unavailable; no session action taken"),!1}}async function Y(){for(let G=0;G<8;G++){if(!B)return;let $=await g();if(!$||B!==$||!E($))return;let D={signal:A.identity.signal,checkpoint(){if(A.identity.checkpoint(),B!==$||!E($))throw new hI("session_control_changed")}},N=await A.identity.post(`${wX}/pull`,U($));if(D.checkpoint(),!N?.ok||!N.request)return;let V=N.request;if(typeof V.request_id!=="string"||!/^(?:bg|sc)_[0-9]{13}_[A-Za-z0-9_-]{8,64}$/.test(V.request_id))return;let Z;try{if(!E($)||V.session_id!==$.session_id||V.binding_id!==$.binding_id)throw new hI("session_control_changed");if(!Number.isFinite(V.expires_at)||V.expires_at<Date.now())throw new hI("session_control_request_expired");let W;if(V.operation==="state")W=await $.session.backgroundControl.state();else if(V.operation==="background")W=await $.session.backgroundControl.background({...U($),request_id:V.request_id,expires_at:V.expires_at},D);else throw new hI("session_control_request_invalid");D.checkpoint(),Z={status:"done",result:W}}catch(W){Z={status:"failed",error:W instanceof hI&&TJA.has(W.code)?W.code:"session_control_unavailable"}}D.checkpoint(),await A.identity.post(`${wX}/${encodeURIComponent(V.request_id)}/ack`,{...U($),...Z})}}function F(){if(C)return C;return C=Y().catch(()=>{A.warn("[session-control] transport unavailable; operation was not replayed")}).finally(()=>{C=null}),C}return{register:J,trigger:F}}import{spawnSync as PJA}from"node:child_process";import{existsSync as SJA,readFileSync as xJA}from"node:fs";import{dirname as eP,join as qX}from"node:path";import{fileURLToPath as kJA}from"node:url";var vJA=3000;function kN(A){if(!A)return;let Q=/(\d+)\.(\d+)\.(\d+)/.exec(A);return Q?`${Q[1]}.${Q[2]}.${Q[3]}`:void 0}function OX(A,Q){let B=(kN(A)??"0.0.0").split(".").map(Number),I=(kN(Q)??"0.0.0").split(".").map(Number);for(let C=0;C<3;C++){let E=(B[C]??0)-(I[C]??0);if(E!==0)return E}return 0}var bJA=(A,Q)=>{try{let B=PJA(A,["--version"],{encoding:"utf8",timeout:Q,stdio:["ignore","pipe","pipe"]});if(B.error||B.status!==0)return;return kN(`${B.stdout??""}
290
+ ${D.text}`}]}),V=N?.turn?.id??N?.turnId;if(!V)throw Error("Codex bring-back returned no turn identity");return{destinationTurnId:V}}),J=new _T({nodeId:A.nodeId,adapter:C,terminalOutbox:g,receipts:new jT($g(Q,"command-receipts")),claimExecution:({nodeId:D,sideThreadId:N,operationId:V})=>I.claimOperation(D,N,V),materializeAttachment:(D)=>NgA(D,{hubUrl:A.hubUrl,nodeToken:typeof A.token==="function"?A.token():A.token,cacheDir:$g(Q,"attachments"),fetchImpl:A.fetchImpl}),bringBack:(D)=>U.execute(D),onDroppedTerminal:(D)=>A.warn?.(`[side-thread] dropped terminal: ${D}`)}),Y=new HT({hubUrl:A.hubUrl,nodeId:A.nodeId,token:A.token,executor:J,terminalOutbox:g,fetchImpl:A.fetchImpl}),F=!1,G=()=>Y.trigger().catch((D)=>A.warn?.(`[side-thread] poll failed: ${D instanceof Error?D.message:String(D)}`)),$=setInterval(G,A.pollMs??1000);return $.unref?.(),G(),A.log?.(`[side-thread] dedicated consumer enabled (${E.runtimeVersion}, ${E.topology})`),{enabled:!0,capability:E,close(){if(F)return;F=!0,clearInterval($),Y.stop(),J.close(),C.close()}}}function jgA(A,Q){return{enabled:!1,capability:Q??{supported:!1,runtime:"codex-app-server",runtimeVersion:"unknown",topology:"unknown",evidenceRevision:qT,reason:A},close(){}}}var qT="test1190-wire-v2",jmA="0.148.0",RmA;var wgA=H(()=>{d0A();n0A();IgA();EgA();$gA();VgA();JN();HgA();RmA=_gA});var PgA={};GA(PgA,{sweepDeletedOnce:()=>OT,startDeletedSweeper:()=>PmA,_stopDeletedSweeperForTest:()=>SmA,SWEEP_INTERVAL_MS:()=>TgA,RETENTION_MS:()=>OgA});import{readdirSync as wmA,rmSync as qmA,statSync as OmA}from"node:fs";import{homedir as TmA}from"node:os";import{join as qgA}from"node:path";function OT(A={}){let Q=A.deletedRoot??qgA(TmA(),".anet","deleted"),B=A.now??Date.now(),I=A.log??(()=>{}),C=A.warn??((F)=>console.warn(F)),E=A.readdir??((F)=>wmA(F)),g=A.stat??((F)=>OmA(F)),U=A.rmDir??((F)=>qmA(F,{recursive:!0,force:!0})),J={purged:[],scanned:0,errors:0},Y;try{Y=E(Q)}catch{return J}for(let F of Y){J.scanned++;let G=F.match(/^(\d{10,})-/);if(!G)continue;let $=qgA(Q,F),D=!1;try{D=g($).isDirectory()}catch{continue}if(!D)continue;let N=Number(G[1]);if(!Number.isFinite(N)||N<=0)continue;let V=B-N;if(V<OgA)continue;try{U($);let Z=Math.floor(V/86400000);J.purged.push({name:F,age_days:Z}),I(`[deleted-sweeper] purged ${F} (age ${Z}d)`)}catch(Z){J.errors++,C(`[deleted-sweeper] failed to purge ${F}: ${Z?.message||Z}`)}}return J}function PmA(A={}){if(Q0)return Q0;try{OT(A)}catch{}if(Q0=setInterval(()=>{try{OT(A)}catch{}},TgA),typeof Q0.unref==="function")Q0.unref();return Q0}function SmA(){if(Q0)clearInterval(Q0),Q0=null}var OgA=2592000000,TgA=86400000,Q0=null;var SgA=()=>{};var xgA={};GA(xgA,{startLoopsHttpServer:()=>fmA});import{randomBytes as xmA}from"crypto";import{createServer as kmA}from"node:http";function TT(A,Q){return{jsonrpc:"2.0",id:A,result:Q}}function dW(A,Q,B,I){return{jsonrpc:"2.0",id:A,error:{code:Q,message:B,...I!==void 0?{data:I}:{}}}}function vmA(A){let Q={};if(A.name==="create_my_loop")Q.task={type:"string"},Q.interval={type:"string"},Q.schedule={type:"object"};else if(A.name==="edit_my_loop")Q.goal_id={type:"string"},Q.task={type:"string"},Q.interval={type:"string"},Q.schedule={type:"object"},Q.paused={type:"boolean"};else if(A.name==="reschedule_my_loop")Q.goal_id={type:"string"},Q.next_wake_in={type:"string"};else if(A.name==="complete_my_loop"||A.name==="cancel_my_loop"){if(Q.goal_id={type:"string"},A.name==="cancel_my_loop")Q.confirm_token={type:"string"}}return{name:A.name,description:A.description,inputSchema:{type:"object",properties:Q,required:A.name==="list_my_loops"?[]:["goal_id"].filter((B)=>(B in Q))}}}async function bmA(A,Q){let{id:B,method:I,params:C}=A||{};if(I==="initialize")return TT(B,{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"loops",version:"0.1.0"}});if(I==="tools/list")return TT(B,{tools:m2.map(vmA)});if(I==="tools/call"){let E=C?.name,g=C?.arguments??{},U=m2.find((Y)=>Y.name===E);if(!U)return dW(B,-32601,`Tool not found: ${E}`);let J=await U.handler(g,Q);return TT(B,{content:[{type:"text",text:JSON.stringify(J)}],isError:!J.ok})}return dW(B,-32601,`Method not found: ${I}`)}function ymA(A){return new Promise((Q,B)=>{let I=[];A.on("data",(C)=>I.push(C)),A.on("end",()=>Q(Buffer.concat(I).toString("utf8"))),A.on("error",B)})}function iW(A,Q,B){A.statusCode=Q,A.setHeader("content-type","application/json"),A.end(JSON.stringify(B))}async function fmA(A){let Q=A.token??xmA(16).toString("base64url"),B=kmA(async(E,g)=>{let U=E.url?.split("?")[0];if(!U||E.method!=="POST"||U!=="/mcp"){g.statusCode=404,g.end("not found");return}let J=E.headers.authorization||"";if(typeof J!=="string"||!J.startsWith("Bearer ")||J.slice(7)!==Q){iW(g,401,{error:"unauthorized"});return}let Y;try{let F=await ymA(E);Y=F?JSON.parse(F):null}catch{iW(g,400,dW(null,-32700,"Parse error"));return}try{let F=await bmA(Y,A.ctx);iW(g,200,F)}catch(F){iW(g,500,dW(Y?.id??null,-32603,`Internal error: ${F?.message??F}`))}});await new Promise((E,g)=>{B.once("error",g),B.listen(A.port??0,"127.0.0.1",()=>{B.removeListener("error",g),E()})});let I=B.address(),C=typeof I==="object"&&I?I.port:0;return{url:`http://127.0.0.1:${C}/mcp`,token:Q,port:C,close:()=>new Promise((E,g)=>B.close((U)=>U?g(U):E()))}}var kgA=H(()=>{Fq()});function LJA(A){return String(A.role??A.type??"")}function KJA(A){let Q=A.content??A.parts??[],B="";for(let I of Q)if(I&&typeof I.text==="string")B+=I.text;return B.trim()}function yP(A,Q){let B=A.findIndex((g)=>g.id===Q);if(B<0)return{state:"missing"};let E=A.slice(0,B).reverse().filter((g)=>LJA(g)==="assistant").map(KJA).filter((g)=>g.length>0).at(-1);if(E)return{state:"done",text:E};return{state:"pending"}}async function fP(A,Q,B,I=40){try{let E=(await AQ(A,Q,`/api/session/${B}/message?order=desc&limit=${I}`,{},8000))?.data;return Array.isArray(E)?E:null}catch{return null}}QQ();import{mkdirSync as jJA,readdirSync as _JA,readFileSync as RJA,rmSync as hP,writeFileSync as wJA}from"node:fs";import{join as xN}from"node:path";var qJA="pending-late-replies";function HX(A){return xN(A,qJA)}function mP(A){return`${A.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)||"unknown"}.json`}function uP(A,Q){let B=HX(A);try{jJA(B,{recursive:!0});let I=xN(B,mP(Q.taskId)),C=`${I}.tmp`;return wJA(C,JSON.stringify(Q,null,2),"utf8"),JA(C,I),!0}catch{return!1}}function jX(A,Q){try{return hP(xN(HX(A),mP(Q)),{force:!0}),!0}catch{return!1}}function cP(A){let Q=HX(A),B;try{B=_JA(Q)}catch{return{records:[],corrupted:0}}let I=[],C=0;for(let E of B){if(!E.endsWith(".json"))continue;let g=xN(Q,E);try{let U=JSON.parse(RJA(g,"utf8"));if(typeof U?.taskId!=="string"||!U.taskId||typeof U?.threadId!=="string"||!U.threadId||typeof U?.turnId!=="string"||!U.turnId)throw Error("incomplete record");I.push({taskId:U.taskId,threadId:U.threadId,turnId:U.turnId,sessionId:typeof U.sessionId==="string"?U.sessionId:U.threadId,armedAt:typeof U.armedAt==="string"?U.armedAt:"",deadlineAt:typeof U.deadlineAt==="string"?U.deadlineAt:""})}catch{C+=1;try{hP(g,{force:!0})}catch{}}}return{records:I,corrupted:C}}var lP=["【轮询纪律】","- 等子任务时不要连环调 get_task。实测(2026-10-29/30):一个节点在空闲等待里以约 13 次/分钟"," 连续拉了 8 小时 get_task(约 6000 次),每次都是一轮 LLM —— 成本全花在「看有没有好」。","- 间隔至少 60 秒;子任务要跑很久时,可以隔几分钟看一次。你不需要盯着它。","- 子任务的最终结果本来就会自动 chain 回上游(parent_task_id),所以「没盯着」不会丢结果。"],pP="- mcp__commhub__get_task(task_id) — 查子任务状态;**两次之间至少隔 60 秒**(见下方【轮询纪律】)。",iP=["3. 用 get_task 查子任务状态,直到 status=replied/failed —— **但两次之间至少隔 60 秒**,"," 见下方【轮询纪律】:每次 get_task 都是一整轮 LLM 调用,连续打等于把一个等待烧成几百轮推理。"],dP=["【不要反复确认自己】","- `org_whoami` 的答案在进程启动时就定了,同一次会话里反复调用不会有新信息。"," 实测(2026-11-01):90 个节点 6 小时里调了 6,474 次 whoami + 5,738 次 get_all_status = 全部调用的 56%。","- 有没有新活,Hub 会**推**给你;不需要靠轮询 `get_all_status` 去发现。","- 确实需要查时,两次之间至少隔 5 分钟,并且要有理由(例如刚派了任务、要看对方是否在线)。","- 同一类还有 `list_tasks`(19.2%)与 `get_task`(9.4%):四项相加 = 全部调用的 **84.9%**。"," 它们回答的都是「现在有没有新东西」,而 Hub 已经用推送回答过你了;反复问只是把等待烧成推理。"];var _X=45000;async function nP(A,Q,B){let I;try{return await Promise.race([A,new Promise((C,E)=>{I=setTimeout(()=>E(Error(B)),Q),I?.unref?.()})])}finally{if(I)clearTimeout(I)}}QQ();RX();var wX="/api/node-session-control",TJA=new Set(["session_control_unavailable","session_control_changed","session_control_unsupported","session_control_invalid_response","session_control_request_invalid","session_control_request_expired","session_control_request_limit","session_background_outcome_unknown"]);function rP(A){let{token:Q,nodeId:B,networkId:I,epoch:C}=A,E=A.hubUrl.replace(/\/+$/,""),g=Object.freeze({node_id:B,network_id:I}),U=new AbortController,J=()=>{U.abort()};if(A.signal.aborted)J();else A.signal.addEventListener("abort",J,{once:!0});let Y=()=>{if(U.signal.aborted||!Q.startsWith("ntok_")||!B||!I||A.currentToken()!==Q||A.currentEpoch()!==C)throw J(),new hI("session_control_changed")};return{expected:g,signal:U.signal,checkpoint:Y,invalidate:J,async post(F,G){if(Y(),!/^\/api\/node-session-control\/(?:bridge|pull|(?:bg|sc)_[0-9]{13}_[A-Za-z0-9_-]{8,64}\/ack)$/.test(F))throw new hI("session_control_request_invalid");let $=await(A.fetch??globalThis.fetch)(`${E}${F}`,{method:"POST",headers:{Authorization:`Bearer ${Q}`,"content-type":"application/json"},body:JSON.stringify(G),redirect:"error",signal:AbortSignal.any([U.signal,AbortSignal.timeout(5000)])});if(Y(),!$.ok)throw new hI("session_control_unavailable");let D=await $.json();return Y(),D}}}function sP(A){let Q=null,B=null,I=null,C=null,E=(G)=>{try{return A.identity.checkpoint(),A.session()===G.session&&G.session.isRunning}catch{return!1}};async function g(){A.identity.checkpoint();let G=A.session();if(!G?.isRunning||!G.backgroundControl)return Q=null,null;if(Q?.session===G)return Q;let $=await G.backgroundControl.state();if(A.identity.checkpoint(),A.session()!==G||!G.isRunning||$.session_id!==G.sessionId)return null;return Q={session:G,session_id:$.session_id,binding_id:$.binding_id}}let U=(G)=>({session_id:G.session_id,binding_id:G.binding_id});async function J(){try{let G=await g();if(!G||!E(G))return!1;let $=await A.identity.post(`${wX}/bridge`,{...U(G),expected:A.identity.expected});if(!E(G))return!1;let D=$?.identity;if($?.ok!==!0||D?.node_id!==A.identity.expected.node_id||D?.network_id!==A.identity.expected.network_id||typeof D?.token_id!=="string"||!D.token_id||D.token_id.length>200||D.token_id.trim()!==D.token_id||I!==null&&I!==D.token_id)return B=null,A.identity.invalidate(),!1;return I=D.token_id,B=G,!0}catch{return A.warn("[session-control] registration unavailable; no session action taken"),!1}}async function Y(){for(let G=0;G<8;G++){if(!B)return;let $=await g();if(!$||B!==$||!E($))return;let D={signal:A.identity.signal,checkpoint(){if(A.identity.checkpoint(),B!==$||!E($))throw new hI("session_control_changed")}},N=await A.identity.post(`${wX}/pull`,U($));if(D.checkpoint(),!N?.ok||!N.request)return;let V=N.request;if(typeof V.request_id!=="string"||!/^(?:bg|sc)_[0-9]{13}_[A-Za-z0-9_-]{8,64}$/.test(V.request_id))return;let Z;try{if(!E($)||V.session_id!==$.session_id||V.binding_id!==$.binding_id)throw new hI("session_control_changed");if(!Number.isFinite(V.expires_at)||V.expires_at<Date.now())throw new hI("session_control_request_expired");let W;if(V.operation==="state")W=await $.session.backgroundControl.state();else if(V.operation==="background")W=await $.session.backgroundControl.background({...U($),request_id:V.request_id,expires_at:V.expires_at},D);else throw new hI("session_control_request_invalid");D.checkpoint(),Z={status:"done",result:W}}catch(W){Z={status:"failed",error:W instanceof hI&&TJA.has(W.code)?W.code:"session_control_unavailable"}}D.checkpoint(),await A.identity.post(`${wX}/${encodeURIComponent(V.request_id)}/ack`,{...U($),...Z})}}function F(){if(C)return C;return C=Y().catch(()=>{A.warn("[session-control] transport unavailable; operation was not replayed")}).finally(()=>{C=null}),C}return{register:J,trigger:F}}import{spawnSync as PJA}from"node:child_process";import{existsSync as SJA,readFileSync as xJA}from"node:fs";import{dirname as eP,join as qX}from"node:path";import{fileURLToPath as kJA}from"node:url";var vJA=3000;function kN(A){if(!A)return;let Q=/(\d+)\.(\d+)\.(\d+)/.exec(A);return Q?`${Q[1]}.${Q[2]}.${Q[3]}`:void 0}function OX(A,Q){let B=(kN(A)??"0.0.0").split(".").map(Number),I=(kN(Q)??"0.0.0").split(".").map(Number);for(let C=0;C<3;C++){let E=(B[C]??0)-(I[C]??0);if(E!==0)return E}return 0}var bJA=(A,Q)=>{try{let B=PJA(A,["--version"],{encoding:"utf8",timeout:Q,stdio:["ignore","pipe","pipe"]});if(B.error||B.status!==0)return;return kN(`${B.stdout??""}
291
291
  ${B.stderr??""}`)}catch{return}};function AS(A,Q){if(!A)return;for(let B of A.split(":")){if(!B)continue;let I=`${B.replace(/\/+$/,"")}/codex`;if(Q(I))return I}return}function QS(A){try{let Q=eP(A.startsWith("file:")?kJA(A):A),B=tP(Q,"@openai/codex-sdk");if(!B)return;let I=tP(B,"@openai/codex");if(!I)return;return kN(JSON.parse(xJA(qX(I,"package.json"),"utf8")).version)}catch{return}}function tP(A,Q){let B=A;for(;;){let I=qX(B,"node_modules",Q);if(SJA(qX(I,"package.json")))return I;let C=eP(B);if(C===B)return;B=C}}function BS(A){let Q=A.probe??bJA,B=A.timeoutMs??vJA,I=[],C=[["config",A.configBin],["env",A.envBin]];for(let[E,g]of C){if(typeof g!=="string"||!g.trim())continue;let U=g.trim(),J=Q(U,B);if(J)return{path:U,version:J,source:E,skipped:I};I.push(`${E} ${U}: --version failed or timed out`)}if(A.pathBin){let E=Q(A.pathBin,B);if(!E)I.push(`path ${A.pathBin}: --version failed or timed out`);else if(!A.bundledVersion)I.push(`path ${A.pathBin} (${E}): bundled version unknown, not overriding`);else if(OX(E,A.bundledVersion)<0)I.push(`path ${A.pathBin} (${E}): older than bundled ${A.bundledVersion}`);else return{path:A.pathBin,version:E,source:"path",skipped:I}}return{version:A.bundledVersion,source:"bundled",skipped:I}}function IS(A){return`[codex] binary: ${A.path??"(bundled @openai/codex)"} (${A.version??"unknown"}) source=${A.source}`}function yJA(A,Q){return Q.path?{config:A,codexPathOverride:Q.path}:{config:A}}function vN(A,Q,B){return new A(yJA(Q,B))}import{accessSync as hmA,constants as mmA}from"node:fs";import{readFileSync as LI,existsSync as XI,writeFileSync as YP,chmodSync as MUA,realpathSync as umA}from"fs";var fJA=/^\[[\w-]+: assistant returned no reply\]$/;function TX(A,Q){let B=Q;if(typeof B?.userReplyText==="string"&&B.userReplyText.trim())return B.userReplyText;let I=typeof B?.message==="string"?B.message:String(Q),C=`${A} 错误: ${I}`,E=typeof B?.unverifiedReplyText==="string"?B.unverifiedReplyText.trim():"";if(!E)return C;let g=typeof B?.ownershipReason==="string"&&B.ownershipReason?`(${B.ownershipReason})`:"";if(fJA.test(E))return`${C}
292
292
 
293
293
  ${"[unverified-owner]"} 这一轮在产出最终答案前被人类插话打断${g},`+"没有可归属的正文。请重派这条任务;节点日志里有该轮的现场。";return`${C}
@@ -326,7 +326,7 @@ ${A}`}function ry(A,Q,B,I,C){let{interactiveDashboardTask:E,messageType:g}=B,U=$
326
326
  `,"config.json",B.stat),!0}function Pl(A,Q){return typeof A.opencodeConfiguredModelAtLastOpen==="string"&&A.opencodeConfiguredModelAtLastOpen!==Q}P0();UC();async function Sl(A,Q){let B=!1,I;for(let C of A)try{await Q(C)}catch(E){if(!B)I=E;B=!0}if(B)throw I}function Kj(A,Q){let B=Promise.resolve(),I=new Map,C=async(E)=>{let g=Q?.initialDelayMs??0;while(!0)try{await E();return}catch(U){if(A(U),!Q)return;await new Promise((J)=>{setTimeout(J,g).unref?.()}),g=Math.min(g*2,Q.maxDelayMs)}};return{schedule(E){let g=I.get(E);if(g){g.dirty=!0;return}let U={dirty:!1};I.set(E,U);let J=async()=>{try{do U.dirty=!1,await C(E);while(U.dirty)}finally{I.delete(E)}};B=B.then(J,J)},idle(){return B}}}var rMA=new Set(["replied","failed","cancelled","expired"]);function sMA(A){return typeof A==="string"&&rMA.has(A)}async function xl(A,Q){if(!Q)return{skip:!1,status:null,reason:"no-task-id"};let B;try{B=await A(Q)}catch{return{skip:!1,status:null,reason:"lookup-failed"}}if(!B||B.ok===!1||!B.task)return{skip:!1,status:null,reason:"not-found"};let I=typeof B.task.status==="string"?B.task.status:null;return sMA(I)?{skip:!0,status:I,reason:"terminal"}:{skip:!1,status:I,reason:"open"}}function kl(A){if(A.meta&&typeof A.meta==="object"&&!Array.isArray(A.meta))return A.meta;if(typeof A.meta_json!=="string"||A.meta_json.length===0)return null;try{let Q=JSON.parse(A.meta_json);return Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{return null}}function kV(A){let Q=A.type??"task";if(Q!=="task"&&Q!=="broadcast")return!1;let B=kl(A);if(!B||B.source!=="dashboard-chat")return!1;if(typeof B.client_request_id!=="string"||!/^dreq_[a-f0-9]{32}$/.test(B.client_request_id))return!1;return B.auth_origin==="user"}function vl(A){if(!kV(A))return null;let Q=kl(A)?.client_request_id;return typeof Q==="string"?Q:null}async function bl(A,Q){for(let B of A)await Q(B)}function yl(A){if(!Number.isInteger(A.maxConcurrent)||A.maxConcurrent<1)throw Error("maxConcurrent must be a positive integer");let Q=new Set,B=new Set,I=A.reservedPrioritySlots??0;if(!Number.isInteger(I)||I<0||I>=A.maxConcurrent)throw Error("reservedPrioritySlots out of range");let C=new Set,E=[],g=()=>{while(Q.size<A.maxConcurrent&&E.length>0){if(!E[0].priority&&B.size>=A.maxConcurrent-I)break;let U=E.shift(),J=A.key(U.message);if(C.delete(J),Q.add(J),!U.priority)B.add(J);let Y;try{Y=U.handler(U.message)}catch(F){Y=Promise.reject(F)}Y.catch(A.onError).finally(()=>{Q.delete(J),B.delete(J);try{A.onSettled?.()}catch(F){A.onError(F)}finally{g()}})}};return{submit(U,J){let Y=0,F=0;for(let G of U){let $=A.key(G);if(Q.has($)||C.has($)){F++;continue}C.add($);let D=A.prioritize?.(G)===!0||A.prioritizeRecovery?.(G)===!0,N=D?E.findIndex((Z)=>!Z.priority):-1,V={message:G,handler:J,priority:D};if(N<0)E.push(V);else E.splice(N,0,V);Y++}return g(),{active:Q.size,queued:E.length,accepted:Y,deduplicated:F}},stats(){return{active:Q.size,queued:E.length}}}}function fl(A,Q){return A!=="codex-app-server"||Q===0}var tMA={self:"sender alias equals node alias; reply-loop guard","own-prefix":"message carries this node's own reply prefix; reply-loop guard",cooldown:"sender cooldown is active","low-value-inbound":"non-task message matched the low-value filter"};function hl(A){let Q=tMA[A.reason]||"inbound filter rejected the message";return`skipped inbound ${A.messageType} ${A.taskId} from ${A.sender}: ${A.reason} (${Q}); acknowledged without model delivery`}function ml(A){let Q=A||"task";return Q==="task"||Q==="broadcast"}function ul(A){let{alias:Q,from:B,content:I,msgType:C}=A;if(B===Q&&!A.imBridge)return"self";if(I.startsWith(`[${Q}]`))return"own-prefix";let E=C==="task"||C==="broadcast"||C==="reply";if(!E&&B!=="hub"&&B!=="api"){if(A.lastReplyAt&&A.now-A.lastReplyAt<A.cooldownMs)return"cooldown"}if(!E&&A.isLowValue(I))return"low-value-inbound";return null}var eMA="skipped by agent-node: self-sent task (sender is this node; reply-loop guard), no turn ran. To wake a node later, use a Hub scheduled task or /aloop instead of send_task to yourself. (#519)",A8A="skipped by agent-node: task text starts with this node's own reply prefix (echo of its own reply; reply-loop guard), no turn ran. (#519)";function Q8A(A){if(A==="self")return eMA;if(A==="own-prefix")return A8A;return null}async function cl(A,Q){let B=Q8A(Q.reason);if(!B)return{kind:"not-applicable",detail:`reason ${Q.reason} does not close a task`};if(!ml(Q.msgType))return{kind:"not-applicable",detail:`type ${Q.msgType} carries no task`};if(!Q.taskId)return{kind:"not-applicable",detail:"no task id"};try{let I=await A("cancel_task",{task_id:Q.taskId,reason:B});if(I&&typeof I==="object"&&I.ok===!0)return{kind:"closed",tool:"cancel_task"};return{kind:"not-closed",tool:"cancel_task",detail:JSON.stringify(I??null).slice(0,200)}}catch(I){return{kind:"error",tool:"cancel_task",detail:String(I?.message??I).slice(0,200)}}}async function ll(A,Q){if(!ml(Q.msgType))return{kind:"not-applicable",detail:`type ${Q.msgType} carries no task`};if(!Q.taskId)return{kind:"not-applicable",detail:"no task id"};let I=`${Q.result.trim()||"(empty reply)"} [low-value reply withheld from sender by agent-node (#519)]`.slice(0,4000);try{return await A("report_completion",{alias:Q.alias,task:Q.taskId,result:I}),{kind:"closed",tool:"report_completion"}}catch(C){return{kind:"error",tool:"report_completion",detail:String(C?.message??C).slice(0,200)}}}function DD(A,Q){switch(Q.kind){case"closed":return`closed task ${A} via ${Q.tool} (#519)`;case"not-closed":return`task ${A} not closed by ${Q.tool} (already terminal?): ${Q.detail}`;case"not-applicable":return`task ${A} left as-is: ${Q.detail}`;case"error":return`failed to close task ${A} via ${Q.tool}: ${Q.detail}`}}function vV(){let A=null;return{run(Q){if(A)return A;let B=Promise.resolve().then(Q);return A=B,B.finally(()=>{if(A===B)A=null}).catch(()=>{}),B},pending(){return A}}}function pl(){let A=null,Q=vV();return{async getOrOpen(B){if(A?.isRunning)return A;return Q.run(async()=>{if(A?.isRunning)return A;A=null;let I=await B();if(!I.isRunning)throw Error("codex app-server session stopped while opening");return A=I,I})},invalidate(B){if(!B||A===B)A=null},current(){return A},pending(){return Q.pending()}}}ND();J4();import{closeSync as VD,constants as vE,existsSync as U8A,fchmodSync as yV,fstatSync as dl,fsyncSync as J8A,ftruncateSync as Y8A,lstatSync as F8A,mkdirSync as G8A,openSync as wj,readdirSync as $8A,readFileSync as D8A,realpathSync as Rj,writeSync as N8A}from"node:fs";import{join as nl,resolve as qj}from"node:path";function ol(){return process.platform==="linux"&&U8A("/proc/self/fd")}function al(A,Q){return ol()?`/proc/self/fd/${A}`:Q}function rl(A,Q){let B=dl(A),I=process.getuid?.();if(!B.isFile()||B.nlink!==1||I!==void 0&&B.uid!==I)throw Error(`private log is not a single owner-controlled file: ${Q}`);yV(A,384)}function sl(A){let Q=qj(A);if(Rj(Q)!==Q)throw Error(`private log directory is not canonical: ${Q}`);let B=wj(Q,vE.O_RDONLY|(vE.O_DIRECTORY||0)|(vE.O_NOFOLLOW||0));try{let I=dl(B),C=process.getuid?.();if(!I.isDirectory()||C!==void 0&&I.uid!==C)throw Error(`private log directory is not owner-controlled: ${Q}`);if(ol()&&Rj(`/proc/self/fd/${B}`)!==Q)throw Error(`private log directory changed during validation: ${Q}`);if(process.platform!=="win32")yV(B,448);return B}catch(I){throw VD(B),I}}function tl(A,Q,B){let I=0;while(I<Q.length){let C=N8A(A,Q,I,Q.length-I,B===null?null:B+I);if(C<=0)throw Error("private log write made no progress");I+=C}}function V8A(A,Q){let B=wj(A,vE.O_RDWR|(vE.O_NOFOLLOW||0));try{rl(B,A);let I=Buffer.from(Q.redactText(D8A(B,"utf8")).text,"utf8");if(Y8A(B,0),I.length>0)tl(B,I,0);J8A(B),yV(B,384)}finally{VD(B)}}function el(A,Q){let B=qj(A);G8A(B,{recursive:!0,mode:448});let I=F8A(B),C=process.getuid?.();if(I.isSymbolicLink()||!I.isDirectory()||Rj(B)!==B||C!==void 0&&I.uid!==C)throw Error(`private log directory is not owner-controlled: ${B}`);let E=sl(B);try{let g=al(E,B);for(let U of $8A(g)){if(!U.endsWith(".log"))continue;V8A(nl(g,U),Q)}}finally{VD(E)}return B}function Oj(A,Q,B,I){if(!/^\d{4}-\d{2}-\d{2}\.log$/.test(Q))throw Error("private log filename is not a canonical daily log name");let C=sl(A),E=nl(al(C,qj(A)),Q),g;try{g=wj(E,vE.O_WRONLY|vE.O_CREAT|vE.O_APPEND|(vE.O_NOFOLLOW||0),384),rl(g,E);let U=Buffer.from(I.redactText(B).text,"utf8");if(U.length>0)tl(g,U,null);yV(g,384)}finally{if(g!==void 0)VD(g);VD(C)}}function Tj(A){return JSON.stringify(A)}function Ap(A){let Q=A.configNodeId||"",B=A.envNodeId||"";if(Q){if(B&&B!==Q)A.warn?.(`COMMHUB_NODE_ID mismatch: env=${Tj(B)} config=${Tj(Q)} config_path=${Tj(A.configPath||"config.json")}; ignoring env COMMHUB_NODE_ID, using config node_id`);return{value:Q,source:"config"}}if(B)return{value:B,source:"env"};return{value:"",source:"none"}}function Z8A(A){let Q=A?.task_id||A?.message_id||A?.id;if(Q)return String(Q);let B=A?.content?.[0]?.text;if(typeof B!=="string")return null;try{let I=JSON.parse(B);return I?.task_id||I?.message_id||I?.id||null}catch{return null}}function hY(A,Q,B,I={}){let C=e1({from_alias:A.fromAlias,to_alias:A.toAlias,task_id:B,parent_task_id:A.parentTaskId,network_id:A.networkId,transport:"mcp_http",status:Q,duration_ms:Date.now()-A.startedAt,lifecycle_tracking:"tracked",...I.errorCode?{error_code:I.errorCode}:{},...I.errorMessage?{error_message:s1(I.errorMessage)}:{}});if(I.event)C.event=I.event;A.log(t1(C))}async function Qp(A,Q,B){let I=B.now??Date.now,C=B.sleep??((V)=>new Promise((Z)=>setTimeout(Z,V))),E=B.timeoutMs??120000,g=B.pollIntervalMs??2000,U=B.stale30Ms??30000,J=B.stale60Ms??60000,Y=B.emit,F=I()+E,G=null,$=new Set,D=!1,N=!1;while(I()<F){G=await B.getTask(A);let V=G?.task||G,Z=V?.status;if((Z==="acked"||Z==="running"||Z==="processing")&&!$.has(Z))$.add(Z),Y(Z==="acked"?"acked":"started",A);if(Z==="replied"||Z==="failed"||Z==="cancelled")return Y(Z==="replied"?"replied":"failed",A,{...Z==="replied"?{}:{errorCode:`task_${Z}`,event:"task.failed"}}),{kind:"terminal",status:Z,latest:G,row:V};let W=I()-Q;if(!D&&W>=U&&Z==="delivered")D=!0,Y("delivered",A,{event:"task.warning.delivered_stale_30s"});if(!N&&W>=J&&Z==="delivered")N=!0,Y("delivered",A,{event:"task.warning.delivered_stale_60s"});await C(g)}return Y("expired",A,{errorCode:"lifecycle_timeout"}),{kind:"expired",latest:G}}async function Bp(A,Q,B){hY(Q,"sending",null);try{let I=await B({alias:A.alias,task:A.task,priority:A.priority||"normal",from_session:Q.fromAlias,parent_task_id:Q.parentTaskId||void 0}),C=Z8A(I);if(!C)hY(Q,"failed",null,{errorCode:"missing_task_id",errorMessage:"CommHub response omitted task_id"});else hY(Q,"delivered",C);return I}catch(I){throw hY(Q,"failed",null,{errorCode:"send_failed",errorMessage:I}),I}}function Ip(A){let Q=A||"task";if(Q==="task"||Q==="broadcast")return{deliverToRuntime:!0,replyExpected:!0};if(Q==="reply")return{deliverToRuntime:!0,replyExpected:!1};return{deliverToRuntime:!1,replyExpected:!1}}async function Cp(A,Q,B){let I=await B.deliverToRuntime(A);if(Q)return{kind:"request",result:I};return await B.acknowledge(A.id),{kind:"terminal_peer_reply",result:I}}function Ep(A,Q){if(A.type!=="new_reply")return!1;return Q(),!0}V9();function Pj(){return{hubSupportsTool:null}}function W8A(A){if(!(A instanceof CI))return!1;if(A.code===-32601)return!0;let Q=String(A.message||"");return A.code===-32602&&/(?:unknown|not found|does not exist).{0,80}send_peer_reply|send_peer_reply.{0,80}(?:unknown|not found|does not exist)/i.test(Q)}function X8A(A){if(!(A instanceof CI))return!1;return A.code==="peer_reply_unsupported"||A.code==="peer_reply_origin_not_node"||A.code==="reply_task_not_owned"||A.code==="peer_reply_node_token_required"||W8A(A)}async function gp(A,Q,B=Pj()){try{let I=await Q.sendAtomic(A);return B.hubSupportsTool=!0,{route:"atomic",payload:I}}catch(I){if(!X8A(I))throw I;return{route:"legacy-reply",payload:await Q.sendLegacyReply(A)}}}QQ();import{chmodSync as Up,closeSync as Sj,existsSync as M8A,fchmodSync as z8A,fsyncSync as L8A,openSync as Jp,readFileSync as K8A,unlinkSync as Yp,writeFileSync as H8A}from"node:fs";import{randomBytes as j8A}from"node:crypto";var Fp=15000,_8A=2500,Dp=300000,ZD=2000,R8A=new Set(["replied","failed","cancelled","expired"]);function kj(A){if(A===void 0||A===null||String(A).trim()==="")return Fp;let Q=Number(A);if(!Number.isSafeInteger(Q))return Fp;return Math.min(Dp,Math.max(_8A,Q))}function xj(){return{version:3,consumed_task_ids:[],consumed_client_request_ids:[],surfaced_outbound_terminal_ids:[],outbound_deliveries:[],outbound_terminal_watermark:0,inbound_lifecycle:[],last_success_at:null}}function m0(A){if(!Array.isArray(A))return[];return[...new Set(A.filter((Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=512))].slice(-ZD)}function w8A(A){if(!A||typeof A!=="object")return xj();let Q=A;return{version:3,consumed_task_ids:m0(Q.consumed_task_ids),consumed_client_request_ids:m0(Q.consumed_client_request_ids),surfaced_outbound_terminal_ids:m0(Q.surfaced_outbound_terminal_ids),outbound_deliveries:Array.isArray(Q.outbound_deliveries)?Q.outbound_deliveries.filter((B)=>!!B&&typeof B.task_id==="string"&&typeof B.idempotency_key==="string"&&["pending","delivering","delivered"].includes(B.state)).slice(-ZD):m0(Q.surfaced_outbound_terminal_ids).map((B)=>({task_id:B,idempotency_key:`commhub-terminal:${B}`,state:"delivered"})),outbound_terminal_watermark:Number.isSafeInteger(Q.outbound_terminal_watermark)&&Number(Q.outbound_terminal_watermark)>=0?Number(Q.outbound_terminal_watermark):0,inbound_lifecycle:Array.isArray(Q.inbound_lifecycle)?Q.inbound_lifecycle.filter((B)=>!!B&&typeof B.task_id==="string"&&["delivered","submitted","consumed","completed"].includes(B.state)).slice(-ZD):m0(Q.consumed_task_ids).map((B)=>({task_id:B,state:"consumed"})),last_success_at:typeof Q.last_success_at==="string"?Q.last_success_at:null}}function Gp(A){return vl(A)}function $p(A){return typeof A.task_id==="string"&&A.task_id?A.task_id:A.id}function q8A(A){let Q=A,B=String(Q?.message??A??"");return Q?.code===-32601||Q?.code===-32602||/unknown tool|tool .+ not found|method not found|-3260[12]/i.test(B)}var O8A=new Set(["from_node_id_identity_mismatch","node_token_required"]);function T8A(A){let Q=A;return Q?.appLevel===!0&&typeof Q.code==="string"&&O8A.has(Q.code)}class Np{path;state;constructor(A){this.path=A;this.state=this.read()}snapshot(){return this.state=this.read(),this.state}update(A){this.withLock(()=>{let Q=this.read();A(Q),Q.consumed_task_ids=m0(Q.consumed_task_ids),Q.consumed_client_request_ids=m0(Q.consumed_client_request_ids),Q.surfaced_outbound_terminal_ids=m0(Q.surfaced_outbound_terminal_ids),Q.outbound_deliveries=Q.outbound_deliveries.filter((B)=>B.state!=="delivered").slice(-ZD),Q.inbound_lifecycle=Q.inbound_lifecycle.slice(-ZD),this.write(Q),this.state=Q})}claimOutbound(A,Q,B,I){return this.withLock(()=>{let C=this.read(),E=C.outbound_deliveries.find((g)=>g.task_id===A);if(E?.state==="delivered"||E?.state==="delivering"&&(E.lease_until??0)>B)return!1;if(E)E.state="delivering",E.lease_until=B+I;else C.outbound_deliveries.push({task_id:A,idempotency_key:Q,state:"delivering",lease_until:B+I});return this.write(C),this.state=C,!0},!1)}withLock(A,Q){let B=`${this.path}.lock`,I;try{I=Jp(B,"wx",384)}catch{if(arguments.length>1)return Q;throw Error("compensation cursor is locked")}try{return A()}finally{Sj(I);try{Yp(B)}catch{}}}read(){if(!M8A(this.path))return xj();try{let A=w8A(JSON.parse(K8A(this.path,"utf8")));return Up(this.path,384),A}catch{return xj()}}write(A){let Q=`${this.path}.tmp-${process.pid}-${j8A(6).toString("hex")}`,B=null;try{B=Jp(Q,"wx",384),z8A(B,384),H8A(B,`${JSON.stringify(A)}
327
327
  `,"utf8"),L8A(B),Sj(B),B=null,JA(Q,this.path),Up(this.path,384)}finally{if(B!==null)Sj(B);try{Yp(Q)}catch{}}}}function Vp(A){let Q=kj(A.intervalMs),B=A.adapters,I=new Np(A.cursorPath),C="probing",E=null,g=!1,U=!1,J=null,Y=0,F=!1,G=!1,$=B.now??Date.now,D=Math.max(30000,Q*2),N=B.setTimer??((R,m)=>{let k=setTimeout(R,m);return k.unref?.(),k}),V=B.clearTimer??((R)=>clearTimeout(R)),Z=(R)=>{let m=I.snapshot(),k=$p(R),S=Gp(R);return m.consumed_task_ids.includes(k)||!!S&&m.consumed_client_request_ids.includes(S)},W=(R)=>{let m=$p(R),k=Gp(R);I.update((S)=>{if(S.consumed_task_ids.push(m),k)S.consumed_client_request_ids.push(k);let b=S.inbound_lifecycle.find((y)=>y.task_id===m);if(b)b.state="completed";else S.inbound_lifecycle.push({task_id:m,state:"completed"})})},X={delivered:0,submitted:1,consumed:2,completed:3},z=(R,m)=>{if(!R)return;I.update((k)=>{let S=k.inbound_lifecycle.find((b)=>b.task_id===R);if(!S)k.inbound_lifecycle.push({task_id:R,state:m});else if(X[m]>X[S.state])S.state=m;if(X[m]>=X.consumed)k.consumed_task_ids.push(R)})},M=(R)=>{if(U||C==="realtime-only")return;if(J!==null)V(J);J=N(()=>{J=null,K("timer")},R)},L=async(R)=>{try{let m=I.snapshot().outbound_terminal_watermark,[k,S]=await Promise.all([B.getInbox(),G?Promise.resolve({tasks:[],hasMore:!1}):B.listOutbound(m).catch((y)=>{if(!T8A(y))throw y;return G=!0,B.warn(`[commhub-compensation] outbound reconciliation disabled: this node's token is not bound to its node_id (${y.code}); inbox compensation continues. Re-issue a node-bound token to restore lost-reply reconciliation.`),{tasks:[],hasMore:!1}})]),b=S.tasks;if(C==="probing")C="active",B.log(`[commhub-compensation] active (${Q}ms; SSE remains primary)`);if(k.some((y)=>!Z(y)))B.scheduleInboxDrain();for(let y of b){if(!y?.task_id||!R8A.has(y.status))continue;if(!Number.isSafeInteger(y.terminal_seq)||Number(y.terminal_seq)<=0)throw Object.assign(Error("Hub terminal sequence missing"),{code:-32602});let T=Number(y.terminal_seq),n=I.snapshot();if(T<=n.outbound_terminal_watermark)continue;let u=I.snapshot().outbound_deliveries.find((v)=>v.task_id===y.task_id);if(u?.state==="delivered"){I.update((v)=>{v.outbound_terminal_watermark=Math.max(v.outbound_terminal_watermark,T)});continue}let O=u?.idempotency_key??`commhub-terminal:${y.task_id}`;if(!I.claimOutbound(y.task_id,O,$(),D))break;try{await B.onOutboundTerminal(y,O)}catch(v){throw I.update((t)=>{let s=t.outbound_deliveries.find((EA)=>EA.task_id===y.task_id);if(s)s.state="pending",s.lease_until=0}),v}I.update((v)=>{let t=v.outbound_deliveries.find((s)=>s.task_id===y.task_id);if(t)t.state="delivered",t.lease_until=0;v.outbound_terminal_watermark=Math.max(v.outbound_terminal_watermark,T)})}if(I.update((y)=>{y.last_success_at=new Date($()).toISOString()}),S.hasMore)g=!0;Y=0,B.log(`[commhub-compensation] ${R} poll ok; inbox=${k.length} outbound=${b.length}`),M(Q)}catch(m){if(q8A(m)){if(C="realtime-only",!F)F=!0,B.warn("[commhub-compensation] Hub lacks durable inbox/outbox polling capability; realtime-only mode (SSE/turn-steer only)");return}Y++;let k=Math.min(Dp,Q*2**Math.min(Y,5));B.warn(`[commhub-compensation] poll failed; retry in ${k}ms: ${m instanceof Error?m.message:String(m)}`),M(k)}},K=(R)=>{if(U||C==="realtime-only")return;if(E){g=!0;return}E=(async()=>{let m=R;do g=!1,await L(m),m="idle";while(g&&!U&&C!=="realtime-only")})().finally(()=>{E=null})};return{get mode(){return C},get outboundDisabled(){return G},trigger:K,recordConsumed:W,recordLifecycle:z,wasConsumed:Z,async idle(){await E},stop(){if(U=!0,J!==null)V(J);J=null}}}import{appendFileSync as xUA,mkdirSync as EX,statSync as kUA}from"fs";import{appendFileSync as P8A,mkdirSync as S8A,writeSync as x8A}from"node:fs";import{join as k8A}from"node:path";function Zp(A){if(A instanceof Error)return`${A.name}: ${A.message}`.replace(/[\r\n]+/g," ");return String(A).replace(/[\r\n]+/g," ")}function v8A(A){if(A instanceof Error)return A.stack||`${A.name}: ${A.message}`;return String(A)}function Wp(A){let Q=A.stdout??process.stdout,B=A.stderr??process.stderr,I=A.now??(()=>new Date),C=A.redact??((Z)=>Z),E=A.exit??((Z)=>process.exit(Z)),g=A.alias??"agent-node",U=!1,J=!1,Y=!1,F="normal",G=!1,$=(Z,W,X)=>{return`[${I().toISOString().slice(11,19)}] [${Z.padEnd(5)}] [${g}] [${W}] ${X}`},D=(Z)=>{try{let W=I().toISOString().slice(0,10),X=C(Z);if(A.appendLine)A.appendLine(W,X);else S8A(A.logDir,{recursive:!0,mode:448}),P8A(k8A(A.logDir,`${W}.log`),X+`
328
328
  `,{mode:384})}catch{}},N=(Z)=>(W)=>{if(W?.code==="EPIPE"){if(Z==="stdout")U=!0;else J=!0;if(!Y)Y=!0,D($("WARN","stream",`${Z} EPIPE; terminal output disabled, file logging continues`));return}if(F=`${Z} error: ${Zp(W)}`,!G)G=!0,E(1)};Q.on("error",N("stdout")),B.on("error",N("stderr"));let V=(Z,W)=>{if(G)return;G=!0,F=`${Z}: ${Zp(W)}`;let X=v8A(W);if(D($("ERROR","fatal",`${Z}: ${X}`)),!J)try{x8A(2,`${X}
329
- `)}catch(z){if(z?.code==="EPIPE")J=!0}E(1)};return process.on("uncaughtException",(Z)=>V("uncaughtException",Z)),process.on("unhandledRejection",(Z)=>V("unhandledRejection",Z)),process.on("exit",(Z)=>D($(Z===0?"INFO":"ERROR","exit",`code=${Z} reason=${F}`))),{outputBroken:()=>U||J}}var Xp={name:"@sleep2agi/agent-node",version:"2.5.0-preview.172",description:"AI Agent runtime for CommHub networks. Supports Claude Code CLI, Claude Agent SDK, Codex SDK, Codex app-server, Grok Build ACP, and OpenCode CLI.",bin:{"agent-node":"dist/cli.js"},type:"module",files:["dist","README.md","build-info.json"],scripts:{build:"bun build src/cli.ts --outdir dist --entry-naming cli.js --target node --minify --external @anthropic-ai/claude-agent-sdk --external '@anthropic-ai/claude-agent-sdk-*' --external @openai/codex-sdk --external node-pty && bun build src/upload-file-mcp-stdio.ts --outdir dist --entry-naming upload-file-mcp-stdio.js --target node --minify",prepublishOnly:"npm run build",prepack:"node scripts/write-build-info.mjs"},keywords:["agent","ai","commhub","claude","claude-code","codex","gpt5","grok","xai","grok-build-cli","copresence","acp","sdk","minimax","mimo","runtime","node","anthropic"],author:"sleep2agi",license:"Apache-2.0",homepage:"https://anet.sh",repository:{type:"git",url:"git+https://github.com/sleep2agi/agent-network.git",directory:"agent-node"},publishConfig:{access:"public",tag:"preview"},bugs:{url:"https://github.com/sleep2agi/agent-network/issues"},engines:{node:">=18.17.0"},dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.289",undici:"^6.27.0",ws:"^8.22.0",zod:"^4.4.3"},optionalDependencies:{"@openai/codex":"^0.133.0","@openai/codex-sdk":"^0.133.0","node-pty":"^1.1.0"},devDependencies:{"@types/ws":"^8.18.2"}};import{readFileSync as y8A}from"node:fs";import{dirname as Mp,join as f8A}from"node:path";import{fileURLToPath as h8A}from"node:url";var m8A="build-info.json",u8A=/^[0-9a-f]{40}$/;function c8A(A){if(typeof A!=="string"||A.length<20)return!1;return Number.isFinite(Date.parse(A))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(A)}function l8A(A){if(!A||typeof A!=="object"||Array.isArray(A))return null;let Q=A;if(Q.schema!==1)return null;if(typeof Q.commit!=="string"||!u8A.test(Q.commit))return null;if(typeof Q.dirty!=="boolean")return null;if(!c8A(Q.built_at))return null;if(Q.source!==void 0&&typeof Q.source!=="string")return null;let B={schema:1,commit:Q.commit,dirty:Q.dirty,built_at:Q.built_at};if(typeof Q.source==="string")B.source=Q.source;return B}function p8A(A){let Q;try{Q=y8A(f8A(A,m8A),"utf8")}catch(C){if(C&&(C.code==="ENOENT"||C.code==="ENOTDIR"))return{kind:"absent"};return{kind:"invalid",error:`unreadable:${C?.code??"unknown"}`}}let B;try{B=JSON.parse(Q)}catch{return{kind:"invalid",error:"invalid_json"}}let I=l8A(B);return I?{kind:"present",info:I}:{kind:"invalid",error:"invalid_shape"}}function zp(){let A=Mp(h8A(import.meta.url));for(let Q=0;Q<3;Q+=1){let B=p8A(A);if(B.kind==="present")return B.info.commit;if(B.kind==="invalid")return;let I=Mp(A);if(I===A)break;A=I}return}s$();R$();import{chmodSync as i8A,existsSync as d8A,mkdirSync as n8A,readFileSync as o8A,writeFileSync as a8A}from"node:fs";import{join as r8A}from"node:path";var Lp="model_reasoning_effort";function vj(A){return j$(A)}function s8A(A,Q){let B=A.includes(`\r
329
+ `)}catch(z){if(z?.code==="EPIPE")J=!0}E(1)};return process.on("uncaughtException",(Z)=>V("uncaughtException",Z)),process.on("unhandledRejection",(Z)=>V("unhandledRejection",Z)),process.on("exit",(Z)=>D($(Z===0?"INFO":"ERROR","exit",`code=${Z} reason=${F}`))),{outputBroken:()=>U||J}}var Xp={name:"@sleep2agi/agent-node",version:"2.5.0-preview.173",description:"AI Agent runtime for CommHub networks. Supports Claude Code CLI, Claude Agent SDK, Codex SDK, Codex app-server, Grok Build ACP, and OpenCode CLI.",bin:{"agent-node":"dist/cli.js"},type:"module",files:["dist","README.md","build-info.json"],scripts:{build:"bun build src/cli.ts --outdir dist --entry-naming cli.js --target node --minify --external @anthropic-ai/claude-agent-sdk --external '@anthropic-ai/claude-agent-sdk-*' --external @openai/codex-sdk --external node-pty && bun build src/upload-file-mcp-stdio.ts --outdir dist --entry-naming upload-file-mcp-stdio.js --target node --minify",prepublishOnly:"npm run build",prepack:"node scripts/write-build-info.mjs"},keywords:["agent","ai","commhub","claude","claude-code","codex","gpt5","grok","xai","grok-build-cli","copresence","acp","sdk","minimax","mimo","runtime","node","anthropic"],author:"sleep2agi",license:"Apache-2.0",homepage:"https://anet.sh",repository:{type:"git",url:"git+https://github.com/sleep2agi/agent-network.git",directory:"agent-node"},publishConfig:{access:"public",tag:"preview"},bugs:{url:"https://github.com/sleep2agi/agent-network/issues"},engines:{node:">=18.17.0"},dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.289",undici:"^6.27.0",ws:"^8.22.0",zod:"^4.4.3"},optionalDependencies:{"@openai/codex":"^0.133.0","@openai/codex-sdk":"^0.133.0","node-pty":"^1.1.0"},devDependencies:{"@types/ws":"^8.18.2"}};import{readFileSync as y8A}from"node:fs";import{dirname as Mp,join as f8A}from"node:path";import{fileURLToPath as h8A}from"node:url";var m8A="build-info.json",u8A=/^[0-9a-f]{40}$/;function c8A(A){if(typeof A!=="string"||A.length<20)return!1;return Number.isFinite(Date.parse(A))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(A)}function l8A(A){if(!A||typeof A!=="object"||Array.isArray(A))return null;let Q=A;if(Q.schema!==1)return null;if(typeof Q.commit!=="string"||!u8A.test(Q.commit))return null;if(typeof Q.dirty!=="boolean")return null;if(!c8A(Q.built_at))return null;if(Q.source!==void 0&&typeof Q.source!=="string")return null;let B={schema:1,commit:Q.commit,dirty:Q.dirty,built_at:Q.built_at};if(typeof Q.source==="string")B.source=Q.source;return B}function p8A(A){let Q;try{Q=y8A(f8A(A,m8A),"utf8")}catch(C){if(C&&(C.code==="ENOENT"||C.code==="ENOTDIR"))return{kind:"absent"};return{kind:"invalid",error:`unreadable:${C?.code??"unknown"}`}}let B;try{B=JSON.parse(Q)}catch{return{kind:"invalid",error:"invalid_json"}}let I=l8A(B);return I?{kind:"present",info:I}:{kind:"invalid",error:"invalid_shape"}}function zp(){let A=Mp(h8A(import.meta.url));for(let Q=0;Q<3;Q+=1){let B=p8A(A);if(B.kind==="present")return B.info.commit;if(B.kind==="invalid")return;let I=Mp(A);if(I===A)break;A=I}return}s$();R$();import{chmodSync as i8A,existsSync as d8A,mkdirSync as n8A,readFileSync as o8A,writeFileSync as a8A}from"node:fs";import{join as r8A}from"node:path";var Lp="model_reasoning_effort";function vj(A){return j$(A)}function s8A(A,Q){let B=A.includes(`\r
330
330
  `)?`\r
331
331
  `:`
332
332
  `,I=A.endsWith(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "2.5.0-preview.172",
3
+ "version": "2.5.0-preview.173",
4
4
  "description": "AI Agent runtime for CommHub networks. Supports Claude Code CLI, Claude Agent SDK, Codex SDK, Codex app-server, Grok Build ACP, and OpenCode CLI.",
5
5
  "bin": {
6
6
  "agent-node": "dist/cli.js"