@sleep2agi/agent-node 2.5.0-preview.43 → 2.5.0-preview.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +4 -2
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -158,7 +158,9 @@ ${I}`;break;case"retry":if(jk(I))Q[C]=I;break;case"id":if(_k(I))Q[C]=I;break;cas
|
|
|
158
158
|
`):void 0}let B=p$(A);if(!B)return;if(typeof B.text==="string")return B.text;if(typeof B.content==="string")return B.content;return l$(B.content,Q+1)}function p$(A){return A!==null&&typeof A==="object"&&!Array.isArray(A)?A:void 0}function sYA(A){let Q=A?.trim();return Q?Q:void 0}function pZ(A){return Buffer.byteLength(A,"utf8")}function cZ(A){return A.length>0&&pZ(A)<=256&&!/[\u0000-\u001f\u007f]/.test(A)&&!A.includes("]")&&!A.includes("/")}function yy(A,Q){if(!cZ(A))throw Error(`invalid network ${Q}`)}function uy(){return{phase:"idle",queue:[],activeTurn:null,recoveryFrom:null,waitingHuman:!1,revision:0}}function cy(A,Q){switch(rZ(A),Q.type){case"network_task_received":{let B=qI(Q.task);if(dZ(B),A.queue.some((C)=>C.taskId===B.taskId)||A.activeTurn?.owner==="network"&&A.activeTurn.task.taskId===B.taskId)throw Error(`duplicate network task ${B.taskId}`);return TB(A,{queue:[...A.queue.map(qI),B]})}case"network_task_cancelled":{let B=A.queue.findIndex((C)=>C.taskId===Q.taskId);if(B<0)return lB(A);return TB(A,{queue:A.queue.filter((C,I)=>I!==B).map(qI)})}case"human_input_started":if(A.phase!=="idle")return lB(A);return TB(A,{phase:"human_editing"});case"human_input_submitted":if(A.phase!=="human_editing")return lB(A);return TB(A,{phase:"human_turn",activeTurn:{owner:"human"},waitingHuman:!1});case"human_input_cancelled":if(A.phase!=="human_editing")return lB(A);return TB(A,{phase:"idle"});case"schedule_network":{if(A.phase!=="idle"||A.queue.length===0)return lB(A);let[B,...C]=A.queue,I=qI(B);return TB(A,{phase:"network_turn",queue:C.map(qI),activeTurn:{owner:"network",task:I},waitingHuman:!1},[{type:"inject_network_task",task:qI(I)}])}case"turn_completed":{if(Q.owner==="human"){if(A.phase!=="human_turn"||A.activeTurn?.owner!=="human")return lB(A);return TB(A,{phase:"idle",activeTurn:null,waitingHuman:!1},[{type:"human_turn_completed"}])}if(A.phase!=="network_turn"||A.activeTurn?.owner!=="network")return lB(A);let B=qI(A.activeTurn.task);return TB(A,{phase:"idle",activeTurn:null,waitingHuman:!1},[{type:"network_turn_completed",task:B}])}case"disconnected":if(A.phase==="recovering")return lB(A);return TB(A,{phase:"recovering",recoveryFrom:A.phase});case"reconnected":if(A.phase!=="recovering"||A.recoveryFrom===null)return lB(A);return TB(A,{phase:A.recoveryFrom,recoveryFrom:null});case"approval_requested":if(!iy(A)||A.waitingHuman)return lB(A);return TB(A,{waitingHuman:!0});case"approval_resolved_by_human":if(!A.waitingHuman)return lB(A);return TB(A,{waitingHuman:!1});case"preview_todo_resolved_automatically":if(!A.waitingHuman||A.phase!=="network_turn"&&A.phase!=="human_turn"||A.activeTurn?.owner!=="network"&&A.activeTurn?.owner!=="human")return lB(A);return TB(A,{waitingHuman:!1})}}function ly(A){return rZ(A),{version:1,phase:A.phase,queue:A.queue.map(qI),activeTurn:nZ(A.activeTurn),recoveryFrom:A.recoveryFrom,waitingHuman:A.waitingHuman,revision:A.revision}}function rZ(A){if(!tYA.includes(A.phase))throw Error(`invalid Grok co-presence phase: ${String(A.phase)}`);if(!Array.isArray(A.queue))throw Error("Grok co-presence queue must be an array");if(typeof A.waitingHuman!=="boolean")throw Error("Grok co-presence waitingHuman must be boolean");if(!Number.isSafeInteger(A.revision)||A.revision<0)throw Error("Grok co-presence state has an invalid revision");for(let Q of A.queue)dZ(Q);if(A.activeTurn!==null&&A.activeTurn.owner!=="human"&&A.activeTurn.owner!=="network")throw Error("Grok co-presence active turn has an invalid owner");if(A.phase==="idle"||A.phase==="human_editing"){if(A.activeTurn!==null)throw Error(`${A.phase} cannot have an active turn`)}if(A.phase==="human_turn"&&A.activeTurn?.owner!=="human")throw Error("human_turn must be owned by a human");if(A.phase==="network_turn"&&A.activeTurn?.owner!=="network")throw Error("network_turn must retain its network task");if(A.activeTurn?.owner==="network")dZ(A.activeTurn.task);if(A.phase==="recovering"){if(A.recoveryFrom===null)throw Error("recovering must record its prior phase");if(!eYA.includes(A.recoveryFrom))throw Error(`invalid Grok co-presence recovery phase: ${String(A.recoveryFrom)}`);if(A.recoveryFrom==="network_turn"&&A.activeTurn?.owner!=="network")throw Error("recovering network turn must retain its network task");if(A.recoveryFrom==="human_turn"&&A.activeTurn?.owner!=="human")throw Error("recovering human turn must retain its owner")}else if(A.recoveryFrom!==null)throw Error("only recovering may record a prior phase");if(A.waitingHuman&&!iy(A))throw Error("waitingHuman requires an active turn")}function iy(A){return A.activeTurn!==null&&(A.phase==="human_turn"||A.phase==="network_turn"||A.phase==="recovering")}function TB(A,Q,B=[]){let C={...A,...Q,queue:Q.queue??A.queue.map(qI),activeTurn:Q.activeTurn===void 0?nZ(A.activeTurn):nZ(Q.activeTurn),revision:A.revision+1};return rZ(C),{state:C,accepted:!0,effects:B}}function lB(A){return{state:A,accepted:!1,effects:[]}}function dZ(A){if(typeof A.taskId!=="string"||!A.taskId.trim())throw Error("network task requires taskId");if(typeof A.from!=="string"||!A.from.trim())throw Error("network task requires from");if(typeof A.message!=="string")throw Error("network task requires message")}function nZ(A){if(A===null||A.owner==="human")return A===null?null:{owner:"human"};return{owner:"network",task:qI(A.task)}}function qI(A){return{taskId:A.taskId,from:A.from,message:A.message,...A.metadata===void 0?{}:{metadata:oZ(A.metadata)}}}function oZ(A){if(Array.isArray(A))return A.map((Q)=>oZ(Q));if(A!==null&&typeof A==="object")return Object.fromEntries(Object.entries(A).map(([Q,B])=>[Q,oZ(B)]));return A}var tYA,eYA;var py=j(()=>{tYA=["idle","human_editing","human_turn","network_turn","recovering"],eYA=["idle","human_editing","human_turn","network_turn"]});import{constants as AJA,existsSync as QJA,lstatSync as oy,readFileSync as o$,readdirSync as aZ,readlinkSync as BJA,realpathSync as eZ,statSync as r$,unlinkSync as IJA}from"fs";import{isAbsolute as ry,delimiter as CJA,join as d$,resolve as EJA}from"path";import{setTimeout as a$}from"timers/promises";async function sy(A){let Q=Date.now()+(A.timeoutMs??5000),B;while(Date.now()<Q)try{return YJA(A)}catch(C){B=C,await a$(25)}throw Error(`could not bind the Grok Leader to this TUI generation: ${wJA(B)}`)}async function ty(A,Q=2000){if(tZ(A.pid,A.startTime)){if(sZ(A),dy(A.pid,"SIGTERM")&&!await ny(A.pid,A.startTime,Q)){if(sZ(A),dy(A.pid,"SIGKILL")&&!await ny(A.pid,A.startTime,Q))throw Error(`owned Grok Leader pid ${A.pid} did not exit after SIGKILL`)}}await GJA(A,Q),await $JA(A,Q),VJA(A)}function FJA(A,Q,B){let C=A.findIndex((E,g)=>g<=1&&NJA(E,Q));if(C<0||A[C+1]!=="agent"||A[C+2]!=="leader")throw Error("Grok Leader argv does not identify the pinned agent leader process");if(C===0&&B!==Q)throw Error("Grok Leader kernel executable differs from the pinned binary");let I=A.slice(C+3);if(!I.includes("--no-exit-on-disconnect")||!I.includes("--relay-on-demand"))throw Error("Grok Leader argv is missing its persistent shared-backend flags")}function YJA(A){WJA(A.ownerNonce);let Q=Q8(A.leaderSocket),B=Af(A.leaderSocket),C=A8(B);if(C.length!==1)throw Error(`Grok Leader listener has ${C.length} process owners instead of one`);let I=C[0];if(I===process.pid)throw Error("Grok Leader listener is unexpectedly owned by agent-node");let E=JJA(A.binary,A.binaryPathEnv),g=B8(r$(E)),D=ey(I,E,{leaderSocket:A.leaderSocket,grokHome:A.grokHome,sandboxProfile:A.sandboxProfile,ownerNonce:A.ownerNonce,expectedParentPid:A.expectedParentPid}),U={generation:A.generation,pid:I,startTime:D.startTime,executable:D.executable,configuredBinary:E,configuredBinaryFile:g,socket:Q,listenerInode:B,leaderSocket:A.leaderSocket,grokHome:A.grokHome,sandboxProfile:A.sandboxProfile,ownerNonce:A.ownerNonce,expectedParentPid:A.expectedParentPid};return sZ(U),U}function sZ(A){let Q=Q8(A.leaderSocket);n$(Q,A.socket,"Grok Leader socket");let B=Af(A.leaderSocket);if(B!==A.listenerInode)throw Error("Grok Leader listener inode changed before termination");let C=A8(B);if(C.length!==1||C[0]!==A.pid)throw Error("Grok Leader listener ownership changed before termination");let I=ey(A.pid,A.configuredBinary,{leaderSocket:A.leaderSocket,grokHome:A.grokHome,sandboxProfile:A.sandboxProfile,ownerNonce:A.ownerNonce,expectedParentPid:A.expectedParentPid});if(I.startTime!==A.startTime)throw Error("Grok Leader PID generation changed before termination");if(n$(I.executable,A.executable,"Grok Leader executable"),I.executable.path!==A.executable.path)throw Error("Grok Leader executable path changed before termination");n$(B8(r$(A.configuredBinary)),A.configuredBinaryFile,"configured Grok binary")}function ey(A,Q,B){let C=`/proc/${A}`,I=oy(C).uid,E=process.getuid?.();if(E!==void 0&&I!==E)throw Error("Grok Leader process owner mismatch");let g=Bf(A);if(g.state==="Z"||g.state==="X")throw Error("Grok Leader process is not live");let D=g.startTime,U=eZ(d$(C,"exe")),F=r$(d$(C,"exe")),Y={path:U,dev:String(F.dev),ino:String(F.ino),uid:F.uid},N=If(d$(C,"cmdline"));FJA(N,Q,U);let J=Cf(d$(C,"environ")),G={[ay]:B.ownerNonce,HOME:B.grokHome,GROK_HOME:B.grokHome,GROK_SANDBOX:B.sandboxProfile,GROK_LEADER_SOCKET:B.leaderSocket,GROK_CHANGELOG_OFFLINE:"1",GROK_LEADER_LOG:"off",ANET_EXPECTED_PARENT_PID:B.expectedParentPid};for(let[$,V]of Object.entries(G))if(J[$]!==V)throw Error(`Grok Leader environment identity mismatch: ${$}`);return{startTime:D,executable:Y}}function Af(A){let Q=[],B=o$("/proc/net/unix","utf8").split(`
|
|
159
159
|
`).slice(1);for(let I of B){if(!I.trim())continue;let E=Qf(I);if(E.path===A&&E.flags===gJA&&E.type===DJA&&E.state===UJA)Q.push(E.inode)}let C=[...new Set(Q)];if(C.length!==1)throw Error(`Grok Leader socket has ${C.length} listening inodes instead of one`);return C[0]}function Qf(A){let Q=A.match(/^\s*\S+:\s+\S+\s+\S+\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)(?:\s+(.*))?$/);if(!Q)throw Error("malformed /proc/net/unix row");return{flags:Q[1],type:Q[2],state:Q[3],inode:Q[4],path:Q[5]??""}}function A8(A){let Q=`socket:[${A}]`,B=new Set;for(let C of aZ("/proc",{withFileTypes:!0})){if(!C.isDirectory()||!/^\d+$/.test(C.name))continue;let I=Number(C.name),E;try{E=aZ(`/proc/${I}/fd`)}catch{continue}for(let g of E)try{if(BJA(`/proc/${I}/fd/${g}`)===Q){B.add(I);break}}catch{}}return[...B].sort((C,I)=>C-I)}function Q8(A){let Q=oy(A),B=process.getuid?.();if(Q.isSymbolicLink()||!Q.isSocket())throw Error("Grok Leader path is not a real Unix socket");if(B!==void 0&&Q.uid!==B)throw Error("Grok Leader socket owner mismatch");return B8(Q)}function B8(A){return{dev:String(A.dev),ino:String(A.ino),uid:A.uid}}function Bf(A){let Q=o$(`/proc/${A}/stat`,"utf8"),B=Q.lastIndexOf(")");if(B<0)throw Error("malformed process stat");let C=Q.slice(B+2).trim().split(/\s+/),I=C[0]||"",E=C[19];if(!/^[A-Z]$/.test(I)||!/^\d+$/.test(E||""))throw Error("missing process state or start time");return{state:I,startTime:E}}function If(A){return o$(A).toString("utf8").split("\x00").filter(Boolean)}function Cf(A){let Q={};for(let B of If(A)){let C=B.indexOf("=");if(C<1)throw Error("malformed process environment");Q[B.slice(0,C)]=B.slice(C+1)}return Q}function JJA(A,Q){let B=ry(A)?[A]:Q.split(CJA).filter(Boolean).map((C)=>EJA(C,A));for(let C of B)try{if((r$(C).mode&AJA.S_IXUSR)!==0)return eZ(C)}catch{}throw Error("could not resolve the pinned Grok executable for Leader identity")}function NJA(A,Q){if(!A||!ry(A))return!1;try{return eZ(A)===Q}catch{return!1}}function tZ(A,Q){try{let B=Bf(A);return B.startTime===Q&&B.state!=="Z"&&B.state!=="X"}catch{return!1}}function dy(A,Q){try{return process.kill(A,Q),!0}catch(B){if(B?.code==="ESRCH")return!1;throw B}}async function ny(A,Q,B){let C=Date.now()+B;while(Date.now()<C){if(!tZ(A,Q))return!0;await a$(20)}return!tZ(A,Q)}async function GJA(A,Q){let B=Date.now()+Q;while(Date.now()<B){let C=Ef(A.leaderSocket,A.listenerInode),I=A8(A.listenerInode).length>0;if(!C&&!I)return;await a$(20)}throw Error("owned Grok Leader listener remained after process termination")}function Ef(A,Q){try{return o$("/proc/net/unix","utf8").split(`
|
|
160
160
|
`).slice(1).some((B)=>{if(!B.trim())return!1;let C=Qf(B);return C.path===A&&C.inode===Q})}catch{return!0}}async function $JA(A,Q){let B=Date.now()+Q;while(Date.now()<B){if(MJA(A).length===0)return;await a$(20)}throw Error("Grok Leader generation still has live processes after termination")}function MJA(A){let Q=[];for(let B of aZ("/proc",{withFileTypes:!0})){if(!B.isDirectory()||!/^\d+$/.test(B.name))continue;let C=Number(B.name);if(C===process.pid)continue;try{let I=Cf(`/proc/${B.name}/environ`);if(I[ay]===A.ownerNonce||I.GROK_HOME===A.grokHome&&I.ANET_EXPECTED_PARENT_PID===A.expectedParentPid)Q.push(C)}catch{}}return Q.sort((B,C)=>B-C)}function VJA(A){if(!QJA(A.leaderSocket))return;let Q=Q8(A.leaderSocket);if(n$(Q,A.socket,"stale Grok Leader socket"),Ef(A.leaderSocket,A.listenerInode))throw Error("refusing to unlink a Grok Leader socket that still has a listener");IJA(A.leaderSocket)}function n$(A,Q,B){if(A.dev!==Q.dev||A.ino!==Q.ino||A.uid!==Q.uid)throw Error(`${B} identity changed`)}function WJA(A){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(A))throw Error("invalid Grok Leader owner generation marker")}function wJA(A){return A instanceof Error?A.message:String(A||"unknown error")}var ay="ANET_GROK_LEADER_OWNER",gJA="00010000",DJA="0001",UJA="01";var gf=()=>{};function Ff(A){let Q=typeof A==="string"?A.trim():"";if(!Q)return I8("invalid_model","a model id is required");if(Q.length>128)return I8("invalid_model","model id is longer than 128 characters");if(!LJA.test(Q))return I8("invalid_model",`model id ${JSON.stringify(Q)} is not a plain slug; it must start with a letter or digit and contain no whitespace, control characters, or leading dash`);return{ok:!0,model:Q,route:"hot",resume:!0}}function Yf(A){return{kind:"hot",method:"session/set_model",params:{sessionId:A.sessionId,modelId:A.modelId}}}function Jf(){return{kind:"restart",resume:!0}}function I8(A,Q){return{ok:!1,code:A,message:Q}}function Nf(A,Q,B){let C=Df(A,"previous"),I=Df(Q,"next");if(I===void 0)throw new DC("the rebuilt argv carries no --model flag");if(I!==B)throw new DC(`the rebuilt argv carries --model ${JSON.stringify(I)}, not the requested ${JSON.stringify(B)}`);let E=Uf(A),g=Uf(Q);if(E.length!==g.length)throw new DC(`a model switch changed the argument count (${E.length} → ${g.length}); only the --model operand may change`);for(let D=0;D<E.length;D++)if(E[D]!==g[D])throw new DC(`a model switch changed argv[${D}] from ${JSON.stringify(E[D])} to ${JSON.stringify(g[D])}; only the --model operand may change`)}function C8(A){let Q=[];for(let B=0;B<A.length;B++){if(A[B]==="--session-id"||A[B]==="--resume"){B++;continue}Q.push(A[B])}return Q}function Df(A,Q){let B;for(let C=0;C<A.length;C++){if(A[C]!=="--model")continue;if(B!==void 0)throw new DC(`the ${Q} argv carries more than one --model flag`);let I=A[C+1];if(I===void 0)throw new DC(`the ${Q} argv ends with a --model flag that has no operand`);B=I}return B}function Uf(A){let Q=[];for(let B=0;B<A.length;B++){if(A[B]==="--model"){B++;continue}Q.push(A[B])}return Q}var LJA,DC;var Gf=j(()=>{LJA=/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/;DC=class DC extends Error{constructor(A){super(A);this.name="GrokModelSwitchArgvError"}}});var w8={};_A(w8,{openGrokCopresenceRuntime:()=>hJA,isGrokPreviewAutomaticResolution:()=>Pf,hasGrokTuiReadyMarker:()=>Rf,grokVerifiedBuild:()=>qf,grokSessionDirectory:()=>Of,grokLeaderSocketTimeoutMs:()=>Tf,grokCopresenceThink:()=>mJA,grokCopresenceFailureSubcode:()=>xJA,grokCopresenceFailureCode:()=>vJA,grokBuildAutoLeader:()=>V8,formatNetworkTuiInput:()=>F8,buildGrokCopresenceArgs:()=>U8,assertGrokCopresenceVersion:()=>yJA,assertGrokCopresenceFeatures:()=>kJA,assertGrokCopresenceExternalSurfaces:()=>bJA,assertGrokCopresenceApprovalOwnership:()=>fJA,GrokCopresenceFailure:()=>UA,GROK_JSONL_TAIL_FAILURE_SUBCODES:()=>_f,GROK_COPRESENCE_VERIFIED_BUILDS:()=>A2,GROK_COPRESENCE_FAILURE_CODES:()=>jf});import{spawn as XJA}from"child_process";import{createHash as $f,randomUUID as Mf}from"crypto";import{closeSync as uF,constants as pC,existsSync as zf,fchmodSync as ZJA,fstatSync as e$,lstatSync as lE,mkdirSync as KJA,openSync as G8,readSync as Hf,realpathSync as D8}from"fs";import{dirname as s$,isAbsolute as uE,join as OI,resolve as mQ}from"path";import{createServer as zJA}from"node:net";import{setTimeout as cE}from"timers/promises";import{StringDecoder as g0}from"string_decoder";function Rf(A){let Q="",B="text";for(let C=0;C<A.length;C+=1){let I=A.charCodeAt(C),E=A[C];if(B==="text"){if(I===27)B="escape";else if(I===155)B="csi";else if(I===157)B="osc";else if(I===144||I===152||I===158||I===159)B="control-string";else if(I>=32&&I!==127&&!(I>=128&&I<=159))Q+=E;continue}if(B==="escape"){if(E==="[")B="csi";else if(E==="]")B="osc";else if(E==="P"||E==="X"||E==="^"||E==="_")B="control-string";else B="text";continue}if(B==="csi"){if(I>=64&&I<=126)B="text";continue}if(B==="osc"&&I===7){B="text";continue}if(I===27&&A[C+1]==="\\")C+=1,B="text"}return Q.includes(OJA)&&Q.includes(SJA)}function $8(A){return typeof A==="string"&&TJA.has(A)}function M8(A){return typeof A==="string"&&PJA.has(A)?A:"unknown"}function vJA(A){return A instanceof UA&&$8(A.failureCode)?A.failureCode:"unknown"}function xJA(A){if(!(A instanceof UA)||!$8(A.failureCode))return"unknown";if(A.failureCode==="jsonl_tail")return M8(A.failureSubcode);return A.failureSubcode==="none"?"none":"unknown"}function PB(A,Q){return new Q2(A,Q)}function BI(A,Q){try{return Q()}catch(B){if(B instanceof Q2)throw B;throw PB(A,B)}}function U8(A){if(W8(A.sessionId),J8(A.leaderSocket,"leader"),!uE(A.agentProfile)||A.agentProfile.includes("\x00"))throw Error("grok copresence requires an absolute runtime-owned agent profile");let Q=[...V8(A.grokVersion)?["--leader"]:[],"--leader-socket",A.leaderSocket,"--cwd",A.cwd,A.resume?"--resume":"--session-id",A.sessionId,"--agent",A.agentProfile,"--permission-mode","bypassPermissions","--always-approve"];if(A.model)Q.push("--model",A.model);if(A.maxTurns!==void 0)throw Error("grok copresence does not support maxTurns; Grok 0.2.93 ignores it in interactive TUI mode");if(A.toolAllowlist!==void 0)throw Error(`grok copresence uses a fixed preview tool profile (${xF.join(",")}); custom tools are unsupported`);if(Q.push("--sandbox",A.sandboxProfile,"--no-auto-update"),!vF)Q.push("--disable-web-search");Q.push("--no-subagents","--no-memory");for(let B of Ey)Q.push("--deny",B);if(!b$)for(let B of["read_file","grep","list_dir"])Q.push("--deny",B);if(!vF)Q.push("--deny","web_search");Q.push("--deny","Bash","--deny","Write","--deny","WebFetch");for(let B of A.protectedPaths??[])if(B){let C=uE(B)&&!YC(NQ())?B.replace(/\\/g,"/"):B;if(!uE(B)||/[\0\r\n\\*?()[\]{},]/.test(C))throw Error("grok copresence protected path cannot be represented safely as a permission rule");Q.push("--deny",`Read(${C})`,"--deny",`Read(${C}/**)`,"--deny",`Grep(${C})`,"--deny",`Grep(${C}/**)`,"--deny",`Edit(${C})`,"--deny",`Edit(${C}/**)`)}return Q}function kJA(A){let B=["--leader-socket","--session-id","--resume","--cwd","--sandbox","--agent","--deny","--permission-mode","--disable-web-search","--no-subagents"].filter((C)=>!A.includes(C));if(B.length)throw Error(`Grok CLI is too old for copresence; missing: ${B.join(", ")}`)}function bJA(A,Q,B=NQ()){let C;try{C=JSON.parse(A)}catch{throw Error("grok copresence inspect is not valid JSON")}let I=[],E=mQ(Q),g=(F)=>{let Y=mQ(F);return Y===E||Y.startsWith(`${E}/`)},D=C.externalCompat;if(D&&typeof D==="object"&&!Array.isArray(D)){if(D.remoteSettingsLoaded===!0)throw Error("grok copresence refuses a build with remote settings loaded");let F=D.cells;if(!Array.isArray(F))throw Error("grok copresence inspect is missing externalCompat cells");let Y=F.filter((N)=>N&&N.enabled!==!1).map((N)=>`${N?.vendor}.${N?.surface}`);if(Y.length)throw Error(`grok copresence refuses enabled cross-vendor compatibility cells: ${Y.join(", ")}`)}let U=C.permissions;if(U&&typeof U==="object"&&!Array.isArray(U)){if(U.managedSettingsActive===!0||U.managedSettingsExists===!0)throw Error(`grok copresence refuses active managed settings at ${String(U.managedSettingsPath||"(unknown path)")}`)}for(let F of["skills","agents","plugins","marketplaces","lspServers"]){let Y=C[F];if(Y===void 0)continue;if(!Array.isArray(Y))throw Error(`grok copresence inspect reports malformed ${F}`);for(let N of Y){if(!N||typeof N!=="object")throw Error(`grok copresence inspect reports malformed ${F} entry`);if(N.compatibilityStatus==="disabled")continue;if(N.compatibilityStatus==="unresolved")throw Error(`grok copresence refuses unresolved ${F} entry ${String(N.name||"(unnamed)")}`);let J=N.source,G=typeof J==="string"?J:J&&typeof J==="object"?J.path:void 0,$=typeof G==="string"&&uE(G)?G:void 0;if($===void 0)continue;if(!g($)){if(!B.homeIsolationHidesVendorSkills&&(F==="skills"||F==="agents")){I.push(`${F}: ${mQ($)}`);continue}throw Error(`grok copresence refuses external ${F} source ${mQ($)}; the fixed tool inventory must stay runtime-owned`)}}}return I}function qf(A){return A2.get((A??"").trim())}function V8(A){return qf(A)?.autoLeader??!0}function yJA(A){let Q=A.trim();if(!A2.has(Q))throw Error(`grok copresence requires a verified grok build; received ${Q||"empty version"}. Verified: ${[...A2.keys()].join(", ")}`)}function fJA(A,Q,B="bun",C=NQ()){let I=[],E;try{let G=JSON.parse(A);if(!G||typeof G!=="object"||Array.isArray(G))throw Error("non-object");E=G}catch{throw Error("grok copresence inspect returned invalid JSON")}let g=E.permissions;if(!g||typeof g!=="object"||Array.isArray(g))throw Error("grok copresence inspect is missing permissions metadata");let D=g;if(!Array.isArray(D.sources))throw Error("grok copresence inspect is missing permission sources");let U=mQ(Q);for(let G of D.sources){let $=typeof G==="string"?G.match(/^(.*?)(?: \([^)]+\))?$/)?.[1]:void 0;if(!$||!uE($))throw Error("grok copresence inspect contains an unknown permission source");let V=mQ($);if(V!==U&&!V.startsWith(`${U}/`))throw Error(`grok copresence refuses external permission source ${V}; approvals must stay human-owned`)}if(!Number.isSafeInteger(D.loaded)||D.loaded!==0||D.sources.length!==0)throw Error("grok copresence refuses preloaded permission rules; approvals must stay human-owned");if(!Array.isArray(D.skipped))throw Error("grok copresence inspect reports skipped or unknown permission rules");if(D.skipped.length!==0){if(C.homeIsolationHidesVendorSkills)throw Error("grok copresence inspect reports skipped or unknown permission rules");for(let G of D.skipped){let $=G&&typeof G==="object"?G.rule:G,V=G&&typeof G==="object"?G.reason:"";I.push(`permission rule (未生效): ${String($)}${V?` — ${V}`:""}`)}}for(let G of["mcpServerAllowlist","marketplaceAllowlist"])if(!Array.isArray(D[G])||D[G].length!==0)throw Error(`grok copresence refuses nonempty ${G}`);if(!Array.isArray(E.mcpServers)||E.mcpServers.length!==1)throw Error("grok copresence requires exactly one discovered commhub MCP server");let F=E.mcpServers[0];if(!F||typeof F!=="object"||Array.isArray(F))throw Error("grok copresence commhub MCP inspection is malformed");let Y=F,N=Y.source;if(Y.name!=="commhub"||Y.transport!=="stdio"||mQ(String(Y.target||""))!==mQ(B)||!N||typeof N!=="object"||Array.isArray(N)||N.type!=="configToml"||mQ(String(N.path||""))!==OI(U,"config.toml"))throw Error("grok copresence refuses any MCP server except its runtime-owned commhub stdio server");if(!Array.isArray(E.lspServers)||E.lspServers.length!==0)throw Error("grok copresence refuses discovered LSP servers");if(!Array.isArray(E.plugins)||E.plugins.length!==0)throw Error("grok copresence refuses discovered plugins");if(!Array.isArray(E.agents)||E.agents.some((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return!0;let $=G.source;return!$||typeof $!=="object"||Array.isArray($)||$.type!=="builtin"}))throw Error("grok copresence refuses discovered non-builtin agents");if([E.permissionMode,D.mode,D.defaultMode,D.effectiveMode].filter((G)=>typeof G==="string").some((G)=>G.trim().toLowerCase()!=="default"))throw Error("grok copresence inspect reports an unknown or non-default permission mode");return I}function Of(A,Q,B){return W8(B),OI(A,"sessions",encodeURIComponent(mQ(Q)),B)}function F8(A){if(Zf(A.from,"from"),Zf(A.taskId,"taskId"),A.message.includes("\x00"))throw Error("network task contains a NUL byte");let Q=A.message.replace(/\r\n?/g,`
|
|
161
|
-
`);if(/[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/.test(Q))throw Error("network task contains terminal control bytes");if(/<\/?user_query(?:\s|>)/i.test(Q))throw Error("network task contains reserved Grok user_query markup");let B=`[Agent Network/from=${A.from}/task=${A.taskId}] ${Q}`;if(Buffer.byteLength(B,"utf8")>Vf)throw Error(`network task exceeds ${Vf} bytes`);return`\x1B[200~${B}\x1B[201~\r`}async function hJA(A){let Q=new Sf(A);return await Q.open(),Q}function mJA(A,Q){return A.submit(Q)}function uJA(A){if(!A.length)return null;let Q=A[0];if(Q===13||Q===10||Q===3)return{bytes:A.subarray(0,1),decisive:!0};return null}function cJA(A){if(A.length>=3&&A[0]===27&&A[1]===79){let B=String.fromCharCode(A[2]);if("AB".includes(B))return{length:3,kind:"history"};if("CDHF".includes(B))return{length:3,kind:"edit"};return null}if(A.length<3||A[0]!==27||A[1]!==91)return null;let Q=Math.min(A.length,16);for(let B=2;B<Q;B++){let C=A[B];if(C<64||C>126)continue;let I=String.fromCharCode(C),E=A.subarray(2,B).toString("ascii");if("AB".includes(I))return{length:B+1,kind:"history"};if("CDHF".includes(I))return{length:B+1,kind:"edit"};if(I==="~"&&/^(?:1|3|4|7|8)(?:;\d+)*$/.test(E))return{length:B+1,kind:"edit"};if(I==="~"&&/^(?:5|6)(?:;\d+)*$/.test(E))return{length:B+1,kind:"viewport"};return null}return null}class Sf{opts;sessionId;leaderSocket;attachSocket;arbitration=uy();phaseSince=Date.now();logState=i$();pty=null;activeTui=null;currentModel;modelSwitchInFlight=null;lastSpawnArgs=null;attach=null;locks=[];chatTail=null;eventsTail=null;pollTimer=null;lifecycleBuffer="";recoveryLifecycleBuffer="";completionPendingSince=0;lastChatActivityAt=0;humanDecoder=new g0("utf8");humanPasteMode=!1;composerPending=Buffer.alloc(0);humanComposerAudit="";humanComposerAuditTainted=!1;humanComposerAuditUnsafe=!1;humanComposerAuditOverflow=!1;humanComposerSawSlash=!1;humanComposerLeadingSlash=!1;pending=new Map;deferredHuman=[];deferredHumanBytes=0;closing=!1;recovering=!1;opened=!1;fatalError=null;fatalShutdownPromise=null;retainLocksForUnconfirmedPty=!1;ownedLeader=null;leaderTeardownPromise=null;leaderOwnerNonce="";quarantinedNetworkTaskId="";approvalDecisionDispatched=!1;activePermissionRequestId=null;pendingAutomaticPermissions=new Map;pendingAutomaticPermissionTotal=0;activeTurnTerminalEventSeen=!1;spawnEnv;controlledSpawnEnv;ptyGeneration=0;ownedAnyTuiGeneration=!1;pendingTuiProcessIds=new Set;recoveryPromise=null;log;warn;tuiReadinessBuffer="";tuiComposerReady=!1;constructor(A){this.opts=A;this.sessionId=A.sessionId||Mf(),this.leaderSocket=A.leaderSocket,this.attachSocket=A.attachSocket,this.log=A.log??(()=>{}),this.warn=A.warn??(()=>{}),this.controlledSpawnEnv=KC(A.env),this.spawnEnv=KC(A.env,this.controlledSpawnEnv),this.currentModel=A.model}get isRunning(){return this.opened&&!this.closing&&!this.recovering&&this.pty!==null}get tuiReady(){return this.tuiComposerReady}liveness(){return WN(this)}get state(){return ly(this.arbitration)}get model(){return this.currentModel}async onAttachSetModel(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=pA(B);this.warn(`[grok-copresence] model switch to ${A} failed: ${C}`),this.attach?.broadcastStatus({...this.attachStatus(),modelSwitch:{ok:!1,code:"failed",message:C}});return}if(Q.ok)this.log(`[grok-copresence] model switch accepted: ${Q.model}`);else this.warn(`[grok-copresence] model switch refused (${Q.code}): ${Q.message}`);this.attach?.broadcastStatus({...this.attachStatus(),modelSwitch:Q})}async switchModel(A){let Q=Ff(A);if(!Q.ok)return Q;if(this.currentModel!==void 0&&this.currentModel===Q.model)return{ok:!1,code:"unchanged",message:`the co-presence TUI is already running ${Q.model}`};if(this.arbitration.phase!=="idle")return{ok:!1,code:"busy",message:`switching models is only safe while idle (current phase: ${this.arbitration.phase})`};if(!this.isRunning)return this.currentModel=Q.model,{ok:!0,model:Q.model,route:"restart",resume:!0};let B=Yf({sessionId:this.sessionId,modelId:Q.model});try{if(B.kind!=="hot")throw Error("unexpected non-hot Grok model switch decision");return await(this.opts.acpModelSwitch??((I)=>this.defaultAcpModelSwitch(I)))({method:B.method,params:B.params}),this.currentModel=Q.model,{ok:!0,model:Q.model,route:"hot",resume:!0}}catch(C){if(!eJA(C))throw C;if(Jf().kind!=="restart")throw Error("unexpected non-restart Grok model switch fallback");return await this.restartTuiForModelSwitch(Q.model),{ok:!0,model:Q.model,route:"restart",resume:!0}}}async restartTuiForModelSwitch(A){if(this.lastSpawnArgs){let B=U8({cwd:this.opts.cwd,sessionId:this.sessionId,resume:!0,leaderSocket:this.leaderSocket,model:A,agentProfile:this.opts.agentProfile,maxTurns:this.opts.maxTurns,toolAllowlist:this.opts.toolAllowlist,sandboxProfile:this.opts.sandboxProfile,protectedPaths:this.opts.protectedPaths,grokVersion:this.opts.grokVersion}),C=B.indexOf("--resume");if(C<0||B[C+1]!==this.sessionId)throw new DC(`a model switch must resume session ${this.sessionId}; the rebuilt argv does not`);Nf(C8(this.lastSpawnArgs),C8(B),A)}this.currentModel=A,this.modelSwitchInFlight=A;let Q=this.activeTui;try{await t$(Q?.pty??null,Q?.exit??null)}catch(B){throw this.modelSwitchInFlight=null,this.retainLocksForUnconfirmedPty=!0,B}}async defaultAcpModelSwitch(A){let Q=new TF;Q.start({binary:this.opts.binary,cwd:this.opts.cwd,env:this.spawnEnv,args:["agent","--leader","--leader-socket",this.leaderSocket,"stdio"]});try{let B=await Q.request("initialize",{protocolVersion:"1",clientCapabilities:{terminal:!1,fs:{readTextFile:!1,writeTextFile:!1}}},5000);if(new Set((B.authMethods??[]).map((I)=>I.id).filter(Boolean)).has("cached_token"))await Q.request("authenticate",{methodId:"cached_token",meta:{headless:!0}},5000);return await Q.request("session/load",{sessionId:A.params.sessionId,cwd:this.opts.cwd,mcpServers:[]},5000),await Q.request(A.method,A.params,1e4)}finally{await Q.close().catch(()=>{})}}async open(){if(this.opened)return;GY(NQ()),W8(this.sessionId),J8(this.leaderSocket,"leader"),J8(this.attachSocket,"attach"),g8(s$(this.leaderSocket)),g8(s$(this.attachSocket));let A=Of(this.opts.grokHome,this.opts.cwd,this.sessionId),Q=this.opts.newSession!==!0&&zf(A);if(this.opts.sessionId&&this.opts.newSession!==!0&&!Q)throw Error(`grok copresence cannot resume missing session ${this.sessionId} for cwd ${this.opts.cwd}`);try{let B=this.opts.flockBinary??"flock";this.locks.push(await bZ(this.opts.cwd,B,this.opts.env));let C=$f("sha256").update(this.leaderSocket).digest("hex").slice(0,20),I=OI(D8(this.opts.grokHome),"copresence-locks");g8(I);let E=$f("sha256").update(D8(this.opts.grokHome)).update("\x00").update(mQ(this.opts.cwd)).update("\x00").update(this.sessionId).digest("hex").slice(0,24);if(this.locks.push(await E8(OI(I,`.session-${E}.lock`),B,this.opts.env)),this.locks.push(await E8(OI(s$(this.leaderSocket),`.leader-${C}.lock`),B,this.opts.env)),oJA(this.leaderSocket,"leader"),this.locks.push(await E8(OI(s$(this.leaderSocket),`.bridge-${C}-${this.sessionId}.lock`),B,this.opts.env)),this.chatTail=new Y8(OI(A,"chat_history.jsonl"),"chat_history",Q),this.eventsTail=new Y8(OI(A,"events.jsonl"),"events",Q),Q)this.chatTail.arm(!0),this.eventsTail.arm(!0),lJA(A);if(await this.spawnTui(Q),await this.settleLeader(),!Q)this.chatTail.arm(!1),this.eventsTail.arm(!1);if(this.recoveryLifecycleBuffer="",!this.chatTail||!this.eventsTail)throw Error("grok copresence startup lost its JSONL cursors");if(await Xf(this.chatTail,this.eventsTail,(g)=>this.auditRecoveryLifecycleChunk(g)),this.recoveryLifecycleBuffer.trim())throw new iC("Grok startup events JSONL ended with an incomplete lifecycle record");this.logState=i$(),this.lifecycleBuffer="",this.attach=await Ty({socketPath:this.attachSocket,alias:this.opts.alias,sessionId:this.sessionId,onInput:(g)=>this.onHumanInput(g),onResize:(g,D)=>this.onResize(g,D),onDetach:()=>this.onHumanDetach(),onSetModel:(g)=>this.onAttachSetModel(g)}),this.startPolling(),this.opened=!0,await this.opts.onSession?.(this.sessionId),this.broadcastState(),this.log(`[grok-copresence] TUI ready session=${this.sessionId.slice(0,8)} attach=${this.attachSocket}`)}catch(B){throw await this.close().catch(()=>{}),B}}submit(A){if(this.fatalError)return Promise.reject(this.fatalError);if(!this.opened||this.closing)return Promise.reject(new UA("runtime_closed","grok copresence runtime is not running"));if(!A.taskId||!A.from)return Promise.reject(new UA("input_validation","grok copresence taskId/from are required"));if(this.pending.has(A.taskId)||this.arbitration.queue.some((I)=>I.taskId===A.taskId)||this.arbitration.activeTurn?.owner==="network"&&this.arbitration.activeTurn.task.taskId===A.taskId)return Promise.reject(new UA("input_validation",`duplicate grok copresence task ${A.taskId}`));let Q={taskId:A.taskId,from:A.from,message:A.text},B=A.timeoutMs??this.opts.turnTimeoutMs??600000;if(!Number.isFinite(B)||B<=0)return Promise.reject(new UA("input_validation","grok copresence timeout must be a positive finite number"));try{F8(Q)}catch(I){return Promise.reject(new UA("input_validation",pA(I)))}let C=this.arbitration.phase!=="idle"||this.arbitration.queue.length>0;return this.transition({type:"network_task_received",task:Q}),new Promise((I,E)=>{let g=setTimeout(()=>{this.pending.delete(A.taskId),this.transition({type:"network_task_cancelled",taskId:A.taskId}),E(new UA("timeout",`grok copresence task ${A.taskId} timed out after ${B}ms`))},B);if(g.unref?.(),this.pending.set(A.taskId,{resolve:I,reject:E,timer:g,queued:C,submitted:!1,consumed:!1,onSubmitted:A.onSubmitted,onConsumed:A.onConsumed}),setImmediate(()=>this.scheduleNetworkIfIdle()),this.broadcastState(),C){let D=Date.now()-this.phaseSince;this.log(`[grok-copresence] queued network task ${A.taskId} (phase=${this.arbitration.phase}, ${Math.round(D/1000)}s in phase, ${this.arbitration.queue.length} queued)`);let U=xy({phase:this.arbitration.phase,phaseAgeMs:D,alreadyQueued:Math.max(0,this.arbitration.queue.length-1),taskTimeoutMs:B});if(U)this.warn(`[grok-copresence] ${U}`)}})}async close(){if(this.closing){await this.fatalShutdownPromise?.catch(()=>{});return}if(this.closing=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null;for(let[Q,B]of this.pending)clearTimeout(B.timer),B.reject(new UA("runtime_closed",`grok copresence runtime closed while task ${Q} was pending`));this.pending.clear(),await this.attach?.close().catch(()=>{}),this.attach=null,await this.recoveryPromise?.catch(()=>{}),this.disposeJsonlTails();let A=this.activeTui;await t$(A?.pty??null,A?.exit??null).then(()=>{this.detachTuiGeneration(A)}).catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] PTY termination failed: ${pA(Q)}`)}),await this.teardownOwnedLeader().catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] retaining locks: ${pA(Q)}`)});try{await this.finalizeStoppedState()}finally{this.opened=!1}}async spawnTui(A){try{let Y=await this.opts.beforeSpawn?.({resume:A});if(Y)this.spawnEnv=KC(Y,this.controlledSpawnEnv)}catch(Y){throw new mF(`grok copresence pre-spawn audit failed: ${pA(Y)}`)}if(mQ(String(this.spawnEnv.GROK_HOME||""))!==mQ(this.opts.grokHome)||mQ(String(this.spawnEnv.HOME||""))!==mQ(this.opts.grokHome))throw new mF("grok copresence spawn audit returned an unexpected HOME/GROK_HOME");try{Dy(this.opts.agentProfile,this.opts.grokHome)}catch(Y){throw new mF(`grok copresence agent profile audit failed: ${pA(Y)}`)}let Q=++this.ptyGeneration;this.leaderOwnerNonce=Mf(),this.tuiComposerReady=!1,this.tuiReadinessBuffer="";let B=this.opts.binary??"grok",C=uE(B)?B:SZ(B,String(this.spawnEnv.PATH||process.env.PATH||"")),I=U8({cwd:this.opts.cwd,sessionId:this.sessionId,resume:A,leaderSocket:this.leaderSocket,model:this.currentModel,agentProfile:this.opts.agentProfile,maxTurns:this.opts.maxTurns,toolAllowlist:this.opts.toolAllowlist,sandboxProfile:this.opts.sandboxProfile,protectedPaths:this.opts.protectedPaths,grokVersion:this.opts.grokVersion});this.lastSpawnArgs=[...I];let g=await(this.opts.ptySpawn??nJA)(C,I,{name:"xterm-256color",cols:120,rows:36,cwd:this.opts.cwd,env:B7(this.spawnEnv,this.controlledSpawnEnv,this.opts.cwd,"xterm-256color",this.opts.sandboxProfile,this.leaderOwnerNonce)}),D,U=new Promise((Y)=>{D=Y}),F={generation:Q,pty:g,exit:U,exited:!1};return this.pendingTuiProcessIds.add(g.pid),this.ownedAnyTuiGeneration=!0,this.pty=g,this.activeTui=F,g.onData((Y)=>{if(this.activeTui!==F||Q!==this.ptyGeneration||this.closing)return;this.observeTuiReadiness(Q,Y),this.attach?.broadcastOutput(Y)}),g.onExit((Y)=>{if(F.exited=!0,D(),this.activeTui!==F||Q!==this.ptyGeneration||this.closing)return;if(this.tuiComposerReady=!1,this.tuiReadinessBuffer="",this.recovering)return;this.pty=null,this.activeTui=null;let N=this.recoverFromExit(Y,g.pid);this.recoveryPromise=N;let J=()=>{if(this.recoveryPromise===N)this.recoveryPromise=null};N.then(J,(G)=>{J(),this.warn(`[grok-copresence] recovery failed: ${pA(G)}`)})}),F}async recoverFromExit(A,Q){if(this.recovering||this.closing)return;if(this.recovering=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null,this.transition({type:"disconnected"});let B=this.modelSwitchInFlight;if(this.modelSwitchInFlight=null,this.warn(B?`[grok-copresence] TUI stopped to switch model to ${B}; resuming same session`:`[grok-copresence] TUI exited code=${A.exitCode} signal=${A.signal??"-"}; resuming same session`),this.arbitration.waitingHuman){await this.failFatal(new UA("approval_boundary","grok TUI exited while a human approval was pending; refusing resume into an ambiguous permission UI"));return}try{await this.teardownOwnedLeader()}catch(E){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("leader_lifecycle",`Grok Leader death was not confirmed; refusing recovery: ${pA(E)}`));return}try{this.cleanupConfirmedTuiGeneration(Q)}catch{this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit","Grok stopped-generation containment cleanup failed; refusing recovery"));return}let C=Math.max(1,this.opts.reconnectAttempts??3),I;for(let E=1;E<=C&&!this.closing;E++){let g=null;try{if(this.closing)return;if(await cE(Math.min(1000,E*250)),this.closing)return;if(g=await this.spawnTui(!0),this.assertOwnedTuiGeneration(g,"spawn"),this.assertOwnedTuiGeneration(g,"leader socket"),await this.settleLeader(),this.assertLiveTuiGeneration(g,"leader bind"),this.closing)return;if(this.recoveryLifecycleBuffer="",!this.chatTail||!this.eventsTail)throw Error("grok copresence recovery lost its JSONL cursors");if(await Xf(this.chatTail,this.eventsTail,(U)=>this.auditRecoveryLifecycleChunk(U)),this.assertLiveTuiGeneration(g,"recovery drain"),this.closing)return;if(this.recoveryLifecycleBuffer.trim())throw new iC("Grok events JSONL ended with an incomplete lifecycle record during recovery");this.logState=i$(),this.lifecycleBuffer="",this.approvalDecisionDispatched=!1,this.activePermissionRequestId=null,this.clearAutomaticPermissionCorrelation(),this.resetHumanComposerAudit(),this.completionPendingSince=0,this.lastChatActivityAt=0;let D=this.arbitration.recoveryFrom;if(this.transition({type:"reconnected"}),this.recovering=!1,this.startPolling(),D==="network_turn"&&this.arbitration.activeTurn?.owner==="network"){let U=this.arbitration.activeTurn.task;this.failPending(U.taskId,new UA("tui_exit",`grok TUI restarted during task ${U.taskId}; task was not replayed to avoid duplicate side effects`)),hF(this.logState,U.taskId),this.transition({type:"turn_completed",owner:"network"})}else if(D==="human_turn")this.transition({type:"turn_completed",owner:"human"});else if(D==="human_editing")this.transition({type:"human_input_cancelled"});this.replayDeferredHumanOrSchedule(),this.log(`[grok-copresence] resumed session after PTY restart (attempt ${E})`);return}catch(D){if(I=D,this.closing)return;let U=g??this.activeTui;try{await t$(U?.pty??null,U?.exit??null)}catch(F){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit",`Grok PTY death was not confirmed; refusing another TUI spawn: ${pA(F)}`));return}this.detachTuiGeneration(U);try{await this.teardownOwnedLeader()}catch(F){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("leader_lifecycle",`Grok Leader death was not confirmed; refusing another TUI spawn: ${pA(F)}`));return}if(U)try{this.cleanupConfirmedTuiGeneration(U.pty.pid)}catch{this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit","Grok failed recovery generation could not be contained"));return}if(D instanceof mF||D instanceof iC){await this.failFatal(tJA(D));return}this.warn(`[grok-copresence] resume attempt ${E}/${C} failed: ${pA(D)}`)}}if(this.closing)return;await this.failFatal(new UA("tui_exit",`grok copresence could not resume session: ${pA(I)}`))}failFatal(A){if(this.fatalShutdownPromise)return this.fatalShutdownPromise;if(this.fatalError)return Promise.resolve();if(this.fatalError=A,this.closing=!0,this.recovering=!1,this.opened=!1,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null,this.disposeJsonlTails(),this.attach?.broadcastStatus({...this.attachStatus(),fatal:A.message});for(let Q of[...this.pending.keys()])this.failPending(Q,A);return this.fatalShutdownPromise=(async()=>{let Q=this.activeTui;await t$(Q?.pty??null,Q?.exit??null).then(()=>{this.detachTuiGeneration(Q)}).catch(()=>{this.retainLocksForUnconfirmedPty=!0}),await this.teardownOwnedLeader().catch(()=>{this.retainLocksForUnconfirmedPty=!0}),await this.attach?.close().catch(()=>{}),this.attach=null,await this.finalizeStoppedState()})(),this.fatalShutdownPromise}disposeJsonlTails(){let A=[this.chatTail,this.eventsTail];this.chatTail=null,this.eventsTail=null;for(let Q of A)try{Q?.dispose()}catch(B){this.warn(`[grok-copresence] JSONL tail close failed: ${pA(B)}`)}}async finalizeStoppedState(){if(this.retainLocksForUnconfirmedPty)return;if(this.ownedAnyTuiGeneration){try{vZ({stateHome:this.opts.grokHome,projectCwd:this.opts.cwd,leaderSocket:this.leaderSocket,tuiProcessIds:[...this.pendingTuiProcessIds]})}catch(A){throw this.retainLocksForUnconfirmedPty=!0,Error(`grok post-stop containment cleanup failed: ${pA(A)}`)}this.pendingTuiProcessIds.clear()}for(let A of this.locks.reverse())await A.release().catch(()=>{});this.locks=[]}assertOwnedTuiGeneration(A,Q){if(this.activeTui!==A||this.pty!==A.pty||this.ptyGeneration!==A.generation)throw Error(`Grok recovery TUI ownership changed before ${Q}`)}assertLiveTuiGeneration(A,Q){if(this.assertOwnedTuiGeneration(A,Q),A.exited)throw Error(`Grok recovery TUI exited before ${Q}`)}detachTuiGeneration(A){if(!A||this.activeTui!==A)return;if(this.activeTui=null,this.pty=null,this.tuiComposerReady=!1,this.tuiReadinessBuffer="",this.ptyGeneration===A.generation)this.ptyGeneration+=1}cleanupConfirmedTuiGeneration(A){if(!this.pendingTuiProcessIds.has(A))throw Error("Grok stopped-generation PID was not bound to this runtime");PZ({stateHome:this.opts.grokHome,projectCwd:this.opts.cwd,tuiProcessId:A}),this.pendingTuiProcessIds.delete(A)}async settleLeader(){if(V8(this.opts.grokVersion)){await rJA(this.leaderSocket,Tf()),await this.bindSpawnedLeader();return}try{lE(this.leaderSocket)}catch(A){if(cF(A,"ENOENT"))return;throw A}throw this.retainLocksForUnconfirmedPty=!0,new UA("leader_lifecycle",`this grok build was verified as leaderless yet created ${this.leaderSocket}; tool calls may be delegated outside the sandboxed process`)}async bindSpawnedLeader(){if(!this.leaderOwnerNonce)throw this.retainLocksForUnconfirmedPty=!0,Error("Grok Leader generation marker was not initialized");try{this.ownedLeader=await sy({generation:this.ptyGeneration,binary:this.opts.binary??"grok",binaryPathEnv:String(this.spawnEnv.PATH||"/usr/local/bin:/usr/bin:/bin"),leaderSocket:this.leaderSocket,grokHome:this.opts.grokHome,sandboxProfile:this.opts.sandboxProfile,ownerNonce:this.leaderOwnerNonce,expectedParentPid:String(this.controlledSpawnEnv.ANET_EXPECTED_PARENT_PID||"")})}catch(A){throw this.retainLocksForUnconfirmedPty=!0,new UA("leader_lifecycle",`could not bind the Grok Leader to this TUI generation: ${pA(A)}`)}}teardownOwnedLeader(){if(this.leaderTeardownPromise)return this.leaderTeardownPromise;let A=this.ownedLeader;if(!A)return Promise.resolve();let Q=ty(A).then(()=>{if(this.ownedLeader===A)this.ownedLeader=null;if(this.leaderOwnerNonce===A.ownerNonce)this.leaderOwnerNonce=""}),B;return B=Q.finally(()=>{if(this.leaderTeardownPromise===B)this.leaderTeardownPromise=null}),this.leaderTeardownPromise=B,this.leaderTeardownPromise}onHumanInput(A){if(!A.length||this.closing)return;if(!this.pty){this.deferHumanInput(A);return}if(this.arbitration.waitingHuman){if(!this.activePermissionRequestId){this.failFatal(new UA("approval_boundary","grok copresence approval input had no correlated request_id"));return}if(this.approvalDecisionDispatched){this.attach?.broadcastStatus({...this.attachStatus(),warning:"approval decision is pending; additional input was dropped"});return}let Q=uJA(A);if(!Q){this.attach?.broadcastStatus({...this.attachStatus(),warning:"unsupported approval input was dropped; co-presence permits only Enter (allow once) or Ctrl-C"});return}if(this.writeHumanBytes(Q.bytes),Q.decisive)this.approvalDecisionDispatched=!0;if(Q.bytes.length<A.length)this.attach?.broadcastStatus({...this.attachStatus(),warning:"only one approval key is accepted per input frame; trailing input was dropped"});return}this.processComposerInput(A)}processComposerInput(A){let Q=this.composerPending.length?Buffer.concat([this.composerPending,A]):A;this.composerPending=Buffer.alloc(0);let B=Buffer.from("\x1B[200~","binary"),C=Buffer.from("\x1B[201~","binary"),I=0;while(I<Q.length){if(this.arbitration.phase==="network_turn"||this.arbitration.phase==="human_turn"||this.arbitration.phase==="recovering"){this.deferHumanInput(Q.subarray(I));return}if(Q[I]===15){I+=1,this.warnBlockedPermissionModeChange("Ctrl+O");continue}if(Q.subarray(I,I+3).equals(Buffer.from("\x1B[Z","binary"))){I+=3,this.warnBlockedPermissionModeChange("Shift+Tab");continue}if(Q[I]===27){let Y=Q.subarray(I);if(Y.length<B.length&&(B.subarray(0,Y.length).equals(Y)||C.subarray(0,Y.length).equals(Y))){this.composerPending=Buffer.from(Y);return}if(Y.subarray(0,B.length).equals(B)){if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});this.writeHumanBytes(B),this.humanPasteMode=!0,I+=B.length;continue}if(Y.subarray(0,C.length).equals(C)){this.writeHumanBytes(C),this.humanPasteMode=!1,I+=C.length;continue}if(!this.humanPasteMode){let J=cJA(Y);if(J){if(J.kind==="history"){this.warnBlockedPermissionModeChange("composer history navigation");return}if(J.kind==="viewport"){this.writeHumanBytes(Y.subarray(0,J.length)),I+=J.length;continue}if(this.humanComposerSawSlash){if(this.writeHumanBytes(Buffer.from("\x03","binary")),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing")this.transition({type:"human_input_cancelled"});this.warnBlockedPermissionModeChange("editor navigation after slash input"),this.scheduleNetworkIfIdle();return}if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});this.writeHumanBytes(Y.subarray(0,J.length)),this.humanComposerAuditTainted=!0,I+=J.length;continue}let G=uZ(Y);this.warnBlockedPermissionModeChange(G??"unknown terminal control sequence");return}}let E=Q[I];if(!this.humanPasteMode&&E<32&&![3,8,10,13,21].includes(E)){let Y=uZ(Q.subarray(I));I+=1,this.warnBlockedPermissionModeChange(Y??"unknown editor control key");continue}if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});let D=Q.subarray(I,I+1),U=Q[I];I+=1;let F=!this.humanPasteMode&&(U===13||U===10);if(F&&this.isForbiddenHumanModeCommand()){if(this.writeHumanBytes(Buffer.from("\x03","binary")),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing")this.transition({type:"human_input_cancelled"});if(this.warnBlockedPermissionModeChange("slash command"),I<Q.length)this.attach?.broadcastStatus({...this.attachStatus(),warning:"trailing input after a blocked permission-mode command was dropped"});this.scheduleNetworkIfIdle();return}if(U===47&&this.humanComposerAuditTainted){this.warnBlockedPermissionModeChange("slash after unmodelled editor control");continue}if(F&&this.arbitration.phase==="human_editing")try{fy(this.logState)}catch(Y){this.failFatal(new UA("correlation",pA(Y)));return}if(this.writeHumanBytes(D),this.auditHumanComposerByte(U),!this.humanPasteMode&&U===3&&this.arbitration.phase==="human_editing"){this.resetHumanComposerAudit(),this.transition({type:"human_input_cancelled"});continue}if(F&&this.arbitration.phase==="human_editing"){if(this.resetHumanComposerAudit(),this.transition({type:"human_input_submitted"}),I<Q.length)this.deferHumanInput(Q.subarray(I));return}}if(this.arbitration.phase==="idle")this.scheduleNetworkIfIdle()}auditHumanComposerByte(A){if(A===8||A===127){if(this.humanComposerAudit=this.humanComposerAudit.slice(0,-1),!this.humanComposerAuditTainted&&!this.humanComposerAuditOverflow)this.humanComposerSawSlash=this.humanComposerAudit.includes("/"),this.humanComposerLeadingSlash=/^\s*\//.test(this.humanComposerAudit)}else if(A===21)this.resetHumanComposerAudit();else if(A>=32&&A<=126){let Q=String.fromCharCode(A);if(Q==="/"){if(this.humanComposerSawSlash=!0,!this.humanComposerAudit.trim())this.humanComposerLeadingSlash=!0}if(this.humanComposerAudit+=Q,this.humanComposerAudit.length>8192)this.humanComposerAudit=this.humanComposerAudit.slice(-8192),this.humanComposerAuditOverflow=!0,this.humanComposerAuditTainted=!0,this.humanComposerAuditUnsafe=!0}}isForbiddenHumanModeCommand(){return this.humanComposerLeadingSlash||this.humanComposerAuditUnsafe}resetHumanComposerAudit(){this.humanComposerAudit="",this.humanComposerAuditTainted=!1,this.humanComposerAuditUnsafe=!1,this.humanComposerAuditOverflow=!1,this.humanComposerSawSlash=!1,this.humanComposerLeadingSlash=!1}warnBlockedPermissionModeChange(A){let Q=`${A} was blocked: Grok co-presence keeps its runtime-owned always-approve policy immutable`;this.warn(`[grok-copresence] ${Q}`),this.attach?.broadcastStatus({...this.attachStatus(),warning:Q})}onResize(A,Q){try{this.pty?.resize(A,Q)}catch(B){this.warn(`[grok-copresence] resize failed: ${pA(B)}`)}}writeHumanBytes(A){if(!this.pty||!A.length)return;let Q=this.humanDecoder.write(A);if(Q)this.pty.write(Q)}onHumanDetach(){if(this.deferredHuman=[],this.deferredHumanBytes=0,this.humanDecoder=new g0("utf8"),this.humanPasteMode=!1,this.composerPending=Buffer.alloc(0),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing"){try{this.pty?.write("\x03")}catch{}this.transition({type:"human_input_cancelled"}),this.scheduleNetworkIfIdle()}this.broadcastState()}deferHumanInput(A){if(this.deferredHumanBytes+A.length>HJA){this.attach?.broadcastStatus({...this.attachStatus(),warning:"human input buffer full; further input was dropped"});return}this.deferredHuman.push(Buffer.from(A)),this.deferredHumanBytes+=A.length,this.broadcastState()}replayDeferredHumanOrSchedule(){if(this.arbitration.phase!=="idle")return;if(this.deferredHuman.length){let A=Buffer.concat(this.deferredHuman,this.deferredHumanBytes);this.deferredHuman=[],this.deferredHumanBytes=0,this.onHumanInput(A)}if(this.arbitration.phase==="idle")this.scheduleNetworkIfIdle()}observeTuiReadiness(A,Q){if(A!==this.ptyGeneration||this.tuiComposerReady||this.closing)return;if(this.tuiReadinessBuffer=`${this.tuiReadinessBuffer}${Q}`.slice(-RJA),!Rf(this.tuiReadinessBuffer))return;this.tuiComposerReady=!0,this.tuiReadinessBuffer="",this.log(`[grok-copresence] TUI input ready generation=${A}`),this.broadcastState();try{this.opts.onTuiReady?.()}catch(B){this.warn(`[grok-copresence] onTuiReady callback failed: ${pA(B)}`)}if(!this.recovering)setImmediate(()=>this.scheduleNetworkIfIdle())}scheduleNetworkIfIdle(){if(!this.pty||!this.tuiComposerReady||this.recovering||this.closing)return;let A=this.transition({type:"schedule_network"});for(let Q of A.effects){if(Q.type!=="inject_network_task")continue;try{lZ(this.logState,{from:Q.task.from,taskId:Q.task.taskId}),this.pty.write(F8(Q.task));let B=this.pending.get(Q.task.taskId);if(B&&!B.submitted){B.submitted=!0;try{B.onSubmitted?.()}catch(C){this.warn(`[grok-copresence] runtime-submitted callback failed: ${pA(C)}`)}}this.log(`[grok-copresence] injected network task ${Q.task.taskId} from=${Q.task.from}`)}catch(B){hF(this.logState,Q.task.taskId),this.failPending(Q.task.taskId,new UA("tui_exit",`grok copresence could not write the network turn to its TUI: ${pA(B)}`)),this.transition({type:"turn_completed",owner:"network"}),setImmediate(()=>this.replayDeferredHumanOrSchedule())}}}pollLogs(){if(this.closing)return;try{this.chatTail?.poll((A)=>BI("chat.reduce.state_invariant",()=>this.reduceLogChunk("chat_history",A)),()=>BI("chat.reduce.state_invariant",()=>this.resetLogFraming("chat_history"))),this.eventsTail?.poll((A)=>{this.reduceEventsChunkInOrder(A)},()=>BI("events.reduce.state_invariant",()=>this.resetLogFraming("events"))),BI("combined.flush.state_invariant",()=>this.flushSettledCompletion())}catch(A){let Q=A instanceof Q2?M8(A.failureSubcode):"unknown",B=new UA("jsonl_tail",`grok copresence lost its trusted JSONL tail: ${pA(A)}`,Q);this.warn(`[grok-copresence] ${B.message}`),this.failFatal(B)}}startPolling(){if(this.pollTimer||this.closing)return;this.pollTimer=setInterval(()=>this.pollLogs(),Math.max(25,this.opts.pollIntervalMs??100)),this.pollTimer.unref?.()}reduceLogChunk(A,Q){if(A==="chat_history"&&Q)this.lastChatActivityAt=Date.now();let B=hy(this.logState,A,Q);this.logState=B.state;for(let C of B.events)this.handleLogEvent(C)}reduceEventsChunkInOrder(A){let Q=0;while(Q<A.length&&!this.closing){let B=A.indexOf(`
|
|
161
|
+
`);if(/[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/.test(Q))throw Error("network task contains terminal control bytes");if(/<\/?user_query(?:\s|>)/i.test(Q))throw Error("network task contains reserved Grok user_query markup");let B=`[Agent Network/from=${A.from}/task=${A.taskId}] ${Q}`;if(Buffer.byteLength(B,"utf8")>Vf)throw Error(`network task exceeds ${Vf} bytes`);return`\x1B[200~${B}\x1B[201~\r`}async function hJA(A){let Q=new Sf(A);return await Q.open(),Q}function mJA(A,Q){return A.submit(Q)}function uJA(A){if(!A.length)return null;let Q=A[0];if(Q===13||Q===10||Q===3)return{bytes:A.subarray(0,1),decisive:!0};return null}function cJA(A){if(A.length>=3&&A[0]===27&&A[1]===79){let B=String.fromCharCode(A[2]);if("AB".includes(B))return{length:3,kind:"history"};if("CDHF".includes(B))return{length:3,kind:"edit"};return null}if(A.length<3||A[0]!==27||A[1]!==91)return null;let Q=Math.min(A.length,16);for(let B=2;B<Q;B++){let C=A[B];if(C<64||C>126)continue;let I=String.fromCharCode(C),E=A.subarray(2,B).toString("ascii");if("AB".includes(I))return{length:B+1,kind:"history"};if("CDHF".includes(I))return{length:B+1,kind:"edit"};if(I==="~"&&/^(?:1|3|4|7|8)(?:;\d+)*$/.test(E))return{length:B+1,kind:"edit"};if(I==="~"&&/^(?:5|6)(?:;\d+)*$/.test(E))return{length:B+1,kind:"viewport"};return null}return null}class Sf{opts;sessionId;leaderSocket;attachSocket;arbitration=uy();phaseSince=Date.now();logState=i$();pty=null;activeTui=null;currentModel;modelSwitchInFlight=null;lastSpawnArgs=null;attach=null;locks=[];chatTail=null;eventsTail=null;pollTimer=null;lifecycleBuffer="";recoveryLifecycleBuffer="";completionPendingSince=0;lastChatActivityAt=0;humanDecoder=new g0("utf8");humanPasteMode=!1;composerPending=Buffer.alloc(0);humanComposerAudit="";humanComposerAuditTainted=!1;humanComposerAuditUnsafe=!1;humanComposerAuditOverflow=!1;humanComposerSawSlash=!1;humanComposerLeadingSlash=!1;pending=new Map;deferredHuman=[];deferredHumanBytes=0;closing=!1;recovering=!1;opened=!1;fatalError=null;fatalShutdownPromise=null;retainLocksForUnconfirmedPty=!1;ownedLeader=null;leaderTeardownPromise=null;leaderOwnerNonce="";quarantinedNetworkTaskId="";approvalDecisionDispatched=!1;activePermissionRequestId=null;pendingAutomaticPermissions=new Map;pendingAutomaticPermissionTotal=0;activeTurnTerminalEventSeen=!1;spawnEnv;controlledSpawnEnv;ptyGeneration=0;ownedAnyTuiGeneration=!1;pendingTuiProcessIds=new Set;recoveryPromise=null;log;warn;tuiReadinessBuffer="";tuiComposerReady=!1;constructor(A){this.opts=A;this.sessionId=A.sessionId||Mf(),this.leaderSocket=A.leaderSocket,this.attachSocket=A.attachSocket,this.log=A.log??(()=>{}),this.warn=A.warn??(()=>{}),this.controlledSpawnEnv=KC(A.env),this.spawnEnv=KC(A.env,this.controlledSpawnEnv),this.currentModel=A.model}get isRunning(){return this.opened&&!this.closing&&!this.recovering&&this.pty!==null}get tuiReady(){return this.tuiComposerReady}liveness(){return WN(this)}get state(){return ly(this.arbitration)}get model(){return this.currentModel}async onAttachSetModel(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=pA(B);this.warn(`[grok-copresence] model switch to ${A} failed: ${C}`),this.attach?.broadcastStatus({...this.attachStatus(),modelSwitch:{ok:!1,code:"failed",message:C}});return}if(Q.ok)this.log(`[grok-copresence] model switch accepted: ${Q.model}`);else this.warn(`[grok-copresence] model switch refused (${Q.code}): ${Q.message}`);this.attach?.broadcastStatus({...this.attachStatus(),modelSwitch:Q})}async switchModel(A){let Q=Ff(A);if(!Q.ok)return Q;if(this.currentModel!==void 0&&this.currentModel===Q.model)return{ok:!1,code:"unchanged",message:`the co-presence TUI is already running ${Q.model}`};if(this.arbitration.phase!=="idle")return{ok:!1,code:"busy",message:`switching models is only safe while idle (current phase: ${this.arbitration.phase})`};if(!this.isRunning)return this.currentModel=Q.model,{ok:!0,model:Q.model,route:"restart",resume:!0};let B=Yf({sessionId:this.sessionId,modelId:Q.model});try{if(B.kind!=="hot")throw Error("unexpected non-hot Grok model switch decision");return await(this.opts.acpModelSwitch??((I)=>this.defaultAcpModelSwitch(I)))({method:B.method,params:B.params}),this.currentModel=Q.model,{ok:!0,model:Q.model,route:"hot",resume:!0}}catch(C){if(!eJA(C))throw C;if(Jf().kind!=="restart")throw Error("unexpected non-restart Grok model switch fallback");return await this.restartTuiForModelSwitch(Q.model),{ok:!0,model:Q.model,route:"restart",resume:!0}}}async restartTuiForModelSwitch(A){if(this.lastSpawnArgs){let B=U8({cwd:this.opts.cwd,sessionId:this.sessionId,resume:!0,leaderSocket:this.leaderSocket,model:A,agentProfile:this.opts.agentProfile,maxTurns:this.opts.maxTurns,toolAllowlist:this.opts.toolAllowlist,sandboxProfile:this.opts.sandboxProfile,protectedPaths:this.opts.protectedPaths,grokVersion:this.opts.grokVersion}),C=B.indexOf("--resume");if(C<0||B[C+1]!==this.sessionId)throw new DC(`a model switch must resume session ${this.sessionId}; the rebuilt argv does not`);Nf(C8(this.lastSpawnArgs),C8(B),A)}this.currentModel=A,this.modelSwitchInFlight=A;let Q=this.activeTui;try{await t$(Q?.pty??null,Q?.exit??null)}catch(B){throw this.modelSwitchInFlight=null,this.retainLocksForUnconfirmedPty=!0,B}}async defaultAcpModelSwitch(A){let Q=new TF;Q.start({binary:this.opts.binary,cwd:this.opts.cwd,env:this.spawnEnv,args:["agent","--leader","--leader-socket",this.leaderSocket,"stdio"]});try{let B=await Q.request("initialize",{protocolVersion:"1",clientCapabilities:{terminal:!1,fs:{readTextFile:!1,writeTextFile:!1}}},5000);if(new Set((B.authMethods??[]).map((I)=>I.id).filter(Boolean)).has("cached_token"))await Q.request("authenticate",{methodId:"cached_token",meta:{headless:!0}},5000);return await Q.request("session/load",{sessionId:A.params.sessionId,cwd:this.opts.cwd,mcpServers:[]},5000),await Q.request(A.method,A.params,1e4)}finally{await Q.close().catch(()=>{})}}async open(){if(this.opened)return;GY(NQ()),W8(this.sessionId),J8(this.leaderSocket,"leader"),J8(this.attachSocket,"attach"),g8(s$(this.leaderSocket)),g8(s$(this.attachSocket));let A=Of(this.opts.grokHome,this.opts.cwd,this.sessionId),Q=this.opts.newSession!==!0&&zf(A);if(this.opts.sessionId&&this.opts.newSession!==!0&&!Q)throw Error(`grok copresence cannot resume missing session ${this.sessionId} for cwd ${this.opts.cwd}`);try{let B=this.opts.flockBinary??"flock";this.locks.push(await bZ(this.opts.cwd,B,this.opts.env));let C=$f("sha256").update(this.leaderSocket).digest("hex").slice(0,20),I=OI(D8(this.opts.grokHome),"copresence-locks");g8(I);let E=$f("sha256").update(D8(this.opts.grokHome)).update("\x00").update(mQ(this.opts.cwd)).update("\x00").update(this.sessionId).digest("hex").slice(0,24);if(this.locks.push(await E8(OI(I,`.session-${E}.lock`),B,this.opts.env)),this.locks.push(await E8(OI(s$(this.leaderSocket),`.leader-${C}.lock`),B,this.opts.env)),oJA(this.leaderSocket,"leader"),this.locks.push(await E8(OI(s$(this.leaderSocket),`.bridge-${C}-${this.sessionId}.lock`),B,this.opts.env)),this.chatTail=new Y8(OI(A,"chat_history.jsonl"),"chat_history",Q),this.eventsTail=new Y8(OI(A,"events.jsonl"),"events",Q),Q)this.chatTail.arm(!0),this.eventsTail.arm(!0),lJA(A);if(await this.spawnTui(Q),await this.settleLeader(),!Q)this.chatTail.arm(!1),this.eventsTail.arm(!1);if(this.recoveryLifecycleBuffer="",!this.chatTail||!this.eventsTail)throw Error("grok copresence startup lost its JSONL cursors");if(await Xf(this.chatTail,this.eventsTail,(g)=>this.auditRecoveryLifecycleChunk(g)),this.recoveryLifecycleBuffer.trim())throw new iC("Grok startup events JSONL ended with an incomplete lifecycle record");this.logState=i$(),this.lifecycleBuffer="",this.attach=await Ty({socketPath:this.attachSocket,alias:this.opts.alias,sessionId:this.sessionId,onInput:(g)=>this.onHumanInput(g),onResize:(g,D)=>this.onResize(g,D),onDetach:()=>this.onHumanDetach(),onSetModel:(g)=>this.onAttachSetModel(g)}),this.startPolling(),this.opened=!0,await this.opts.onSession?.(this.sessionId),this.broadcastState(),this.log(`[grok-copresence] TUI ready session=${this.sessionId.slice(0,8)} attach=${this.attachSocket}`)}catch(B){throw await this.close().catch(()=>{}),B}}submit(A){if(this.fatalError)return Promise.reject(this.fatalError);if(!this.opened||this.closing)return Promise.reject(new UA("runtime_closed","grok copresence runtime is not running"));if(!A.taskId||!A.from)return Promise.reject(new UA("input_validation","grok copresence taskId/from are required"));if(this.pending.has(A.taskId)||this.arbitration.queue.some((I)=>I.taskId===A.taskId)||this.arbitration.activeTurn?.owner==="network"&&this.arbitration.activeTurn.task.taskId===A.taskId)return Promise.reject(new UA("input_validation",`duplicate grok copresence task ${A.taskId}`));let Q={taskId:A.taskId,from:A.from,message:A.text},B=A.timeoutMs??this.opts.turnTimeoutMs??600000;if(!Number.isFinite(B)||B<=0)return Promise.reject(new UA("input_validation","grok copresence timeout must be a positive finite number"));try{F8(Q)}catch(I){return Promise.reject(new UA("input_validation",pA(I)))}let C=this.arbitration.phase!=="idle"||this.arbitration.queue.length>0;return this.transition({type:"network_task_received",task:Q}),new Promise((I,E)=>{let g=setTimeout(()=>{this.pending.delete(A.taskId),this.transition({type:"network_task_cancelled",taskId:A.taskId}),E(new UA("timeout",`grok copresence task ${A.taskId} timed out after ${B}ms`))},B);if(g.unref?.(),this.pending.set(A.taskId,{resolve:I,reject:E,timer:g,queued:C,submitted:!1,consumed:!1,onSubmitted:A.onSubmitted,onConsumed:A.onConsumed}),setImmediate(()=>this.scheduleNetworkIfIdle()),this.broadcastState(),C){let D=Date.now()-this.phaseSince;this.log(`[grok-copresence] queued network task ${A.taskId} (phase=${this.arbitration.phase}, ${Math.round(D/1000)}s in phase, ${this.arbitration.queue.length} queued)`);let U=xy({phase:this.arbitration.phase,phaseAgeMs:D,alreadyQueued:Math.max(0,this.arbitration.queue.length-1),taskTimeoutMs:B});if(U)this.warn(`[grok-copresence] ${U}`)}})}async close(){if(this.closing){await this.fatalShutdownPromise?.catch(()=>{});return}if(this.closing=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null;for(let[Q,B]of this.pending)clearTimeout(B.timer),B.reject(new UA("runtime_closed",`grok copresence runtime closed while task ${Q} was pending`));this.pending.clear(),await this.attach?.close().catch(()=>{}),this.attach=null,await this.recoveryPromise?.catch(()=>{}),this.disposeJsonlTails();let A=this.activeTui;await t$(A?.pty??null,A?.exit??null).then(()=>{this.detachTuiGeneration(A)}).catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] PTY termination failed: ${pA(Q)}`)}),await this.teardownOwnedLeader().catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] retaining locks: ${pA(Q)}`)});try{await this.finalizeStoppedState()}finally{this.opened=!1}}async spawnTui(A){try{let Y=await this.opts.beforeSpawn?.({resume:A});if(Y)this.spawnEnv=KC(Y,this.controlledSpawnEnv)}catch(Y){throw new mF(`grok copresence pre-spawn audit failed: ${pA(Y)}`)}if(mQ(String(this.spawnEnv.GROK_HOME||""))!==mQ(this.opts.grokHome)||mQ(String(this.spawnEnv.HOME||""))!==mQ(this.opts.grokHome))throw new mF("grok copresence spawn audit returned an unexpected HOME/GROK_HOME");try{Dy(this.opts.agentProfile,this.opts.grokHome)}catch(Y){throw new mF(`grok copresence agent profile audit failed: ${pA(Y)}`)}let Q=++this.ptyGeneration;this.leaderOwnerNonce=Mf(),this.tuiComposerReady=!1,this.tuiReadinessBuffer="";let B=this.opts.binary??"grok",C=uE(B)?B:SZ(B,String(this.spawnEnv.PATH||process.env.PATH||"")),I=U8({cwd:this.opts.cwd,sessionId:this.sessionId,resume:A,leaderSocket:this.leaderSocket,model:this.currentModel,agentProfile:this.opts.agentProfile,maxTurns:this.opts.maxTurns,toolAllowlist:this.opts.toolAllowlist,sandboxProfile:this.opts.sandboxProfile,protectedPaths:this.opts.protectedPaths,grokVersion:this.opts.grokVersion});this.lastSpawnArgs=[...I];let g=await(this.opts.ptySpawn??nJA)(C,I,{name:"xterm-256color",cols:120,rows:36,cwd:this.opts.cwd,env:B7(this.spawnEnv,this.controlledSpawnEnv,this.opts.cwd,"xterm-256color",this.opts.sandboxProfile,this.leaderOwnerNonce)}),D,U=new Promise((Y)=>{D=Y}),F={generation:Q,pty:g,exit:U,exited:!1};return this.pendingTuiProcessIds.add(g.pid),this.ownedAnyTuiGeneration=!0,this.pty=g,this.activeTui=F,g.onData((Y)=>{if(this.activeTui!==F||Q!==this.ptyGeneration||this.closing)return;this.observeTuiReadiness(Q,Y),this.attach?.broadcastOutput(Y)}),g.onExit((Y)=>{if(F.exited=!0,D(),this.activeTui!==F||Q!==this.ptyGeneration||this.closing)return;if(this.tuiComposerReady=!1,this.tuiReadinessBuffer="",this.recovering)return;this.pty=null,this.activeTui=null;let N=this.recoverFromExit(Y,g.pid);this.recoveryPromise=N;let J=()=>{if(this.recoveryPromise===N)this.recoveryPromise=null};N.then(J,(G)=>{J(),this.warn(`[grok-copresence] recovery failed: ${pA(G)}`)})}),F}async recoverFromExit(A,Q){if(this.recovering||this.closing)return;if(this.recovering=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null,this.transition({type:"disconnected"});let B=this.modelSwitchInFlight;if(this.modelSwitchInFlight=null,this.warn(B?`[grok-copresence] TUI stopped to switch model to ${B}; resuming same session`:`[grok-copresence] TUI exited code=${A.exitCode} signal=${A.signal??"-"}; resuming same session`),this.arbitration.waitingHuman){await this.failFatal(new UA("approval_boundary","grok TUI exited while a human approval was pending; refusing resume into an ambiguous permission UI"));return}try{await this.teardownOwnedLeader()}catch(E){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("leader_lifecycle",`Grok Leader death was not confirmed; refusing recovery: ${pA(E)}`));return}try{this.cleanupConfirmedTuiGeneration(Q)}catch{this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit","Grok stopped-generation containment cleanup failed; refusing recovery"));return}let C=Math.max(1,this.opts.reconnectAttempts??3),I;for(let E=1;E<=C&&!this.closing;E++){let g=null;try{if(this.closing)return;if(await cE(Math.min(1000,E*250)),this.closing)return;if(g=await this.spawnTui(!0),this.assertOwnedTuiGeneration(g,"spawn"),this.assertOwnedTuiGeneration(g,"leader socket"),await this.settleLeader(),this.assertLiveTuiGeneration(g,"leader bind"),this.closing)return;if(this.recoveryLifecycleBuffer="",!this.chatTail||!this.eventsTail)throw Error("grok copresence recovery lost its JSONL cursors");if(await Xf(this.chatTail,this.eventsTail,(U)=>this.auditRecoveryLifecycleChunk(U)),this.assertLiveTuiGeneration(g,"recovery drain"),this.closing)return;if(this.recoveryLifecycleBuffer.trim())throw new iC("Grok events JSONL ended with an incomplete lifecycle record during recovery");this.logState=i$(),this.lifecycleBuffer="",this.approvalDecisionDispatched=!1,this.activePermissionRequestId=null,this.clearAutomaticPermissionCorrelation(),this.resetHumanComposerAudit(),this.completionPendingSince=0,this.lastChatActivityAt=0;let D=this.arbitration.recoveryFrom;if(this.transition({type:"reconnected"}),this.recovering=!1,this.startPolling(),D==="network_turn"&&this.arbitration.activeTurn?.owner==="network"){let U=this.arbitration.activeTurn.task;this.failPending(U.taskId,new UA("tui_exit",`grok TUI restarted during task ${U.taskId}; task was not replayed to avoid duplicate side effects`)),hF(this.logState,U.taskId),this.transition({type:"turn_completed",owner:"network"})}else if(D==="human_turn")this.transition({type:"turn_completed",owner:"human"});else if(D==="human_editing")this.transition({type:"human_input_cancelled"});this.replayDeferredHumanOrSchedule(),this.log(`[grok-copresence] resumed session after PTY restart (attempt ${E})`);return}catch(D){if(I=D,this.closing)return;let U=g??this.activeTui;try{await t$(U?.pty??null,U?.exit??null)}catch(F){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit",`Grok PTY death was not confirmed; refusing another TUI spawn: ${pA(F)}`));return}this.detachTuiGeneration(U);try{await this.teardownOwnedLeader()}catch(F){this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("leader_lifecycle",`Grok Leader death was not confirmed; refusing another TUI spawn: ${pA(F)}`));return}if(U)try{this.cleanupConfirmedTuiGeneration(U.pty.pid)}catch{this.retainLocksForUnconfirmedPty=!0,await this.failFatal(new UA("tui_exit","Grok failed recovery generation could not be contained"));return}if(D instanceof mF||D instanceof iC){await this.failFatal(tJA(D));return}this.warn(`[grok-copresence] resume attempt ${E}/${C} failed: ${pA(D)}`)}}if(this.closing)return;await this.failFatal(new UA("tui_exit",`grok copresence could not resume session: ${pA(I)}`))}failFatal(A){if(this.fatalShutdownPromise)return this.fatalShutdownPromise;if(this.fatalError)return Promise.resolve();if(this.fatalError=A,this.closing=!0,this.recovering=!1,this.opened=!1,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null,this.disposeJsonlTails(),this.attach?.broadcastStatus({...this.attachStatus(),fatal:A.message});for(let Q of[...this.pending.keys()])this.failPending(Q,A);return this.fatalShutdownPromise=(async()=>{let Q=this.activeTui;await t$(Q?.pty??null,Q?.exit??null).then(()=>{this.detachTuiGeneration(Q)}).catch(()=>{this.retainLocksForUnconfirmedPty=!0}),await this.teardownOwnedLeader().catch(()=>{this.retainLocksForUnconfirmedPty=!0}),await this.attach?.close().catch(()=>{}),this.attach=null,await this.finalizeStoppedState()})(),this.fatalShutdownPromise}disposeJsonlTails(){let A=[this.chatTail,this.eventsTail];this.chatTail=null,this.eventsTail=null;for(let Q of A)try{Q?.dispose()}catch(B){this.warn(`[grok-copresence] JSONL tail close failed: ${pA(B)}`)}}async finalizeStoppedState(){if(this.retainLocksForUnconfirmedPty)return;if(this.ownedAnyTuiGeneration){try{vZ({stateHome:this.opts.grokHome,projectCwd:this.opts.cwd,leaderSocket:this.leaderSocket,tuiProcessIds:[...this.pendingTuiProcessIds]})}catch(A){throw this.retainLocksForUnconfirmedPty=!0,Error(`grok post-stop containment cleanup failed: ${pA(A)}`)}this.pendingTuiProcessIds.clear()}for(let A of this.locks.reverse())await A.release().catch(()=>{});this.locks=[]}assertOwnedTuiGeneration(A,Q){if(this.activeTui!==A||this.pty!==A.pty||this.ptyGeneration!==A.generation)throw Error(`Grok recovery TUI ownership changed before ${Q}`)}assertLiveTuiGeneration(A,Q){if(this.assertOwnedTuiGeneration(A,Q),A.exited)throw Error(`Grok recovery TUI exited before ${Q}`)}detachTuiGeneration(A){if(!A||this.activeTui!==A)return;if(this.activeTui=null,this.pty=null,this.tuiComposerReady=!1,this.tuiReadinessBuffer="",this.ptyGeneration===A.generation)this.ptyGeneration+=1}cleanupConfirmedTuiGeneration(A){if(!this.pendingTuiProcessIds.has(A))throw Error("Grok stopped-generation PID was not bound to this runtime");PZ({stateHome:this.opts.grokHome,projectCwd:this.opts.cwd,tuiProcessId:A}),this.pendingTuiProcessIds.delete(A)}async settleLeader(){if(V8(this.opts.grokVersion)){await rJA(this.leaderSocket,Tf()),await this.bindSpawnedLeader();return}try{lE(this.leaderSocket)}catch(A){if(cF(A,"ENOENT"))return;throw A}throw this.retainLocksForUnconfirmedPty=!0,new UA("leader_lifecycle",`this grok build was verified as leaderless yet created ${this.leaderSocket}; tool calls may be delegated outside the sandboxed process`)}async bindSpawnedLeader(){if(!this.leaderOwnerNonce)throw this.retainLocksForUnconfirmedPty=!0,Error("Grok Leader generation marker was not initialized");try{this.ownedLeader=await sy({generation:this.ptyGeneration,binary:this.opts.binary??"grok",binaryPathEnv:String(this.spawnEnv.PATH||"/usr/local/bin:/usr/bin:/bin"),leaderSocket:this.leaderSocket,grokHome:this.opts.grokHome,sandboxProfile:this.opts.sandboxProfile,ownerNonce:this.leaderOwnerNonce,expectedParentPid:String(this.controlledSpawnEnv.ANET_EXPECTED_PARENT_PID||"")})}catch(A){throw this.retainLocksForUnconfirmedPty=!0,new UA("leader_lifecycle",`could not bind the Grok Leader to this TUI generation: ${pA(A)}`)}}teardownOwnedLeader(){if(this.leaderTeardownPromise)return this.leaderTeardownPromise;let A=this.ownedLeader;if(!A)return Promise.resolve();let Q=ty(A).then(()=>{if(this.ownedLeader===A)this.ownedLeader=null;if(this.leaderOwnerNonce===A.ownerNonce)this.leaderOwnerNonce=""}),B;return B=Q.finally(()=>{if(this.leaderTeardownPromise===B)this.leaderTeardownPromise=null}),this.leaderTeardownPromise=B,this.leaderTeardownPromise}onHumanInput(A){if(!A.length||this.closing)return;if(!this.pty){this.deferHumanInput(A);return}if(this.arbitration.waitingHuman){if(!this.activePermissionRequestId){this.failFatal(new UA("approval_boundary","grok copresence approval input had no correlated request_id"));return}if(this.approvalDecisionDispatched){this.attach?.broadcastStatus({...this.attachStatus(),warning:"approval decision is pending; additional input was dropped"});return}let Q=uJA(A);if(!Q){this.attach?.broadcastStatus({...this.attachStatus(),warning:"unsupported approval input was dropped; co-presence permits only Enter (allow once) or Ctrl-C"});return}if(this.writeHumanBytes(Q.bytes),Q.decisive)this.approvalDecisionDispatched=!0;if(Q.bytes.length<A.length)this.attach?.broadcastStatus({...this.attachStatus(),warning:"only one approval key is accepted per input frame; trailing input was dropped"});return}this.processComposerInput(A)}processComposerInput(A){let Q=this.composerPending.length?Buffer.concat([this.composerPending,A]):A;this.composerPending=Buffer.alloc(0);let B=Buffer.from("\x1B[200~","binary"),C=Buffer.from("\x1B[201~","binary"),I=0;while(I<Q.length){if(this.arbitration.phase==="network_turn"||this.arbitration.phase==="human_turn"||this.arbitration.phase==="recovering"){this.deferHumanInput(Q.subarray(I));return}if(Q[I]===15){I+=1,this.warnBlockedPermissionModeChange("Ctrl+O");continue}if(Q.subarray(I,I+3).equals(Buffer.from("\x1B[Z","binary"))){I+=3,this.warnBlockedPermissionModeChange("Shift+Tab");continue}if(Q[I]===27){let Y=Q.subarray(I);if(Y.length<B.length&&(B.subarray(0,Y.length).equals(Y)||C.subarray(0,Y.length).equals(Y))){this.composerPending=Buffer.from(Y);return}if(Y.subarray(0,B.length).equals(B)){if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});this.writeHumanBytes(B),this.humanPasteMode=!0,I+=B.length;continue}if(Y.subarray(0,C.length).equals(C)){this.writeHumanBytes(C),this.humanPasteMode=!1,I+=C.length;continue}if(!this.humanPasteMode){let J=cJA(Y);if(J){if(J.kind==="history"){this.warnBlockedPermissionModeChange("composer history navigation");return}if(J.kind==="viewport"){this.writeHumanBytes(Y.subarray(0,J.length)),I+=J.length;continue}if(this.humanComposerSawSlash){if(this.writeHumanBytes(Buffer.from("\x03","binary")),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing")this.transition({type:"human_input_cancelled"});this.warnBlockedPermissionModeChange("editor navigation after slash input"),this.scheduleNetworkIfIdle();return}if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});this.writeHumanBytes(Y.subarray(0,J.length)),this.humanComposerAuditTainted=!0,I+=J.length;continue}let G=uZ(Y);this.warnBlockedPermissionModeChange(G??"unknown terminal control sequence");return}}let E=Q[I];if(!this.humanPasteMode&&E<32&&![3,8,10,13,21].includes(E)){let Y=uZ(Q.subarray(I));I+=1,this.warnBlockedPermissionModeChange(Y??"unknown editor control key");continue}if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"});let D=Q.subarray(I,I+1),U=Q[I];I+=1;let F=!this.humanPasteMode&&(U===13||U===10);if(F&&this.isForbiddenHumanModeCommand()){let Y=this.humanComposerLeadingSlash?"slash command":"edited line (arrow/Home/End/Delete make the editor contents unverifiable; press Ctrl+U to clear and retype)";if(this.writeHumanBytes(Buffer.from("\x03","binary")),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing")this.transition({type:"human_input_cancelled"});if(this.warnBlockedPermissionModeChange(Y),I<Q.length)this.attach?.broadcastStatus({...this.attachStatus(),warning:"trailing input after a blocked permission-mode command was dropped"});this.scheduleNetworkIfIdle();return}if(U===47&&this.humanComposerAuditTainted){this.warnBlockedPermissionModeChange("slash after unmodelled editor control");continue}if(F&&this.arbitration.phase==="human_editing")try{fy(this.logState)}catch(Y){this.failFatal(new UA("correlation",pA(Y)));return}if(this.writeHumanBytes(D),this.auditHumanComposerByte(U),!this.humanPasteMode&&U===3&&this.arbitration.phase==="human_editing"){this.resetHumanComposerAudit(),this.transition({type:"human_input_cancelled"});continue}if(F&&this.arbitration.phase==="human_editing"){if(this.resetHumanComposerAudit(),this.transition({type:"human_input_submitted"}),I<Q.length)this.deferHumanInput(Q.subarray(I));return}}if(this.arbitration.phase==="idle")this.scheduleNetworkIfIdle()}auditHumanComposerByte(A){if(A===8||A===127){if(this.humanComposerAudit=this.humanComposerAudit.slice(0,-1),!this.humanComposerAuditTainted&&!this.humanComposerAuditOverflow)this.humanComposerSawSlash=this.humanComposerAudit.includes("/"),this.humanComposerLeadingSlash=/^\s*\//.test(this.humanComposerAudit)}else if(A===21)this.resetHumanComposerAudit();else if(A>=32&&A<=126){let Q=String.fromCharCode(A);if(Q==="/"){if(this.humanComposerSawSlash=!0,!this.humanComposerAudit.trim())this.humanComposerLeadingSlash=!0}if(this.humanComposerAudit+=Q,this.humanComposerAudit.length>8192)this.humanComposerAudit=this.humanComposerAudit.slice(-8192),this.humanComposerAuditOverflow=!0,this.humanComposerAuditTainted=!0,this.humanComposerAuditUnsafe=!0}}isForbiddenHumanModeCommand(){return this.humanComposerLeadingSlash||this.humanComposerAuditUnsafe}resetHumanComposerAudit(){this.humanComposerAudit="",this.humanComposerAuditTainted=!1,this.humanComposerAuditUnsafe=!1,this.humanComposerAuditOverflow=!1,this.humanComposerSawSlash=!1,this.humanComposerLeadingSlash=!1}warnBlockedPermissionModeChange(A){let Q=`${A} was blocked: Grok co-presence keeps its runtime-owned always-approve policy immutable`;if(this.warn(`[grok-copresence] ${Q}`),/slash/.test(A))this.attach?.broadcastOutput(`\r
|
|
162
|
+
[anet] 斜杠命令在共存会话被禁用;换模型请另开终端: anet grok model <node> <model>\r
|
|
163
|
+
`);this.attach?.broadcastStatus({...this.attachStatus(),warning:Q})}onResize(A,Q){try{this.pty?.resize(A,Q)}catch(B){this.warn(`[grok-copresence] resize failed: ${pA(B)}`)}}writeHumanBytes(A){if(!this.pty||!A.length)return;let Q=this.humanDecoder.write(A);if(Q)this.pty.write(Q)}onHumanDetach(){if(this.deferredHuman=[],this.deferredHumanBytes=0,this.humanDecoder=new g0("utf8"),this.humanPasteMode=!1,this.composerPending=Buffer.alloc(0),this.resetHumanComposerAudit(),this.arbitration.phase==="human_editing"){try{this.pty?.write("\x03")}catch{}this.transition({type:"human_input_cancelled"}),this.scheduleNetworkIfIdle()}this.broadcastState()}deferHumanInput(A){if(this.deferredHumanBytes+A.length>HJA){this.attach?.broadcastStatus({...this.attachStatus(),warning:"human input buffer full; further input was dropped"});return}this.deferredHuman.push(Buffer.from(A)),this.deferredHumanBytes+=A.length,this.broadcastState()}replayDeferredHumanOrSchedule(){if(this.arbitration.phase!=="idle")return;if(this.deferredHuman.length){let A=Buffer.concat(this.deferredHuman,this.deferredHumanBytes);this.deferredHuman=[],this.deferredHumanBytes=0,this.onHumanInput(A)}if(this.arbitration.phase==="idle")this.scheduleNetworkIfIdle()}observeTuiReadiness(A,Q){if(A!==this.ptyGeneration||this.tuiComposerReady||this.closing)return;if(this.tuiReadinessBuffer=`${this.tuiReadinessBuffer}${Q}`.slice(-RJA),!Rf(this.tuiReadinessBuffer))return;this.tuiComposerReady=!0,this.tuiReadinessBuffer="",this.log(`[grok-copresence] TUI input ready generation=${A}`),this.broadcastState();try{this.opts.onTuiReady?.()}catch(B){this.warn(`[grok-copresence] onTuiReady callback failed: ${pA(B)}`)}if(!this.recovering)setImmediate(()=>this.scheduleNetworkIfIdle())}scheduleNetworkIfIdle(){if(!this.pty||!this.tuiComposerReady||this.recovering||this.closing)return;let A=this.transition({type:"schedule_network"});for(let Q of A.effects){if(Q.type!=="inject_network_task")continue;try{lZ(this.logState,{from:Q.task.from,taskId:Q.task.taskId}),this.pty.write(F8(Q.task));let B=this.pending.get(Q.task.taskId);if(B&&!B.submitted){B.submitted=!0;try{B.onSubmitted?.()}catch(C){this.warn(`[grok-copresence] runtime-submitted callback failed: ${pA(C)}`)}}this.log(`[grok-copresence] injected network task ${Q.task.taskId} from=${Q.task.from}`)}catch(B){hF(this.logState,Q.task.taskId),this.failPending(Q.task.taskId,new UA("tui_exit",`grok copresence could not write the network turn to its TUI: ${pA(B)}`)),this.transition({type:"turn_completed",owner:"network"}),setImmediate(()=>this.replayDeferredHumanOrSchedule())}}}pollLogs(){if(this.closing)return;try{this.chatTail?.poll((A)=>BI("chat.reduce.state_invariant",()=>this.reduceLogChunk("chat_history",A)),()=>BI("chat.reduce.state_invariant",()=>this.resetLogFraming("chat_history"))),this.eventsTail?.poll((A)=>{this.reduceEventsChunkInOrder(A)},()=>BI("events.reduce.state_invariant",()=>this.resetLogFraming("events"))),BI("combined.flush.state_invariant",()=>this.flushSettledCompletion())}catch(A){let Q=A instanceof Q2?M8(A.failureSubcode):"unknown",B=new UA("jsonl_tail",`grok copresence lost its trusted JSONL tail: ${pA(A)}`,Q);this.warn(`[grok-copresence] ${B.message}`),this.failFatal(B)}}startPolling(){if(this.pollTimer||this.closing)return;this.pollTimer=setInterval(()=>this.pollLogs(),Math.max(25,this.opts.pollIntervalMs??100)),this.pollTimer.unref?.()}reduceLogChunk(A,Q){if(A==="chat_history"&&Q)this.lastChatActivityAt=Date.now();let B=hy(this.logState,A,Q);this.logState=B.state;for(let C of B.events)this.handleLogEvent(C)}reduceEventsChunkInOrder(A){let Q=0;while(Q<A.length&&!this.closing){let B=A.indexOf(`
|
|
162
164
|
`,Q),C=B<0?A.length:B+1,I=A.slice(Q,C);if(BI("events.lifecycle.state_invariant",()=>this.reduceLifecycleChunk(I)),this.closing)return;BI("events.reduce.state_invariant",()=>this.reduceLogChunk("events",I)),Q=C}}flushSettledCompletion(){if(!this.completionPendingSince)return;let A=Date.now();if(A-this.completionPendingSince<wf||A-this.lastChatActivityAt<wf)return;let Q=my(this.logState);if(this.logState=Q.state,Q.events.length)this.completionPendingSince=0;for(let B of Q.events)this.handleLogEvent(B)}resetLogFraming(A){if(this.logState.partialLines[A]="",this.logState.droppingOversizedLine[A]=!1,A==="events")this.lifecycleBuffer="";this.warn(`[grok-copresence] ${A} JSONL was rotated/truncated; reset line framing`)}handleLogEvent(A){switch(A.kind){case"human_user":if(this.completionPendingSince=0,this.arbitration.activeTurn?.owner==="network"){let Q=this.arbitration.activeTurn.task.taskId;this.warn(`[grok-copresence] user log lost trusted network correlation for task=${Q}`),this.failPending(Q,new UA("correlation","Grok user log did not preserve the trusted network envelope")),hF(this.logState,Q),this.quarantinedNetworkTaskId=Q;return}if(this.arbitration.phase==="idle")this.transition({type:"human_input_started"}),this.transition({type:"human_input_submitted"});else if(this.arbitration.phase==="human_editing")this.transition({type:"human_input_submitted"});if(!A.unownedNetworkEnvelope)Promise.resolve(this.opts.onHumanPrompt?.(A.query)).catch((Q)=>this.warn(`[grok-copresence] human delegation callback failed: ${pA(Q)}`));return;case"network_user":{this.completionPendingSince=this.logState.activeTurn?.pendingCompletion?this.completionPendingSince||Date.now():0;let Q=this.arbitration.activeTurn;if(Q?.owner!=="network"||Q.task.taskId!==A.task.taskId){this.warn(`[grok-copresence] dropped mismatched network user log task=${A.task.taskId}`);return}let B=this.pending.get(A.task.taskId);if(B&&!B.consumed){B.consumed=!0;try{B.onConsumed?.()}catch(C){this.warn(`[grok-copresence] consumed callback failed: ${pA(C)}`)}}return}case"network_reply":this.completionPendingSince=0,this.finishNetwork(A.task.taskId,A.text);return;case"turn_completed":if(A.origin==="network"&&A.status==="completed")this.activeTurnTerminalEventSeen=!0;if(A.status==="completed"&&this.hasUnresolvedApproval()){this.failFatal(new UA("approval_boundary","grok copresence turn completed while a human approval was still unresolved"));return}if(A.origin==="human"){if(this.quarantinedNetworkTaskId&&this.arbitration.activeTurn?.owner==="network"&&this.arbitration.activeTurn.task.taskId===this.quarantinedNetworkTaskId)this.quarantinedNetworkTaskId="",this.transition({type:"turn_completed",owner:"network"});else this.transition({type:"turn_completed",owner:"human"});setImmediate(()=>this.replayDeferredHumanOrSchedule())}else if(A.origin==="network"&&A.task&&A.status!=="completed")this.failNetwork(A.task.taskId,new UA("native_outcome",`grok copresence turn ${A.status} (${A.completion.discriminator??"turn_ended"})`));return;case"turn_abandoned":if(A.origin==="network"&&A.task)this.failNetwork(A.task.taskId,new UA("correlation","grok copresence saw a new user turn before network completion"));return;case"malformed":this.warn(`[grok-copresence] ignored malformed ${A.source} JSONL (${A.reason})`);return;case"completion_pending_reply":if(this.activeTurnTerminalEventSeen=!0,this.hasUnresolvedApproval()){this.failFatal(new UA("approval_boundary","grok copresence turn completed while a human approval was still unresolved"));return}this.completionPendingSince||=Date.now();return}}reduceLifecycleChunk(A){let Q=this.lifecycleBuffer+A;this.lifecycleBuffer="";let B;while((B=Q.indexOf(`
|
|
163
165
|
`))>=0){let C=Q.slice(0,B).trim();if(Q=Q.slice(B+1),!C)continue;if(Buffer.byteLength(C,"utf8")>E0){this.failFatal(new UA("approval_boundary","grok copresence observed an oversized permission lifecycle JSONL event"));return}let I;try{I=JSON.parse(C)}catch{this.failFatal(new UA("approval_boundary","grok copresence observed malformed permission lifecycle JSONL"));return}if(I?.type==="permission_requested"){if(this.activeTurnTerminalEventSeen){this.failFatal(new UA("approval_boundary","grok copresence observed a permission request after the terminal turn event"));return}let E=D0(I);if(!E){this.failFatal(new UA("approval_boundary","grok copresence permission request lacked a trusted identity"));return}let g=aJA(I);if(g){if(this.activePermissionRequestId||this.arbitration.waitingHuman||this.arbitration.activeTurn?.owner!=="network"&&this.arbitration.activeTurn?.owner!=="human"){this.failFatal(new UA("approval_boundary","grok copresence could not correlate an automatic permission request to the active turn"));return}if(this.pendingAutomaticPermissionTotal>=_JA){this.failFatal(new UA("approval_boundary","grok copresence observed too many pending automatic permission requests"));return}this.pendingAutomaticPermissions.set(g,(this.pendingAutomaticPermissions.get(g)??0)+1),this.pendingAutomaticPermissionTotal+=1;continue}if(this.pendingAutomaticPermissionTotal>0){this.failFatal(new UA("approval_boundary","grok copresence observed a manual permission request overlapping an automatic batch"));return}if(this.activePermissionRequestId){if(this.activePermissionRequestId!==E){this.failFatal(new UA("approval_boundary","grok copresence observed overlapping permission request IDs"));return}continue}if(!this.transition({type:"approval_requested"}).accepted){this.failFatal(new UA("approval_boundary","grok copresence could not correlate a permission request to the active turn"));return}if(this.activePermissionRequestId=E,this.approvalDecisionDispatched=!1,this.deferredHuman.length)this.deferredHuman=[],this.deferredHumanBytes=0,this.humanDecoder=new g0("utf8"),this.attach?.broadcastStatus({...this.attachStatus(),warning:"input typed before the approval prompt was discarded"})}else if(I?.type==="permission_resolved"){let E=D0(I),g=Kf(I);if(Pf({requestTool:g,pendingRequestCount:g?this.pendingAutomaticPermissions.get(g)??0:0,humanDecisionDispatched:this.approvalDecisionDispatched,waitingHuman:this.arbitration.waitingHuman,turnOwner:this.arbitration.activeTurn?.owner??null,terminalEventSeen:this.activeTurnTerminalEventSeen,event:I})){this.resolveAutomaticPermission(g);continue}if(this.pendingAutomaticPermissionTotal>0){this.failFatal(new UA("approval_boundary","grok copresence observed an unmatched automatic permission resolution"));return}if(!E||E!==this.activePermissionRequestId||!this.approvalDecisionDispatched){this.failFatal(new UA("approval_boundary","grok copresence observed an unowned or automatically resolved permission request"));return}this.clearApprovalCorrelation(),this.transition({type:"approval_resolved_by_human"})}else if(I?.type==="permission_rejected"||I?.type==="permission_cancelled"){let E=D0(I),g=Kf(I);if(g&&(this.pendingAutomaticPermissions.get(g)??0)>0){this.resolveAutomaticPermission(g);continue}if(this.pendingAutomaticPermissionTotal>0){this.failFatal(new UA("approval_boundary","grok copresence observed an unmatched automatic permission rejection"));return}if(E&&E===this.activePermissionRequestId)this.clearApprovalCorrelation(),this.transition({type:"approval_resolved_by_human"})}else if(N8(I))continue}if(Buffer.byteLength(Q,"utf8")<=E0)this.lifecycleBuffer=Q}auditRecoveryLifecycleChunk(A){let Q=this.recoveryLifecycleBuffer+A;this.recoveryLifecycleBuffer="";let B;while((B=Q.indexOf(`
|
|
164
166
|
`))>=0){let C=Q.slice(0,B).trim();if(Q=Q.slice(B+1),!C)continue;if(Buffer.byteLength(C,"utf8")>E0)throw new iC("oversized Grok lifecycle record during recovery");let I;try{I=JSON.parse(C)}catch{throw new iC("malformed Grok lifecycle record during recovery")}if(I.type==="permission_requested"||I.type==="permission_resolved"||I.type==="permission_rejected"||I.type==="permission_cancelled")throw new iC("Grok recovery crossed an unresolved or unaudited permission lifecycle");else if(N8(I))continue}if(Buffer.byteLength(Q,"utf8")>E0)throw new iC("oversized partial Grok lifecycle record during recovery");this.recoveryLifecycleBuffer=Q}finishNetwork(A,Q){if(this.hasUnresolvedApproval()){this.failFatal(new UA("approval_boundary","grok copresence refused a network reply that completed without resolving human approval"));return}let B=this.arbitration.activeTurn;if(B?.owner!=="network"||B.task.taskId!==A){this.warn(`[grok-copresence] refused reply misroute for task=${A}`);return}this.transition({type:"turn_completed",owner:"network"});let C=this.pending.get(A);if(C)this.pending.delete(A),clearTimeout(C.timer),C.resolve({replyText:Q.trim(),sessionId:this.sessionId,queued:C.queued});setImmediate(()=>this.replayDeferredHumanOrSchedule())}failNetwork(A,Q){let B=this.arbitration.activeTurn;if(B?.owner!=="network"||B.task.taskId!==A)return;this.failPending(A,Q),hF(this.logState,A),this.transition({type:"turn_completed",owner:"network"}),setImmediate(()=>this.replayDeferredHumanOrSchedule())}failPending(A,Q){let B=this.pending.get(A);if(!B)return;this.pending.delete(A),clearTimeout(B.timer),B.reject(Q)}transition(A){let Q=this.arbitration.phase,B=cy(this.arbitration,A);if(this.arbitration=B.state,B.state.phase!==Q)this.phaseSince=Date.now();if(B.accepted&&A.type==="schedule_network")this.activeTurnTerminalEventSeen=!1;else if(B.accepted&&A.type==="human_input_submitted")this.activeTurnTerminalEventSeen=!1;if(B.accepted&&A.type==="turn_completed")this.clearApprovalCorrelation(!0);if(B.accepted)this.broadcastState();return B}clearApprovalCorrelation(A=!1){if(this.activePermissionRequestId=null,this.approvalDecisionDispatched=!1,A)this.clearAutomaticPermissionCorrelation()}hasUnresolvedApproval(){return this.activePermissionRequestId!==null||this.arbitration.waitingHuman||this.pendingAutomaticPermissionTotal>0}resolveAutomaticPermission(A){let Q=this.pendingAutomaticPermissions.get(A)??0;if(Q<=1)this.pendingAutomaticPermissions.delete(A);else this.pendingAutomaticPermissions.set(A,Q-1);this.pendingAutomaticPermissionTotal-=1}clearAutomaticPermissionCorrelation(){this.pendingAutomaticPermissions.clear(),this.pendingAutomaticPermissionTotal=0}broadcastState(){this.attach?.broadcastStatus(this.attachStatus())}attachStatus(){let A=this.arbitration.activeTurn;return{version:1,phase:this.arbitration.phase,revision:this.arbitration.revision,waitingHuman:this.arbitration.waitingHuman,tuiReady:this.tuiComposerReady,queueLength:this.arbitration.queue.length,queuedTaskIds:this.arbitration.queue.slice(0,16).map((Q)=>Q.taskId),active:A?.owner==="network"?{owner:"network",taskId:A.task.taskId,from:A.task.from}:A,deferredHumanBytes:this.deferredHumanBytes}}}function lJA(A){let Q=OI(A,"chat_history.jsonl"),B=OI(A,"events.jsonl");Lf(Q,"chat_history",!1);let C="",I=null;if(Lf(B,"events",!0,(E)=>{let g=C+E;C="";let D;while((D=g.indexOf(`
|
|
@@ -196,7 +198,7 @@ ${A}`}function YR(A,Q,B,C,I){let{interactiveDashboardTask:E,messageType:g}=B,D=Y
|
|
|
196
198
|
`,"config.json",Q?.stat),{config:I,source:"prev",primaryError:B}}function b3(A){return JSON.parse(og(A,"config.json").body)}function y3(A,Q){let B=og(A,"config.json");jN(A,JSON.stringify(Q,null,2)+`
|
|
197
199
|
`,"config.json",B.stat)}function f3(A){let Q=og(A,"config.json");return jN(`${A}.prev`,Q.body,"config.json.prev"),{backedUp:!0}}function h3(A,Q){let B=og(A,"config.json"),C=JSON.parse(B.body);if(C.session===Q)return!1;return C.session=Q,jN(A,JSON.stringify(C,null,2)+`
|
|
198
200
|
`,"config.json",B.stat),!0}vN();async function o3(A,Q){let B=!1,C;for(let I of A)try{await Q(I)}catch(E){if(!B)C=E;B=!0}if(B)throw C}function n1(A,Q){let B=Promise.resolve(),C=new Map,I=async(E)=>{let g=Q?.initialDelayMs??0;while(!0)try{await E();return}catch(D){if(A(D),!Q)return;await new Promise((U)=>{setTimeout(U,g).unref?.()}),g=Math.min(g*2,Q.maxDelayMs)}};return{schedule(E){let g=C.get(E);if(g){g.dirty=!0;return}let D={dirty:!1};C.set(E,D);let U=async()=>{try{do D.dirty=!1,await I(E);while(D.dirty)}finally{C.delete(E)}};B=B.then(U,U)},idle(){return B}}}function r3(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 o1(A){let Q=A.type??"task";if(Q!=="task"&&Q!=="broadcast")return!1;let B=r3(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 a3(A){if(!o1(A))return null;let Q=r3(A)?.client_request_id;return typeof Q==="string"?Q:null}async function s3(A,Q){for(let B of A)await Q(B)}function t3(A){if(!Number.isInteger(A.maxConcurrent)||A.maxConcurrent<1)throw Error("maxConcurrent must be a positive integer");let Q=new Set,B=new Set,C=[],I=()=>{while(Q.size<A.maxConcurrent&&C.length>0){let E=C.shift(),g=A.key(E.message);B.delete(g),Q.add(g);let D;try{D=E.handler(E.message)}catch(U){D=Promise.reject(U)}D.catch(A.onError).finally(()=>{Q.delete(g);try{A.onSettled?.()}catch(U){A.onError(U)}finally{I()}})}};return{submit(E,g){let D=0,U=0;for(let F of E){let Y=A.key(F);if(Q.has(Y)||B.has(Y)){U++;continue}B.add(Y),C.push({message:F,handler:g}),D++}return I(),{active:Q.size,queued:C.length,accepted:D,deduplicated:U}},stats(){return{active:Q.size,queued:C.length}}}}function e3(A,Q){return A!=="codex-app-server"||Q===0}var Dn={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 A7(A){let Q=Dn[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 xN(){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 Q7(){let A=null,Q=xN();return{async getOrOpen(B){if(A?.isRunning)return A;return Q.run(async()=>{if(A?.isRunning)return A;A=null;let C=await B();if(!C.isRunning)throw Error("codex app-server session stopped while opening");return A=C,C})},invalidate(B){if(!B||A===B)A=null},current(){return A},pending(){return Q.pending()}}}wU();import{closeSync as LU,constants as iI,existsSync as Gn,fchmodSync as bN,fstatSync as I7,fsyncSync as $n,ftruncateSync as Mn,lstatSync as Vn,mkdirSync as Wn,openSync as e1,readdirSync as wn,readFileSync as Ln,realpathSync as t1,writeSync as Xn}from"node:fs";import{join as C7,resolve as A6}from"node:path";function E7(){return process.platform==="linux"&&Gn("/proc/self/fd")}function g7(A,Q){return E7()?`/proc/self/fd/${A}`:Q}function D7(A,Q){let B=I7(A),C=process.getuid?.();if(!B.isFile()||B.nlink!==1||C!==void 0&&B.uid!==C)throw Error(`private log is not a single owner-controlled file: ${Q}`);bN(A,384)}function U7(A){let Q=A6(A);if(t1(Q)!==Q)throw Error(`private log directory is not canonical: ${Q}`);let B=e1(Q,iI.O_RDONLY|(iI.O_DIRECTORY||0)|(iI.O_NOFOLLOW||0));try{let C=I7(B),I=process.getuid?.();if(!C.isDirectory()||I!==void 0&&C.uid!==I)throw Error(`private log directory is not owner-controlled: ${Q}`);if(E7()&&t1(`/proc/self/fd/${B}`)!==Q)throw Error(`private log directory changed during validation: ${Q}`);if(process.platform!=="win32")bN(B,448);return B}catch(C){throw LU(B),C}}function F7(A,Q,B){let C=0;while(C<Q.length){let I=Xn(A,Q,C,Q.length-C,B===null?null:B+C);if(I<=0)throw Error("private log write made no progress");C+=I}}function Zn(A,Q){let B=e1(A,iI.O_RDWR|(iI.O_NOFOLLOW||0));try{D7(B,A);let C=Buffer.from(Q.redactText(Ln(B,"utf8")).text,"utf8");if(Mn(B,0),C.length>0)F7(B,C,0);$n(B),bN(B,384)}finally{LU(B)}}function Y7(A,Q){let B=A6(A);Wn(B,{recursive:!0,mode:448});let C=Vn(B),I=process.getuid?.();if(C.isSymbolicLink()||!C.isDirectory()||t1(B)!==B||I!==void 0&&C.uid!==I)throw Error(`private log directory is not owner-controlled: ${B}`);let E=U7(B);try{let g=g7(E,B);for(let D of wn(g)){if(!D.endsWith(".log"))continue;Zn(C7(g,D),Q)}}finally{LU(E)}return B}function J7(A,Q,B,C){if(!/^\d{4}-\d{2}-\d{2}\.log$/.test(Q))throw Error("private log filename is not a canonical daily log name");let I=U7(A),E=C7(g7(I,A6(A)),Q),g;try{g=e1(E,iI.O_WRONLY|iI.O_CREAT|iI.O_APPEND|(iI.O_NOFOLLOW||0),384),D7(g,E);let D=Buffer.from(C.redactText(B).text,"utf8");if(D.length>0)F7(g,D,null);bN(g,384)}finally{if(g!==void 0)LU(g);LU(I)}}function Q6(A){return JSON.stringify(A)}function N7(A){let Q=A.configNodeId||"",B=A.envNodeId||"";if(Q){if(B&&B!==Q)A.warn?.(`COMMHUB_NODE_ID mismatch: env=${Q6(B)} config=${Q6(Q)} config_path=${Q6(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 Kn(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 C=JSON.parse(B);return C?.task_id||C?.message_id||C?.id||null}catch{return null}}function sg(A,Q,B,C={}){let I=AN({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",...C.errorCode?{error_code:C.errorCode}:{},...C.errorMessage?{error_message:tJ(C.errorMessage)}:{}});if(C.event)I.event=C.event;A.log(eJ(I))}async function G7(A,Q,B){let C=B.now??Date.now,I=B.sleep??((V)=>new Promise((M)=>setTimeout(M,V))),E=B.timeoutMs??120000,g=B.pollIntervalMs??2000,D=B.stale30Ms??30000,U=B.stale60Ms??60000,F=B.emit,Y=C()+E,N=null,J=new Set,G=!1,$=!1;while(C()<Y){N=await B.getTask(A);let V=N?.task||N,M=V?.status;if((M==="acked"||M==="running"||M==="processing")&&!J.has(M))J.add(M),F(M==="acked"?"acked":"started",A);if(M==="replied"||M==="failed"||M==="cancelled")return F(M==="replied"?"replied":"failed",A,{...M==="replied"?{}:{errorCode:`task_${M}`,event:"task.failed"}}),{kind:"terminal",status:M,latest:N,row:V};let W=C()-Q;if(!G&&W>=D&&M==="delivered")G=!0,F("delivered",A,{event:"task.warning.delivered_stale_30s"});if(!$&&W>=U&&M==="delivered")$=!0,F("delivered",A,{event:"task.warning.delivered_stale_60s"});await I(g)}return F("expired",A,{errorCode:"lifecycle_timeout"}),{kind:"expired",latest:N}}async function $7(A,Q,B){sg(Q,"sending",null);try{let C=await B({alias:A.alias,task:A.task,priority:A.priority||"normal",from_session:Q.fromAlias,parent_task_id:Q.parentTaskId||void 0}),I=Kn(C);if(!I)sg(Q,"failed",null,{errorCode:"missing_task_id",errorMessage:"CommHub response omitted task_id"});else sg(Q,"delivered",I);return C}catch(C){throw sg(Q,"failed",null,{errorCode:"send_failed",errorMessage:C}),C}}function M7(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 V7(A,Q,B){let C=await B.deliverToRuntime(A);if(Q)return{kind:"request",result:C};return await B.acknowledge(A.id),{kind:"terminal_peer_reply",result:C}}function W7(A,Q){if(A.type!=="new_reply")return!1;return Q(),!0}function B6(){return{hubSupportsTool:null}}function zn(A){if(!(A instanceof bB))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 Hn(A){if(!(A instanceof bB))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"||zn(A)}async function w7(A,Q,B=B6()){try{let C=await Q.sendAtomic(A);return B.hubSupportsTool=!0,{route:"atomic",payload:C}}catch(C){if(!Hn(C))throw C;return{route:"legacy-reply",payload:await Q.sendLegacyReply(A)}}}import{chmodSync as L7,closeSync as I6,existsSync as Rn,fchmodSync as jn,fsyncSync as _n,openSync as X7,readFileSync as qn,renameSync as On,unlinkSync as Z7,writeFileSync as Sn}from"node:fs";import{randomBytes as Tn}from"node:crypto";var K7=15000,Pn=2500,R7=300000,XU=2000,vn=new Set(["replied","failed","cancelled","expired"]);function E6(A){if(A===void 0||A===null||String(A).trim()==="")return K7;let Q=Number(A);if(!Number.isSafeInteger(Q))return K7;return Math.min(R7,Math.max(Pn,Q))}function C6(){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 zC(A){if(!Array.isArray(A))return[];return[...new Set(A.filter((Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=512))].slice(-XU)}function xn(A){if(!A||typeof A!=="object")return C6();let Q=A;return{version:3,consumed_task_ids:zC(Q.consumed_task_ids),consumed_client_request_ids:zC(Q.consumed_client_request_ids),surfaced_outbound_terminal_ids:zC(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(-XU):zC(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(-XU):zC(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 z7(A){return a3(A)}function H7(A){return typeof A.task_id==="string"&&A.task_id?A.task_id:A.id}function kn(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)}class j7{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=zC(Q.consumed_task_ids),Q.consumed_client_request_ids=zC(Q.consumed_client_request_ids),Q.surfaced_outbound_terminal_ids=zC(Q.surfaced_outbound_terminal_ids),Q.outbound_deliveries=Q.outbound_deliveries.filter((B)=>B.state!=="delivered").slice(-XU),Q.inbound_lifecycle=Q.inbound_lifecycle.slice(-XU),this.write(Q),this.state=Q})}claimOutbound(A,Q,B,C){return this.withLock(()=>{let I=this.read(),E=I.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+C;else I.outbound_deliveries.push({task_id:A,idempotency_key:Q,state:"delivering",lease_until:B+C});return this.write(I),this.state=I,!0},!1)}withLock(A,Q){let B=`${this.path}.lock`,C;try{C=X7(B,"wx",384)}catch{if(arguments.length>1)return Q;throw Error("compensation cursor is locked")}try{return A()}finally{I6(C);try{Z7(B)}catch{}}}read(){if(!Rn(this.path))return C6();try{let A=xn(JSON.parse(qn(this.path,"utf8")));return L7(this.path,384),A}catch{return C6()}}write(A){let Q=`${this.path}.tmp-${process.pid}-${Tn(6).toString("hex")}`,B=null;try{B=X7(Q,"wx",384),jn(B,384),Sn(B,`${JSON.stringify(A)}
|
|
199
|
-
`,"utf8"),_n(B),I6(B),B=null,On(Q,this.path),L7(this.path,384)}finally{if(B!==null)I6(B);try{Z7(Q)}catch{}}}}function _7(A){let Q=E6(A.intervalMs),B=A.adapters,C=new j7(A.cursorPath),I="probing",E=null,g=!1,D=!1,U=null,F=0,Y=!1,N=B.now??Date.now,J=Math.max(30000,Q*2),G=B.setTimer??((x,y)=>{let u=setTimeout(x,y);return u.unref?.(),u}),$=B.clearTimer??((x)=>clearTimeout(x)),V=(x)=>{let y=C.snapshot(),u=H7(x),m=z7(x);return y.consumed_task_ids.includes(u)||!!m&&y.consumed_client_request_ids.includes(m)},M=(x)=>{let y=H7(x),u=z7(x);C.update((m)=>{if(m.consumed_task_ids.push(y),u)m.consumed_client_request_ids.push(u);let n=m.inbound_lifecycle.find((T)=>T.task_id===y);if(n)n.state="completed";else m.inbound_lifecycle.push({task_id:y,state:"completed"})})},W={delivered:0,submitted:1,consumed:2,completed:3},X=(x,y)=>{if(!x)return;C.update((u)=>{let m=u.inbound_lifecycle.find((n)=>n.task_id===x);if(!m)u.inbound_lifecycle.push({task_id:x,state:y});else if(W[y]>W[m.state])m.state=y;if(W[y]>=W.consumed)u.consumed_task_ids.push(x)})},L=(x)=>{if(D||I==="realtime-only")return;if(U!==null)$(U);U=G(()=>{U=null,R("timer")},x)},Z=async(x)=>{try{let y=C.snapshot().outbound_terminal_watermark,[u,m]=await Promise.all([B.getInbox(),B.listOutbound(y)]),n=m.tasks;if(I==="probing")I="active",B.log(`[commhub-compensation] active (${Q}ms; SSE remains primary)`);if(u.some((T)=>!V(T)))B.scheduleInboxDrain();for(let T of n){if(!T?.task_id||!vn.has(T.status))continue;if(!Number.isSafeInteger(T.terminal_seq)||Number(T.terminal_seq)<=0)throw Object.assign(Error("Hub terminal sequence missing"),{code:-32602});let p=Number(T.terminal_seq),HA=C.snapshot();if(p<=HA.outbound_terminal_watermark)continue;let HQ=C.snapshot().outbound_deliveries.find((CA)=>CA.task_id===T.task_id);if(HQ?.state==="delivered"){C.update((CA)=>{CA.outbound_terminal_watermark=Math.max(CA.outbound_terminal_watermark,p)});continue}let JQ=HQ?.idempotency_key??`commhub-terminal:${T.task_id}`;if(!C.claimOutbound(T.task_id,JQ,N(),J))break;try{await B.onOutboundTerminal(T,JQ)}catch(CA){throw C.update((nA)=>{let XQ=nA.outbound_deliveries.find((BA)=>BA.task_id===T.task_id);if(XQ)XQ.state="pending",XQ.lease_until=0}),CA}C.update((CA)=>{let nA=CA.outbound_deliveries.find((XQ)=>XQ.task_id===T.task_id);if(nA)nA.state="delivered",nA.lease_until=0;CA.outbound_terminal_watermark=Math.max(CA.outbound_terminal_watermark,p)})}if(C.update((T)=>{T.last_success_at=new Date(N()).toISOString()}),m.hasMore)g=!0;F=0,B.log(`[commhub-compensation] ${x} poll ok; inbox=${u.length} outbound=${n.length}`),L(Q)}catch(y){if(kn(y)){if(I="realtime-only",!Y)Y=!0,B.warn("[commhub-compensation] Hub lacks durable inbox/outbox polling capability; realtime-only mode (SSE/turn-steer only)");return}F++;let u=Math.min(R7,Q*2**Math.min(F,5));B.warn(`[commhub-compensation] poll failed; retry in ${u}ms: ${y instanceof Error?y.message:String(y)}`),L(u)}},R=(x)=>{if(D||I==="realtime-only")return;if(E){g=!0;return}E=(async()=>{let y=x;do g=!1,await Z(y),y="idle";while(g&&!D&&I!=="realtime-only")})().finally(()=>{E=null})};return{get mode(){return I},trigger:R,recordConsumed:M,recordLifecycle:X,wasConsumed:V,async idle(){await E},stop(){if(D=!0,U!==null)$(U);U=null}}}import{appendFileSync as xm,mkdirSync as z2}from"fs";var q7={name:"@sleep2agi/agent-node",version:"2.5.0-preview.
|
|
201
|
+
`,"utf8"),_n(B),I6(B),B=null,On(Q,this.path),L7(this.path,384)}finally{if(B!==null)I6(B);try{Z7(Q)}catch{}}}}function _7(A){let Q=E6(A.intervalMs),B=A.adapters,C=new j7(A.cursorPath),I="probing",E=null,g=!1,D=!1,U=null,F=0,Y=!1,N=B.now??Date.now,J=Math.max(30000,Q*2),G=B.setTimer??((x,y)=>{let u=setTimeout(x,y);return u.unref?.(),u}),$=B.clearTimer??((x)=>clearTimeout(x)),V=(x)=>{let y=C.snapshot(),u=H7(x),m=z7(x);return y.consumed_task_ids.includes(u)||!!m&&y.consumed_client_request_ids.includes(m)},M=(x)=>{let y=H7(x),u=z7(x);C.update((m)=>{if(m.consumed_task_ids.push(y),u)m.consumed_client_request_ids.push(u);let n=m.inbound_lifecycle.find((T)=>T.task_id===y);if(n)n.state="completed";else m.inbound_lifecycle.push({task_id:y,state:"completed"})})},W={delivered:0,submitted:1,consumed:2,completed:3},X=(x,y)=>{if(!x)return;C.update((u)=>{let m=u.inbound_lifecycle.find((n)=>n.task_id===x);if(!m)u.inbound_lifecycle.push({task_id:x,state:y});else if(W[y]>W[m.state])m.state=y;if(W[y]>=W.consumed)u.consumed_task_ids.push(x)})},L=(x)=>{if(D||I==="realtime-only")return;if(U!==null)$(U);U=G(()=>{U=null,R("timer")},x)},Z=async(x)=>{try{let y=C.snapshot().outbound_terminal_watermark,[u,m]=await Promise.all([B.getInbox(),B.listOutbound(y)]),n=m.tasks;if(I==="probing")I="active",B.log(`[commhub-compensation] active (${Q}ms; SSE remains primary)`);if(u.some((T)=>!V(T)))B.scheduleInboxDrain();for(let T of n){if(!T?.task_id||!vn.has(T.status))continue;if(!Number.isSafeInteger(T.terminal_seq)||Number(T.terminal_seq)<=0)throw Object.assign(Error("Hub terminal sequence missing"),{code:-32602});let p=Number(T.terminal_seq),HA=C.snapshot();if(p<=HA.outbound_terminal_watermark)continue;let HQ=C.snapshot().outbound_deliveries.find((CA)=>CA.task_id===T.task_id);if(HQ?.state==="delivered"){C.update((CA)=>{CA.outbound_terminal_watermark=Math.max(CA.outbound_terminal_watermark,p)});continue}let JQ=HQ?.idempotency_key??`commhub-terminal:${T.task_id}`;if(!C.claimOutbound(T.task_id,JQ,N(),J))break;try{await B.onOutboundTerminal(T,JQ)}catch(CA){throw C.update((nA)=>{let XQ=nA.outbound_deliveries.find((BA)=>BA.task_id===T.task_id);if(XQ)XQ.state="pending",XQ.lease_until=0}),CA}C.update((CA)=>{let nA=CA.outbound_deliveries.find((XQ)=>XQ.task_id===T.task_id);if(nA)nA.state="delivered",nA.lease_until=0;CA.outbound_terminal_watermark=Math.max(CA.outbound_terminal_watermark,p)})}if(C.update((T)=>{T.last_success_at=new Date(N()).toISOString()}),m.hasMore)g=!0;F=0,B.log(`[commhub-compensation] ${x} poll ok; inbox=${u.length} outbound=${n.length}`),L(Q)}catch(y){if(kn(y)){if(I="realtime-only",!Y)Y=!0,B.warn("[commhub-compensation] Hub lacks durable inbox/outbox polling capability; realtime-only mode (SSE/turn-steer only)");return}F++;let u=Math.min(R7,Q*2**Math.min(F,5));B.warn(`[commhub-compensation] poll failed; retry in ${u}ms: ${y instanceof Error?y.message:String(y)}`),L(u)}},R=(x)=>{if(D||I==="realtime-only")return;if(E){g=!0;return}E=(async()=>{let y=x;do g=!1,await Z(y),y="idle";while(g&&!D&&I!=="realtime-only")})().finally(()=>{E=null})};return{get mode(){return I},trigger:R,recordConsumed:M,recordLifecycle:X,wasConsumed:V,async idle(){await E},stop(){if(D=!0,U!==null)$(U);U=null}}}import{appendFileSync as xm,mkdirSync as z2}from"fs";var q7={name:"@sleep2agi/agent-node",version:"2.5.0-preview.44",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"],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"},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.226",undici:"^6.27.0",zod:"^4.4.3"},optionalDependencies:{"@openai/codex":"^0.133.0","@openai/codex-sdk":"^0.133.0","node-pty":"^1.1.0"}};var __dirname="/home/runner/work/agent-network/agent-network/agent-node/src";var F0;function uGA(){if(F0!==void 0)return F0??void 0;if(q?.role!=="host_supervisor"){F0=null;return}try{(hN(),OK(fN)).loadAndVerifyAnetBin(),F0={ok:!0}}catch(A){let Q=A?.anetBinCode;F0={ok:!1,reason:["anet_bin_identity","anet_bin_source","anet_bin_shape","anet_bin_permission"].includes(Q)?Q:"anet_bin_unknown"}}return F0}var VB=mGA(),cGA=B6(),Hm=process.env.ANET_OPENCODE_BIN,BY=process.env.ANET_OPENCODE_VERSION,Rm=process.env.PATH||"",th=process.env.ANET_OPENCODE_SAFE_BASE,tQ=process.argv.slice(2),wA={},jm=[];if(tQ.length===1&&tQ[0]==="--print-entrypoint")console.log(fGA(process.argv[1])),process.exit(0);var _m="2.1.0";try{let A=new URL(".",import.meta.url).pathname;for(let Q of["../package.json","../../package.json"])try{let B=JSON.parse(bI(e(A,Q),"utf-8"));if(B.version){_m=B.version;break}}catch{}}catch{}for(let A=0;A<tQ.length;A++){if(tQ[A]==="--version"||tQ[A]==="-v")console.log(`agent-node v${_m}`),process.exit(0);if(tQ[A]==="-h"||tQ[A]==="--help")console.log(`
|
|
200
202
|
@sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
|
|
201
203
|
|
|
202
204
|
用法:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-node",
|
|
3
|
-
"version": "2.5.0-preview.
|
|
3
|
+
"version": "2.5.0-preview.44",
|
|
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"
|