Skip to content

Instantly share code, notes, and snippets.

@Sidreyas
Created November 6, 2026 22:57
Show Gist options
  • Select an option

  • Save Sidreyas/0869510014ca765acc0fe481db2baba0 to your computer and use it in GitHub Desktop.

Select an option

Save Sidreyas/0869510014ca765acc0fe481db2baba0 to your computer and use it in GitHub Desktop.
Issue 22865: deterministic T3 CLI, WebSocket, Grok ACP and MCP delegation reproduction
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import http from "node:http";
import crypto from "node:crypto";
import {spawn,execFileSync} from "node:child_process";
import {createRequire} from "node:module";
import {pathToFileURL} from "node:url";
const phase = process.argv[2];
assert.ok(["baseline","fixed"].includes(phase));
const checkout = process.cwd();
const requireLocal = createRequire(path.join(checkout,"apps/server/package.json"));
const local = name => import(pathToFileURL(requireLocal.resolve(name)).href);
const [Effect,Layer,Stream,Deferred,{Socket},{RpcClient,RpcSerialization},contracts] = await Promise.all([
local("effect/Effect"),local("effect/Layer"),local("effect/Stream"),local("effect/Deferred"),local("effect/socket"),local("effect/rpc"),import(pathToFileURL(path.join(checkout,"packages/contracts/src/index.ts")).href)
]);
const {WsRpcGroup,ORCHESTRATION_PROTOCOL_VERSION,ORCHESTRATION_PROTOCOL_HEADER} = contracts;
const {PING_TIMEOUT} = await import(pathToFileURL(path.join(checkout,"packages/client-runtime/src/rpc/protocol.ts")).href);
const evidence = fs.mkdtempSync(path.join(os.tmpdir(),"t3-22865-" + phase + "-"));
const home = path.join(evidence,"home");
const workspace = path.join(evidence,"workspace");
fs.mkdirSync(path.join(home,"userdata"),{recursive:true});
fs.mkdirSync(workspace);
execFileSync("git",["init","-q",workspace]);
fs.writeFileSync(path.join(workspace,"fixture.txt"),"Issue 22865 isolated protocol fixture\n");
execFileSync("git",["-C",workspace,"add","fixture.txt"]);
execFileSync("git",["-C",workspace,"-c","user.name=Verifier","-c","user.email=verifier@localhost","commit","-qm","Fixture"]);
const fixture = path.join(os.tmpdir(),"slot8-22865-grok-fixture.mjs");
fs.copyFileSync(fixture,path.join(evidence,"grok-fixture.mjs"));
fs.copyFileSync(import.meta.filename,path.join(evidence,"verifier.mjs"));
const binary = path.join(evidence,"grok-fixture.cmd");
fs.writeFileSync(binary,'@echo off\r\n"' + process.execPath + '" "' + fixture + '" %*\r\n');
const providerInstances = Object.fromEntries(["codex","claude","cursor","grok","opencode","antigravity","kiro","pi","muse","fx"].map(driver=>[driver,{driver,enabled:false}]));
providerInstances["grok-e2e"]={driver:"grok",displayName:"Issue 22865 fixture",enabled:true,config:{binaryPath:process.execPath,customModels:["grok-4.7"]},environment:[{name:"NODE_OPTIONS",value:"--import="+pathToFileURL(fixture).href}]};
fs.writeFileSync(path.join(home,"userdata","settings.json"),JSON.stringify({enableProviderUpdateChecks:false,compactIdleThreads:false,providerInstances,defaultModelSelection:{instanceId:"grok-e2e",model:"grok-4.7"}}));
const granted = new Set();
const gated = new Map();
const gate = http.createServer((req,res)=>{
if (!["/root","/finish","/wake"].includes(req.url)) {res.writeHead(404).end();return;}
if (granted.has(req.url)) res.end("continue");
else gated.set(req.url,res);
});
await new Promise(resolve=>gate.listen(0,"127.0.0.1",resolve));
const gateOrigin = "http://127.0.0.1:" + gate.address().port;
const release = route => {granted.add(route);gated.get(route)?.end("continue");gated.delete(route);};
const reserve = http.createServer();
await new Promise(resolve=>reserve.listen(0,"127.0.0.1",resolve));
const port = reserve.address().port;
await new Promise(resolve=>reserve.close(resolve));
const origin = "http://127.0.0.1:" + port;
const bootstrap = crypto.randomUUID();
const env={...process.env,T3CODE_HOME:home,T3_22865_EVIDENCE:evidence,T3_22865_GATE:gateOrigin,T3_22865_CHECKOUT:checkout,T3CODE_DEV_SEED:"0"};
for (const name of ["VITE_HTTP_URL","VITE_WS_URL","VITE_DEV_SERVER_URL","T3CODE_BOOTSTRAP_FD","T3CODE_DEV_AUTH_TOKEN"]) delete env[name];
const server = spawn(process.execPath,[path.join(checkout,"apps/server/src/bin.ts"),"start","--base-dir",home,"--mode","desktop","--port",String(port),"--host","127.0.0.1","--no-browser","--bootstrap-fd","3","--log-level","debug"],{cwd:checkout,env,windowsHide:true,stdio:["ignore","pipe","pipe","pipe"]});
fs.writeFileSync(path.join(evidence,"server.pid"),String(server.pid));
console.log(JSON.stringify({phase,evidence,serverPid:server.pid,origin}));
server.stdio[3].end(JSON.stringify({mode:"desktop",noBrowser:true,port,t3Home:home,host:"127.0.0.1",desktopBootstrapToken:bootstrap,tailscaleServeEnabled:false,tailscaleServePort:443}));
const ready=Promise.withResolvers();
let tail="";
for (const pipe of [server.stdout,server.stderr]) pipe.on("data",data=>{
const text=data.toString().replaceAll(bootstrap,"[REDACTED]");
fs.appendFileSync(path.join(evidence,"server.log"),text);
tail=(tail+text).slice(-16384);
if (tail.includes("startup phase: complete")) ready.resolve();
});
const closed = new Promise(resolve=>server.once("close",(code,signal)=>{ready.reject(new Error("Server exited " + code + "/" + signal + "; inspect " + evidence));resolve();}));
server.once("error",ready.reject);
const startupDeadline=setTimeout(()=>ready.reject(new Error("Server startup deadline; inspect " + evidence)),120000);
const abort = new AbortController();
let verifierDeadline;
const milestones = value => {console.log(JSON.stringify(value));fs.appendFileSync(path.join(evidence,"milestones.ndjson"),JSON.stringify(value)+"\n");};
try {
await ready.promise;
clearTimeout(startupDeadline);
verifierDeadline=setTimeout(()=>abort.abort(new Error("E2E deadline; inspect " + evidence)),180000);
milestones({event:"server-ready"});
const tokenResponse=await fetch(origin+"/oauth/token",{method:"POST",body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:bootstrap,subject_token_type:"urn:t3:params:oauth:token-type:environment-bootstrap",requested_token_type:"urn:ietf:params:oauth:token-type:access_token"})});
assert.ok(tokenResponse.ok);
const token=await tokenResponse.json();
const headers={Authorization:"Bearer "+token.access_token,"Content-Type":"application/json",[ORCHESTRATION_PROTOCOL_HEADER]:String(ORCHESTRATION_PROTOCOL_VERSION)};
const projectId=crypto.randomUUID();
const created=await fetch(origin+"/api/projects/mutate",{method:"POST",headers,body:JSON.stringify({type:"project.create",commandId:crypto.randomUUID(),projectId,title:"Issue 22865",workspaceRoot:workspace})});
assert.ok(created.ok,await created.text());
const ticketResponse=await fetch(origin+"/api/auth/websocket-ticket",{method:"POST",headers});
assert.ok(ticketResponse.ok);
const ticket=await ticketResponse.json();
const socket=Socket.layerWebSocket(origin.replace("http:","ws:")+"/ws?orchestrationProtocol="+ORCHESTRATION_PROTOCOL_VERSION+"&wsTicket="+encodeURIComponent(ticket.ticket)).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
const protocol=RpcClient.layerProtocolSocket({pingTimeout:PING_TIMEOUT}).pipe(Layer.provide(socket),Layer.provide(RpcSerialization.layerJson));
const expectedSummary=phase==="baseline" ? "Child task completed without an assistant result." : "EARLY_SUCCESS_DONE";
let parentProjection;
let childProjection;
let childThreadId;
let acknowledged=false;
const parentThreadId=crypto.randomUUID();
const program=Effect.gen(function*(){
const client=yield* RpcClient.make(WsRpcGroup);
const done=yield* Deferred.make();
const checkChild=projection=>{
childProjection=projection;
fs.writeFileSync(path.join(evidence,"child-projection.json"),JSON.stringify(projection,null,2));
assert.ok(!projection.runs.some(r=>r.status==="failed"),"Child run failed");
if(projection.turnItems.some(item=>item.nativeItemRef?.nativeId?.endsWith("foreground")&&item.status==="completed"))release("/finish");
const final=projection.messages.some(m=>m.role==="assistant"&&m.text==="LATE_NATIVE_ANSWER");
return acknowledged&&final&&projection.runs.length===(phase==="baseline"?3:2)&&projection.runs.every(r=>r.status==="completed");
};
const onParent=Effect.fn(function*(item){
const projection=item.kind==="snapshot"?item.projection:yield*client["orchestration.getThreadProjection"]({threadId:parentThreadId});
parentProjection=projection;
fs.writeFileSync(path.join(evidence,"parent-projection.json"),JSON.stringify(projection,null,2));
assert.ok(!projection.runs.some(r=>r.status==="failed"),"Parent run failed");
const child=projection.subagents[0]?.childThreadId;
if(child&&!childThreadId){
childThreadId=child;
yield*client["orchestration.subscribeThread"]({threadId:child}).pipe(Stream.runForEach(Effect.fn(function*(childItem){
const current=childItem.kind==="snapshot"?childItem.projection:yield*client["orchestration.getThreadProjection"]({threadId:child});
if(checkChild(current))yield*Deferred.succeed(done,undefined);
})),Effect.catchCause(cause=>Deferred.failCause(done,cause)),Effect.forkScoped);
}
if(projection.runs[0]?.status==="completed")release("/root");
if(!acknowledged&&projection.messages.some(m=>m.role==="assistant"&&m.text.startsWith("TASK_RESULT:"))){
const answer=projection.messages.find(m=>m.role==="assistant"&&m.text.startsWith("TASK_RESULT:")).text;
assert.equal(answer,"TASK_RESULT:"+expectedSummary);
assert.equal(projection.subagents[0].result,expectedSummary);
acknowledged=true;
milestones({event:"delegated-result",phase,summary:projection.subagents[0].result,childThreadId});
release("/wake");
}
});
yield*client["orchestration.launchThread"]({commandId:crypto.randomUUID(),threadId:parentThreadId,projectId,title:"Issue 22865 parent",modelSelection:{instanceId:"grok-e2e",model:"grok-4.7"},runtimeMode:"full-access",interactionMode:"default",workspaceStrategy:{type:"root"},initialMessage:{text:"E2E_22865_PARENT",attachments:[]}});
yield*client["orchestration.subscribeThread"]({threadId:parentThreadId}).pipe(Stream.runForEach(onParent),Effect.catchCause(cause=>Deferred.failCause(done,cause)),Effect.forkScoped);
yield*Deferred.await(done);
}).pipe(Effect.scoped,Effect.provide(protocol));
await Effect.runPromise(program,{signal:abort.signal});
assert.ok(childProjection.messages.some(m=>m.role==="assistant"&&m.text==="EARLY_SUCCESS_DONE"));
const report={phase,parentThreadId,childThreadId,summary:parentProjection.subagents[0].result,childRuns:childProjection.runs.map(r=>({ordinal:r.ordinal,status:r.status})),childAnswers:childProjection.messages.filter(m=>m.role==="assistant").map(m=>m.text)};
fs.writeFileSync(path.join(evidence,"observations.json"),JSON.stringify(report,null,2));
milestones({event:"E2E-passed",...report});
} finally {
clearTimeout(startupDeadline);clearTimeout(verifierDeadline);
release("/root");release("/finish");release("/wake");
gate.closeAllConnections();
await new Promise(resolve=>gate.close(resolve));
if(server.exitCode===null)server.kill("SIGINT");
await closed;
milestones({event:"owned-server-stopped",pid:server.pid});
}
import fs from "node:fs";
import path from "node:path";
import readline from "node:readline";
import crypto from "node:crypto";
if (process.argv.includes("--version")) { console.log("1.0.62 (deterministic issue-22865 fixture)"); process.exit(0); }
if (process.argv.includes("models") || path.basename(process.argv[1]) === "models") { console.log("You are logged in\n* grok-4.7 (default)"); process.exit(0); }
if (process.argv.includes("inspect") || path.basename(process.argv[1]) === "inspect") { console.log(JSON.stringify({skills:[]})); process.exit(0); }
const evidence = process.env.T3_22865_EVIDENCE;
const gate = process.env.T3_22865_GATE;
const sessionId = crypto.randomUUID();
const transcript = fs.readFileSync(path.join(process.env.T3_22865_CHECKOUT, "apps/server/src/orchestration-v2/testkit/fixtures/grok_background_bash/grok_transcript.ndjson"), "utf8").trim().split("\n").map(JSON.parse);
const initializeResult = transcript.find(r => r.label === "response:initialize").frame.result;
const sessionResult = transcript.find(r => r.label === "response:session/new").frame.result;
let mcp;
let task;
let mcpSession;
let mcpRequest = 0;
const record = value => fs.appendFileSync(path.join(evidence, "fixture.ndjson"), JSON.stringify({pid:process.pid, ...value}) + "\n");
record({event:"spawn",sessionId,command:process.argv.slice(2).filter(a=>["agent","stdio","inspect","models","version","--version"].includes(a))});
const send = value => process.stdout.write(JSON.stringify(value) + "\n");
const notify = (method, params) => send({jsonrpc:"2.0",method,params});
const update = (value, promptId) => notify("session/update", {sessionId, update:value, ...(promptId ? {_meta:{promptId}} : {})});
const assistant = (text,promptId) => update({sessionUpdate:"agent_message_chunk",content:{type:"text",text}},promptId);
const finish = request => {
send({jsonrpc:"2.0",id:request.id,result:{stopReason:"end_turn",_meta:request.params._meta}});
record({event:"prompt-completed"});
};
async function mcpRpc(method,params) {
if (!mcp) throw new Error("T3 MCP server was not supplied to the fixture");
const vars = Object.fromEntries((mcp.env ?? []).map(v => [v.name,v.value]));
const endpoint = mcp.url ?? vars.T3_ACP_MCP_ENDPOINT;
const authorization = mcp.headers?.find(h => h.name.toLowerCase() === "authorization")?.value ?? vars.T3_ACP_MCP_AUTHORIZATION;
const response = await fetch(endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",Authorization:authorization,...(mcpSession ? {"Mcp-Session-Id":mcpSession} : {})},body:JSON.stringify({jsonrpc:"2.0",id:++mcpRequest,method,params})});
mcpSession = response.headers.get("mcp-session-id") ?? mcpSession;
const text = await response.text();
const data = response.headers.get("content-type")?.includes("text/event-stream") ? JSON.parse(text.split("\n").find(l => l.startsWith("data:")).slice(5)) : JSON.parse(text);
if (!response.ok || data.error) throw new Error("MCP " + method + " failed: " + JSON.stringify(data.error ?? data));
return data.result;
}
async function callTool(name,args) {
const result = await mcpRpc("tools/call",{name,arguments:args});
if (result.isError) throw new Error("Tool failed: " + JSON.stringify(result.content));
return result.structuredContent ?? JSON.parse(result.content.find(c => c.type === "text").text);
}
async function prompt(request) {
const text = request.params.prompt.map(c => c.text ?? "").join("\n");
if (text.includes("E2E_22865_PARENT") && !text.includes("E2E_22865_CHILD") && !task) {
await mcpRpc("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"issue-22865-fixture",version:"1"}});
task = await callTool("delegate_task",{task:"E2E_22865_CHILD",title:"Early completion child",mode:"async",isolation:"shared",target:{providerInstanceId:"grok-e2e",model:"grok-4.7"}});
record({event:"delegated",taskId:task.taskId,childThreadId:task.childThreadId});
assistant("PARENT_RELEASED");
finish(request);
return;
}
if (text.includes("E2E_22865_CHILD")) {
await fetch(gate + "/root");
update({sessionUpdate:"tool_call",toolCallId:"early",title:"Background command",kind:"execute",status:"completed",rawInput:{command:"echo EARLY_BG_DONE"},rawOutput:{type:"BackgroundTaskStarted",task_id:"early"}});
notify("x.ai/task_backgrounded",{sessionId,update:{sessionUpdate:"task_backgrounded",task_id:"early",task_snapshot:{task_id:"early",kind:"bash",command:"echo EARLY_BG_DONE"}}});
update({sessionUpdate:"tool_call",toolCallId:"foreground",title:"Foreground command",kind:"execute",status:"in_progress",rawInput:{command:"echo FOREGROUND_DONE"}});
notify("x.ai/task_completed",{sessionId,update:{sessionUpdate:"task_completed",task_id:"early",will_wake:true,task_snapshot:{task_id:"early",kind:"bash",command:"echo EARLY_BG_DONE",exit_code:0,output:"EARLY_BG_DONE\n"}}});
update({sessionUpdate:"tool_call_update",toolCallId:"foreground",status:"completed",rawOutput:{type:"Text",text:"FOREGROUND_DONE\n"}});
await fetch(gate + "/finish");
assistant("EARLY_SUCCESS_DONE");
record({event:"root-answer",text:"EARLY_SUCCESS_DONE"});
finish(request);
await fetch(gate + "/wake");
update({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:"Preparing the delayed report"}},"task-completed-early");
assistant("LATE_NATIVE_ANSWER","task-completed-early");
notify("x.ai/session_notification",{sessionId,update:{sessionUpdate:"turn_completed",prompt_id:"task-completed-early",stop_reason:"end_turn"}});
record({event:"native-wake-answer",text:"LATE_NATIVE_ANSWER"});
return;
}
if (task) {
const status = await callTool("task_status",{taskId:task.taskId});
record({event:"task-status",summary:status.summary,status:status.status});
assistant("TASK_RESULT:" + status.summary);
finish(request);
return;
}
assistant("Fixture title");
finish(request);
}
const reader = readline.createInterface({input:process.stdin});
reader.on("line", line => {
let request;
try { request = JSON.parse(line); } catch { return; }
record({event:"frame",keys:Object.keys(request)});
if (!request.method) return;
record({event:"request",method:request.method});
(async () => {
if (request.method === "initialize") return send({jsonrpc:"2.0",id:request.id,result:initializeResult});
if (request.method === "session/new" || request.method === "session/load") {
mcp = request.params.mcpServers?.find(s => s.name === "t3-code");
return send({jsonrpc:"2.0",id:request.id,result:{...sessionResult,sessionId}});
}
if (request.method === "session/prompt") return await prompt(request);
if (request.id !== undefined) send({jsonrpc:"2.0",id:request.id,result:{}});
})().catch(error => { record({event:"error",message:error.message}); if (request.id !== undefined) send({jsonrpc:"2.0",id:request.id,error:{code:-32603,message:error.message}}); });
});
reader.on("close",()=>process.exit(0));
await new Promise(resolve => reader.once("close", resolve));

Issue 22865 integrated reproduction

This deterministic fixture exercises T3's actual CLI, HTTP authentication, WebSocket RPC, Grok ACP subprocess adapter, MCP delegation, persistence, and delegated-result delivery. It does not make paid provider calls.

Tested on Windows with Node 26.12.1 and the repository's local frozen-lockfile dependencies. Save slot8-22865-e2e.mjs and slot8-22865-grok-fixture.mjs from this gist in the directory returned by Node's os.tmpdir() (normally $env:TEMP). Run from the repository root.

On baseline 32a0531748c44b25072d7495ce0b9bd7e9450a87:

node "$env:TEMP/slot8-22865-e2e.mjs" baseline

On the fix:

node "$env:TEMP/slot8-22865-e2e.mjs" fixed

Each run creates its own temporary T3 home and fixture workspace, starts apps/server/src/bin.ts start with an explicit --base-dir, loopback address, and private bootstrap FD, and stops its captured server PID in finally. It does not use live userdata or VITE_HTTP_URL/VITE_WS_URL.

The verifier authenticates a real WS client and launches a parent turn. The native ACP fixture calls T3's actual MCP delegate_task. The child sends a background command completion while its root prompt is open, then answers EARLY_SUCCESS_DONE. The parent calls actual MCP task_status to read the durable published result. A network gate then releases a native task-completed-early wake containing LATE_NATIVE_ANSWER. Assertions consume real thread projections over WebSocket, and all ordering gates are driven by protocol/projection events.

Observed with byte-identical verifier and fixture scripts:

baseline:
  delegated result: Child task completed without an assistant result.
  completed child runs: 1, 2, 3
  child answers: EARLY_SUCCESS_DONE, LATE_NATIVE_ANSWER

fixed:
  delegated result: EARLY_SUCCESS_DONE
  completed child runs: 1, 2
  child answers: EARLY_SUCCESS_DONE, LATE_NATIVE_ANSWER

Each evidence directory contains observations.json, milestones.ndjson, saved projections, and fixture/runtime logs. The observations and milestones show the result and cleanup. Raw runtime logs and database state can contain generated local authentication material; they are not included here.

The fixture uses the repository's recorded Grok handshake responses and launches Node directly with a per-provider preload. This avoids a Windows .cmd fixture launch that stalled during initialization. Node's own inspect command prevents the separate skill-discovery probe from being served by this fixture; the ACP handshake and turn protocol complete. The WS verifier imports the shipping client's 15-second PING_TIMEOUT, instead of Effect's shorter default. No production lifecycle timeout was changed. This is a production service/protocol pass with deterministic native traffic, not live Grok-service or UI verification.

Implemented with OpenAI GPT-6 via the Codex harness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment