@gonovus-ai/spec-flow-cli 1.3.1 → 1.4.1

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 (42) hide show
  1. package/README.md +17 -3
  2. package/dist/cli.js +113 -22
  3. package/dist/cli.js.map +1 -1
  4. package/dist/commands/work-item-output.d.ts +18 -0
  5. package/dist/discuss-commands.d.ts +3 -0
  6. package/dist/discuss-commands.js +763 -0
  7. package/dist/discuss-commands.js.map +1 -0
  8. package/dist/member-references.d.ts +28 -0
  9. package/dist/member-references.js +94 -0
  10. package/dist/member-references.js.map +1 -0
  11. package/dist/runner/adapters/codex-app-server.d.ts +14 -1
  12. package/dist/runner/adapters/codex-app-server.js +541 -292
  13. package/dist/runner/adapters/codex-app-server.js.map +1 -1
  14. package/dist/runner/adapters/exec-adapter.js +31 -11
  15. package/dist/runner/adapters/exec-adapter.js.map +1 -1
  16. package/dist/runner/orchestrator.d.ts +10 -1
  17. package/dist/runner/orchestrator.js +438 -8
  18. package/dist/runner/orchestrator.js.map +1 -1
  19. package/dist/runner/redact.d.ts +1 -0
  20. package/dist/runner/redact.js +1 -0
  21. package/dist/runner/redact.js.map +1 -1
  22. package/dist/runner/state-store.d.ts +4 -1
  23. package/dist/runner/state-store.js +61 -1
  24. package/dist/runner/state-store.js.map +1 -1
  25. package/dist/runner/telemetry-bridge.d.ts +24 -2
  26. package/dist/runner/telemetry-bridge.js +168 -4
  27. package/dist/runner/telemetry-bridge.js.map +1 -1
  28. package/dist/runner/types.d.ts +70 -2
  29. package/dist/runner/types.js +13 -1
  30. package/dist/runner/types.js.map +1 -1
  31. package/dist/runner/workflow.d.ts +5 -1
  32. package/dist/runner/workflow.js +58 -0
  33. package/dist/runner/workflow.js.map +1 -1
  34. package/dist/work-item-delivery-commands.js +1 -2
  35. package/dist/work-item-delivery-commands.js.map +1 -1
  36. package/guides/agent-sessions.md +8 -2
  37. package/guides/delivery.md +1 -1
  38. package/guides/discuss.md +72 -0
  39. package/guides/search.md +4 -2
  40. package/guides/work-items.md +58 -4
  41. package/guides/workspace-admin.md +4 -0
  42. package/package.json +1 -1
@@ -101,31 +101,242 @@ function mapCodexSandboxPolicy(sandbox) {
101
101
  return { type: "dangerFullAccess" };
102
102
  return { type: "workspaceWrite" };
103
103
  }
104
- export class CodexAppServerAdapter {
105
- kind = "codex";
106
- codexCommand;
104
+ function extractRoutingIds(rawParams) {
105
+ const params = asRecord(rawParams);
106
+ if (params === undefined)
107
+ return { threadId: undefined, turnId: undefined };
108
+ const turn = asRecord(params.turn);
109
+ const threadId = asString(params.threadId) ?? asString(turn?.threadId) ?? asString(params.conversationId);
110
+ const turnId = asString(params.turnId) ?? asString(turn?.id);
111
+ return { threadId, turnId };
112
+ }
113
+ class CodexAppServerTransport {
114
+ child;
107
115
  cliVersion;
108
- constructor(codexCommand = "codex", cliVersion = "1.3.0") {
109
- this.codexCommand = codexCommand;
116
+ onClosed;
117
+ nextRpcId = 1;
118
+ pendingRpc = new Map();
119
+ turnsByThreadId = new Map();
120
+ turnsByTurnId = new Map();
121
+ allActiveTurns = new Set();
122
+ loadedThreads = new Set();
123
+ stderrLines = [];
124
+ initPromise = null;
125
+ closed = false;
126
+ constructor(child, cliVersion, onClosed) {
127
+ this.child = child;
110
128
  this.cliVersion = cliVersion;
129
+ this.onClosed = onClosed;
130
+ const stdoutReader = createInterface({ input: child.stdout, crlfDelay: Infinity });
131
+ stdoutReader.on("line", (line) => {
132
+ this.handleStdoutLine(line);
133
+ });
134
+ const stderrReader = createInterface({ input: child.stderr, crlfDelay: Infinity });
135
+ stderrReader.on("line", (line) => {
136
+ const trimmed = line.trim();
137
+ if (trimmed.length === 0)
138
+ return;
139
+ this.stderrLines.push(trimmed);
140
+ if (this.stderrLines.length > 20)
141
+ this.stderrLines.shift();
142
+ });
143
+ child.on("error", (error) => {
144
+ this.closed = true;
145
+ this.onClosed();
146
+ this.rejectAllPendingRpc(`Failed to start codex app-server: ${error.message}`);
147
+ for (const turn of [...this.allActiveTurns]) {
148
+ turn.failImmediately(`Failed to start codex app-server: ${error.message}`, "CODEX_SPAWN_FAILED");
149
+ }
150
+ });
151
+ child.on("close", (code) => {
152
+ this.closed = true;
153
+ this.onClosed();
154
+ this.rejectAllPendingRpc(`codex app-server exited (code ${String(code)})`);
155
+ const stderrTail = this.stderrLines.slice(-3).join(" | ");
156
+ for (const turn of [...this.allActiveTurns]) {
157
+ turn.flushAndFinishOnTransportClose(code, stderrTail);
158
+ }
159
+ });
111
160
  }
112
- startTurn(input) {
113
- const launch = buildCodexLaunch(this.codexCommand, input.extraArgs);
114
- const child = spawnManagedProcess(launch.bin, launch.args, {
115
- cwd: input.cwd,
116
- env: buildSanitizedChildEnv(input.environment),
161
+ get isClosed() {
162
+ return this.closed;
163
+ }
164
+ get activeTurnCount() {
165
+ return this.allActiveTurns.size;
166
+ }
167
+ writeJsonLine(payload) {
168
+ if (this.closed ||
169
+ this.child.killed ||
170
+ this.child.stdin.destroyed ||
171
+ !this.child.stdin.writable) {
172
+ return;
173
+ }
174
+ this.child.stdin.write(`${JSON.stringify(payload)}\n`);
175
+ }
176
+ sendRequest(method, params, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
177
+ if (this.closed) {
178
+ return Promise.reject(new Error(`Codex app-server already closed before ${method}`));
179
+ }
180
+ const id = this.nextRpcId;
181
+ this.nextRpcId += 1;
182
+ return new Promise((resolve, reject) => {
183
+ const timer = setTimeout(() => {
184
+ this.pendingRpc.delete(id);
185
+ reject(new Error(`Codex app-server RPC timeout for ${method}`));
186
+ }, timeoutMs);
187
+ timer.unref();
188
+ this.pendingRpc.set(id, { resolve, reject, timer });
189
+ this.writeJsonLine({ jsonrpc: "2.0", id, method, params });
190
+ });
191
+ }
192
+ sendNotification(method, params) {
193
+ this.writeJsonLine({
194
+ jsonrpc: "2.0",
195
+ method,
196
+ ...(params === undefined ? {} : { params }),
197
+ });
198
+ }
199
+ sendResponse(id, result) {
200
+ this.writeJsonLine({ jsonrpc: "2.0", id, result });
201
+ }
202
+ sendErrorResponse(id, code, message) {
203
+ this.writeJsonLine({ jsonrpc: "2.0", id, error: { code, message } });
204
+ }
205
+ ensureInitialized() {
206
+ if (this.initPromise !== null) {
207
+ return this.initPromise;
208
+ }
209
+ this.initPromise = (async () => {
210
+ await this.sendRequest("initialize", {
211
+ clientInfo: {
212
+ name: "specflow-cli",
213
+ title: "SpecFlow CLI Runner",
214
+ version: this.cliVersion,
215
+ },
216
+ capabilities: {
217
+ experimentalApi: true,
218
+ },
219
+ });
220
+ if (this.closed) {
221
+ throw new Error("Codex app-server closed during initialize");
222
+ }
223
+ this.sendNotification("initialized");
224
+ })();
225
+ this.initPromise.catch(() => {
226
+ if (!this.closed) {
227
+ this.initPromise = null;
228
+ }
229
+ });
230
+ return this.initPromise;
231
+ }
232
+ registerTurn(turn) {
233
+ this.allActiveTurns.add(turn);
234
+ }
235
+ bindTurnThread(turn, threadId) {
236
+ turn.threadId = threadId;
237
+ this.turnsByThreadId.set(threadId, turn);
238
+ }
239
+ bindTurnId(turn, turnId) {
240
+ turn.activeTurnId = turnId;
241
+ this.turnsByTurnId.set(turnId, turn);
242
+ }
243
+ unregisterTurn(turn) {
244
+ this.allActiveTurns.delete(turn);
245
+ if (turn.threadId !== undefined && this.turnsByThreadId.get(turn.threadId) === turn) {
246
+ this.turnsByThreadId.delete(turn.threadId);
247
+ }
248
+ if (turn.activeTurnId !== undefined && this.turnsByTurnId.get(turn.activeTurnId) === turn) {
249
+ this.turnsByTurnId.delete(turn.activeTurnId);
250
+ }
251
+ }
252
+ resolveTurn(rawParams) {
253
+ const { threadId, turnId } = extractRoutingIds(rawParams);
254
+ if (threadId !== undefined) {
255
+ const byThread = this.turnsByThreadId.get(threadId);
256
+ if (byThread !== undefined)
257
+ return byThread;
258
+ }
259
+ if (turnId !== undefined) {
260
+ const byTurn = this.turnsByTurnId.get(turnId);
261
+ if (byTurn !== undefined)
262
+ return byTurn;
263
+ }
264
+ if (this.allActiveTurns.size === 1) {
265
+ return this.allActiveTurns.values().next().value;
266
+ }
267
+ return undefined;
268
+ }
269
+ handleStdoutLine(line) {
270
+ const trimmed = line.trim();
271
+ if (trimmed.length === 0)
272
+ return;
273
+ let parsed;
274
+ try {
275
+ parsed = JSON.parse(trimmed);
276
+ }
277
+ catch {
278
+ return;
279
+ }
280
+ if (parsed.method !== undefined && parsed.id !== undefined && parsed.id !== null) {
281
+ const target = this.resolveTurn(parsed.params);
282
+ if (target !== undefined) {
283
+ target.enqueueServerRequest(parsed.id, parsed.method, parsed.params);
284
+ }
285
+ else {
286
+ this.sendErrorResponse(parsed.id, -32601, `No active turn for server request ${parsed.method}`);
287
+ }
288
+ return;
289
+ }
290
+ if (parsed.method !== undefined) {
291
+ const target = this.resolveTurn(parsed.params);
292
+ if (target !== undefined) {
293
+ target.enqueueNotification(parsed.method, parsed.params);
294
+ }
295
+ return;
296
+ }
297
+ const response = parsed;
298
+ if (response.id !== undefined && response.id !== null) {
299
+ const pending = this.pendingRpc.get(response.id);
300
+ if (pending !== undefined) {
301
+ clearTimeout(pending.timer);
302
+ this.pendingRpc.delete(response.id);
303
+ if (response.error !== undefined) {
304
+ pending.reject(new Error(response.error.message ?? `JSON-RPC error ${String(response.error.code ?? -1)}`));
305
+ }
306
+ else {
307
+ pending.resolve(response.result);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ rejectAllPendingRpc(reason) {
313
+ for (const [id, entry] of this.pendingRpc.entries()) {
314
+ clearTimeout(entry.timer);
315
+ entry.reject(new Error(`${reason} (RPC ${String(id)})`));
316
+ }
317
+ this.pendingRpc.clear();
318
+ }
319
+ async terminate(forceAfterGrace) {
320
+ if (this.closed)
321
+ return;
322
+ this.closed = true;
323
+ this.onClosed();
324
+ this.rejectAllPendingRpc("Codex app-server terminated");
325
+ for (const turn of [...this.allActiveTurns]) {
326
+ turn.finishOnce({
327
+ outcome: "interrupted",
328
+ finalMessage: turn.getFinalText(),
329
+ ...(turn.threadId === undefined ? {} : { runnerThreadId: turn.threadId }),
330
+ });
331
+ }
332
+ await terminateProcessTree(this.child, {
333
+ forceAfterGrace,
334
+ graceMs: 4_000,
335
+ closeStdin: true,
117
336
  });
118
- return Promise.resolve(runCodexAppServerSession(child, input, this.cliVersion));
119
337
  }
120
338
  }
121
- function runCodexAppServerSession(child, input, cliVersion) {
122
- let nextRpcId = 1;
123
- const pendingRpc = new Map();
124
- let threadId = input.resumeThreadId;
125
- let activeTurnId;
126
- let stoppedRequested = false;
127
- const isStopRequested = () => stoppedRequested;
128
- let finished = false;
339
+ function createTurnController(transport, input, terminateTransportOnFinish) {
129
340
  let agentMessageText = "";
130
341
  let reasoningBuffer = "";
131
342
  let lastThoughtFlushAt = 0;
@@ -141,55 +352,79 @@ function runCodexAppServerSession(child, input, cliVersion) {
141
352
  const readyPromise = new Promise((resolve) => {
142
353
  resolveReady = resolve;
143
354
  });
144
- const rejectAllPendingRpc = (reason) => {
145
- for (const [id, entry] of pendingRpc.entries()) {
146
- clearTimeout(entry.timer);
147
- entry.reject(new Error(`${reason} (RPC ${String(id)})`));
148
- }
149
- pendingRpc.clear();
150
- };
151
- const finishOnce = (result) => {
152
- if (finished)
153
- return;
154
- finished = true;
155
- resolveReady();
156
- rejectAllPendingRpc("Codex app-server closed before RPC completed");
157
- void terminateProcessTree(child, { forceAfterGrace: false, closeStdin: true });
158
- resolveCompletion(result);
159
- };
160
- const writeJsonLine = (payload) => {
161
- if (child.killed || child.stdin.destroyed || !child.stdin.writable)
162
- return;
163
- child.stdin.write(`${JSON.stringify(payload)}\n`);
164
- };
165
- const sendRequest = (method, params, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) => {
166
- if (finished) {
167
- return Promise.reject(new Error(`Codex app-server already finished before ${method}`));
168
- }
169
- const id = nextRpcId;
170
- nextRpcId += 1;
171
- return new Promise((resolve, reject) => {
172
- const timer = setTimeout(() => {
173
- pendingRpc.delete(id);
174
- reject(new Error(`Codex app-server RPC timeout for ${method}`));
175
- }, timeoutMs);
176
- timer.unref();
177
- pendingRpc.set(id, { resolve, reject, timer });
178
- writeJsonLine({ jsonrpc: "2.0", id, method, params });
179
- });
180
- };
181
- const sendNotification = (method, params) => {
182
- writeJsonLine({
183
- jsonrpc: "2.0",
184
- method,
185
- ...(params === undefined ? {} : { params }),
186
- });
187
- };
188
- const sendResponse = (id, result) => {
189
- writeJsonLine({ jsonrpc: "2.0", id, result });
190
- };
191
- const sendErrorResponse = (id, code, message) => {
192
- writeJsonLine({ jsonrpc: "2.0", id, error: { code, message } });
355
+ const controller = {
356
+ input,
357
+ threadId: input.resumeThreadId,
358
+ activeTurnId: undefined,
359
+ stoppedRequested: false,
360
+ finished: false,
361
+ completion,
362
+ markReady: () => {
363
+ resolveReady();
364
+ },
365
+ waitReadyOrDone: async () => {
366
+ await Promise.race([readyPromise, completion.then(() => undefined)]);
367
+ },
368
+ getFinalText: () => agentMessageText.trim(),
369
+ finishOnce: (result) => {
370
+ if (controller.finished)
371
+ return;
372
+ controller.finished = true;
373
+ resolveReady();
374
+ transport.unregisterTurn(controller);
375
+ if (terminateTransportOnFinish) {
376
+ void transport.terminate(false);
377
+ }
378
+ resolveCompletion(result);
379
+ },
380
+ failImmediately: (errorMessage, errorCode) => {
381
+ controller.finishOnce({
382
+ outcome: "failed",
383
+ finalMessage: agentMessageText.trim(),
384
+ errorMessage,
385
+ errorCode,
386
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
387
+ });
388
+ },
389
+ flushAndFinishOnTransportClose: (code, stderrTail) => {
390
+ if (controller.finished)
391
+ return;
392
+ void notificationChain.finally(() => {
393
+ if (controller.finished)
394
+ return;
395
+ if (controller.stoppedRequested) {
396
+ controller.finishOnce({
397
+ outcome: "interrupted",
398
+ finalMessage: agentMessageText.trim(),
399
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
400
+ });
401
+ return;
402
+ }
403
+ controller.finishOnce({
404
+ outcome: "failed",
405
+ finalMessage: agentMessageText.trim(),
406
+ errorMessage: stderrTail.length > 0
407
+ ? `codex app-server exited unexpectedly (code ${String(code)}): ${stderrTail}`
408
+ : `codex app-server exited unexpectedly (code ${String(code)})`,
409
+ errorCode: "CODEX_PROCESS_EXITED",
410
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
411
+ });
412
+ });
413
+ },
414
+ enqueueNotification: (method, rawParams) => {
415
+ notificationChain = notificationChain
416
+ .then(() => handleNotification(method, rawParams))
417
+ .catch((error) => {
418
+ input.callbacks.onDiagnostic(`Codex notification handler error (${method}): ${error instanceof Error ? error.message : String(error)}`);
419
+ });
420
+ },
421
+ enqueueServerRequest: (id, method, rawParams) => {
422
+ serverRequestChain = serverRequestChain
423
+ .then(() => handleServerRequest(id, method, rawParams))
424
+ .catch((error) => {
425
+ transport.sendErrorResponse(id, -32603, error instanceof Error ? error.message : String(error));
426
+ });
427
+ },
193
428
  };
194
429
  const flushReasoning = async (force) => {
195
430
  const trimmed = reasoningBuffer.trim();
@@ -210,7 +445,7 @@ function runCodexAppServerSession(child, input, cliVersion) {
210
445
  const params = asRecord(rawParams) ?? {};
211
446
  if (method === "item/commandExecution/requestApproval" || method === "execCommandApproval") {
212
447
  if (autoApproveForSession) {
213
- sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
448
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
214
449
  return;
215
450
  }
216
451
  const command = asString(params.command) ?? "Shell command";
@@ -228,22 +463,22 @@ function runCodexAppServerSession(child, input, cliVersion) {
228
463
  allowFreeText: false,
229
464
  });
230
465
  if (answer.cancelled) {
231
- sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
466
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
232
467
  return;
233
468
  }
234
469
  if (answer.selectedOptionId === "acceptForSession") {
235
470
  autoApproveForSession = true;
236
- sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
471
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
237
472
  return;
238
473
  }
239
- sendResponse(id, {
474
+ transport.sendResponse(id, {
240
475
  decision: mapApprovalDecision(method, answer.selectedOptionId === "accept" ? "accept" : "decline"),
241
476
  });
242
477
  return;
243
478
  }
244
479
  if (method === "item/fileChange/requestApproval" || method === "applyPatchApproval") {
245
480
  if (autoApproveForSession) {
246
- sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
481
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
247
482
  return;
248
483
  }
249
484
  const reason = asString(params.reason) ?? "修改工作区文件";
@@ -257,15 +492,15 @@ function runCodexAppServerSession(child, input, cliVersion) {
257
492
  allowFreeText: false,
258
493
  });
259
494
  if (answer.cancelled) {
260
- sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
495
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
261
496
  return;
262
497
  }
263
498
  if (answer.selectedOptionId === "acceptForSession") {
264
499
  autoApproveForSession = true;
265
- sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
500
+ transport.sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
266
501
  return;
267
502
  }
268
- sendResponse(id, {
503
+ transport.sendResponse(id, {
269
504
  decision: mapApprovalDecision(method, answer.selectedOptionId === "accept" ? "accept" : "decline"),
270
505
  });
271
506
  return;
@@ -309,7 +544,7 @@ function runCodexAppServerSession(child, input, cliVersion) {
309
544
  answers[questionId] = { answers: [resolvedValue] };
310
545
  }
311
546
  }
312
- sendResponse(id, { answers });
547
+ transport.sendResponse(id, { answers });
313
548
  return;
314
549
  }
315
550
  if (method === "mcpServer/elicitation/request") {
@@ -319,11 +554,11 @@ function runCodexAppServerSession(child, input, cliVersion) {
319
554
  const rawUrl = asString(params.url);
320
555
  if (rawUrl !== undefined && !isGitHubAuthUrl(rawUrl)) {
321
556
  input.callbacks.onDiagnostic("Codex MCP URL elicitation rejected for unsupported non-github.com host");
322
- sendResponse(id, { action: "cancel", content: null, _meta: null });
557
+ transport.sendResponse(id, { action: "cancel", content: null, _meta: null });
323
558
  return;
324
559
  }
325
560
  const completed = await input.callbacks.onAuthRequired(message, "github");
326
- sendResponse(id, {
561
+ transport.sendResponse(id, {
327
562
  action: completed ? "accept" : "cancel",
328
563
  content: null,
329
564
  _meta: null,
@@ -339,21 +574,21 @@ function runCodexAppServerSession(child, input, cliVersion) {
339
574
  allowFreeText: true,
340
575
  });
341
576
  if (answer.cancelled) {
342
- sendResponse(id, { action: "cancel", content: null, _meta: null });
577
+ transport.sendResponse(id, { action: "cancel", content: null, _meta: null });
343
578
  return;
344
579
  }
345
580
  if (answer.selectedOptionId === "decline") {
346
- sendResponse(id, { action: "decline", content: null, _meta: null });
581
+ transport.sendResponse(id, { action: "decline", content: null, _meta: null });
347
582
  return;
348
583
  }
349
- sendResponse(id, {
584
+ transport.sendResponse(id, {
350
585
  action: "accept",
351
586
  content: answer.freeText ? { text: answer.freeText } : {},
352
587
  _meta: null,
353
588
  });
354
589
  return;
355
590
  }
356
- sendErrorResponse(id, -32601, `Unsupported server request method: ${method}`);
591
+ transport.sendErrorResponse(id, -32601, `Unsupported server request method: ${method}`);
357
592
  };
358
593
  const handleNotification = async (method, rawParams) => {
359
594
  input.callbacks.onActivity();
@@ -505,258 +740,209 @@ function runCodexAppServerSession(child, input, cliVersion) {
505
740
  const status = asString(turn?.status) ?? "completed";
506
741
  const turnError = asRecord(turn?.error);
507
742
  const errorMessage = asString(turnError?.message);
508
- if (status === "interrupted" || isStopRequested()) {
509
- finishOnce({
743
+ if (status === "interrupted" || controller.stoppedRequested) {
744
+ controller.finishOnce({
510
745
  outcome: "interrupted",
511
746
  finalMessage: agentMessageText.trim(),
512
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
747
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
513
748
  });
514
749
  return;
515
750
  }
516
751
  if (status === "failed") {
517
- finishOnce({
752
+ controller.finishOnce({
518
753
  outcome: "failed",
519
754
  finalMessage: agentMessageText.trim(),
520
755
  errorMessage: errorMessage ?? "Codex turn failed",
521
756
  errorCode: "CODEX_TURN_FAILED",
522
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
757
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
523
758
  });
524
759
  return;
525
760
  }
526
761
  const finalText = agentMessageText.trim();
527
762
  const firstLine = finalText.split("\n")[0]?.trim() ?? "";
528
763
  const prUrl = extractPullRequestUrl(finalText);
529
- finishOnce({
764
+ controller.finishOnce({
530
765
  outcome: "completed",
531
766
  finalMessage: finalText,
532
767
  summary: firstLine.length > 0 ? firstLine : `Completed ${input.workItemKey}`,
533
768
  ...(prUrl === undefined ? {} : { pullRequestUrl: prUrl }),
534
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
769
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
535
770
  });
536
771
  }
537
772
  };
538
- const stdoutReader = createInterface({ input: child.stdout, crlfDelay: Infinity });
539
- stdoutReader.on("line", (line) => {
540
- const trimmed = line.trim();
541
- if (trimmed.length === 0)
542
- return;
543
- let parsed;
544
- try {
545
- parsed = JSON.parse(trimmed);
546
- }
547
- catch {
548
- return;
549
- }
550
- if (parsed.method !== undefined && parsed.id !== undefined && parsed.id !== null) {
551
- const requestId = parsed.id;
552
- const method = parsed.method;
553
- const reqParams = parsed.params;
554
- serverRequestChain = serverRequestChain
555
- .then(() => handleServerRequest(requestId, method, reqParams))
556
- .catch((error) => {
557
- sendErrorResponse(requestId, -32603, error instanceof Error ? error.message : String(error));
558
- });
559
- return;
560
- }
561
- if (parsed.method !== undefined) {
562
- const method = parsed.method;
563
- notificationChain = notificationChain
564
- .then(() => handleNotification(method, parsed.params))
565
- .catch((error) => {
566
- input.callbacks.onDiagnostic(`Codex notification handler error (${method}): ${error instanceof Error ? error.message : String(error)}`);
567
- });
568
- return;
569
- }
570
- const response = parsed;
571
- if (response.id !== undefined && response.id !== null) {
572
- const pending = pendingRpc.get(response.id);
573
- if (pending !== undefined) {
574
- clearTimeout(pending.timer);
575
- pendingRpc.delete(response.id);
576
- if (response.error !== undefined) {
577
- pending.reject(new Error(response.error.message ?? `JSON-RPC error ${String(response.error.code ?? -1)}`));
578
- }
579
- else {
580
- pending.resolve(response.result);
581
- }
773
+ return controller;
774
+ }
775
+ function executeTurnOnTransport(transport, input, persistent) {
776
+ const controller = createTurnController(transport, input, !persistent);
777
+ transport.registerTurn(controller);
778
+ const openOrResumeThread = async (approvalPolicy, preferResume) => {
779
+ let threadResult;
780
+ if (preferResume && input.resumeThreadId !== undefined) {
781
+ try {
782
+ threadResult = await transport.sendRequest("thread/resume", {
783
+ threadId: input.resumeThreadId,
784
+ cwd: input.cwd,
785
+ approvalPolicy,
786
+ sandbox: input.sandbox,
787
+ ...(input.model === undefined ? {} : { model: input.model }),
788
+ excludeTurns: true,
789
+ });
582
790
  }
583
- }
584
- });
585
- const stderrLines = [];
586
- const stderrReader = createInterface({ input: child.stderr, crlfDelay: Infinity });
587
- stderrReader.on("line", (line) => {
588
- const trimmed = line.trim();
589
- if (trimmed.length === 0)
590
- return;
591
- stderrLines.push(trimmed);
592
- if (stderrLines.length > 20)
593
- stderrLines.shift();
594
- });
595
- child.on("error", (error) => {
596
- finishOnce({
597
- outcome: "failed",
598
- finalMessage: agentMessageText.trim(),
599
- errorMessage: `Failed to start codex app-server: ${error.message}`,
600
- errorCode: "CODEX_SPAWN_FAILED",
601
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
602
- });
603
- });
604
- child.on("close", (code) => {
605
- if (finished)
606
- return;
607
- void notificationChain.finally(() => {
608
- if (finished)
609
- return;
610
- if (isStopRequested()) {
611
- finishOnce({
612
- outcome: "interrupted",
613
- finalMessage: agentMessageText.trim(),
614
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
791
+ catch {
792
+ if (controller.stoppedRequested) {
793
+ throw new Error("STOPPED");
794
+ }
795
+ // If prior rollout is unavailable on disk, start a fresh thread cleanly.
796
+ threadResult = await transport.sendRequest("thread/start", {
797
+ cwd: input.cwd,
798
+ approvalPolicy,
799
+ sandbox: input.sandbox,
800
+ ...(input.model === undefined ? {} : { model: input.model }),
615
801
  });
616
- return;
617
802
  }
618
- const stderrTail = stderrLines.slice(-3).join(" | ");
619
- finishOnce({
620
- outcome: "failed",
621
- finalMessage: agentMessageText.trim(),
622
- errorMessage: stderrTail.length > 0
623
- ? `codex app-server exited unexpectedly (code ${String(code)}): ${stderrTail}`
624
- : `codex app-server exited unexpectedly (code ${String(code)})`,
625
- errorCode: "CODEX_PROCESS_EXITED",
626
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
803
+ }
804
+ else {
805
+ threadResult = await transport.sendRequest("thread/start", {
806
+ cwd: input.cwd,
807
+ approvalPolicy,
808
+ sandbox: input.sandbox,
809
+ ...(input.model === undefined ? {} : { model: input.model }),
627
810
  });
628
- });
811
+ }
812
+ const threadObj = asRecord(asRecord(threadResult)?.thread);
813
+ const resolvedThreadId = asString(threadObj?.id);
814
+ if (resolvedThreadId === undefined) {
815
+ throw new Error("codex app-server did not return a thread id");
816
+ }
817
+ transport.loadedThreads.add(resolvedThreadId);
818
+ return resolvedThreadId;
819
+ };
820
+ const startTurnRpc = (resolvedThreadId, approvalPolicy) => transport.sendRequest("turn/start", {
821
+ threadId: resolvedThreadId,
822
+ cwd: input.cwd,
823
+ approvalPolicy,
824
+ sandboxPolicy: mapCodexSandboxPolicy(input.sandbox),
825
+ ...(input.model === undefined ? {} : { model: input.model }),
826
+ input: [{ type: "text", text: input.prompt, text_elements: [] }],
629
827
  });
630
- // Run handshake asynchronously so startTurn returns an immediately interruptible handle.
828
+ // Run handshake + turn/start asynchronously so startTurn returns an immediately interruptible handle.
829
+ const isStopRequested = () => controller.stoppedRequested;
631
830
  void (async () => {
632
831
  try {
633
- await sendRequest("initialize", {
634
- clientInfo: {
635
- name: "specflow-cli",
636
- title: "SpecFlow CLI Runner",
637
- version: cliVersion,
638
- },
639
- capabilities: {
640
- experimentalApi: true,
641
- },
642
- });
832
+ await transport.ensureInitialized();
643
833
  if (isStopRequested()) {
644
- finishOnce({
834
+ controller.finishOnce({
645
835
  outcome: "interrupted",
646
- finalMessage: agentMessageText.trim(),
647
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
836
+ finalMessage: controller.getFinalText(),
837
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
648
838
  });
649
839
  return;
650
840
  }
651
- sendNotification("initialized");
652
841
  const approvalPolicy = mapApprovalPolicy(input.approval);
653
- let threadResult;
654
- if (input.resumeThreadId !== undefined) {
842
+ let resolvedThreadId;
843
+ let turnResult;
844
+ if (persistent &&
845
+ input.resumeThreadId !== undefined &&
846
+ transport.loadedThreads.has(input.resumeThreadId)) {
847
+ resolvedThreadId = input.resumeThreadId;
848
+ transport.bindTurnThread(controller, resolvedThreadId);
849
+ input.callbacks.onThreadId(resolvedThreadId);
655
850
  try {
656
- threadResult = await sendRequest("thread/resume", {
657
- threadId: input.resumeThreadId,
658
- cwd: input.cwd,
659
- approvalPolicy,
660
- sandbox: input.sandbox,
661
- ...(input.model === undefined ? {} : { model: input.model }),
662
- excludeTurns: true,
663
- });
851
+ turnResult = await startTurnRpc(resolvedThreadId, approvalPolicy);
664
852
  }
665
853
  catch {
666
854
  if (isStopRequested()) {
667
- finishOnce({
855
+ controller.finishOnce({
668
856
  outcome: "interrupted",
669
- finalMessage: agentMessageText.trim(),
670
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
857
+ finalMessage: controller.getFinalText(),
858
+ runnerThreadId: resolvedThreadId,
671
859
  });
672
860
  return;
673
861
  }
674
- // If prior rollout is unavailable on disk, start a fresh thread cleanly.
675
- threadResult = await sendRequest("thread/start", {
676
- cwd: input.cwd,
677
- approvalPolicy,
678
- sandbox: input.sandbox,
679
- ...(input.model === undefined ? {} : { model: input.model }),
680
- });
862
+ // Thread may have been evicted from server memory; fall back to thread/resume -> thread/start.
863
+ transport.loadedThreads.delete(resolvedThreadId);
864
+ resolvedThreadId = await openOrResumeThread(approvalPolicy, true);
865
+ transport.bindTurnThread(controller, resolvedThreadId);
866
+ input.callbacks.onThreadId(resolvedThreadId);
867
+ if (isStopRequested()) {
868
+ controller.finishOnce({
869
+ outcome: "interrupted",
870
+ finalMessage: controller.getFinalText(),
871
+ runnerThreadId: resolvedThreadId,
872
+ });
873
+ return;
874
+ }
875
+ turnResult = await startTurnRpc(resolvedThreadId, approvalPolicy);
681
876
  }
682
877
  }
683
878
  else {
684
- threadResult = await sendRequest("thread/start", {
685
- cwd: input.cwd,
686
- approvalPolicy,
687
- sandbox: input.sandbox,
688
- ...(input.model === undefined ? {} : { model: input.model }),
689
- });
690
- }
691
- const threadObj = asRecord(asRecord(threadResult)?.thread);
692
- const resolvedThreadId = asString(threadObj?.id);
693
- if (resolvedThreadId === undefined) {
694
- throw new Error("codex app-server did not return a thread id");
695
- }
696
- threadId = resolvedThreadId;
697
- input.callbacks.onThreadId(resolvedThreadId);
698
- if (isStopRequested()) {
699
- finishOnce({
700
- outcome: "interrupted",
701
- finalMessage: agentMessageText.trim(),
702
- runnerThreadId: resolvedThreadId,
703
- });
704
- return;
879
+ resolvedThreadId = await openOrResumeThread(approvalPolicy, input.resumeThreadId !== undefined);
880
+ transport.bindTurnThread(controller, resolvedThreadId);
881
+ input.callbacks.onThreadId(resolvedThreadId);
882
+ if (isStopRequested()) {
883
+ controller.finishOnce({
884
+ outcome: "interrupted",
885
+ finalMessage: controller.getFinalText(),
886
+ runnerThreadId: resolvedThreadId,
887
+ });
888
+ return;
889
+ }
890
+ turnResult = await startTurnRpc(resolvedThreadId, approvalPolicy);
705
891
  }
706
- const turnResult = await sendRequest("turn/start", {
707
- threadId: resolvedThreadId,
708
- cwd: input.cwd,
709
- approvalPolicy,
710
- sandboxPolicy: mapCodexSandboxPolicy(input.sandbox),
711
- ...(input.model === undefined ? {} : { model: input.model }),
712
- input: [{ type: "text", text: input.prompt, text_elements: [] }],
713
- });
714
892
  const turnObj = asRecord(asRecord(turnResult)?.turn);
715
- activeTurnId = asString(turnObj?.id);
716
- resolveReady();
893
+ const turnId = asString(turnObj?.id);
894
+ if (turnId !== undefined) {
895
+ transport.bindTurnId(controller, turnId);
896
+ }
897
+ controller.markReady();
717
898
  if (isStopRequested()) {
718
- if (activeTurnId !== undefined) {
719
- await sendRequest("turn/interrupt", { threadId: resolvedThreadId, turnId: activeTurnId }, 5_000).catch(() => undefined);
899
+ if (controller.activeTurnId !== undefined) {
900
+ await transport
901
+ .sendRequest("turn/interrupt", { threadId: resolvedThreadId, turnId: controller.activeTurnId }, 5_000)
902
+ .catch(() => undefined);
720
903
  }
721
904
  else {
722
- finishOnce({
905
+ controller.finishOnce({
723
906
  outcome: "interrupted",
724
- finalMessage: agentMessageText.trim(),
907
+ finalMessage: controller.getFinalText(),
725
908
  runnerThreadId: resolvedThreadId,
726
909
  });
727
910
  }
728
911
  }
729
912
  }
730
913
  catch (error) {
731
- resolveReady();
914
+ controller.markReady();
732
915
  if (isStopRequested()) {
733
- finishOnce({
916
+ controller.finishOnce({
734
917
  outcome: "interrupted",
735
- finalMessage: agentMessageText.trim(),
736
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
918
+ finalMessage: controller.getFinalText(),
919
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
737
920
  });
738
921
  return;
739
922
  }
740
- finishOnce({
923
+ controller.finishOnce({
741
924
  outcome: "failed",
742
925
  finalMessage: "",
743
926
  errorMessage: error instanceof Error ? error.message : String(error),
744
927
  errorCode: "CODEX_INIT_FAILED",
745
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
928
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
746
929
  });
747
930
  }
748
931
  })();
749
932
  return {
750
- completion,
933
+ completion: controller.completion,
751
934
  steer: async (message) => {
752
- await Promise.race([readyPromise, completion.then(() => undefined)]);
753
- if (finished || isStopRequested() || threadId === undefined || activeTurnId === undefined) {
935
+ await controller.waitReadyOrDone();
936
+ if (controller.finished ||
937
+ controller.stoppedRequested ||
938
+ controller.threadId === undefined ||
939
+ controller.activeTurnId === undefined) {
754
940
  return false;
755
941
  }
756
942
  try {
757
- await sendRequest("turn/steer", {
758
- threadId,
759
- expectedTurnId: activeTurnId,
943
+ await transport.sendRequest("turn/steer", {
944
+ threadId: controller.threadId,
945
+ expectedTurnId: controller.activeTurnId,
760
946
  input: [{ type: "text", text: message, text_elements: [] }],
761
947
  });
762
948
  return true;
@@ -767,55 +953,118 @@ function runCodexAppServerSession(child, input, cliVersion) {
767
953
  }
768
954
  },
769
955
  stop: async () => {
770
- stoppedRequested = true;
771
- if (finished)
956
+ controller.stoppedRequested = true;
957
+ if (controller.finished)
772
958
  return;
773
- if (threadId !== undefined && activeTurnId !== undefined) {
774
- await sendRequest("turn/interrupt", { threadId, turnId: activeTurnId }, 5_000).catch(() => undefined);
959
+ const stopThreadId = controller.threadId;
960
+ if (stopThreadId !== undefined && controller.activeTurnId !== undefined) {
961
+ await transport
962
+ .sendRequest("turn/interrupt", { threadId: stopThreadId, turnId: controller.activeTurnId }, 5_000)
963
+ .catch(() => undefined);
775
964
  }
776
965
  else {
777
- // Interrupt in-flight handshake RPCs immediately if turn has not started yet.
778
- rejectAllPendingRpc("Codex app-server stopped during handshake");
779
- await terminateProcessTree(child, {
780
- forceAfterGrace: true,
781
- graceMs: 4_000,
782
- closeStdin: true,
783
- });
784
- finishOnce({
966
+ if (!persistent || transport.activeTurnCount <= 1) {
967
+ await transport.terminate(true);
968
+ }
969
+ controller.finishOnce({
785
970
  outcome: "interrupted",
786
- finalMessage: agentMessageText.trim(),
787
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
971
+ finalMessage: controller.getFinalText(),
972
+ ...(stopThreadId === undefined ? {} : { runnerThreadId: stopThreadId }),
788
973
  });
789
974
  return;
790
975
  }
791
- const settled = await raceWithTimeout(completion.then(() => true), 8_000, false);
976
+ const settled = await raceWithTimeout(controller.completion.then(() => true), 8_000, false);
792
977
  if (!settled) {
793
- await terminateProcessTree(child, {
794
- forceAfterGrace: true,
795
- graceMs: 4_000,
796
- closeStdin: true,
797
- });
798
- finishOnce({
978
+ if (!persistent || transport.activeTurnCount <= 1) {
979
+ await transport.terminate(true);
980
+ }
981
+ controller.finishOnce({
799
982
  outcome: "interrupted",
800
- finalMessage: agentMessageText.trim(),
801
- runnerThreadId: threadId,
983
+ finalMessage: controller.getFinalText(),
984
+ runnerThreadId: stopThreadId,
802
985
  });
803
986
  }
804
987
  },
805
988
  kill: async () => {
806
- stoppedRequested = true;
807
- rejectAllPendingRpc("Codex app-server killed");
808
- await terminateProcessTree(child, {
809
- forceAfterGrace: true,
810
- graceMs: 4_000,
811
- closeStdin: true,
812
- });
813
- finishOnce({
989
+ controller.stoppedRequested = true;
990
+ if (controller.finished)
991
+ return;
992
+ if (persistent && transport.activeTurnCount > 1) {
993
+ if (controller.threadId !== undefined && controller.activeTurnId !== undefined) {
994
+ await transport
995
+ .sendRequest("turn/interrupt", { threadId: controller.threadId, turnId: controller.activeTurnId }, 2_000)
996
+ .catch(() => undefined);
997
+ }
998
+ controller.finishOnce({
999
+ outcome: "interrupted",
1000
+ finalMessage: controller.getFinalText(),
1001
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
1002
+ });
1003
+ return;
1004
+ }
1005
+ await transport.terminate(true);
1006
+ controller.finishOnce({
814
1007
  outcome: "interrupted",
815
- finalMessage: agentMessageText.trim(),
816
- ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
1008
+ finalMessage: controller.getFinalText(),
1009
+ ...(controller.threadId === undefined ? {} : { runnerThreadId: controller.threadId }),
817
1010
  });
818
1011
  },
819
1012
  };
820
1013
  }
1014
+ export class CodexAppServerAdapter {
1015
+ kind = "codex";
1016
+ codexCommand;
1017
+ cliVersion;
1018
+ persistent;
1019
+ sharedTransport = null;
1020
+ sharedLaunchKey = null;
1021
+ constructor(codexCommand = "codex", cliVersion = "1.4.0", options = {}) {
1022
+ this.codexCommand = codexCommand;
1023
+ this.cliVersion = cliVersion;
1024
+ this.persistent = options.persistent === true;
1025
+ }
1026
+ getOrCreateTransport(input) {
1027
+ const launch = buildCodexLaunch(this.codexCommand, input.extraArgs);
1028
+ const launchKey = JSON.stringify({ bin: launch.bin, args: launch.args });
1029
+ if (this.persistent &&
1030
+ this.sharedTransport !== null &&
1031
+ !this.sharedTransport.isClosed &&
1032
+ this.sharedLaunchKey === launchKey) {
1033
+ return this.sharedTransport;
1034
+ }
1035
+ if (this.persistent && this.sharedTransport !== null && !this.sharedTransport.isClosed) {
1036
+ const previous = this.sharedTransport;
1037
+ this.sharedTransport = null;
1038
+ this.sharedLaunchKey = null;
1039
+ void previous.terminate(false);
1040
+ }
1041
+ const child = spawnManagedProcess(launch.bin, launch.args, {
1042
+ cwd: input.cwd,
1043
+ env: buildSanitizedChildEnv(input.environment),
1044
+ });
1045
+ const transport = new CodexAppServerTransport(child, this.cliVersion, () => {
1046
+ if (this.sharedTransport === transport) {
1047
+ this.sharedTransport = null;
1048
+ this.sharedLaunchKey = null;
1049
+ }
1050
+ });
1051
+ if (this.persistent) {
1052
+ this.sharedTransport = transport;
1053
+ this.sharedLaunchKey = launchKey;
1054
+ }
1055
+ return transport;
1056
+ }
1057
+ startTurn(input) {
1058
+ const transport = this.getOrCreateTransport(input);
1059
+ return Promise.resolve(executeTurnOnTransport(transport, input, this.persistent));
1060
+ }
1061
+ async dispose() {
1062
+ const transport = this.sharedTransport;
1063
+ this.sharedTransport = null;
1064
+ this.sharedLaunchKey = null;
1065
+ if (transport !== null) {
1066
+ await transport.terminate(true);
1067
+ }
1068
+ }
1069
+ }
821
1070
  //# sourceMappingURL=codex-app-server.js.map