Open History to see the last commit
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({ id, result: { account: { type: "apiKey" }, requiresOpenaiAuth: false } });
88 return;
89 }
90 if (method === "skills/list" || method === "model/list") {
91 write({ id, result: { data: [] } });
92 return;
93 }
94 if (method === "thread/start") {
95 write({ id, result: fixture.responses.threadStart });
96 return;
97 }
98 if (method === "thread/resume") {
99 if (script.recordRequests) {
100 NodeFS.appendFileSync(
101 `${process.env.T3_CODEX_COLLAB_SCRIPT}.requests`,
102 `${JSON.stringify({ method, params: message.params })}\n`,
103 );
104 }
105 const threadId = message.params?.threadId;
106 const childSnapshot = script.childResumeSnapshots?.[threadId];
107 if (script.resumeRequestMarker) {
108 write({
109 jsonrpc: "2.0",
110 method: "serverRequest/resolved",
111 params: {
112 threadId: script.rootThreadId,
113 requestId: script.resumeRequestMarker,
114 },
115 });
116 }
117 if (childSnapshot?.hang) {
118 return;
119 }
120 if (childSnapshot?.error) {
121 write({ id, error: { code: -32000, message: childSnapshot.error } });
122 return;
123 }
124 if (childSnapshot) {
125 write({
126 id,
127 result: {
128 ...fixture.responses.threadStart,
129 model: childSnapshot.model,
130 reasoningEffort: childSnapshot.reasoningEffort,
131 thread: {
132 ...fixture.responses.threadStart.thread,
133 id: threadId,
134 sessionId: threadId,
135 },
136 },
137 });
138 for (const notification of childSnapshot.notifications ?? []) {
139 write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
140 }
141 return;
142 }
143 write({ id, result: fixture.responses.threadStart });
144 return;
145 }
146 if (method === "turn/start") {
147 const turnId = script.turnIds?.[turnStartCount];
148 const turn = turnId
149 ? { ...fixture.responses.turnStart.turn, id: turnId }
150 : fixture.responses.turnStart.turn;
151 activeTurn = turn;
152 turnStartCount += 1;
153 write({ id, result: { ...fixture.responses.turnStart, turn } });
154 const rootThreadId = script.rootThreadId;
155 if (script.onlyFirstTurnStarts !== true || turnStartCount === 1) {
156 write({
157 jsonrpc: "2.0",
158 method: "turn/started",
159 params: { threadId: rootThreadId, turn },
160 });
161 }
162 for (const notification of script.notifications) {
163 write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
164 }
165 for (const [index, request] of (script.serverRequests ?? []).entries()) {
166 if (request.id !== undefined) {
167 // Legacy form: caller-supplied JSON-RPC ids recorded in .responses.
168 write({ jsonrpc: "2.0", id: request.id, method: request.method, params: request.params });
169 continue;
170 }
171 // Scripted server->client requests (approval prompts). String values in
172 // params may reference "${threadId}" / "${turnId}" placeholders that are
173 // substituted with the ids this peer actually allocated.
174 const requestId = 9000 + index;
175 const label = request.label ?? `approval-${requestId}`;
176 openServerRequests.set(requestId, { label, itemId: request.params?.itemId });
177 const params = JSON.parse(
178 JSON.stringify(request.params)
179 .replaceAll("${threadId}", String(rootThreadId))
180 .replaceAll("${turnId}", String(turn.id)),
181 );
182 write({ jsonrpc: "2.0", id: requestId, method: request.method, params });
183 }
184 if (script.holdTurnOpen !== true) {
185 write({
186 jsonrpc: "2.0",
187 method: "turn/completed",
188 params: {
189 threadId: rootThreadId,
190 turn: { ...turn, status: "completed" },
191 },
192 });
193 }
194 return;
195 }
196 if (method === "turn/interrupt") {
197 // Record which thread/turn was interrupted (append-only sidecar file the
198 // test reads) so Stop coverage can assert every live child was reached.
199 // failInterruptFor simulates a dead child whose interrupt errors.
200 const target = message.params?.threadId;
201 NodeFS.appendFileSync(
202 `${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,
203 `${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,
204 );
205 if (
206 script.expectedActiveTurnId &&
207 message.params?.threadId === script.rootThreadId &&
208 message.params?.turnId !== script.expectedActiveTurnId
209 ) {
210 write({
211 id,
212 error: {
213 code: -32000,
214 message: `expected active turn id ${message.params?.turnId} but found ${script.expectedActiveTurnId}`,
215 },
216 });
217 return;
218 }
219 if (script.failInterruptFor && script.failInterruptFor === target) {
220 write({ id, error: { code: -32000, message: "thread already closed" } });
221 return;
222 }
223 if (script.hangInterruptFor && script.hangInterruptFor === target) {
224 // Never respond: simulates a wedged child whose RPC neither resolves
225 // nor rejects. The runtime's bounded deadline must move on.
226 return;
227 }
228 write({ id, result: {} });
229 return;
230 }
231 if (id !== undefined) {
232 write({ id, result: {} });
233 }
234});