@sleep2agi/agent-node 2.5.0-preview.45 → 2.5.0-preview.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +4 -4
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -151,14 +151,14 @@ ${I}`;break;case"retry":if(_k(I))Q[C]=I;break;case"id":if(qk(I))Q[C]=I;break;cas
151
151
  `));let x=gA(C,"trusted_folders.toml");if(A.useLeader===!0)lC(x,[`[folders.${JSON.stringify(U)}]`,"trusted = true",`decided_at = ${Math.floor(Date.now()/1000)}`,""].join(`
152
152
  `));else Yy(x);let y=gA(C,KZ);if(A.useLeader===!0)lC(y,zZ());else Yy(y);if(A.useLeader===!0)lC(gA(C,"requirements.toml"),["[ui]","disable_bypass_permissions_mode = false",""].join(`
153
153
  `));lC(gA(C,"sandbox.toml"),[`[profiles.${JSON.stringify(V)}]`,'extends = "read-only"',`deny = [${R}]`,"",`[profiles.${JSON.stringify(M)}]`,'extends = "strict"',`read_only = [${[Q,...J?[J.command]:[],...N?[N.credentialDir]:[]].map((n)=>JSON.stringify(n)).join(", ")}]`,`deny = [${R}]`,"",`[profiles.${JSON.stringify(W)}]`,'extends = "workspace"',`deny = [${R}]`,""].join(`
154
- `)),NYA(Q,C,"agent_id");let u,m;try{let n=JSON.parse(Y??""),T=Object.keys(n).find((p)=>p.startsWith("http")&&p.includes("::"));if(T){let p=T.lastIndexOf("::");u=T.slice(0,p),m=T.slice(p+2)}}catch{}return{home:C,authPath:I,...u&&m?{oidcIssuer:u,oidcClientId:m}:{},...N?{commhubCredentialDir:N.credentialDir}:{},readOnlyProfile:V,strictProfile:M,workspaceProfile:W,...A.useLeader===!0?{copresenceAgentProfile:y}:{}}}var cC,AYA=".anet-grok-turn.lock",Fy,CYA,UYA;var fF=j(()=>{wU();HZ();Eg();cC=Object.freeze({stateFiles:Object.freeze(["CHANGELOG.json","CHANGELOG.md","README.md","sandbox-events.jsonl"]),emptyStateFiles:Object.freeze(["leader.log"]),cwdSessionFiles:Object.freeze(["prompt_history.jsonl"]),sessionRootFiles:Object.freeze(["session_search.sqlite"]),transientStateDirectories:Object.freeze([".bun",".grok","marketplace-cache"]),projectSandboxPlaceholders:Object.freeze({basenames:Object.freeze([".grok",".claude",".cursor",".mcp.json",".envrc"]),type:"single-link-empty-regular-file",mode:"0444",owner:"currentUid"}),sandboxBlockedDirectoryBinding:Object.freeze({source:"confirmedTuiProcessIds",prefix:"sandbox-blocked-dir."}),nativeLeaderLockBinding:Object.freeze({source:"leaderSocket",replaceExtension:".lock"})});Fy=new Set;CYA=new Set([".grok",".claude",".cursor"]);UYA=Object.freeze(["sandbox-blocked.","sandbox-blocked-dir."])});import{chmodSync as XYA,lstatSync as c$,realpathSync as ZYA,unlinkSync as KYA}from"node:fs";import{createServer as zYA}from"node:net";import{dirname as HYA,isAbsolute as RYA,resolve as jYA}from"node:path";async function Py(A){let Q=TYA(A);hZ({type:"hello",protocol:Sy,version:Ty,alias:A.alias,sessionId:A.sessionId},Q.maxFrameBytes),PYA(A.socketPath);let B=new vy(A,Q.maxFrameBytes,Q.maxBufferedBytes);return await B.start(),B}class vy{options;socketPath;server;maxFrameBytes;maxBufferedBytes;activeClient=null;controlClients=new Set;identity=null;started=!1;closing=!1;closePromise=null;arbiterCallbacks=Promise.resolve();constructor(A,Q,B){this.options=A;this.socketPath=A.socketPath,this.maxFrameBytes=Q,this.maxBufferedBytes=B,this.server=zYA((C)=>this.accept(C)),this.server.on("error",(C)=>{if(!this.started||this.closing)return;let I=this.activeClient;if(I)this.rejectActive(I,"server_error",u$(C))})}get clientAttached(){return this.activeClient!==null&&!this.activeClient.closed}async start(){await new Promise((A,Q)=>{let B=(I)=>{this.server.off("listening",C),Q(I)},C=()=>{this.server.off("error",B),A()};this.server.once("error",B),this.server.once("listening",C),this.server.listen(Cg(this.socketPath,NQ()))});try{if(YC(NQ())){XYA(this.socketPath,384);let A=c$(this.socketPath);if(!A.isSocket()||A.isSymbolicLink())throw Error("Grok attach endpoint is not a real Unix socket");if(!tC(A.mode))throw Error("Grok attach Unix socket must be owner-only (0600)");this.identity={dev:A.dev,ino:A.ino}}this.started=!0}catch(A){throw await this.stopListeningAfterStartFailure(),this.unlinkOwnedSocket(),A}}broadcastOutput(A){let Q=this.activeClient;if(!Q||Q.closed)return!1;let B=typeof A==="string"?Buffer.from(A,"utf8"):Buffer.from(A),C=Math.max(1,Math.floor((this.maxFrameBytes-128)*3/4));if(B.length===0)return this.sendActive(Q,{type:"output",data:"",encoding:"base64"});for(let I=0;I<B.length;I+=C){let E=B.subarray(I,Math.min(I+C,B.length));if(!this.sendActive(Q,{type:"output",data:E.toString("base64"),encoding:"base64"}))return!1}return!0}broadcastStatus(A){let Q=this.activeClient&&!this.activeClient.closed?this.activeClient:null,B=[...this.controlClients].filter((I)=>!I.closed);if(!Q&&B.length===0)return!1;try{if(JSON.stringify(A)===void 0)throw Error("status is not JSON serializable")}catch(I){for(let E of[Q,...B])if(E)this.rejectActive(E,"invalid_status",u$(I));return!1}let C=!1;for(let I of[Q,...B])if(I&&this.sendActive(I,{type:"status",status:A}))C=!0;return C}close(){if(this.closePromise)return this.closePromise;return this.closing=!0,this.closePromise=this.closeInternal(),this.closePromise}async closeInternal(){let A=this.activeClient;if(this.activeClient=null,A)A.closed=!0,this.notifyDetach(A,"server_close"),A.socket.destroy();for(let Q of[...this.controlClients])this.controlClients.delete(Q),Q.closed=!0,Q.socket.destroy();if(this.started||this.server.listening)await new Promise((Q)=>{this.server.close(()=>Q())});this.started=!1,this.unlinkOwnedSocket()}accept(A){if(A.on("error",()=>{}),this.closing){this.rejectUnattached(A,"server_closing","Grok attach server is closing");return}let Q=this.activeClient===null?"terminal":"control";if(Q==="control"&&this.controlClients.size>=qy){this.rejectUnattached(A,"control_clients_exhausted",`at most ${qy} control connections may be open`);return}let B={socket:A,role:Q,buffer:Buffer.alloc(0),pendingCallbacks:0,pendingInputBytes:0,detachNotified:!1,closed:!1};if(Q==="terminal")this.activeClient=B;else this.controlClients.add(B);if(A.on("data",(C)=>this.receive(B,C)),A.on("end",()=>this.releaseDisconnected(B)),A.on("close",()=>this.releaseDisconnected(B)),!this.sendActive(B,{type:"hello",protocol:Sy,version:Ty,alias:this.options.alias,sessionId:this.options.sessionId,role:B.role}))this.releaseDisconnected(B)}receive(A,Q){if(!this.isLive(A))return;if(!Buffer.isBuffer(Q))Q=Buffer.from(Q);if(A.buffer.length+Q.length>this.maxBufferedBytes){this.rejectActive(A,"buffer_limit","attach receive buffer limit exceeded");return}A.buffer=A.buffer.length===0?Buffer.from(Q):Buffer.concat([A.buffer,Q],A.buffer.length+Q.length);while(!A.closed){let B=A.buffer.indexOf(10);if(B===-1)break;let C=A.buffer.subarray(0,B);if(A.buffer=Buffer.from(A.buffer.subarray(B+1)),C.length>0&&C[C.length-1]===13)C=C.subarray(0,-1);if(C.length>this.maxFrameBytes){this.rejectActive(A,"frame_too_large","attach frame limit exceeded");return}if(C.length===0){this.rejectActive(A,"invalid_frame","empty attach frame");return}this.handleLine(A,C)}if(!A.closed&&A.buffer.length>this.maxFrameBytes)this.rejectActive(A,"frame_too_large","attach frame limit exceeded")}handleLine(A,Q){let B;try{B=JSON.parse(vYA(Q))}catch{this.rejectActive(A,"invalid_frame","attach frame must be valid UTF-8 JSON");return}if(!kYA(B)||typeof B.type!=="string"){this.rejectActive(A,"invalid_frame","attach frame must have a string type");return}switch(B.type){case"input":{if(A.role!=="terminal"){this.rejectActive(A,"control_client_cannot_type","a control connection may only send set-model");return}if(!fZ(B,["type","data","encoding"])||B.encoding!=="base64"||typeof B.data!=="string"||!xYA(B.data)){this.rejectActive(A,"invalid_input","input data must be canonical base64");return}let C=Buffer.from(B.data,"base64");this.enqueueCallback(A,()=>this.options.onInput(C),C.length);return}case"resize":{if(A.role!=="terminal"){this.rejectActive(A,"control_client_cannot_type","a control connection may only send set-model");return}if(!fZ(B,["type","cols","rows"])||!Oy(B.cols)||!Oy(B.rows)){this.rejectActive(A,"invalid_resize","resize cols and rows must be positive safe integers");return}this.enqueueCallback(A,()=>this.options.onResize(B.cols,B.rows),0);return}case"set-model":{if(!this.options.onSetModel){this.rejectActive(A,"unsupported_frame","this node does not support set-model");return}if(!fZ(B,["type","model"])||typeof B.model!=="string"){this.rejectActive(A,"invalid_set_model","set-model requires a string model field");return}let C=B.model;this.enqueueCallback(A,()=>this.options.onSetModel(C),0);return}case"detach":if(Object.keys(B).some((C)=>C!=="type")){this.rejectActive(A,"invalid_detach","detach frame has unexpected fields");return}this.forget(A),A.closed=!0,this.notifyDetach(A,"client"),A.socket.end();return;default:this.rejectActive(A,"invalid_frame",`unsupported client frame type: ${B.type}`)}}enqueueCallback(A,Q,B){if(A.pendingCallbacks>=SYA||A.pendingInputBytes+B>this.maxBufferedBytes){this.rejectActive(A,"arbiter_queue_limit","attach arbiter callback queue limit exceeded");return}A.pendingCallbacks+=1,A.pendingInputBytes+=B,this.arbiterCallbacks=this.arbiterCallbacks.then(async()=>{try{if(this.isLive(A))await Q()}finally{A.pendingCallbacks-=1,A.pendingInputBytes-=B}}).catch((C)=>{if(!A.closed)this.rejectActive(A,"arbiter_callback_failed",u$(C))})}notifyDetach(A,Q){if(A.detachNotified)return;if(A.detachNotified=!0,A.role!=="terminal")return;if(!this.options.onDetach)return;this.arbiterCallbacks=this.arbiterCallbacks.then(()=>this.options.onDetach?.(Q)).catch(()=>{})}releaseDisconnected(A){if(this.forget(A),!A.closed)A.closed=!0;this.notifyDetach(A,"disconnect")}sendActive(A,Q){if(!this.isLive(A)||!A.socket.writable)return!1;let B;try{B=hZ(Q,this.maxFrameBytes)}catch(C){return this.rejectActive(A,"outbound_frame_too_large",u$(C)),!1}if(A.socket.writableLength+B.length>this.maxBufferedBytes)return this.rejectActive(A,"outbound_buffer_limit","attach send buffer limit exceeded"),!1;return A.socket.write(B),!0}isLive(A){if(A.closed)return!1;return A.role==="terminal"?this.activeClient===A:this.controlClients.has(A)}forget(A){if(this.activeClient===A)this.activeClient=null;this.controlClients.delete(A)}rejectActive(A,Q,B){if(this.forget(A),A.closed)return;A.closed=!0,this.notifyDetach(A,"protocol_error"),this.endWithError(A.socket,Q,B)}rejectUnattached(A,Q,B){this.endWithError(A,Q,B)}endWithError(A,Q,B){try{let C=hZ({type:"error",code:Q,message:bYA(B,512),fatal:!0},this.maxFrameBytes);if(A.writable&&A.writableLength+C.length<=this.maxBufferedBytes)A.end(C),A.resume();else A.destroy()}catch{A.destroy()}}async stopListeningAfterStartFailure(){if(!this.server.listening)return;await new Promise((A)=>this.server.close(()=>A()))}unlinkOwnedSocket(){if(!this.identity)return;let A;try{A=c$(this.socketPath)}catch(Q){if(mZ(Q,"ENOENT"))return;throw Q}if(A.isSocket()&&!A.isSymbolicLink()&&A.dev===this.identity.dev&&A.ino===this.identity.ino)try{KYA(this.socketPath)}catch(Q){if(!mZ(Q,"ENOENT"))throw Q}}}function TYA(A){if(typeof A.onInput!=="function"||typeof A.onResize!=="function")throw Error("Grok attach server requires onInput and onResize arbiter callbacks");if(typeof A.alias!=="string"||A.alias.length===0||Buffer.byteLength(A.alias,"utf8")>256)throw Error("Grok attach alias must be a non-empty string of at most 256 bytes");if(typeof A.sessionId!=="string"||A.sessionId.length===0||Buffer.byteLength(A.sessionId,"utf8")>256)throw Error("Grok attach sessionId must be a non-empty string of at most 256 bytes");let Q=A.maxFrameBytes??_YA,B=A.maxBufferedBytes??qYA;if(!Number.isSafeInteger(Q)||Q<_y)throw Error(`maxFrameBytes must be a safe integer >= ${_y}`);if(!Number.isSafeInteger(B)||B<Q+1)throw Error("maxBufferedBytes must be a safe integer larger than maxFrameBytes");return{maxFrameBytes:Q,maxBufferedBytes:B}}function PYA(A){if(!RYA(A)||jYA(A)!==A)throw Error("Grok attach socket path must be absolute and normalized");if(!YC(NQ()))return;let Q=HYA(A),B=c$(Q);if(!B.isDirectory()||B.isSymbolicLink())throw Error("Grok attach socket parent must be a real directory");if(ZYA(Q)!==Q)throw Error("Grok attach socket parent path may not contain symlinks");if(typeof process.getuid!=="function"||B.uid!==process.getuid())throw Error("Grok attach socket parent must be owned by the current uid");if(!tC(B.mode))throw Error("Grok attach socket parent must be owner-only (0700)");try{let C=c$(A);if(C.isSymbolicLink())throw Error("Grok attach socket path may not be a symlink");if(!C.isSocket())throw Error("Grok attach socket path may not be a regular filesystem entry");throw Error("Grok attach socket path is already in use")}catch(C){if(!mZ(C,"ENOENT"))throw C}}function hZ(A,Q){let B=JSON.stringify(A),C=Buffer.from(B,"utf8");if(C.length>Q)throw Error(`outbound attach frame exceeds ${Q} bytes`);return Buffer.concat([C,Buffer.from(`
154
+ `)),NYA(Q,C,"agent_id");let u,m;try{let n=JSON.parse(Y??""),T=Object.keys(n).find((p)=>p.startsWith("http")&&p.includes("::"));if(T){let p=T.lastIndexOf("::");u=T.slice(0,p),m=T.slice(p+2)}}catch{}return{home:C,authPath:I,...u&&m?{oidcIssuer:u,oidcClientId:m}:{},...N?{commhubCredentialDir:N.credentialDir}:{},readOnlyProfile:V,strictProfile:M,workspaceProfile:W,...A.useLeader===!0?{copresenceAgentProfile:y}:{}}}var cC,AYA=".anet-grok-turn.lock",Fy,CYA,UYA;var fF=j(()=>{wU();HZ();Eg();cC=Object.freeze({stateFiles:Object.freeze(["CHANGELOG.json","CHANGELOG.md","README.md","sandbox-events.jsonl"]),emptyStateFiles:Object.freeze(["leader.log"]),cwdSessionFiles:Object.freeze(["prompt_history.jsonl"]),sessionRootFiles:Object.freeze(["session_search.sqlite"]),transientStateDirectories:Object.freeze([".bun",".grok","marketplace-cache"]),projectSandboxPlaceholders:Object.freeze({basenames:Object.freeze([".grok",".claude",".cursor",".mcp.json",".envrc"]),type:"single-link-empty-regular-file",mode:"0444",owner:"currentUid"}),sandboxBlockedDirectoryBinding:Object.freeze({source:"confirmedTuiProcessIds",prefix:"sandbox-blocked-dir."}),nativeLeaderLockBinding:Object.freeze({source:"leaderSocket",replaceExtension:".lock"})});Fy=new Set;CYA=new Set([".grok",".claude",".cursor"]);UYA=Object.freeze(["sandbox-blocked.","sandbox-blocked-dir."])});import{chmodSync as XYA,lstatSync as c$,realpathSync as ZYA,unlinkSync as KYA}from"node:fs";import{createServer as zYA}from"node:net";import{dirname as HYA,isAbsolute as RYA,resolve as jYA}from"node:path";async function Py(A){let Q=TYA(A);hZ({type:"hello",protocol:Sy,version:Ty,alias:A.alias,sessionId:A.sessionId},Q.maxFrameBytes),PYA(A.socketPath);let B=new vy(A,Q.maxFrameBytes,Q.maxBufferedBytes);return await B.start(),B}class vy{options;socketPath;server;maxFrameBytes;maxBufferedBytes;activeClient=null;controlClients=new Set;identity=null;started=!1;closing=!1;closePromise=null;arbiterCallbacks=Promise.resolve();constructor(A,Q,B){this.options=A;this.socketPath=A.socketPath,this.maxFrameBytes=Q,this.maxBufferedBytes=B,this.server=zYA((C)=>this.accept(C)),this.server.on("error",(C)=>{if(!this.started||this.closing)return;let I=this.activeClient;if(I)this.rejectActive(I,"server_error",u$(C))})}get clientAttached(){return this.activeClient!==null&&!this.activeClient.closed}async start(){await new Promise((A,Q)=>{let B=(I)=>{this.server.off("listening",C),Q(I)},C=()=>{this.server.off("error",B),A()};this.server.once("error",B),this.server.once("listening",C),this.server.listen(Cg(this.socketPath,NQ()))});try{if(YC(NQ())){XYA(this.socketPath,384);let A=c$(this.socketPath);if(!A.isSocket()||A.isSymbolicLink())throw Error("Grok attach endpoint is not a real Unix socket");if(!tC(A.mode))throw Error("Grok attach Unix socket must be owner-only (0600)");this.identity={dev:A.dev,ino:A.ino}}this.started=!0}catch(A){throw await this.stopListeningAfterStartFailure(),this.unlinkOwnedSocket(),A}}broadcastOutput(A){let Q=this.activeClient;if(!Q||Q.closed)return!1;let B=typeof A==="string"?Buffer.from(A,"utf8"):Buffer.from(A),C=Math.max(1,Math.floor((this.maxFrameBytes-128)*3/4));if(B.length===0)return this.sendActive(Q,{type:"output",data:"",encoding:"base64"});for(let I=0;I<B.length;I+=C){let E=B.subarray(I,Math.min(I+C,B.length));if(!this.sendActive(Q,{type:"output",data:E.toString("base64"),encoding:"base64"}))return!1}return!0}broadcastStatus(A){let Q=this.activeClient&&!this.activeClient.closed?this.activeClient:null,B=[...this.controlClients].filter((I)=>!I.closed);if(!Q&&B.length===0)return!1;try{if(JSON.stringify(A)===void 0)throw Error("status is not JSON serializable")}catch(I){for(let E of[Q,...B])if(E)this.rejectActive(E,"invalid_status",u$(I));return!1}let C=!1;for(let I of[Q,...B])if(I&&this.sendActive(I,{type:"status",status:A}))C=!0;return C}close(){if(this.closePromise)return this.closePromise;return this.closing=!0,this.closePromise=this.closeInternal(),this.closePromise}async closeInternal(){let A=this.activeClient;if(this.activeClient=null,A)A.closed=!0,this.notifyDetach(A,"server_close"),A.socket.destroy();for(let Q of[...this.controlClients])this.controlClients.delete(Q),Q.closed=!0,Q.socket.destroy();if(this.started||this.server.listening)await new Promise((Q)=>{this.server.close(()=>Q())});this.started=!1,this.unlinkOwnedSocket()}accept(A){if(A.on("error",()=>{}),this.closing){this.rejectUnattached(A,"server_closing","Grok attach server is closing");return}let Q=this.activeClient===null?"terminal":"control";if(Q==="control"&&this.controlClients.size>=qy){this.rejectUnattached(A,"control_clients_exhausted",`at most ${qy} control connections may be open`);return}let B={socket:A,role:Q,buffer:Buffer.alloc(0),pendingCallbacks:0,pendingInputBytes:0,detachNotified:!1,closed:!1};if(Q==="terminal")this.activeClient=B;else this.controlClients.add(B);if(A.on("data",(C)=>this.receive(B,C)),A.on("end",()=>this.releaseDisconnected(B)),A.on("close",()=>this.releaseDisconnected(B)),!this.sendActive(B,{type:"hello",protocol:Sy,version:Ty,alias:this.options.alias,sessionId:this.options.sessionId,role:B.role})){this.releaseDisconnected(B);return}if(B.role==="terminal"&&this.options.onTerminalAttached)this.enqueueCallback(B,()=>this.options.onTerminalAttached(),0)}receive(A,Q){if(!this.isLive(A))return;if(!Buffer.isBuffer(Q))Q=Buffer.from(Q);if(A.buffer.length+Q.length>this.maxBufferedBytes){this.rejectActive(A,"buffer_limit","attach receive buffer limit exceeded");return}A.buffer=A.buffer.length===0?Buffer.from(Q):Buffer.concat([A.buffer,Q],A.buffer.length+Q.length);while(!A.closed){let B=A.buffer.indexOf(10);if(B===-1)break;let C=A.buffer.subarray(0,B);if(A.buffer=Buffer.from(A.buffer.subarray(B+1)),C.length>0&&C[C.length-1]===13)C=C.subarray(0,-1);if(C.length>this.maxFrameBytes){this.rejectActive(A,"frame_too_large","attach frame limit exceeded");return}if(C.length===0){this.rejectActive(A,"invalid_frame","empty attach frame");return}this.handleLine(A,C)}if(!A.closed&&A.buffer.length>this.maxFrameBytes)this.rejectActive(A,"frame_too_large","attach frame limit exceeded")}handleLine(A,Q){let B;try{B=JSON.parse(vYA(Q))}catch{this.rejectActive(A,"invalid_frame","attach frame must be valid UTF-8 JSON");return}if(!kYA(B)||typeof B.type!=="string"){this.rejectActive(A,"invalid_frame","attach frame must have a string type");return}switch(B.type){case"input":{if(A.role!=="terminal"){this.rejectActive(A,"control_client_cannot_type","a control connection may only send set-model");return}if(!fZ(B,["type","data","encoding"])||B.encoding!=="base64"||typeof B.data!=="string"||!xYA(B.data)){this.rejectActive(A,"invalid_input","input data must be canonical base64");return}let C=Buffer.from(B.data,"base64");this.enqueueCallback(A,()=>this.options.onInput(C),C.length);return}case"resize":{if(A.role!=="terminal"){this.rejectActive(A,"control_client_cannot_type","a control connection may only send set-model");return}if(!fZ(B,["type","cols","rows"])||!Oy(B.cols)||!Oy(B.rows)){this.rejectActive(A,"invalid_resize","resize cols and rows must be positive safe integers");return}this.enqueueCallback(A,()=>this.options.onResize(B.cols,B.rows),0);return}case"set-model":{if(!this.options.onSetModel){this.rejectActive(A,"unsupported_frame","this node does not support set-model");return}if(!fZ(B,["type","model"])||typeof B.model!=="string"){this.rejectActive(A,"invalid_set_model","set-model requires a string model field");return}let C=B.model;this.enqueueCallback(A,()=>this.options.onSetModel(C),0);return}case"detach":if(Object.keys(B).some((C)=>C!=="type")){this.rejectActive(A,"invalid_detach","detach frame has unexpected fields");return}this.forget(A),A.closed=!0,this.notifyDetach(A,"client"),A.socket.end();return;default:this.rejectActive(A,"invalid_frame",`unsupported client frame type: ${B.type}`)}}enqueueCallback(A,Q,B){if(A.pendingCallbacks>=SYA||A.pendingInputBytes+B>this.maxBufferedBytes){this.rejectActive(A,"arbiter_queue_limit","attach arbiter callback queue limit exceeded");return}A.pendingCallbacks+=1,A.pendingInputBytes+=B,this.arbiterCallbacks=this.arbiterCallbacks.then(async()=>{try{if(this.isLive(A))await Q()}finally{A.pendingCallbacks-=1,A.pendingInputBytes-=B}}).catch((C)=>{if(!A.closed)this.rejectActive(A,"arbiter_callback_failed",u$(C))})}notifyDetach(A,Q){if(A.detachNotified)return;if(A.detachNotified=!0,A.role!=="terminal")return;if(!this.options.onDetach)return;this.arbiterCallbacks=this.arbiterCallbacks.then(()=>this.options.onDetach?.(Q)).catch(()=>{})}releaseDisconnected(A){if(this.forget(A),!A.closed)A.closed=!0;this.notifyDetach(A,"disconnect")}sendActive(A,Q){if(!this.isLive(A)||!A.socket.writable)return!1;let B;try{B=hZ(Q,this.maxFrameBytes)}catch(C){return this.rejectActive(A,"outbound_frame_too_large",u$(C)),!1}if(A.socket.writableLength+B.length>this.maxBufferedBytes)return this.rejectActive(A,"outbound_buffer_limit","attach send buffer limit exceeded"),!1;return A.socket.write(B),!0}isLive(A){if(A.closed)return!1;return A.role==="terminal"?this.activeClient===A:this.controlClients.has(A)}forget(A){if(this.activeClient===A)this.activeClient=null;this.controlClients.delete(A)}rejectActive(A,Q,B){if(this.forget(A),A.closed)return;A.closed=!0,this.notifyDetach(A,"protocol_error"),this.endWithError(A.socket,Q,B)}rejectUnattached(A,Q,B){this.endWithError(A,Q,B)}endWithError(A,Q,B){try{let C=hZ({type:"error",code:Q,message:bYA(B,512),fatal:!0},this.maxFrameBytes);if(A.writable&&A.writableLength+C.length<=this.maxBufferedBytes)A.end(C),A.resume();else A.destroy()}catch{A.destroy()}}async stopListeningAfterStartFailure(){if(!this.server.listening)return;await new Promise((A)=>this.server.close(()=>A()))}unlinkOwnedSocket(){if(!this.identity)return;let A;try{A=c$(this.socketPath)}catch(Q){if(mZ(Q,"ENOENT"))return;throw Q}if(A.isSocket()&&!A.isSymbolicLink()&&A.dev===this.identity.dev&&A.ino===this.identity.ino)try{KYA(this.socketPath)}catch(Q){if(!mZ(Q,"ENOENT"))throw Q}}}function TYA(A){if(typeof A.onInput!=="function"||typeof A.onResize!=="function")throw Error("Grok attach server requires onInput and onResize arbiter callbacks");if(typeof A.alias!=="string"||A.alias.length===0||Buffer.byteLength(A.alias,"utf8")>256)throw Error("Grok attach alias must be a non-empty string of at most 256 bytes");if(typeof A.sessionId!=="string"||A.sessionId.length===0||Buffer.byteLength(A.sessionId,"utf8")>256)throw Error("Grok attach sessionId must be a non-empty string of at most 256 bytes");let Q=A.maxFrameBytes??_YA,B=A.maxBufferedBytes??qYA;if(!Number.isSafeInteger(Q)||Q<_y)throw Error(`maxFrameBytes must be a safe integer >= ${_y}`);if(!Number.isSafeInteger(B)||B<Q+1)throw Error("maxBufferedBytes must be a safe integer larger than maxFrameBytes");return{maxFrameBytes:Q,maxBufferedBytes:B}}function PYA(A){if(!RYA(A)||jYA(A)!==A)throw Error("Grok attach socket path must be absolute and normalized");if(!YC(NQ()))return;let Q=HYA(A),B=c$(Q);if(!B.isDirectory()||B.isSymbolicLink())throw Error("Grok attach socket parent must be a real directory");if(ZYA(Q)!==Q)throw Error("Grok attach socket parent path may not contain symlinks");if(typeof process.getuid!=="function"||B.uid!==process.getuid())throw Error("Grok attach socket parent must be owned by the current uid");if(!tC(B.mode))throw Error("Grok attach socket parent must be owner-only (0700)");try{let C=c$(A);if(C.isSymbolicLink())throw Error("Grok attach socket path may not be a symlink");if(!C.isSocket())throw Error("Grok attach socket path may not be a regular filesystem entry");throw Error("Grok attach socket path is already in use")}catch(C){if(!mZ(C,"ENOENT"))throw C}}function hZ(A,Q){let B=JSON.stringify(A),C=Buffer.from(B,"utf8");if(C.length>Q)throw Error(`outbound attach frame exceeds ${Q} bytes`);return Buffer.concat([C,Buffer.from(`
155
155
  `)],C.length+1)}function vYA(A){return new TextDecoder("utf-8",{fatal:!0}).decode(A)}function xYA(A){if(A==="")return!0;if(A.length%4!==0)return!1;if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(A))return!1;return Buffer.from(A,"base64").toString("base64")===A}function Oy(A){return Number.isSafeInteger(A)&&A>0&&A<=OYA}function kYA(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function fZ(A,Q){let B=new Set(Q);return Object.keys(A).every((C)=>B.has(C))}function u$(A){return A instanceof Error?A.message:String(A)}function bYA(A,Q){let B=Buffer.from(A,"utf8");if(B.length<=Q)return A;return B.subarray(0,Q).toString("utf8")}function mZ(A,Q){return typeof A==="object"&&A!==null&&"code"in A&&A.code===Q}var Sy="anet-grok-copresence-attach",Ty=1,_YA=65536,qYA=131072,_y=256,OYA=16384,SYA=128,qy=4;var xy=j(()=>{Eg()});function ky(A){if(A.phase==="idle")return null;if(!Number.isFinite(A.phaseAgeMs)||A.phaseAgeMs<120000)return null;let Q=Math.floor(A.phaseAgeMs/60000),B=A.alreadyQueued>0?`${A.alreadyQueued} task(s) already waiting behind it; `:"";return`arbitration has been phase=${A.phase} for ${Q}m without reaching idle — `+`${B}network tasks cannot be injected until a turn_ended boundary arrives, and each will fail after ${Math.round(A.taskTimeoutMs/1000)}s. This is the shape of issue #870; there is no automatic recovery from it.`}function mYA(A){let Q=hYA[A];if(Q)return Q;if(A<1||A>26)return null;return`Ctrl+${String.fromCharCode(A+64)}`}function by(A){let Q=yYA[A];return Q?`${A} (${Q})`:A}function uZ(A){if(!A.length)return null;let Q=fYA.exec(A.toString("binary"));if(Q){let C=Number(Q[1]),I=Q[2]===void 0?1:Number(Q[2]);if(!Number.isFinite(C)||!Number.isFinite(I))return null;if((I-1&4)===0)return null;if(C<97||C>122)return null;return by(`Ctrl+${String.fromCharCode(C).toUpperCase()}`)}if(A[0]===27)return null;let B=mYA(A[0]);return B===null?null:by(B)}var yYA,fYA,hYA;var yy=j(()=>{yYA=Object.freeze({"Ctrl+P":"Grok's command palette","Ctrl+M":"Grok's model picker; it shares a byte with Enter","Ctrl+O":"Grok's always-approve toggle"}),fYA=/^\x1b\[(\d+)(?:;(\d+))?u/,hYA=Object.freeze({8:"Backspace (same byte as Ctrl+H)",9:"Tab (same byte as Ctrl+I)",10:"Enter (same byte as Ctrl+J)",13:"Enter (same byte as Ctrl+M, Grok's model picker)"})});function p$(A=[]){let Q={version:1,ownedNetworkTasks:[],expectedHumanTurn:!1,completionCandidates:[],partialLines:{chat_history:"",events:""},droppingOversizedLine:{chat_history:!1,events:!1},stats:{parsedLines:0,ignoredLines:0,malformedLines:0,oversizedLines:0,orphanAssistants:0,orphanCompletions:0}};for(let B of A)lZ(Q,B);return Q}function hy(A){if(A.expectedHumanTurn)throw Error("a Grok human turn is already awaiting its user log");A.expectedHumanTurn=!0}function lZ(A,Q){fy(Q.from,"from"),fy(Q.taskId,"taskId");let B=A.ownedNetworkTasks.find((C)=>C.taskId===Q.taskId);if(B){if(B.from!==Q.from)throw Error(`network task ${Q.taskId} is already owned by a different sender`);return}if(A.ownedNetworkTasks.length>=1024)throw Error("too many pending network tasks (max 1024)");A.ownedNetworkTasks.push({from:Q.from,taskId:Q.taskId})}function hF(A,Q){let B=A.ownedNetworkTasks.findIndex((I)=>I.taskId===Q);if(B<0)return!1;let[C]=A.ownedNetworkTasks.splice(B,1);if(A.pendingOrphanOrigin==="network"&&iZ(A.pendingOrphanNetworkTask,C))l$(A);return!0}function uYA(A){let Q=A.match(/^\s*\[Agent Network\/from=([^\]/\r\n]+)\/task=([^\]/\r\n]+)\][ \t]*(.*)$/s);if(!Q)return;let B=Q[1].trim(),C=Q[2].trim();if(!cZ(B)||!cZ(C))return;return{from:B,taskId:C,message:Q[3]}}function cYA(A){let Q=d$(A);if(!Q||Q.type!=="user")return;let B=i$(Q.content);if(B===void 0)return;let C=B.match(/<user_query>([\s\S]*?)<\/user_query>/);return C?C[1].trim():void 0}function lYA(A){let Q=d$(A);if(!Q)return;let B=typeof Q.type==="string"?Q.type:void 0;if(!B)return;let C=sYA(B),I=B==="turn_ended";if(!(I||/(^|_)turn(_|$)/.test(C)&&/(complet|end|finish|done)/.test(C)))return;let g=typeof Q.outcome==="string"?Q.outcome:void 0,D="unknown";if(I&&g==="completed")D="completed";else if(I&&g&&/^(?:cancelled|canceled|aborted|interrupted)$/.test(g))D="cancelled";else if(I&&g)D="failed";return{recognized:I,candidate:!0,status:D,discriminator:B,raw:Q}}function iYA(A,Q,B){let C=[],I=B.endsWith("\r")?B.slice(0,-1):B;if(!I.trim())return{state:A,events:C};if(pZ(I)>1048576)return A.stats.oversizedLines++,C.push({kind:"malformed",source:Q,reason:"line_too_large"}),{state:A,events:C};let E;try{E=JSON.parse(I)}catch{return A.stats.malformedLines++,C.push({kind:"malformed",source:Q,reason:"invalid_json"}),{state:A,events:C}}let g=d$(E);if(!g)return A.stats.malformedLines++,C.push({kind:"malformed",source:Q,reason:"non_object_json"}),{state:A,events:C};if(A.stats.parsedLines++,Q==="chat_history")pYA(A,g,C);else dYA(A,g,C);return{state:A,events:C}}function my(A,Q,B){let C=[],I=B;if(A.droppingOversizedLine[Q]){let D=I.indexOf(`
156
156
  `);if(D<0)return{state:A,events:C};A.droppingOversizedLine[Q]=!1,I=I.slice(D+1)}let E=A.partialLines[Q]+I;A.partialLines[Q]="";let g;while((g=E.indexOf(`
157
157
  `))>=0){let D=iYA(A,Q,E.slice(0,g));C.push(...D.events),E=E.slice(g+1)}if(pZ(E)>1048576)A.stats.oversizedLines++,A.droppingOversizedLine[Q]=!0,C.push({kind:"malformed",source:Q,reason:"line_too_large"});else A.partialLines[Q]=E;return{state:A,events:C}}function pYA(A,Q,B){if(Q.type==="user"){let C=cYA(Q);if(C===void 0){A.stats.ignoredLines++;return}if(A.activeTurn){if(B.push({kind:"turn_abandoned",origin:A.activeTurn.origin,reason:"new_user_before_completion",task:A.activeTurn.networkTask}),A.openTurnNumber!==void 0&&A.activeTurn.turnNumber===A.openTurnNumber)A.abandonedTurnNumber=A.openTurnNumber,A.openTurnNumber=void 0;else if(A.activeTurn.turnNumber===void 0)A.abandonedUnnumberedTurns=(A.abandonedUnnumberedTurns??0)+1}let{pendingOrphanCompletion:I,pendingOrphanTurnNumber:E,pendingOrphanOrigin:g,pendingOrphanNetworkTask:D}=A;l$(A);let U=uYA(C),F=U?A.ownedNetworkTasks.findIndex(($)=>$.taskId===U.taskId&&$.from===U.from):-1,Y=U&&F>=0?"network":"human",N=Y==="network"&&F>=0&&iZ(D,A.ownedNetworkTasks[F]),J=g==="human"&&Y==="human"||g==="network"&&N?I:void 0,G=J?E:A.openTurnNumber;if(U&&F>=0){if(A.expectedHumanTurn)A.expectedHumanTurn=!1,A.lifecycleInvalid=!0;let[$]=A.ownedNetworkTasks.splice(F,1);if(A.activeTurn={origin:"network",query:U.message,...G!==void 0?{turnNumber:G}:{},parsedEnvelope:U,networkTask:$,assistantMessages:0,...J?{pendingCompletion:J}:{}},B.push({kind:"network_user",query:U.message,rawQuery:C,task:$}),J&&J.status!=="completed")B.push({kind:"turn_completed",origin:"network",status:J.status,completion:J,task:$}),A.activeTurn=void 0;return}if(A.expectedHumanTurn=!1,A.activeTurn={origin:"human",query:C,...G!==void 0?{turnNumber:G}:{},parsedEnvelope:U,assistantMessages:0},B.push(U?{kind:"human_user",query:C,unownedNetworkEnvelope:U}:{kind:"human_user",query:C}),J)B.push({kind:"turn_completed",origin:"human",status:J.status,completion:J}),A.activeTurn=void 0;return}if(Q.type==="assistant"){let C=oYA(Q),I=A.activeTurn;if(!I){A.stats.orphanAssistants++;return}if(I.assistantMessages++,C.eligibleFinal&&C.text)I.finalAssistantText=C.text;return}A.stats.ignoredLines++}function uy(A){let Q=A.activeTurn;if(!Q||Q.origin!=="network"||!Q.networkTask||Q.pendingCompletion?.status!=="completed")return{state:A,events:[]};let B=nYA(Q);if(!B)return{state:A,events:[]};let C={kind:"network_reply",task:Q.networkTask,text:B,completion:Q.pendingCompletion};return A.activeTurn=void 0,{state:A,events:[C]}}function dYA(A,Q,B){if(Q.type==="turn_started"){let F=rYA(Q.turn_number);if(F===void 0){A.lifecycleInvalid=!0,A.stats.ignoredLines++;return}if((A.abandonedUnnumberedTurns??0)>0){if(A.openTurnNumber!==void 0||A.abandonedTurnNumber!==void 0||A.pendingOrphanCompletion||A.activeTurn?.pendingCompletion){A.lifecycleInvalid=!0,A.stats.ignoredLines++;return}let Y=(A.abandonedUnnumberedTurns??1)-1;A.abandonedUnnumberedTurns=Y>0?Y:void 0,A.abandonedTurnNumber=F;return}if(A.openTurnNumber!==void 0||A.abandonedTurnNumber!==void 0||A.pendingOrphanCompletion||A.activeTurn?.pendingCompletion||A.activeTurn?.turnNumber!==void 0){A.lifecycleInvalid=!0,A.stats.ignoredLines++;return}if(A.openTurnNumber=F,A.activeTurn)A.activeTurn.turnNumber=F;return}let C=lYA(Q);if(!C){A.stats.ignoredLines++;return}if(aYA(A,C),!C.recognized){A.stats.ignoredLines++;return}if(A.abandonedTurnNumber!==void 0&&A.openTurnNumber===void 0){A.abandonedTurnNumber=void 0,A.lifecycleInvalid=!1,A.stats.ignoredLines++;return}let I=A.openTurnNumber;A.openTurnNumber=void 0;let E=A.activeTurn,g=!A.lifecycleInvalid&&I!==void 0&&(!E||E.turnNumber===I);A.lifecycleInvalid=!1;let D=g?C:{...C,status:"unknown"};if(!E){A.stats.orphanCompletions++;let F=A.ownedNetworkTasks.length===1?A.ownedNetworkTasks[0]:void 0,Y=F&&!A.expectedHumanTurn?"network":!F&&A.expectedHumanTurn?"human":void 0;if(I!==void 0&&Y){if(A.pendingOrphanCompletion=D,A.pendingOrphanTurnNumber=I,A.pendingOrphanOrigin=Y,A.pendingOrphanNetworkTask=Y==="network"&&F?{...F}:void 0,F&&D.status==="completed")B.push({kind:"completion_pending_reply",task:F,completion:D})}else if(F){if(A.ownedNetworkTasks.splice(0,1),A.pendingOrphanOrigin==="network"&&iZ(A.pendingOrphanNetworkTask,F))l$(A);A.expectedHumanTurn=!1,B.push({kind:"turn_completed",origin:"network",status:"unknown",completion:D,task:F});return}else if(A.pendingOrphanCompletion){l$(A),A.expectedHumanTurn=!1,B.push({kind:"turn_completed",origin:"human",status:"unknown",completion:D});return}B.push({kind:"turn_completed",origin:"orphan",status:D.status,completion:D});return}if(E.origin==="human"){B.push({kind:"turn_completed",origin:"human",status:D.status,completion:D}),A.activeTurn=void 0;return}let U=E.networkTask;if(!U){B.push({kind:"turn_completed",origin:"network",status:D.status,completion:D}),A.activeTurn=void 0;return}if(D.status!=="completed"){B.push({kind:"turn_completed",origin:"network",status:D.status,completion:D,task:U}),A.activeTurn=void 0;return}E.pendingCompletion=D,B.push({kind:"completion_pending_reply",task:U,completion:D})}function nYA(A){return A.finalAssistantText}function oYA(A){let Q=tYA(i$(A.content)),B=A.tool_calls===void 0||Array.isArray(A.tool_calls)&&A.tool_calls.length===0;return{...Q?{text:Q}:{},eligibleFinal:B}}function rYA(A){return typeof A==="number"&&Number.isSafeInteger(A)&&A>=0?A:void 0}function iZ(A,Q){return!!A&&!!Q&&A.from===Q.from&&A.taskId===Q.taskId}function l$(A){A.pendingOrphanCompletion=void 0,A.pendingOrphanTurnNumber=void 0,A.pendingOrphanOrigin=void 0,A.pendingOrphanNetworkTask=void 0}function aYA(A,Q){if(A.completionCandidates.push(Q),A.completionCandidates.length>8)A.completionCandidates.splice(0,A.completionCandidates.length-8)}function sYA(A){return A.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}function i$(A,Q=0){if(typeof A==="string")return A;if(Q>4)return;if(Array.isArray(A)){let C=A.map((I)=>i$(I,Q+1)).filter((I)=>I!==void 0&&I.length>0);return C.length?C.join(`
158
158
  `):void 0}let B=d$(A);if(!B)return;if(typeof B.text==="string")return B.text;if(typeof B.content==="string")return B.content;return i$(B.content,Q+1)}function d$(A){return A!==null&&typeof A==="object"&&!Array.isArray(A)?A:void 0}function tYA(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 fy(A,Q){if(!cZ(A))throw Error(`invalid network ${Q}`)}function cy(){return{phase:"idle",queue:[],activeTurn:null,recoveryFrom:null,waitingHuman:!1,revision:0}}function ly(A,Q){switch(rZ(A),Q.type){case"network_task_received":{let B=OI(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(OI),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(OI)})}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=OI(B);return TB(A,{phase:"network_turn",queue:C.map(OI),activeTurn:{owner:"network",task:I},waitingHuman:!1},[{type:"inject_network_task",task:OI(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=OI(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(!py(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 iy(A){return rZ(A),{version:1,phase:A.phase,queue:A.queue.map(OI),activeTurn:nZ(A.activeTurn),recoveryFrom:A.recoveryFrom,waitingHuman:A.waitingHuman,revision:A.revision}}function rZ(A){if(!eYA.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(!AJA.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&&!py(A))throw Error("waitingHuman requires an active turn")}function py(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(OI),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:OI(A.task)}}function OI(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 eYA,AJA;var dy=j(()=>{eYA=["idle","human_editing","human_turn","network_turn","recovering"],AJA=["idle","human_editing","human_turn","network_turn"]});import{constants as QJA,existsSync as BJA,lstatSync as ry,readFileSync as r$,readdirSync as aZ,readlinkSync as IJA,realpathSync as eZ,statSync as a$,unlinkSync as CJA}from"fs";import{isAbsolute as ay,delimiter as EJA,join as n$,resolve as gJA}from"path";import{setTimeout as s$}from"timers/promises";async function ty(A){let Q=Date.now()+(A.timeoutMs??5000),B;while(Date.now()<Q)try{return JJA(A)}catch(C){B=C,await s$(25)}throw Error(`could not bind the Grok Leader to this TUI generation: ${LJA(B)}`)}async function ey(A,Q=2000){if(tZ(A.pid,A.startTime)){if(sZ(A),ny(A.pid,"SIGTERM")&&!await oy(A.pid,A.startTime,Q)){if(sZ(A),ny(A.pid,"SIGKILL")&&!await oy(A.pid,A.startTime,Q))throw Error(`owned Grok Leader pid ${A.pid} did not exit after SIGKILL`)}}await $JA(A,Q),await MJA(A,Q),WJA(A)}function YJA(A,Q,B){let C=A.findIndex((E,g)=>g<=1&&GJA(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 JJA(A){wJA(A.ownerNonce);let Q=Q8(A.leaderSocket),B=Qf(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=NJA(A.binary,A.binaryPathEnv),g=B8(a$(E)),D=Af(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);o$(Q,A.socket,"Grok Leader socket");let B=Qf(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=Af(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(o$(I.executable,A.executable,"Grok Leader executable"),I.executable.path!==A.executable.path)throw Error("Grok Leader executable path changed before termination");o$(B8(a$(A.configuredBinary)),A.configuredBinaryFile,"configured Grok binary")}function Af(A,Q,B){let C=`/proc/${A}`,I=ry(C).uid,E=process.getuid?.();if(E!==void 0&&I!==E)throw Error("Grok Leader process owner mismatch");let g=If(A);if(g.state==="Z"||g.state==="X")throw Error("Grok Leader process is not live");let D=g.startTime,U=eZ(n$(C,"exe")),F=a$(n$(C,"exe")),Y={path:U,dev:String(F.dev),ino:String(F.ino),uid:F.uid},N=Cf(n$(C,"cmdline"));YJA(N,Q,U);let J=Ef(n$(C,"environ")),G={[sy]: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 Qf(A){let Q=[],B=r$("/proc/net/unix","utf8").split(`
159
159
  `).slice(1);for(let I of B){if(!I.trim())continue;let E=Bf(I);if(E.path===A&&E.flags===DJA&&E.type===UJA&&E.state===FJA)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 Bf(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(IJA(`/proc/${I}/fd/${g}`)===Q){B.add(I);break}}catch{}}return[...B].sort((C,I)=>C-I)}function Q8(A){let Q=ry(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 If(A){let Q=r$(`/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 Cf(A){return r$(A).toString("utf8").split("\x00").filter(Boolean)}function Ef(A){let Q={};for(let B of Cf(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 NJA(A,Q){let B=ay(A)?[A]:Q.split(EJA).filter(Boolean).map((C)=>gJA(C,A));for(let C of B)try{if((a$(C).mode&QJA.S_IXUSR)!==0)return eZ(C)}catch{}throw Error("could not resolve the pinned Grok executable for Leader identity")}function GJA(A,Q){if(!A||!ay(A))return!1;try{return eZ(A)===Q}catch{return!1}}function tZ(A,Q){try{let B=If(A);return B.startTime===Q&&B.state!=="Z"&&B.state!=="X"}catch{return!1}}function ny(A,Q){try{return process.kill(A,Q),!0}catch(B){if(B?.code==="ESRCH")return!1;throw B}}async function oy(A,Q,B){let C=Date.now()+B;while(Date.now()<C){if(!tZ(A,Q))return!0;await s$(20)}return!tZ(A,Q)}async function $JA(A,Q){let B=Date.now()+Q;while(Date.now()<B){let C=gf(A.leaderSocket,A.listenerInode),I=A8(A.listenerInode).length>0;if(!C&&!I)return;await s$(20)}throw Error("owned Grok Leader listener remained after process termination")}function gf(A,Q){try{return r$("/proc/net/unix","utf8").split(`
160
160
  `).slice(1).some((B)=>{if(!B.trim())return!1;let C=Bf(B);return C.path===A&&C.inode===Q})}catch{return!0}}async function MJA(A,Q){let B=Date.now()+Q;while(Date.now()<B){if(VJA(A).length===0)return;await s$(20)}throw Error("Grok Leader generation still has live processes after termination")}function VJA(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=Ef(`/proc/${B.name}/environ`);if(I[sy]===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 WJA(A){if(!BJA(A.leaderSocket))return;let Q=Q8(A.leaderSocket);if(o$(Q,A.socket,"stale Grok Leader socket"),gf(A.leaderSocket,A.listenerInode))throw Error("refusing to unlink a Grok Leader socket that still has a listener");CJA(A.leaderSocket)}function o$(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 LJA(A){return A instanceof Error?A.message:String(A||"unknown error")}var sy="ANET_GROK_LEADER_OWNER",DJA="00010000",UJA="0001",FJA="01";var Df=()=>{};function Yf(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(!XJA.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 Jf(A){return{kind:"hot",method:"session/set_model",params:{sessionId:A.sessionId,modelId:A.modelId}}}function Nf(){return{kind:"restart",resume:!0}}function I8(A,Q){return{ok:!1,code:A,message:Q}}function Gf(A,Q,B){let C=Uf(A,"previous"),I=Uf(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=Ff(A),g=Ff(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 Uf(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 Ff(A){let Q=[];for(let B=0;B<A.length;B++){if(A[B]==="--model"){B++;continue}Q.push(A[B])}return Q}var XJA,DC;var $f=j(()=>{XJA=/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/;DC=class DC extends Error{constructor(A){super(A);this.name="GrokModelSwitchArgvError"}}});var L8={};_A(L8,{openGrokCopresenceRuntime:()=>cJA,isGrokPreviewAutomaticResolution:()=>vf,hasGrokTuiReadyMarker:()=>Rf,grokVerifiedBuild:()=>qf,grokSessionDirectory:()=>Of,grokLeaderSocketTimeoutMs:()=>Pf,grokCopresenceThink:()=>lJA,grokCopresenceFailureSubcode:()=>yJA,grokCopresenceFailureCode:()=>bJA,grokBuildAutoLeader:()=>W8,formatNetworkTuiInput:()=>F8,ensurePtySpawnHelperExecutable:()=>Tf,buildGrokCopresenceArgs:()=>U8,assertGrokCopresenceVersion:()=>mJA,assertGrokCopresenceFeatures:()=>fJA,assertGrokCopresenceExternalSurfaces:()=>hJA,assertGrokCopresenceApprovalOwnership:()=>uJA,GrokCopresenceFailure:()=>UA,GROK_JSONL_TAIL_FAILURE_SUBCODES:()=>_f,GROK_COPRESENCE_VERIFIED_BUILDS:()=>A2,GROK_COPRESENCE_FAILURE_CODES:()=>jf});import{spawn as ZJA}from"child_process";import{createHash as Mf,randomUUID as Vf}from"crypto";import{chmodSync as KJA,closeSync as cF,constants as pC,existsSync as G8,fchmodSync as zJA,fstatSync as e$,lstatSync as lE,mkdirSync as HJA,openSync as $8,readSync as Hf,realpathSync as D8}from"fs";import{dirname as mF,isAbsolute as uE,join as BI,resolve as mQ}from"path";import{createRequire as RJA}from"module";import{createServer as jJA}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(PJA)&&Q.includes(vJA)}function M8(A){return typeof A==="string"&&xJA.has(A)}function V8(A){return typeof A==="string"&&kJA.has(A)?A:"unknown"}function bJA(A){return A instanceof UA&&M8(A.failureCode)?A.failureCode:"unknown"}function yJA(A){if(!(A instanceof UA)||!M8(A.failureCode))return"unknown";if(A.failureCode==="jsonl_tail")return V8(A.failureSubcode);return A.failureSubcode==="none"?"none":"unknown"}function PB(A,Q){return new Q2(A,Q)}function II(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=[...W8(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 gy)Q.push("--deny",B);if(!y$)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 fJA(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 hJA(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 W8(A){return qf(A)?.autoLeader??!0}function mJA(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 uJA(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||""))!==BI(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),BI(A,"sessions",encodeURIComponent(mQ(Q)),B)}function F8(A){if(Kf(A.from,"from"),Kf(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")>Wf)throw Error(`network task exceeds ${Wf} bytes`);return`\x1B[200~${B}\x1B[201~\r`}async function cJA(A){let Q=new Sf(A);return await Q.open(),Q}function lJA(A,Q){return A.submit(Q)}function iJA(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 pJA(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=cy();phaseSince=Date.now();logState=p$();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||Vf(),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 iy(this.arbitration)}get model(){return this.currentModel}async onAttachSetModel(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=lA(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=Yf(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=Jf({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(!BNA(C))throw C;if(Nf().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`);Gf(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;$Y(NQ()),w8(this.sessionId),J8(this.leaderSocket,"leader"),J8(this.attachSocket,"attach"),g8(mF(this.leaderSocket)),g8(mF(this.attachSocket));let A=Of(this.opts.grokHome,this.opts.cwd,this.sessionId),Q=this.opts.newSession!==!0&&G8(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=Mf("sha256").update(this.leaderSocket).digest("hex").slice(0,20),I=BI(D8(this.opts.grokHome),"copresence-locks");g8(I);let E=Mf("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(BI(I,`.session-${E}.lock`),B,this.opts.env)),this.locks.push(await E8(BI(mF(this.leaderSocket),`.leader-${C}.lock`),B,this.opts.env)),sJA(this.leaderSocket,"leader"),this.locks.push(await E8(BI(mF(this.leaderSocket),`.bridge-${C}-${this.sessionId}.lock`),B,this.opts.env)),this.chatTail=new Y8(BI(A,"chat_history.jsonl"),"chat_history",Q),this.eventsTail=new Y8(BI(A,"events.jsonl"),"events",Q),Q)this.chatTail.arm(!0),this.eventsTail.arm(!0),dJA(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 Zf(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=p$(),this.lifecycleBuffer="",this.attach=await Py({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",lA(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=ky({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: ${lA(Q)}`)}),await this.teardownOwnedLeader().catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] retaining locks: ${lA(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 uF(`grok copresence pre-spawn audit failed: ${lA(Y)}`)}if(mQ(String(this.spawnEnv.GROK_HOME||""))!==mQ(this.opts.grokHome)||mQ(String(this.spawnEnv.HOME||""))!==mQ(this.opts.grokHome))throw new uF("grok copresence spawn audit returned an unexpected HOME/GROK_HOME");try{Uy(this.opts.agentProfile,this.opts.grokHome)}catch(Y){throw new uF(`grok copresence agent profile audit failed: ${lA(Y)}`)}let Q=++this.ptyGeneration;this.leaderOwnerNonce=Vf(),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??aJA)(C,I,{name:"xterm-256color",cols:120,rows:36,cwd:this.opts.cwd,env:I7(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: ${lA(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: ${lA(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 Zf(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=p$(),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: ${lA(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: ${lA(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 uF||D instanceof iC){await this.failFatal(QNA(D));return}this.warn(`[grok-copresence] resume attempt ${E}/${C} failed: ${lA(D)}`)}}if(this.closing)return;await this.failFatal(new UA("tui_exit",`grok copresence could not resume session: ${lA(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: ${lA(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: ${lA(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(W8(this.opts.grokVersion)){await tJA(this.leaderSocket,Pf()),await this.bindSpawnedLeader();return}try{lE(this.leaderSocket)}catch(A){if(lF(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 ty({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: ${lA(A)}`)}}teardownOwnedLeader(){if(this.leaderTeardownPromise)return this.leaderTeardownPromise;let A=this.ownedLeader;if(!A)return Promise.resolve();let Q=ey(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=iJA(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=pJA(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.matchExactHumanModelCommand(),N=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(Y!==null)this.log(`[grok-copresence] in-TUI /model proxied out-of-band (#879): ${Y}`),this.proxyHumanModelSwitch(Y);else this.warnBlockedPermissionModeChange(N);if(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{hy(this.logState)}catch(Y){this.failFatal(new UA("correlation",lA(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}}matchExactHumanModelCommand(){if(!this.humanComposerLeadingSlash)return null;if(this.humanComposerAuditTainted||this.humanComposerAuditUnsafe||this.humanComposerAuditOverflow)return null;let A=/^\s*\/model[ \t]+(\S+)[ \t]*$/.exec(this.humanComposerAudit);return A?A[1]:null}async proxyHumanModelSwitch(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=lA(B);this.warn(`[grok-copresence] in-TUI /model switch to ${A} failed: ${C}`),this.attach?.broadcastOutput(`\r
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")>Wf)throw Error(`network task exceeds ${Wf} bytes`);return`\x1B[200~${B}\x1B[201~\r`}async function cJA(A){let Q=new Sf(A);return await Q.open(),Q}function lJA(A,Q){return A.submit(Q)}function iJA(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 pJA(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=cy();phaseSince=Date.now();logState=p$();pty=null;activeTui=null;currentModel;modelSwitchInFlight=null;pendingRedrawOnResize=!1;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||Vf(),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 iy(this.arbitration)}get model(){return this.currentModel}async onAttachSetModel(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=lA(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=Yf(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=Jf({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(!BNA(C))throw C;if(Nf().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`);Gf(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;$Y(NQ()),w8(this.sessionId),J8(this.leaderSocket,"leader"),J8(this.attachSocket,"attach"),g8(mF(this.leaderSocket)),g8(mF(this.attachSocket));let A=Of(this.opts.grokHome,this.opts.cwd,this.sessionId),Q=this.opts.newSession!==!0&&G8(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=Mf("sha256").update(this.leaderSocket).digest("hex").slice(0,20),I=BI(D8(this.opts.grokHome),"copresence-locks");g8(I);let E=Mf("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(BI(I,`.session-${E}.lock`),B,this.opts.env)),this.locks.push(await E8(BI(mF(this.leaderSocket),`.leader-${C}.lock`),B,this.opts.env)),sJA(this.leaderSocket,"leader"),this.locks.push(await E8(BI(mF(this.leaderSocket),`.bridge-${C}-${this.sessionId}.lock`),B,this.opts.env)),this.chatTail=new Y8(BI(A,"chat_history.jsonl"),"chat_history",Q),this.eventsTail=new Y8(BI(A,"events.jsonl"),"events",Q),Q)this.chatTail.arm(!0),this.eventsTail.arm(!0),dJA(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 Zf(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=p$(),this.lifecycleBuffer="",this.attach=await Py({socketPath:this.attachSocket,alias:this.opts.alias,sessionId:this.sessionId,onInput:(g)=>this.onHumanInput(g),onResize:(g,D)=>this.onResize(g,D),onTerminalAttached:()=>{this.pendingRedrawOnResize=!0},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",lA(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=ky({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: ${lA(Q)}`)}),await this.teardownOwnedLeader().catch((Q)=>{this.retainLocksForUnconfirmedPty=!0,this.warn(`[grok-copresence] retaining locks: ${lA(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 uF(`grok copresence pre-spawn audit failed: ${lA(Y)}`)}if(mQ(String(this.spawnEnv.GROK_HOME||""))!==mQ(this.opts.grokHome)||mQ(String(this.spawnEnv.HOME||""))!==mQ(this.opts.grokHome))throw new uF("grok copresence spawn audit returned an unexpected HOME/GROK_HOME");try{Uy(this.opts.agentProfile,this.opts.grokHome)}catch(Y){throw new uF(`grok copresence agent profile audit failed: ${lA(Y)}`)}let Q=++this.ptyGeneration;this.leaderOwnerNonce=Vf(),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??aJA)(C,I,{name:"xterm-256color",cols:120,rows:36,cwd:this.opts.cwd,env:I7(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: ${lA(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: ${lA(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 Zf(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=p$(),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: ${lA(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: ${lA(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 uF||D instanceof iC){await this.failFatal(QNA(D));return}this.warn(`[grok-copresence] resume attempt ${E}/${C} failed: ${lA(D)}`)}}if(this.closing)return;await this.failFatal(new UA("tui_exit",`grok copresence could not resume session: ${lA(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: ${lA(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: ${lA(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(W8(this.opts.grokVersion)){await tJA(this.leaderSocket,Pf()),await this.bindSpawnedLeader();return}try{lE(this.leaderSocket)}catch(A){if(lF(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 ty({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: ${lA(A)}`)}}teardownOwnedLeader(){if(this.leaderTeardownPromise)return this.leaderTeardownPromise;let A=this.ownedLeader;if(!A)return Promise.resolve();let Q=ey(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=iJA(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=pJA(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.matchExactHumanModelCommand(),N=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(Y!==null)this.log(`[grok-copresence] in-TUI /model proxied out-of-band (#879): ${Y}`),this.proxyHumanModelSwitch(Y);else this.warnBlockedPermissionModeChange(N);if(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{hy(this.logState)}catch(Y){this.failFatal(new UA("correlation",lA(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}}matchExactHumanModelCommand(){if(!this.humanComposerLeadingSlash)return null;if(this.humanComposerAuditTainted||this.humanComposerAuditUnsafe||this.humanComposerAuditOverflow)return null;let A=/^\s*\/model[ \t]+(\S+)[ \t]*$/.exec(this.humanComposerAudit);return A?A[1]:null}async proxyHumanModelSwitch(A){let Q;try{Q=await this.switchModel(A)}catch(B){let C=lA(B);this.warn(`[grok-copresence] in-TUI /model switch to ${A} failed: ${C}`),this.attach?.broadcastOutput(`\r
162
162
  [anet] 模型未切换(failed):${C}\r
163
163
  `),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}`),this.attach?.broadcastOutput(`\r
164
164
  [anet] 已代为切换模型 → ${Q.model}(${Q.route==="hot"?"热切换":"重启续会话"})\r
@@ -166,7 +166,7 @@ ${I}`;break;case"retry":if(_k(I))Q[C]=I;break;case"id":if(qk(I))Q[C]=I;break;cas
166
166
  [anet] 模型未切换(${Q.code}):${Q.message}\r
167
167
  `);this.attach?.broadcastStatus({...this.attachStatus(),modelSwitch:Q})}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
168
168
  [anet] 斜杠命令在共存会话被禁用;换模型请另开终端: anet grok model <node> <model>\r
169
- `);this.attach?.broadcastStatus({...this.attachStatus(),warning:Q})}onResize(A,Q){try{this.pty?.resize(A,Q)}catch(B){this.warn(`[grok-copresence] resize failed: ${lA(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>_JA){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(-qJA),!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: ${lA(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: ${lA(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: ${lA(B)}`)),this.transition({type:"turn_completed",owner:"network"}),setImmediate(()=>this.replayDeferredHumanOrSchedule())}}}pollLogs(){if(this.closing)return;try{this.chatTail?.poll((A)=>II("chat.reduce.state_invariant",()=>this.reduceLogChunk("chat_history",A)),()=>II("chat.reduce.state_invariant",()=>this.resetLogFraming("chat_history"))),this.eventsTail?.poll((A)=>{this.reduceEventsChunkInOrder(A)},()=>II("events.reduce.state_invariant",()=>this.resetLogFraming("events"))),II("combined.flush.state_invariant",()=>this.flushSettledCompletion())}catch(A){let Q=A instanceof Q2?V8(A.failureSubcode):"unknown",B=new UA("jsonl_tail",`grok copresence lost its trusted JSONL tail: ${lA(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=my(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(`
169
+ `);this.attach?.broadcastStatus({...this.attachStatus(),warning:Q})}onResize(A,Q){try{if(this.pty?.resize(A,Q),this.pendingRedrawOnResize&&this.pty){this.pendingRedrawOnResize=!1;let B=Q>1?Q-1:Q+1;this.pty.resize(A,B),this.pty.resize(A,Q)}}catch(B){this.warn(`[grok-copresence] resize failed: ${lA(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>_JA){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(-qJA),!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: ${lA(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: ${lA(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: ${lA(B)}`)),this.transition({type:"turn_completed",owner:"network"}),setImmediate(()=>this.replayDeferredHumanOrSchedule())}}}pollLogs(){if(this.closing)return;try{this.chatTail?.poll((A)=>II("chat.reduce.state_invariant",()=>this.reduceLogChunk("chat_history",A)),()=>II("chat.reduce.state_invariant",()=>this.resetLogFraming("chat_history"))),this.eventsTail?.poll((A)=>{this.reduceEventsChunkInOrder(A)},()=>II("events.reduce.state_invariant",()=>this.resetLogFraming("events"))),II("combined.flush.state_invariant",()=>this.flushSettledCompletion())}catch(A){let Q=A instanceof Q2?V8(A.failureSubcode):"unknown",B=new UA("jsonl_tail",`grok copresence lost its trusted JSONL tail: ${lA(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=my(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(`
170
170
  `,Q),C=B<0?A.length:B+1,I=A.slice(Q,C);if(II("events.lifecycle.state_invariant",()=>this.reduceLifecycleChunk(I)),this.closing)return;II("events.reduce.state_invariant",()=>this.reduceLogChunk("events",I)),Q=C}}flushSettledCompletion(){if(!this.completionPendingSince)return;let A=Date.now();if(A-this.completionPendingSince<Lf||A-this.lastChatActivityAt<Lf)return;let Q=uy(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: ${lA(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: ${lA(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(`
171
171
  `))>=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=eJA(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>=SJA){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=zf(I);if(vf({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=zf(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(`
172
172
  `))>=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=ly(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 dJA(A){let Q=BI(A,"chat_history.jsonl"),B=BI(A,"events.jsonl");Xf(Q,"chat_history",!1);let C="",I=null;if(Xf(B,"events",!0,(E)=>{let g=C+E;C="";let D;while((D=g.indexOf(`
@@ -204,7 +204,7 @@ ${A}`}function JR(A,Q,B,C,I){let{interactiveDashboardTask:E,messageType:g}=B,D=J
204
204
  `,"config.json",Q?.stat),{config:I,source:"prev",primaryError:B}}function y3(A){return JSON.parse(og(A,"config.json").body)}function f3(A,Q){let B=og(A,"config.json");_N(A,JSON.stringify(Q,null,2)+`
205
205
  `,"config.json",B.stat)}function h3(A){let Q=og(A,"config.json");return _N(`${A}.prev`,Q.body,"config.json.prev"),{backedUp:!0}}function m3(A,Q){let B=og(A,"config.json"),C=JSON.parse(B.body);if(C.session===Q)return!1;return C.session=Q,_N(A,JSON.stringify(C,null,2)+`
206
206
  `,"config.json",B.stat),!0}xN();async function r3(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 a3(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=a3(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 s3(A){if(!o1(A))return null;let Q=a3(A)?.client_request_id;return typeof Q==="string"?Q:null}async function t3(A,Q){for(let B of A)await Q(B)}function e3(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 A7(A,Q){return A!=="codex-app-server"||Q===0}var Un={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 Q7(A){let Q=Un[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 kN(){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 B7(){let A=null,Q=kN();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 $n,fchmodSync as yN,fstatSync as C7,fsyncSync as Mn,ftruncateSync as Vn,lstatSync as Wn,mkdirSync as wn,openSync as e1,readdirSync as Ln,readFileSync as Xn,realpathSync as t1,writeSync as Zn}from"node:fs";import{join as E7,resolve as A6}from"node:path";function g7(){return process.platform==="linux"&&$n("/proc/self/fd")}function D7(A,Q){return g7()?`/proc/self/fd/${A}`:Q}function U7(A,Q){let B=C7(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}`);yN(A,384)}function F7(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=C7(B),I=process.getuid?.();if(!C.isDirectory()||I!==void 0&&C.uid!==I)throw Error(`private log directory is not owner-controlled: ${Q}`);if(g7()&&t1(`/proc/self/fd/${B}`)!==Q)throw Error(`private log directory changed during validation: ${Q}`);if(process.platform!=="win32")yN(B,448);return B}catch(C){throw LU(B),C}}function Y7(A,Q,B){let C=0;while(C<Q.length){let I=Zn(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 Kn(A,Q){let B=e1(A,iI.O_RDWR|(iI.O_NOFOLLOW||0));try{U7(B,A);let C=Buffer.from(Q.redactText(Xn(B,"utf8")).text,"utf8");if(Vn(B,0),C.length>0)Y7(B,C,0);Mn(B),yN(B,384)}finally{LU(B)}}function J7(A,Q){let B=A6(A);wn(B,{recursive:!0,mode:448});let C=Wn(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=F7(B);try{let g=D7(E,B);for(let D of Ln(g)){if(!D.endsWith(".log"))continue;Kn(E7(g,D),Q)}}finally{LU(E)}return B}function N7(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=F7(A),E=E7(D7(I,A6(A)),Q),g;try{g=e1(E,iI.O_WRONLY|iI.O_CREAT|iI.O_APPEND|(iI.O_NOFOLLOW||0),384),U7(g,E);let D=Buffer.from(C.redactText(B).text,"utf8");if(D.length>0)Y7(g,D,null);yN(g,384)}finally{if(g!==void 0)LU(g);LU(I)}}function Q6(A){return JSON.stringify(A)}function G7(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 zn(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=QN({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:eJ(C.errorMessage)}:{}});if(C.event)I.event=C.event;A.log(AN(I))}async function $7(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 M7(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=zn(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 V7(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 W7(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 Hn(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 Rn(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"||Hn(A)}async function L7(A,Q,B=B6()){try{let C=await Q.sendAtomic(A);return B.hubSupportsTool=!0,{route:"atomic",payload:C}}catch(C){if(!Rn(C))throw C;return{route:"legacy-reply",payload:await Q.sendLegacyReply(A)}}}import{chmodSync as X7,closeSync as I6,existsSync as jn,fchmodSync as _n,fsyncSync as qn,openSync as Z7,readFileSync as On,renameSync as Sn,unlinkSync as K7,writeFileSync as Tn}from"node:fs";import{randomBytes as Pn}from"node:crypto";var z7=15000,vn=2500,j7=300000,XU=2000,xn=new Set(["replied","failed","cancelled","expired"]);function E6(A){if(A===void 0||A===null||String(A).trim()==="")return z7;let Q=Number(A);if(!Number.isSafeInteger(Q))return z7;return Math.min(j7,Math.max(vn,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 kn(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 H7(A){return s3(A)}function R7(A){return typeof A.task_id==="string"&&A.task_id?A.task_id:A.id}function bn(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 _7{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=Z7(B,"wx",384)}catch{if(arguments.length>1)return Q;throw Error("compensation cursor is locked")}try{return A()}finally{I6(C);try{K7(B)}catch{}}}read(){if(!jn(this.path))return C6();try{let A=kn(JSON.parse(On(this.path,"utf8")));return X7(this.path,384),A}catch{return C6()}}write(A){let Q=`${this.path}.tmp-${process.pid}-${Pn(6).toString("hex")}`,B=null;try{B=Z7(Q,"wx",384),_n(B,384),Tn(B,`${JSON.stringify(A)}
207
- `,"utf8"),qn(B),I6(B),B=null,Sn(Q,this.path),X7(this.path,384)}finally{if(B!==null)I6(B);try{K7(Q)}catch{}}}}function q7(A){let Q=E6(A.intervalMs),B=A.adapters,C=new _7(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=R7(x),m=H7(x);return y.consumed_task_ids.includes(u)||!!m&&y.consumed_client_request_ids.includes(m)},M=(x)=>{let y=R7(x),u=H7(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||!xn.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(bn(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(j7,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 km,mkdirSync as z2}from"fs";var O7={name:"@sleep2agi/agent-node",version:"2.5.0-preview.45",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 iGA(){if(F0!==void 0)return F0??void 0;if(q?.role!=="host_supervisor"){F0=null;return}try{(mN(),SK(hN)).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=lGA(),pGA=B6(),Rm=process.env.ANET_OPENCODE_BIN,IY=process.env.ANET_OPENCODE_VERSION,jm=process.env.PATH||"",eh=process.env.ANET_OPENCODE_SAFE_BASE,tQ=process.argv.slice(2),wA={},_m=[];if(tQ.length===1&&tQ[0]==="--print-entrypoint")console.log(uGA(process.argv[1])),process.exit(0);var qm="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){qm=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${qm}`),process.exit(0);if(tQ[A]==="-h"||tQ[A]==="--help")console.log(`
207
+ `,"utf8"),qn(B),I6(B),B=null,Sn(Q,this.path),X7(this.path,384)}finally{if(B!==null)I6(B);try{K7(Q)}catch{}}}}function q7(A){let Q=E6(A.intervalMs),B=A.adapters,C=new _7(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=R7(x),m=H7(x);return y.consumed_task_ids.includes(u)||!!m&&y.consumed_client_request_ids.includes(m)},M=(x)=>{let y=R7(x),u=H7(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||!xn.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(bn(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(j7,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 km,mkdirSync as z2}from"fs";var O7={name:"@sleep2agi/agent-node",version:"2.5.0-preview.46",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 iGA(){if(F0!==void 0)return F0??void 0;if(q?.role!=="host_supervisor"){F0=null;return}try{(mN(),SK(hN)).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=lGA(),pGA=B6(),Rm=process.env.ANET_OPENCODE_BIN,IY=process.env.ANET_OPENCODE_VERSION,jm=process.env.PATH||"",eh=process.env.ANET_OPENCODE_SAFE_BASE,tQ=process.argv.slice(2),wA={},_m=[];if(tQ.length===1&&tQ[0]==="--print-entrypoint")console.log(uGA(process.argv[1])),process.exit(0);var qm="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){qm=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${qm}`),process.exit(0);if(tQ[A]==="-h"||tQ[A]==="--help")console.log(`
208
208
  @sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
209
209
 
210
210
  用法:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/agent-node",
3
- "version": "2.5.0-preview.45",
3
+ "version": "2.5.0-preview.46",
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"