Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

codexCollabMockPeer.mjs

245 lines8.5 KB

1// Minimal codex app-server stand-in for runtime-level collab tests.
2// Speaks just enough of the protocol for CodexSessionRuntime to start a
3// session, using REAL captured responses (codexMultiAgentWire.json), then
4// replays a scripted multi-agent notification sequence read from the
5// T3_CODEX_COLLAB_SCRIPT env var (a JSON file path) when the first turn
6// starts. Runs as a plain Node process — stdlib only.
7import * as NodeFS from "node:fs";
8import * as NodeReadline from "node:readline";
9import * as NodePath from "node:path";
10import * as NodeURL from "node:url";
11​
12const here = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
13const fixture = JSON.parse(
14 NodeFS.readFileSync(NodePath.join(here, "codexMultiAgentWire.json"), "utf8"),
15);
16const script = JSON.parse(NodeFS.readFileSync(process.env.T3_CODEX_COLLAB_SCRIPT, "utf8"));
17​
18const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
19let turnStartCount = 0;
20let activeTurn;
21// Server->client requests the runtime must answer (approval prompts), keyed
22// by the numeric JSON-RPC id this peer allocated for them.
23const openServerRequests = new Map();
24const rl = NodeReadline.createInterface({ input: process.stdin });
25rl.on("line", (line) => {
26 let message;
27 try {
28 message = JSON.parse(line);
29 } catch {
30 return;
31 }
32 const { id, method } = message;
33 if (openServerRequests.has(id)) {
34 // The runtime answered an approval request. Record the response so tests
35 // can assert settlement behavior, then emit serverRequest/resolved as a
36 // deterministic receipt (tests wait on the runtime's event stream rather
37 // than polling the sidecar file). Real codex identifies the resolved
38 // request by its item id — the key the runtime correlates on — so the
39 // receipt exercises the same path that closes the approval card in the
40 // UI.
41 const request = openServerRequests.get(id);
42 openServerRequests.delete(id);
43 NodeFS.appendFileSync(
44 `${process.env.T3_CODEX_COLLAB_SCRIPT}.approvalResponses`,
45 `${JSON.stringify({ id, label: request.label, result: message.result ?? null })}\n`,
46 );
47 write({
48 jsonrpc: "2.0",
49 method: "serverRequest/resolved",
50 params: {
51 threadId: script.rootThreadId,
52 requestId: request.itemId ?? request.label,
53 },
54 });
55 return;
56 }
57 if (method === undefined && script.serverRequests?.some((request) => request.id === id)) {
58 NodeFS.appendFileSync(
59 `${process.env.T3_CODEX_COLLAB_SCRIPT}.responses`,
60 `${JSON.stringify({ id, result: message.result, error: message.error })}\n`,
61 );
62 if (script.completeTurnOnServerResponse && activeTurn) {
63 write({
64 jsonrpc: "2.0",
65 method: "turn/completed",
66 params: {
67 threadId: script.rootThreadId,
68 turn: { ...activeTurn, status: "completed" },
69 },
70 });
71 }
72 return;
73 }
74 if (method === "initialize") {
75 write({
76 id,
77 result: {
78 userAgent: "t3-collab-mock/0.0.0",
79 codexHome: "/tmp",
80 platformFamily: "unix",
81 platformOs: "linux",
82 },
83 });
84 return;
85 }
86 if (method === "account/read") {
87 write({
88 id,
89 result: { account: script.account ?? { type: "apiKey" }, requiresOpenaiAuth: false },
90 });
91 return;
92 }
93 if (method === "account/rateLimits/read" && script.failRateLimitsRead) {
94 write({ id, error: { code: -32000, message: "usage unavailable" } });
95 return;
96 }
97 if (method === "account/rateLimitResetCredit/consume" && script.resetCreditOutcome) {
98 write({ id, result: { outcome: script.resetCreditOutcome } });
99 return;
100 }
101 if (method === "skills/list" || method === "model/list") {
102 write({ id, result: { data: [] } });
103 return;
104 }
105 if (method === "thread/start") {
106 write({ id, result: fixture.responses.threadStart });
107 return;
108 }
109 if (method === "thread/resume") {
110 if (script.recordRequests) {
111 NodeFS.appendFileSync(
112 `${process.env.T3_CODEX_COLLAB_SCRIPT}.requests`,
113 `${JSON.stringify({ method, params: message.params })}\n`,
114 );
115 }
116 const threadId = message.params?.threadId;
117 const childSnapshot = script.childResumeSnapshots?.[threadId];
118 if (script.resumeRequestMarker) {
119 write({
120 jsonrpc: "2.0",
121 method: "serverRequest/resolved",
122 params: {
123 threadId: script.rootThreadId,
124 requestId: script.resumeRequestMarker,
125 },
126 });
127 }
128 if (childSnapshot?.hang) {
129 return;
130 }
131 if (childSnapshot?.error) {
132 write({ id, error: { code: -32000, message: childSnapshot.error } });
133 return;
134 }
135 if (childSnapshot) {
136 write({
137 id,
138 result: {
139 ...fixture.responses.threadStart,
140 model: childSnapshot.model,
141 reasoningEffort: childSnapshot.reasoningEffort,
142 thread: {
143 ...fixture.responses.threadStart.thread,
144 id: threadId,
145 sessionId: threadId,
146 },
147 },
148 });
149 for (const notification of childSnapshot.notifications ?? []) {
150 write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
151 }
152 return;
153 }
154 write({ id, result: fixture.responses.threadStart });
155 return;
156 }
157 if (method === "turn/start") {
158 const turnId = script.turnIds?.[turnStartCount];
159 const turn = turnId
160 ? { ...fixture.responses.turnStart.turn, id: turnId }
161 : fixture.responses.turnStart.turn;
162 activeTurn = turn;
163 turnStartCount += 1;
164 write({ id, result: { ...fixture.responses.turnStart, turn } });
165 const rootThreadId = script.rootThreadId;
166 if (script.onlyFirstTurnStarts !== true || turnStartCount === 1) {
167 write({
168 jsonrpc: "2.0",
169 method: "turn/started",
170 params: { threadId: rootThreadId, turn },
171 });
172 }
173 for (const notification of script.notifications) {
174 write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
175 }
176 for (const [index, request] of (script.serverRequests ?? []).entries()) {
177 if (request.id !== undefined) {
178 // Legacy form: caller-supplied JSON-RPC ids recorded in .responses.
179 write({ jsonrpc: "2.0", id: request.id, method: request.method, params: request.params });
180 continue;
181 }
182 // Scripted server->client requests (approval prompts). String values in
183 // params may reference "${threadId}" / "${turnId}" placeholders that are
184 // substituted with the ids this peer actually allocated.
185 const requestId = 9000 + index;
186 const label = request.label ?? `approval-${requestId}`;
187 openServerRequests.set(requestId, { label, itemId: request.params?.itemId });
188 const params = JSON.parse(
189 JSON.stringify(request.params)
190 .replaceAll("${threadId}", String(rootThreadId))
191 .replaceAll("${turnId}", String(turn.id)),
192 );
193 write({ jsonrpc: "2.0", id: requestId, method: request.method, params });
194 }
195 if (script.holdTurnOpen !== true) {
196 write({
197 jsonrpc: "2.0",
198 method: "turn/completed",
199 params: {
200 threadId: rootThreadId,
201 turn: { ...turn, status: "completed" },
202 },
203 });
204 }
205 return;
206 }
207 if (method === "turn/interrupt") {
208 // Record which thread/turn was interrupted (append-only sidecar file the
209 // test reads) so Stop coverage can assert every live child was reached.
210 // failInterruptFor simulates a dead child whose interrupt errors.
211 const target = message.params?.threadId;
212 NodeFS.appendFileSync(
213 `${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,
214 `${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,
215 );
216 if (
217 script.expectedActiveTurnId &&
218 message.params?.threadId === script.rootThreadId &&
219 message.params?.turnId !== script.expectedActiveTurnId
220 ) {
221 write({
222 id,
223 error: {
224 code: -32000,
225 message: `expected active turn id ${message.params?.turnId} but found ${script.expectedActiveTurnId}`,
226 },
227 });
228 return;
229 }
230 if (script.failInterruptFor && script.failInterruptFor === target) {
231 write({ id, error: { code: -32000, message: "thread already closed" } });
232 return;
233 }
234 if (script.hangInterruptFor && script.hangInterruptFor === target) {
235 // Never respond: simulates a wedged child whose RPC neither resolves
236 // nor rejects. The runtime's bounded deadline must move on.
237 return;
238 }
239 write({ id, result: {} });
240 return;
241 }
242 if (id !== undefined) {
243 write({ id, result: {} });
244 }
245});