@gonovus-ai/spec-flow-cli 1.2.1 → 1.3.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 (55) hide show
  1. package/README.md +20 -2
  2. package/dist/agent-commands.d.ts +30 -0
  3. package/dist/agent-commands.js +14 -17
  4. package/dist/agent-commands.js.map +1 -1
  5. package/dist/cli.d.ts +3 -0
  6. package/dist/cli.js.map +1 -1
  7. package/dist/credential-store.js +9 -8
  8. package/dist/credential-store.js.map +1 -1
  9. package/dist/index.js +16 -13
  10. package/dist/index.js.map +1 -1
  11. package/dist/input/text-source.js +5 -4
  12. package/dist/input/text-source.js.map +1 -1
  13. package/dist/runner/adapters/acp-adapter.d.ts +14 -0
  14. package/dist/runner/adapters/acp-adapter.js +593 -0
  15. package/dist/runner/adapters/acp-adapter.js.map +1 -0
  16. package/dist/runner/adapters/claude-stream.d.ts +7 -0
  17. package/dist/runner/adapters/claude-stream.js +324 -0
  18. package/dist/runner/adapters/claude-stream.js.map +1 -0
  19. package/dist/runner/adapters/codex-app-server.d.ts +8 -0
  20. package/dist/runner/adapters/codex-app-server.js +821 -0
  21. package/dist/runner/adapters/codex-app-server.js.map +1 -0
  22. package/dist/runner/adapters/exec-adapter.d.ts +13 -0
  23. package/dist/runner/adapters/exec-adapter.js +212 -0
  24. package/dist/runner/adapters/exec-adapter.js.map +1 -0
  25. package/dist/runner/orchestrator.d.ts +65 -0
  26. package/dist/runner/orchestrator.js +1166 -0
  27. package/dist/runner/orchestrator.js.map +1 -0
  28. package/dist/runner/process-utils.d.ts +22 -0
  29. package/dist/runner/process-utils.js +105 -0
  30. package/dist/runner/process-utils.js.map +1 -0
  31. package/dist/runner/redact.d.ts +26 -0
  32. package/dist/runner/redact.js +119 -0
  33. package/dist/runner/redact.js.map +1 -0
  34. package/dist/runner/run-command.d.ts +3 -0
  35. package/dist/runner/run-command.js +508 -0
  36. package/dist/runner/run-command.js.map +1 -0
  37. package/dist/runner/state-store.d.ts +18 -0
  38. package/dist/runner/state-store.js +156 -0
  39. package/dist/runner/state-store.js.map +1 -0
  40. package/dist/runner/telemetry-bridge.d.ts +44 -0
  41. package/dist/runner/telemetry-bridge.js +357 -0
  42. package/dist/runner/telemetry-bridge.js.map +1 -0
  43. package/dist/runner/types.d.ts +182 -0
  44. package/dist/runner/types.js +2 -0
  45. package/dist/runner/types.js.map +1 -0
  46. package/dist/runner/workflow.d.ts +4 -0
  47. package/dist/runner/workflow.js +272 -0
  48. package/dist/runner/workflow.js.map +1 -0
  49. package/dist/runner/workspace-manager.d.ts +29 -0
  50. package/dist/runner/workspace-manager.js +196 -0
  51. package/dist/runner/workspace-manager.js.map +1 -0
  52. package/dist/work-item-exchange-file.js +1 -1
  53. package/guides/agent-sessions.md +47 -2
  54. package/guides/boards.md +25 -6
  55. package/package.json +2 -1
@@ -0,0 +1,821 @@
1
+ import { createInterface } from "node:readline";
2
+ import { raceWithTimeout, spawnManagedProcess, terminateProcessTree } from "../process-utils.js";
3
+ import { buildSanitizedChildEnv, extractPullRequestUrl, summarizeOutput } from "../redact.js";
4
+ const DEFAULT_RPC_TIMEOUT_MS = 30_000;
5
+ const THOUGHT_FLUSH_INTERVAL_MS = 1_500;
6
+ const THOUGHT_FLUSH_MIN_CHARS = 180;
7
+ function asRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value)
9
+ ? value
10
+ : undefined;
11
+ }
12
+ function asString(value) {
13
+ return typeof value === "string" ? value : undefined;
14
+ }
15
+ function isGitHubAuthUrl(rawUrl) {
16
+ if (rawUrl === undefined)
17
+ return false;
18
+ try {
19
+ const parsed = new URL(rawUrl);
20
+ if (parsed.protocol !== "https:")
21
+ return false;
22
+ const host = parsed.hostname.toLowerCase();
23
+ return host === "github.com" || host === "www.github.com";
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ function mapApprovalPolicy(approval) {
30
+ if (approval === "never" || approval === "auto") {
31
+ return "never";
32
+ }
33
+ return "on-request";
34
+ }
35
+ function mapApprovalDecision(method, decision) {
36
+ const isLegacyV1 = method === "execCommandApproval" || method === "applyPatchApproval";
37
+ if (!isLegacyV1)
38
+ return decision;
39
+ switch (decision) {
40
+ case "accept":
41
+ return "approved";
42
+ case "acceptForSession":
43
+ return "approved_for_session";
44
+ case "decline":
45
+ return "denied";
46
+ case "cancel":
47
+ return "abort";
48
+ }
49
+ }
50
+ function mapPlanStepStatus(status) {
51
+ if (status === "completed")
52
+ return "completed";
53
+ if (status === "inProgress" || status === "in_progress")
54
+ return "in_progress";
55
+ return "pending";
56
+ }
57
+ function splitCommandArgs(command) {
58
+ const parts = [];
59
+ let current = "";
60
+ let quote = null;
61
+ for (const ch of command) {
62
+ if (quote !== null) {
63
+ if (ch === quote) {
64
+ quote = null;
65
+ }
66
+ else {
67
+ current += ch;
68
+ }
69
+ continue;
70
+ }
71
+ if (ch === '"' || ch === "'") {
72
+ quote = ch;
73
+ continue;
74
+ }
75
+ if (/\s/u.test(ch)) {
76
+ if (current.length > 0) {
77
+ parts.push(current);
78
+ current = "";
79
+ }
80
+ continue;
81
+ }
82
+ current += ch;
83
+ }
84
+ if (current.length > 0)
85
+ parts.push(current);
86
+ const [bin = "codex", ...args] = parts;
87
+ return { bin, args };
88
+ }
89
+ function buildCodexLaunch(commandString, extraArgs) {
90
+ const parsed = splitCommandArgs(commandString);
91
+ const hasAppServer = parsed.args.includes("app-server");
92
+ const args = hasAppServer
93
+ ? [...parsed.args, ...extraArgs]
94
+ : [...parsed.args, "app-server", "--stdio", ...extraArgs];
95
+ return { bin: parsed.bin, args };
96
+ }
97
+ function mapCodexSandboxPolicy(sandbox) {
98
+ if (sandbox === "read-only")
99
+ return { type: "readOnly" };
100
+ if (sandbox === "danger-full-access")
101
+ return { type: "dangerFullAccess" };
102
+ return { type: "workspaceWrite" };
103
+ }
104
+ export class CodexAppServerAdapter {
105
+ kind = "codex";
106
+ codexCommand;
107
+ cliVersion;
108
+ constructor(codexCommand = "codex", cliVersion = "1.3.0") {
109
+ this.codexCommand = codexCommand;
110
+ this.cliVersion = cliVersion;
111
+ }
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),
117
+ });
118
+ return Promise.resolve(runCodexAppServerSession(child, input, this.cliVersion));
119
+ }
120
+ }
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;
129
+ let agentMessageText = "";
130
+ let reasoningBuffer = "";
131
+ let lastThoughtFlushAt = 0;
132
+ let autoApproveForSession = input.approval === "auto" || input.approval === "never";
133
+ const itemStartTimes = new Map();
134
+ let notificationChain = Promise.resolve();
135
+ let serverRequestChain = Promise.resolve();
136
+ let resolveCompletion;
137
+ const completion = new Promise((resolve) => {
138
+ resolveCompletion = resolve;
139
+ });
140
+ let resolveReady;
141
+ const readyPromise = new Promise((resolve) => {
142
+ resolveReady = resolve;
143
+ });
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 } });
193
+ };
194
+ const flushReasoning = async (force) => {
195
+ const trimmed = reasoningBuffer.trim();
196
+ if (trimmed.length === 0)
197
+ return;
198
+ const now = Date.now();
199
+ if (!force &&
200
+ trimmed.length < THOUGHT_FLUSH_MIN_CHARS &&
201
+ now - lastThoughtFlushAt < THOUGHT_FLUSH_INTERVAL_MS) {
202
+ return;
203
+ }
204
+ reasoningBuffer = "";
205
+ lastThoughtFlushAt = now;
206
+ await input.callbacks.onThought(trimmed);
207
+ };
208
+ const handleServerRequest = async (id, method, rawParams) => {
209
+ input.callbacks.onActivity();
210
+ const params = asRecord(rawParams) ?? {};
211
+ if (method === "item/commandExecution/requestApproval" || method === "execCommandApproval") {
212
+ if (autoApproveForSession) {
213
+ sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
214
+ return;
215
+ }
216
+ const command = asString(params.command) ?? "Shell command";
217
+ const reason = asString(params.reason);
218
+ const promptText = reason
219
+ ? `Codex 请求执行命令:${command}\n原因:${reason}`
220
+ : `Codex 请求执行命令:${command}`;
221
+ const answer = await input.callbacks.onAsk({
222
+ prompt: promptText,
223
+ options: [
224
+ { id: "accept", label: "允许本次执行" },
225
+ { id: "acceptForSession", label: "本会话自动允许后续命令" },
226
+ { id: "decline", label: "拒绝执行" },
227
+ ],
228
+ allowFreeText: false,
229
+ });
230
+ if (answer.cancelled) {
231
+ sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
232
+ return;
233
+ }
234
+ if (answer.selectedOptionId === "acceptForSession") {
235
+ autoApproveForSession = true;
236
+ sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
237
+ return;
238
+ }
239
+ sendResponse(id, {
240
+ decision: mapApprovalDecision(method, answer.selectedOptionId === "accept" ? "accept" : "decline"),
241
+ });
242
+ return;
243
+ }
244
+ if (method === "item/fileChange/requestApproval" || method === "applyPatchApproval") {
245
+ if (autoApproveForSession) {
246
+ sendResponse(id, { decision: mapApprovalDecision(method, "accept") });
247
+ return;
248
+ }
249
+ const reason = asString(params.reason) ?? "修改工作区文件";
250
+ const answer = await input.callbacks.onAsk({
251
+ prompt: `Codex 请求修改文件:${reason}`,
252
+ options: [
253
+ { id: "accept", label: "允许修改" },
254
+ { id: "acceptForSession", label: "本会话自动允许文件修改" },
255
+ { id: "decline", label: "拒绝修改" },
256
+ ],
257
+ allowFreeText: false,
258
+ });
259
+ if (answer.cancelled) {
260
+ sendResponse(id, { decision: mapApprovalDecision(method, "cancel") });
261
+ return;
262
+ }
263
+ if (answer.selectedOptionId === "acceptForSession") {
264
+ autoApproveForSession = true;
265
+ sendResponse(id, { decision: mapApprovalDecision(method, "acceptForSession") });
266
+ return;
267
+ }
268
+ sendResponse(id, {
269
+ decision: mapApprovalDecision(method, answer.selectedOptionId === "accept" ? "accept" : "decline"),
270
+ });
271
+ return;
272
+ }
273
+ if (method === "item/tool/requestUserInput") {
274
+ const questions = Array.isArray(params.questions) ? params.questions : [];
275
+ const answers = {};
276
+ for (let qIndex = 0; qIndex < questions.length; qIndex += 1) {
277
+ const question = asRecord(questions[qIndex]);
278
+ if (question === undefined)
279
+ continue;
280
+ const questionId = asString(question.id) ?? `q${String(qIndex + 1)}`;
281
+ const questionText = asString(question.question) ?? "Codex 需要你的确认";
282
+ const rawOptions = Array.isArray(question.options) ? question.options : [];
283
+ const options = rawOptions.length > 0
284
+ ? rawOptions.map((opt, idx) => {
285
+ const rec = asRecord(opt);
286
+ return {
287
+ id: `opt-${String(idx + 1)}`,
288
+ label: asString(rec?.label) ?? `Option ${String(idx + 1)}`,
289
+ description: asString(rec?.description) ?? null,
290
+ };
291
+ })
292
+ : [
293
+ { id: "confirm", label: "继续执行" },
294
+ { id: "cancel", label: "取消当前步骤" },
295
+ ];
296
+ const answer = await input.callbacks.onAsk({
297
+ prompt: questionText,
298
+ options,
299
+ allowFreeText: question.isOther !== false,
300
+ });
301
+ if (answer.cancelled) {
302
+ break;
303
+ }
304
+ const trimmedFreeText = answer.freeText?.trim() ?? "";
305
+ const resolvedValue = trimmedFreeText.length > 0
306
+ ? trimmedFreeText
307
+ : (answer.selectedOptionLabel ?? answer.selectedOptionId ?? "");
308
+ if (resolvedValue.length > 0) {
309
+ answers[questionId] = { answers: [resolvedValue] };
310
+ }
311
+ }
312
+ sendResponse(id, { answers });
313
+ return;
314
+ }
315
+ if (method === "mcpServer/elicitation/request") {
316
+ const mode = asString(params.mode);
317
+ const message = asString(params.message) ?? "External tool requires confirmation";
318
+ if (mode === "url") {
319
+ const rawUrl = asString(params.url);
320
+ if (rawUrl !== undefined && !isGitHubAuthUrl(rawUrl)) {
321
+ input.callbacks.onDiagnostic("Codex MCP URL elicitation rejected for unsupported non-github.com host");
322
+ sendResponse(id, { action: "cancel", content: null, _meta: null });
323
+ return;
324
+ }
325
+ const completed = await input.callbacks.onAuthRequired(message, "github");
326
+ sendResponse(id, {
327
+ action: completed ? "accept" : "cancel",
328
+ content: null,
329
+ _meta: null,
330
+ });
331
+ return;
332
+ }
333
+ const answer = await input.callbacks.onAsk({
334
+ prompt: message,
335
+ options: [
336
+ { id: "accept", label: "同意并继续" },
337
+ { id: "decline", label: "拒绝" },
338
+ ],
339
+ allowFreeText: true,
340
+ });
341
+ if (answer.cancelled) {
342
+ sendResponse(id, { action: "cancel", content: null, _meta: null });
343
+ return;
344
+ }
345
+ if (answer.selectedOptionId === "decline") {
346
+ sendResponse(id, { action: "decline", content: null, _meta: null });
347
+ return;
348
+ }
349
+ sendResponse(id, {
350
+ action: "accept",
351
+ content: answer.freeText ? { text: answer.freeText } : {},
352
+ _meta: null,
353
+ });
354
+ return;
355
+ }
356
+ sendErrorResponse(id, -32601, `Unsupported server request method: ${method}`);
357
+ };
358
+ const handleNotification = async (method, rawParams) => {
359
+ input.callbacks.onActivity();
360
+ const params = asRecord(rawParams) ?? {};
361
+ if (method === "turn/plan/updated") {
362
+ const rawPlan = Array.isArray(params.plan) ? params.plan : [];
363
+ const steps = rawPlan.map((entry, idx) => {
364
+ const rec = asRecord(entry);
365
+ return {
366
+ id: `plan-${String(idx + 1)}`,
367
+ title: asString(rec?.step) ?? `Step ${String(idx + 1)}`,
368
+ status: mapPlanStepStatus(rec?.status),
369
+ };
370
+ });
371
+ const explanation = asString(params.explanation);
372
+ if (steps.length > 0) {
373
+ await input.callbacks.onPlan(steps, explanation);
374
+ }
375
+ return;
376
+ }
377
+ if (method === "item/reasoning/summaryTextDelta") {
378
+ const delta = asString(params.delta) ?? "";
379
+ if (delta.length > 0) {
380
+ reasoningBuffer += delta;
381
+ await flushReasoning(false);
382
+ }
383
+ return;
384
+ }
385
+ if (method === "item/agentMessage/delta") {
386
+ const delta = asString(params.delta) ?? "";
387
+ if (delta.length > 0) {
388
+ agentMessageText += delta;
389
+ }
390
+ return;
391
+ }
392
+ if (method === "item/started") {
393
+ const item = asRecord(params.item);
394
+ const itemId = asString(item?.id);
395
+ const itemType = asString(item?.type);
396
+ if (itemId !== undefined) {
397
+ itemStartTimes.set(itemId, Date.now());
398
+ }
399
+ if (itemType === "commandExecution") {
400
+ const command = asString(item?.command) ?? "Run command";
401
+ await input.callbacks.onStep({
402
+ title: command,
403
+ tool: "shell",
404
+ status: "running",
405
+ command,
406
+ });
407
+ }
408
+ else if (itemType === "mcpToolCall") {
409
+ const toolName = asString(item?.tool) ?? "mcp";
410
+ const serverName = asString(item?.server);
411
+ await input.callbacks.onStep({
412
+ title: serverName ? `${serverName}:${toolName}` : toolName,
413
+ tool: serverName ?? "mcp",
414
+ status: "running",
415
+ });
416
+ }
417
+ return;
418
+ }
419
+ if (method === "item/completed") {
420
+ const item = asRecord(params.item);
421
+ const itemId = asString(item?.id);
422
+ const itemType = asString(item?.type);
423
+ const startedAt = itemId !== undefined ? itemStartTimes.get(itemId) : undefined;
424
+ if (itemId !== undefined)
425
+ itemStartTimes.delete(itemId);
426
+ const fallbackDuration = startedAt !== undefined ? Math.max(0, Date.now() - startedAt) : undefined;
427
+ if (itemType === "agentMessage") {
428
+ const text = asString(item?.text);
429
+ if (text !== undefined && text.trim().length > 0) {
430
+ agentMessageText = text;
431
+ }
432
+ return;
433
+ }
434
+ if (itemType === "reasoning") {
435
+ const summaryParts = Array.isArray(item?.summary)
436
+ ? item.summary.filter((part) => typeof part === "string")
437
+ : [];
438
+ if (summaryParts.length > 0) {
439
+ reasoningBuffer = "";
440
+ await input.callbacks.onThought(summaryParts.join("\n"));
441
+ }
442
+ else {
443
+ await flushReasoning(true);
444
+ }
445
+ return;
446
+ }
447
+ if (itemType === "commandExecution") {
448
+ const command = asString(item?.command) ?? "Run command";
449
+ const exitCode = typeof item?.exitCode === "number" ? item.exitCode : null;
450
+ const statusRaw = asString(item?.status);
451
+ const failed = statusRaw === "failed" ||
452
+ statusRaw === "declined" ||
453
+ (exitCode !== null && exitCode !== 0);
454
+ const durationMs = typeof item?.durationMs === "number" ? item.durationMs : fallbackDuration;
455
+ const aggregatedOutput = asString(item?.aggregatedOutput);
456
+ await input.callbacks.onStep({
457
+ title: command,
458
+ tool: "shell",
459
+ status: failed ? "failed" : "completed",
460
+ command,
461
+ ...(durationMs === undefined ? {} : { durationMs }),
462
+ ...(aggregatedOutput !== undefined && aggregatedOutput.trim().length > 0
463
+ ? { outputSummary: summarizeOutput(aggregatedOutput) }
464
+ : exitCode !== null
465
+ ? { outputSummary: `exit code ${String(exitCode)}` }
466
+ : {}),
467
+ });
468
+ return;
469
+ }
470
+ if (itemType === "fileChange") {
471
+ const changes = Array.isArray(item?.changes) ? item.changes : [];
472
+ const pathsList = changes
473
+ .map((entry) => asString(asRecord(entry)?.path))
474
+ .filter((p) => p !== undefined);
475
+ const failed = asString(item?.status) === "failed" || asString(item?.status) === "declined";
476
+ await input.callbacks.onStep({
477
+ title: pathsList.length > 0
478
+ ? `Edit ${pathsList.slice(0, 3).join(", ")}${pathsList.length > 3 ? ` (+${String(pathsList.length - 3)})` : ""}`
479
+ : "Apply workspace file changes",
480
+ tool: "edit",
481
+ status: failed ? "failed" : "completed",
482
+ ...(fallbackDuration === undefined ? {} : { durationMs: fallbackDuration }),
483
+ ...(pathsList.length > 0 ? { outputSummary: pathsList.join("\n") } : {}),
484
+ });
485
+ return;
486
+ }
487
+ if (itemType === "mcpToolCall") {
488
+ const toolName = asString(item?.tool) ?? "mcp";
489
+ const serverName = asString(item?.server);
490
+ const failed = asString(item?.status) === "failed";
491
+ const errMessage = asString(asRecord(item?.error)?.message);
492
+ await input.callbacks.onStep({
493
+ title: serverName ? `${serverName}:${toolName}` : toolName,
494
+ tool: serverName ?? "mcp",
495
+ status: failed ? "failed" : "completed",
496
+ ...(fallbackDuration === undefined ? {} : { durationMs: fallbackDuration }),
497
+ ...(errMessage === undefined ? {} : { outputSummary: errMessage }),
498
+ });
499
+ }
500
+ return;
501
+ }
502
+ if (method === "turn/completed") {
503
+ await flushReasoning(true);
504
+ const turn = asRecord(params.turn);
505
+ const status = asString(turn?.status) ?? "completed";
506
+ const turnError = asRecord(turn?.error);
507
+ const errorMessage = asString(turnError?.message);
508
+ if (status === "interrupted" || isStopRequested()) {
509
+ finishOnce({
510
+ outcome: "interrupted",
511
+ finalMessage: agentMessageText.trim(),
512
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
513
+ });
514
+ return;
515
+ }
516
+ if (status === "failed") {
517
+ finishOnce({
518
+ outcome: "failed",
519
+ finalMessage: agentMessageText.trim(),
520
+ errorMessage: errorMessage ?? "Codex turn failed",
521
+ errorCode: "CODEX_TURN_FAILED",
522
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
523
+ });
524
+ return;
525
+ }
526
+ const finalText = agentMessageText.trim();
527
+ const firstLine = finalText.split("\n")[0]?.trim() ?? "";
528
+ const prUrl = extractPullRequestUrl(finalText);
529
+ finishOnce({
530
+ outcome: "completed",
531
+ finalMessage: finalText,
532
+ summary: firstLine.length > 0 ? firstLine : `Completed ${input.workItemKey}`,
533
+ ...(prUrl === undefined ? {} : { pullRequestUrl: prUrl }),
534
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
535
+ });
536
+ }
537
+ };
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
+ }
582
+ }
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 }),
615
+ });
616
+ return;
617
+ }
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 }),
627
+ });
628
+ });
629
+ });
630
+ // Run handshake asynchronously so startTurn returns an immediately interruptible handle.
631
+ void (async () => {
632
+ 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
+ });
643
+ if (isStopRequested()) {
644
+ finishOnce({
645
+ outcome: "interrupted",
646
+ finalMessage: agentMessageText.trim(),
647
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
648
+ });
649
+ return;
650
+ }
651
+ sendNotification("initialized");
652
+ const approvalPolicy = mapApprovalPolicy(input.approval);
653
+ let threadResult;
654
+ if (input.resumeThreadId !== undefined) {
655
+ 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
+ });
664
+ }
665
+ catch {
666
+ if (isStopRequested()) {
667
+ finishOnce({
668
+ outcome: "interrupted",
669
+ finalMessage: agentMessageText.trim(),
670
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
671
+ });
672
+ return;
673
+ }
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
+ });
681
+ }
682
+ }
683
+ 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;
705
+ }
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
+ const turnObj = asRecord(asRecord(turnResult)?.turn);
715
+ activeTurnId = asString(turnObj?.id);
716
+ resolveReady();
717
+ if (isStopRequested()) {
718
+ if (activeTurnId !== undefined) {
719
+ await sendRequest("turn/interrupt", { threadId: resolvedThreadId, turnId: activeTurnId }, 5_000).catch(() => undefined);
720
+ }
721
+ else {
722
+ finishOnce({
723
+ outcome: "interrupted",
724
+ finalMessage: agentMessageText.trim(),
725
+ runnerThreadId: resolvedThreadId,
726
+ });
727
+ }
728
+ }
729
+ }
730
+ catch (error) {
731
+ resolveReady();
732
+ if (isStopRequested()) {
733
+ finishOnce({
734
+ outcome: "interrupted",
735
+ finalMessage: agentMessageText.trim(),
736
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
737
+ });
738
+ return;
739
+ }
740
+ finishOnce({
741
+ outcome: "failed",
742
+ finalMessage: "",
743
+ errorMessage: error instanceof Error ? error.message : String(error),
744
+ errorCode: "CODEX_INIT_FAILED",
745
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
746
+ });
747
+ }
748
+ })();
749
+ return {
750
+ completion,
751
+ steer: async (message) => {
752
+ await Promise.race([readyPromise, completion.then(() => undefined)]);
753
+ if (finished || isStopRequested() || threadId === undefined || activeTurnId === undefined) {
754
+ return false;
755
+ }
756
+ try {
757
+ await sendRequest("turn/steer", {
758
+ threadId,
759
+ expectedTurnId: activeTurnId,
760
+ input: [{ type: "text", text: message, text_elements: [] }],
761
+ });
762
+ return true;
763
+ }
764
+ catch (error) {
765
+ input.callbacks.onDiagnostic(`Codex turn/steer fallback to follow-up turn: ${error instanceof Error ? error.message : String(error)}`);
766
+ return false;
767
+ }
768
+ },
769
+ stop: async () => {
770
+ stoppedRequested = true;
771
+ if (finished)
772
+ return;
773
+ if (threadId !== undefined && activeTurnId !== undefined) {
774
+ await sendRequest("turn/interrupt", { threadId, turnId: activeTurnId }, 5_000).catch(() => undefined);
775
+ }
776
+ 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({
785
+ outcome: "interrupted",
786
+ finalMessage: agentMessageText.trim(),
787
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
788
+ });
789
+ return;
790
+ }
791
+ const settled = await raceWithTimeout(completion.then(() => true), 8_000, false);
792
+ if (!settled) {
793
+ await terminateProcessTree(child, {
794
+ forceAfterGrace: true,
795
+ graceMs: 4_000,
796
+ closeStdin: true,
797
+ });
798
+ finishOnce({
799
+ outcome: "interrupted",
800
+ finalMessage: agentMessageText.trim(),
801
+ runnerThreadId: threadId,
802
+ });
803
+ }
804
+ },
805
+ 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({
814
+ outcome: "interrupted",
815
+ finalMessage: agentMessageText.trim(),
816
+ ...(threadId === undefined ? {} : { runnerThreadId: threadId }),
817
+ });
818
+ },
819
+ };
820
+ }
821
+ //# sourceMappingURL=codex-app-server.js.map