@gonovus-ai/spec-flow-cli 1.2.1 → 1.3.0

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 (54) 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/package.json +2 -1
@@ -0,0 +1,1166 @@
1
+ import { AcpAdapter } from "./adapters/acp-adapter.js";
2
+ import { ClaudeStreamAdapter } from "./adapters/claude-stream.js";
3
+ import { CodexAppServerAdapter } from "./adapters/codex-app-server.js";
4
+ import { CustomExecAdapter } from "./adapters/exec-adapter.js";
5
+ import { raceWithTimeout } from "./process-utils.js";
6
+ import { buildSanitizedChildEnv, sanitizeAndClamp } from "./redact.js";
7
+ import { loadWorkflowIfPresent, renderWorkItemPrompt } from "./workflow.js";
8
+ import { prepareWorkItemWorkspace, resolveEffectiveWorkspaceMode, runLifecycleHook, summarizeWorkspaceChanges, } from "./workspace-manager.js";
9
+ const MAX_SESSION_EVENT_PAGES = 50;
10
+ const SESSION_EVENTS_PAGE_SIZE = 200;
11
+ const EMPTY_HOOKS = { timeoutMs: 60_000 };
12
+ function hasExecutableWorkflowFields(wf) {
13
+ return (wf.runner !== undefined ||
14
+ wf.sandbox !== undefined ||
15
+ wf.approval !== undefined ||
16
+ wf.workspaceMode !== undefined ||
17
+ wf.worktreeRoot !== undefined ||
18
+ wf.acpCommand !== undefined ||
19
+ wf.execCommand !== undefined ||
20
+ wf.hooks.afterCreate !== undefined ||
21
+ wf.hooks.beforeRun !== undefined ||
22
+ wf.hooks.afterRun !== undefined);
23
+ }
24
+ function snapshotExecutableWorkflow(wf) {
25
+ return {
26
+ ...(wf.runner === undefined ? {} : { runner: wf.runner }),
27
+ ...(wf.sandbox === undefined ? {} : { sandbox: wf.sandbox }),
28
+ ...(wf.approval === undefined ? {} : { approval: wf.approval }),
29
+ ...(wf.workspaceMode === undefined ? {} : { workspaceMode: wf.workspaceMode }),
30
+ ...(wf.worktreeRoot === undefined ? {} : { worktreeRoot: wf.worktreeRoot }),
31
+ ...(wf.acpCommand === undefined ? {} : { acpCommand: wf.acpCommand }),
32
+ ...(wf.execCommand === undefined ? {} : { execCommand: wf.execCommand }),
33
+ hooks: { ...wf.hooks },
34
+ };
35
+ }
36
+ export function isSessionControlEventType(eventType) {
37
+ return (eventType === "session.prompted" ||
38
+ eventType === "session.elicitation_answered" ||
39
+ eventType === "session.auth_completed" ||
40
+ eventType === "session.stop_requested" ||
41
+ eventType === "work_item.unassigned");
42
+ }
43
+ export function createDefaultRunnerAdapter(config, cliVersion) {
44
+ switch (config.runner) {
45
+ case "codex":
46
+ return new CodexAppServerAdapter(config.codexCommand, cliVersion);
47
+ case "claude":
48
+ return new ClaudeStreamAdapter(config.claudeCommand);
49
+ case "acp":
50
+ return new AcpAdapter({
51
+ ...(config.acpCommand === undefined ? {} : { acpCommand: config.acpCommand }),
52
+ cliVersion,
53
+ });
54
+ case "exec":
55
+ if (config.execCommand === undefined || config.execCommand.trim().length === 0) {
56
+ throw new Error("--runner exec requires --exec <command>");
57
+ }
58
+ return new CustomExecAdapter(config.execCommand);
59
+ }
60
+ }
61
+ export class AgentRunOrchestrator {
62
+ deps;
63
+ activeByWorkItem = new Map();
64
+ activeBySession = new Map();
65
+ pendingQueue = [];
66
+ workflow = null;
67
+ frozenExecutableWorkflow = null;
68
+ freezeExecutableOnReload = false;
69
+ warnedUntrustedWorkflow = false;
70
+ stallTimer = null;
71
+ shuttingDown = false;
72
+ shutdownPromise = null;
73
+ constructor(deps) {
74
+ this.deps = deps;
75
+ }
76
+ now() {
77
+ return this.deps.now?.() ?? Date.now();
78
+ }
79
+ isWorkflowTrusted() {
80
+ return this.deps.config.workflowPath !== undefined || this.deps.config.trustWorkflow === true;
81
+ }
82
+ isCliOverridden(key) {
83
+ return this.deps.config.cliOverrides?.has(key) === true;
84
+ }
85
+ async initialize() {
86
+ await this.deps.stateStore.load();
87
+ await this.reloadWorkflowSafe(true);
88
+ // Freeze executable workflow fields/hooks whenever effective execution runs in the
89
+ // shared working directory (explicit shared mode or non-Git fallback from worktree).
90
+ const effectiveWorkspaceMode = await resolveEffectiveWorkspaceMode(this.deps.config.cwd, this.effectiveConfig().workspaceMode);
91
+ if (effectiveWorkspaceMode === "shared") {
92
+ this.freezeExecutableOnReload = true;
93
+ this.frozenExecutableWorkflow =
94
+ this.workflow !== null && this.isWorkflowTrusted()
95
+ ? snapshotExecutableWorkflow(this.workflow)
96
+ : { hooks: EMPTY_HOOKS };
97
+ }
98
+ if (!this.deps.config.dryRun) {
99
+ await this.recoverStaleSessions();
100
+ }
101
+ if (this.deps.config.stallTimeoutMs > 0) {
102
+ this.stallTimer = setInterval(() => {
103
+ void this.checkStalledRuns();
104
+ }, 15_000);
105
+ this.stallTimer.unref();
106
+ }
107
+ }
108
+ async reloadWorkflowSafe(isInitialLoad = false) {
109
+ try {
110
+ const sanitizedEnv = buildSanitizedChildEnv(this.deps.environment);
111
+ const loaded = await loadWorkflowIfPresent(this.deps.config.cwd, this.deps.config.workflowPath, sanitizedEnv, this.workflow);
112
+ if (loaded === null) {
113
+ this.workflow = null;
114
+ return null;
115
+ }
116
+ if (!this.isWorkflowTrusted()) {
117
+ if (!this.warnedUntrustedWorkflow && hasExecutableWorkflowFields(loaded)) {
118
+ this.warnedUntrustedWorkflow = true;
119
+ this.deps.onDiagnostic(`Ignoring executable settings and hooks in auto-discovered ${loaded.sourcePath}; pass --workflow or --trust-workflow to opt in.`);
120
+ }
121
+ this.workflow = {
122
+ sourcePath: loaded.sourcePath,
123
+ mtimeMs: loaded.mtimeMs,
124
+ ...(loaded.model === undefined ? {} : { model: loaded.model }),
125
+ ...(loaded.concurrency === undefined ? {} : { concurrency: loaded.concurrency }),
126
+ ...(loaded.commentMode === undefined ? {} : { commentMode: loaded.commentMode }),
127
+ ...(loaded.stallTimeoutMs === undefined ? {} : { stallTimeoutMs: loaded.stallTimeoutMs }),
128
+ hooks: EMPTY_HOOKS,
129
+ promptTemplate: loaded.promptTemplate,
130
+ };
131
+ return this.workflow;
132
+ }
133
+ if (!isInitialLoad && this.freezeExecutableOnReload && this.frozenExecutableWorkflow !== null) {
134
+ const frozen = this.frozenExecutableWorkflow;
135
+ this.workflow = {
136
+ sourcePath: loaded.sourcePath,
137
+ mtimeMs: loaded.mtimeMs,
138
+ ...(frozen.runner === undefined ? {} : { runner: frozen.runner }),
139
+ ...(loaded.model === undefined ? {} : { model: loaded.model }),
140
+ ...(frozen.sandbox === undefined ? {} : { sandbox: frozen.sandbox }),
141
+ ...(frozen.approval === undefined ? {} : { approval: frozen.approval }),
142
+ ...(frozen.workspaceMode === undefined ? {} : { workspaceMode: frozen.workspaceMode }),
143
+ ...(frozen.worktreeRoot === undefined ? {} : { worktreeRoot: frozen.worktreeRoot }),
144
+ ...(loaded.concurrency === undefined ? {} : { concurrency: loaded.concurrency }),
145
+ ...(loaded.commentMode === undefined ? {} : { commentMode: loaded.commentMode }),
146
+ ...(frozen.acpCommand === undefined ? {} : { acpCommand: frozen.acpCommand }),
147
+ ...(frozen.execCommand === undefined ? {} : { execCommand: frozen.execCommand }),
148
+ ...(loaded.stallTimeoutMs === undefined ? {} : { stallTimeoutMs: loaded.stallTimeoutMs }),
149
+ hooks: frozen.hooks,
150
+ promptTemplate: loaded.promptTemplate,
151
+ };
152
+ return this.workflow;
153
+ }
154
+ this.workflow = loaded;
155
+ }
156
+ catch (error) {
157
+ this.deps.onDiagnostic(`WORKFLOW.md reload warning: ${error instanceof Error ? error.message : String(error)}`);
158
+ }
159
+ return this.workflow;
160
+ }
161
+ effectiveConfig() {
162
+ const wf = this.workflow;
163
+ const execSource = this.freezeExecutableOnReload && this.frozenExecutableWorkflow !== null
164
+ ? this.frozenExecutableWorkflow
165
+ : wf !== null && this.isWorkflowTrusted()
166
+ ? wf
167
+ : null;
168
+ if (wf === null && execSource === null)
169
+ return this.deps.config;
170
+ const base = this.deps.config;
171
+ return {
172
+ ...base,
173
+ ...(execSource !== null && !this.isCliOverridden("runner") && execSource.runner !== undefined
174
+ ? { runner: execSource.runner }
175
+ : {}),
176
+ ...(wf !== null &&
177
+ !this.isCliOverridden("model") &&
178
+ base.model === undefined &&
179
+ wf.model !== undefined
180
+ ? { model: wf.model }
181
+ : {}),
182
+ ...(execSource !== null &&
183
+ !this.isCliOverridden("sandbox") &&
184
+ execSource.sandbox !== undefined
185
+ ? { sandbox: execSource.sandbox }
186
+ : {}),
187
+ ...(execSource !== null &&
188
+ !this.isCliOverridden("approval") &&
189
+ execSource.approval !== undefined
190
+ ? { approval: execSource.approval }
191
+ : {}),
192
+ ...(execSource !== null &&
193
+ !this.isCliOverridden("workspaceMode") &&
194
+ execSource.workspaceMode !== undefined
195
+ ? { workspaceMode: execSource.workspaceMode }
196
+ : {}),
197
+ ...(execSource !== null &&
198
+ !this.isCliOverridden("worktreeRoot") &&
199
+ base.worktreeRoot === undefined &&
200
+ execSource.worktreeRoot !== undefined
201
+ ? { worktreeRoot: execSource.worktreeRoot }
202
+ : {}),
203
+ ...(wf !== null && !this.isCliOverridden("concurrency") && wf.concurrency !== undefined
204
+ ? { concurrency: wf.concurrency }
205
+ : {}),
206
+ ...(wf !== null && !this.isCliOverridden("commentMode") && wf.commentMode !== undefined
207
+ ? { commentMode: wf.commentMode }
208
+ : {}),
209
+ ...(execSource !== null &&
210
+ !this.isCliOverridden("acpCommand") &&
211
+ base.acpCommand === undefined &&
212
+ execSource.acpCommand !== undefined
213
+ ? { acpCommand: execSource.acpCommand }
214
+ : {}),
215
+ ...(execSource !== null &&
216
+ !this.isCliOverridden("execCommand") &&
217
+ base.execCommand === undefined &&
218
+ execSource.execCommand !== undefined
219
+ ? { execCommand: execSource.execCommand }
220
+ : {}),
221
+ ...(wf !== null && !this.isCliOverridden("stallTimeoutMs") && wf.stallTimeoutMs !== undefined
222
+ ? { stallTimeoutMs: wf.stallTimeoutMs }
223
+ : {}),
224
+ };
225
+ }
226
+ effectiveHooks() {
227
+ if (this.freezeExecutableOnReload && this.frozenExecutableWorkflow !== null) {
228
+ return this.frozenExecutableWorkflow.hooks;
229
+ }
230
+ if (this.workflow === null || !this.isWorkflowTrusted()) {
231
+ return undefined;
232
+ }
233
+ return this.workflow.hooks;
234
+ }
235
+ async recoverStaleSessions() {
236
+ const staleEntries = this.deps.hasExclusiveLock === true
237
+ ? this.deps.stateStore.listActiveSessions()
238
+ : this.deps.stateStore.listStaleActiveSessions();
239
+ for (const entry of staleEntries) {
240
+ const sessionId = entry.activeSessionId;
241
+ if (sessionId === null)
242
+ continue;
243
+ const read = await this.deps.telemetry.readSessionOutcome(entry.projectId, sessionId);
244
+ if (read.kind === "error") {
245
+ this.deps.onDiagnostic(`Startup recovery could not read session ${sessionId} (${entry.workItemKey}); retaining recovery marker.`);
246
+ continue;
247
+ }
248
+ if (read.kind === "not_found") {
249
+ await this.deps.stateStore.markSessionEnded(entry.workItemId, sessionId);
250
+ continue;
251
+ }
252
+ const { detail } = read;
253
+ if (detail.status === "active" ||
254
+ detail.status === "awaiting_input" ||
255
+ detail.status === "stopping") {
256
+ const accepted = detail.status === "stopping"
257
+ ? await this.deps.telemetry.acknowledgeStop(entry.projectId, sessionId, "Recovered after local runner restart; session marked stopped.")
258
+ : await this.deps.telemetry.failSession(entry.projectId, sessionId, "Local SpecFlow runner exited unexpectedly before finishing. Click Retry to start a new attempt.", "RUNNER_RESTARTED");
259
+ if (!accepted) {
260
+ this.deps.onDiagnostic(`Startup recovery could not finalize session ${sessionId} (${entry.workItemKey}); retaining recovery marker.`);
261
+ continue;
262
+ }
263
+ this.deps.emitStatus({
264
+ runnerEvent: "recovered_stale_session",
265
+ workItemKey: entry.workItemKey,
266
+ sessionId,
267
+ });
268
+ }
269
+ await this.deps.stateStore.markSessionEnded(entry.workItemId, sessionId);
270
+ }
271
+ }
272
+ hasActiveWork() {
273
+ return this.activeByWorkItem.size > 0 || this.pendingQueue.length > 0;
274
+ }
275
+ hasPendingWaiters() {
276
+ for (const run of this.activeByWorkItem.values()) {
277
+ if (run.pendingElicitation !== null || run.pendingAuth !== null) {
278
+ return true;
279
+ }
280
+ }
281
+ return false;
282
+ }
283
+ getEarliestPendingEventSeq() {
284
+ let minSeq = null;
285
+ for (const item of this.pendingQueue) {
286
+ if (minSeq === null || item.event.agentSeq < minSeq) {
287
+ minSeq = item.event.agentSeq;
288
+ }
289
+ }
290
+ return minSeq;
291
+ }
292
+ async handleEvent(event) {
293
+ if (this.shuttingDown)
294
+ return;
295
+ if (this.deps.config.dryRun) {
296
+ this.deps.emitStatus({
297
+ runnerEvent: "dry_run_event",
298
+ agentSeq: event.agentSeq,
299
+ eventType: event.eventType,
300
+ workItemKey: event.workItemKey,
301
+ sessionId: event.sessionId,
302
+ });
303
+ return;
304
+ }
305
+ switch (event.eventType) {
306
+ case "work_item.assigned":
307
+ await this.onAssigned(event);
308
+ break;
309
+ case "work_item.mentioned":
310
+ await this.onMentioned(event);
311
+ break;
312
+ case "session.prompted":
313
+ await this.onSessionPrompted(event);
314
+ break;
315
+ case "session.elicitation_answered":
316
+ await this.onElicitationAnswered(event);
317
+ break;
318
+ case "session.auth_completed":
319
+ await this.onAuthCompleted(event);
320
+ break;
321
+ case "session.stop_requested":
322
+ case "work_item.unassigned":
323
+ await this.onStopRequested(event);
324
+ break;
325
+ case "work_item.comment_created":
326
+ // Non-mention comments do not auto-trigger new turns to avoid noisy loops.
327
+ break;
328
+ }
329
+ }
330
+ async onAssigned(event) {
331
+ const existing = this.activeByWorkItem.get(event.workItemId);
332
+ if (existing !== undefined) {
333
+ if (event.sessionId !== null && existing.sessionId === event.sessionId) {
334
+ return;
335
+ }
336
+ this.enqueueDispatch({ event, isFollowUpMention: false });
337
+ return;
338
+ }
339
+ this.enqueueDispatch({ event, isFollowUpMention: false });
340
+ await this.drainQueue();
341
+ }
342
+ isRunActiveForSteering(run) {
343
+ return run.turnLoopActive && !run.stopRequested;
344
+ }
345
+ isRunAborted(run) {
346
+ return run.stopRequested || this.shuttingDown;
347
+ }
348
+ async onMentioned(event) {
349
+ const existing = this.activeByWorkItem.get(event.workItemId);
350
+ if (existing !== undefined && this.isRunActiveForSteering(existing)) {
351
+ try {
352
+ const ctx = await this.deps.telemetry.fetchWorkItemContext(event);
353
+ const matchingComment = event.commentId !== null
354
+ ? ctx.recentComments.find((c) => c.id === event.commentId)
355
+ : ctx.recentComments[ctx.recentComments.length - 1];
356
+ const steerText = matchingComment !== undefined
357
+ ? `Follow-up @mention comment from ${matchingComment.authorName}:\n${matchingComment.content}`
358
+ : `You were @mentioned on ${event.workItemKey}. Check the latest comments and respond.`;
359
+ if (this.isRunActiveForSteering(existing)) {
360
+ const deliveredLive = existing.handle !== null ? await existing.handle.steer(steerText) : false;
361
+ if (!deliveredLive && this.isRunActiveForSteering(existing)) {
362
+ existing.queuedSteerMessages.push(steerText);
363
+ }
364
+ return;
365
+ }
366
+ }
367
+ catch (error) {
368
+ this.deps.onDiagnostic(`Failed to load @mention context for active run ${event.workItemKey}; queueing follow-up dispatch: ${error instanceof Error ? error.message : String(error)}`);
369
+ }
370
+ }
371
+ this.enqueueDispatch({ event, isFollowUpMention: true });
372
+ await this.drainQueue();
373
+ }
374
+ async fetchNewPromptMessages(projectId, run) {
375
+ const messages = [];
376
+ for (let page = 0; page < MAX_SESSION_EVENT_PAGES; page += 1) {
377
+ const beforeSeq = run.lastSeenSessionSeq;
378
+ const detail = await this.deps.telemetry.readSession(projectId, run.sessionId, beforeSeq);
379
+ if (detail === null || detail.events.length === 0) {
380
+ break;
381
+ }
382
+ let maxSeq = beforeSeq;
383
+ for (const sessionEvent of detail.events) {
384
+ if (sessionEvent.seq > maxSeq) {
385
+ maxSeq = sessionEvent.seq;
386
+ }
387
+ if (sessionEvent.seq > beforeSeq &&
388
+ sessionEvent.kind === "prompt" &&
389
+ sessionEvent.body !== null &&
390
+ sessionEvent.body.trim().length > 0) {
391
+ messages.push(sessionEvent.body.trim());
392
+ }
393
+ }
394
+ run.lastSeenSessionSeq = maxSeq;
395
+ if (detail.events.length < SESSION_EVENTS_PAGE_SIZE || maxSeq === beforeSeq) {
396
+ break;
397
+ }
398
+ }
399
+ return messages;
400
+ }
401
+ async onSessionPrompted(event) {
402
+ const run = this.findActiveRun(event);
403
+ if (run === undefined)
404
+ return;
405
+ const messages = await this.fetchNewPromptMessages(event.projectId, run);
406
+ if (messages.length === 0)
407
+ return;
408
+ for (const message of messages) {
409
+ if (!this.isRunActiveForSteering(run)) {
410
+ this.deps.onDiagnostic(`Ignoring steering prompt for finalizing session ${run.sessionId} (${run.workItemKey}).`);
411
+ return;
412
+ }
413
+ const steered = run.handle !== null ? await run.handle.steer(message) : false;
414
+ if (steered) {
415
+ this.deps.emitStatus({
416
+ runnerEvent: "steered_live",
417
+ workItemKey: run.workItemKey,
418
+ sessionId: run.sessionId,
419
+ });
420
+ }
421
+ else if (this.isRunActiveForSteering(run)) {
422
+ run.queuedSteerMessages.push(message);
423
+ this.deps.emitStatus({
424
+ runnerEvent: "steer_queued",
425
+ workItemKey: run.workItemKey,
426
+ sessionId: run.sessionId,
427
+ });
428
+ }
429
+ }
430
+ }
431
+ async onElicitationAnswered(event) {
432
+ const sessionId = event.sessionId;
433
+ if (sessionId === null)
434
+ return;
435
+ const detail = await this.deps.telemetry.readSession(event.projectId, sessionId);
436
+ const elicitation = detail?.latestElicitation ?? null;
437
+ if (elicitation?.status !== "answered")
438
+ return;
439
+ const activeRun = this.activeBySession.get(sessionId);
440
+ const selectedOpt = elicitation.selectedOptionId !== null
441
+ ? elicitation.options.find((opt) => opt.id === elicitation.selectedOptionId)
442
+ : undefined;
443
+ const answer = {
444
+ elicitationId: elicitation.id,
445
+ selectedOptionId: elicitation.selectedOptionId,
446
+ selectedOptionLabel: selectedOpt?.label ?? null,
447
+ freeText: elicitation.freeText,
448
+ cancelled: false,
449
+ };
450
+ if (activeRun !== undefined) {
451
+ const waiter = activeRun.pendingElicitation;
452
+ if (waiter !== null) {
453
+ if (waiter.elicitationId !== null && waiter.elicitationId !== elicitation.id) {
454
+ this.deps.onDiagnostic(`Ignoring mismatched elicitation answer ${elicitation.id} while waiting on ${waiter.elicitationId}.`);
455
+ return;
456
+ }
457
+ activeRun.pendingElicitation = null;
458
+ activeRun.lastActivityAt = this.now();
459
+ waiter.resolve(answer);
460
+ }
461
+ else {
462
+ activeRun.bufferedElicitationAnswers.set(elicitation.id, answer);
463
+ }
464
+ return;
465
+ }
466
+ if (detail === null || (detail.status !== "active" && detail.status !== "awaiting_input")) {
467
+ this.deps.onDiagnostic(`Ignoring delayed elicitation answer for non-resumable session ${sessionId} (status=${detail?.status ?? "unknown"}).`);
468
+ return;
469
+ }
470
+ // If runner was restarted after posting an elicitation, resume the session with the answer.
471
+ const trimmedFreeText = answer.freeText?.trim() ?? "";
472
+ const answerSummary = trimmedFreeText.length > 0
473
+ ? trimmedFreeText
474
+ : (answer.selectedOptionLabel ?? answer.selectedOptionId ?? "Confirmed");
475
+ this.enqueueDispatch({
476
+ event,
477
+ isFollowUpMention: false,
478
+ overrideSessionId: sessionId,
479
+ overridePrompt: `The human operator answered your confirmation prompt ("${elicitation.prompt}") with:\n${answerSummary}\n\nPlease continue completing Work Item ${event.workItemKey}.`,
480
+ });
481
+ await this.drainQueue();
482
+ }
483
+ async onAuthCompleted(event) {
484
+ const sessionId = event.sessionId;
485
+ if (sessionId === null)
486
+ return;
487
+ const activeRun = this.activeBySession.get(sessionId);
488
+ if (activeRun?.pendingAuth !== null && activeRun?.pendingAuth !== undefined) {
489
+ const waiter = activeRun.pendingAuth;
490
+ activeRun.pendingAuth = null;
491
+ activeRun.lastActivityAt = this.now();
492
+ waiter.resolve(true);
493
+ return;
494
+ }
495
+ if (activeRun === undefined) {
496
+ const detail = await this.deps.telemetry.readSession(event.projectId, sessionId);
497
+ if (detail === null || (detail.status !== "active" && detail.status !== "awaiting_input")) {
498
+ this.deps.onDiagnostic(`Ignoring delayed auth completion for non-resumable session ${sessionId} (status=${detail?.status ?? "unknown"}).`);
499
+ return;
500
+ }
501
+ this.enqueueDispatch({
502
+ event,
503
+ isFollowUpMention: false,
504
+ overrideSessionId: sessionId,
505
+ overridePrompt: `External authorization has been completed by the operator. Please continue completing Work Item ${event.workItemKey}.`,
506
+ });
507
+ await this.drainQueue();
508
+ }
509
+ }
510
+ async onStopRequested(event) {
511
+ const isRemoteStop = event.eventType === "session.stop_requested";
512
+ // Always remove matching queued dispatches: session-scoped for session.stop_requested,
513
+ // Work Item-scoped for work_item.unassigned or sessionless stops (even if an active run exists).
514
+ let removed = false;
515
+ for (let i = this.pendingQueue.length - 1; i >= 0; i -= 1) {
516
+ const queued = this.pendingQueue[i];
517
+ if (queued === undefined)
518
+ continue;
519
+ const matches = isRemoteStop && event.sessionId !== null
520
+ ? (queued.overrideSessionId ?? queued.event.sessionId) === event.sessionId
521
+ : queued.event.workItemId === event.workItemId;
522
+ if (matches) {
523
+ this.pendingQueue.splice(i, 1);
524
+ removed = true;
525
+ }
526
+ }
527
+ if (removed) {
528
+ this.deps.onQueueChanged?.();
529
+ }
530
+ const run = this.findActiveRun(event);
531
+ if (run === undefined) {
532
+ if (isRemoteStop && event.sessionId !== null) {
533
+ await this.deps.telemetry.acknowledgeStop(event.projectId, event.sessionId, "No active local turn was running; acknowledged stop cleanly.");
534
+ }
535
+ return;
536
+ }
537
+ run.stopRequested = true;
538
+ if (isRemoteStop) {
539
+ run.stopReason = "remote_stop";
540
+ }
541
+ else {
542
+ run.stopReason ??= "unassigned";
543
+ }
544
+ this.cancelRunWaiters(run);
545
+ if (run.handle !== null) {
546
+ await run.handle.stop();
547
+ }
548
+ }
549
+ findActiveRun(event) {
550
+ if (event.sessionId !== null) {
551
+ return this.activeBySession.get(event.sessionId);
552
+ }
553
+ return this.activeByWorkItem.get(event.workItemId);
554
+ }
555
+ cancelRunWaiters(run) {
556
+ if (run.pendingElicitation !== null) {
557
+ const waiter = run.pendingElicitation;
558
+ run.pendingElicitation = null;
559
+ waiter.resolve({
560
+ elicitationId: waiter.elicitationId ?? "",
561
+ selectedOptionId: null,
562
+ selectedOptionLabel: null,
563
+ freeText: null,
564
+ cancelled: true,
565
+ });
566
+ }
567
+ if (run.pendingAuth !== null) {
568
+ const waiter = run.pendingAuth;
569
+ run.pendingAuth = null;
570
+ waiter.resolve(false);
571
+ }
572
+ run.bufferedElicitationAnswers.clear();
573
+ }
574
+ enqueueDispatch(item) {
575
+ const duplicate = this.pendingQueue.some((queued) => queued.event.workItemId === item.event.workItemId &&
576
+ queued.event.eventType === item.event.eventType &&
577
+ queued.event.sessionId === item.event.sessionId);
578
+ if (!duplicate) {
579
+ this.pendingQueue.push(item);
580
+ this.deps.onQueueChanged?.();
581
+ }
582
+ }
583
+ async drainQueue() {
584
+ if (this.shuttingDown)
585
+ return;
586
+ await this.reloadWorkflowSafe();
587
+ const cfg = this.effectiveConfig();
588
+ let dequeuedAny = false;
589
+ while (this.activeByWorkItem.size < cfg.concurrency && this.pendingQueue.length > 0) {
590
+ const nextIndex = this.pendingQueue.findIndex((item) => !this.activeByWorkItem.has(item.event.workItemId));
591
+ if (nextIndex === -1)
592
+ break;
593
+ const [dispatch] = this.pendingQueue.splice(nextIndex, 1);
594
+ if (dispatch === undefined)
595
+ break;
596
+ dequeuedAny = true;
597
+ this.launchDispatch(dispatch, cfg);
598
+ }
599
+ if (dequeuedAny) {
600
+ this.deps.onQueueChanged?.();
601
+ }
602
+ }
603
+ launchDispatch(dispatch, cfg) {
604
+ const { event } = dispatch;
605
+ let resolveRunDone;
606
+ const completionPromise = new Promise((resolve) => {
607
+ resolveRunDone = resolve;
608
+ });
609
+ const placeholderRun = {
610
+ workItemId: event.workItemId,
611
+ workItemKey: event.workItemKey,
612
+ projectId: event.projectId,
613
+ sessionId: dispatch.overrideSessionId ?? event.sessionId ?? `pending-${event.workItemId}`,
614
+ workspacePath: cfg.cwd,
615
+ runnerThreadId: undefined,
616
+ handle: null,
617
+ lastActivityAt: this.now(),
618
+ lastSeenSessionSeq: 0,
619
+ turnLoopActive: true,
620
+ stopRequested: false,
621
+ stopReason: null,
622
+ stopAcknowledged: false,
623
+ pendingElicitation: null,
624
+ pendingAuth: null,
625
+ bufferedElicitationAnswers: new Map(),
626
+ interactionQueue: Promise.resolve(),
627
+ queuedSteerMessages: [],
628
+ completionPromise,
629
+ };
630
+ this.activeByWorkItem.set(event.workItemId, placeholderRun);
631
+ if (dispatch.overrideSessionId !== undefined || event.sessionId !== null) {
632
+ this.activeBySession.set(placeholderRun.sessionId, placeholderRun);
633
+ }
634
+ void this.executeRun(dispatch, cfg, placeholderRun).finally(() => {
635
+ this.activeByWorkItem.delete(event.workItemId);
636
+ this.activeBySession.delete(placeholderRun.sessionId);
637
+ resolveRunDone();
638
+ void this.drainQueue();
639
+ });
640
+ }
641
+ async executeRun(dispatch, cfg, run) {
642
+ const { event } = dispatch;
643
+ const persisted = this.deps.stateStore.getWorkItem(event.workItemId);
644
+ let sessionId = dispatch.overrideSessionId ?? event.sessionId ?? "";
645
+ let terminalEventAccepted = false;
646
+ try {
647
+ const context = await this.deps.telemetry.fetchWorkItemContext(event);
648
+ if (dispatch.overrideSessionId === undefined) {
649
+ const started = await this.deps.telemetry.startSession(event.projectId, event.workItemId, dispatch.isFollowUpMention
650
+ ? `Responding to @mention on ${event.workItemKey} via ${cfg.runner}`
651
+ : `Running ${event.workItemKey} via ${cfg.runner}`, !dispatch.isFollowUpMention);
652
+ sessionId = started.sessionId;
653
+ }
654
+ else {
655
+ const resumed = await this.deps.telemetry.readSession(event.projectId, dispatch.overrideSessionId);
656
+ if (resumed === null ||
657
+ (resumed.status !== "active" && resumed.status !== "awaiting_input")) {
658
+ this.deps.onDiagnostic(`Skipping resume of non-resumable session ${dispatch.overrideSessionId} (status=${resumed?.status ?? "unknown"}).`);
659
+ terminalEventAccepted = true;
660
+ return;
661
+ }
662
+ }
663
+ if (run.sessionId !== sessionId) {
664
+ this.activeBySession.delete(run.sessionId);
665
+ run.sessionId = sessionId;
666
+ this.activeBySession.set(sessionId, run);
667
+ }
668
+ const reusableThreadId = persisted?.runnerKind === cfg.runner && persisted.runnerThreadId !== null
669
+ ? persisted.runnerThreadId
670
+ : undefined;
671
+ run.runnerThreadId = reusableThreadId;
672
+ // Persist the active session immediately so startup recovery can reconcile it
673
+ // even if workspace preparation, hooks, or a subsequent failure report fail.
674
+ await this.deps.stateStore.upsertWorkItem({
675
+ workItemId: event.workItemId,
676
+ workItemKey: event.workItemKey,
677
+ projectId: event.projectId,
678
+ lastSessionId: sessionId,
679
+ activeSessionId: sessionId,
680
+ runnerKind: cfg.runner,
681
+ runnerThreadId: reusableThreadId ?? null,
682
+ workspacePath: cfg.cwd,
683
+ pid: process.pid,
684
+ updatedAt: new Date().toISOString(),
685
+ });
686
+ const hookEnv = buildSanitizedChildEnv(this.deps.environment, {
687
+ SPECFLOW_WORK_ITEM_KEY: event.workItemKey,
688
+ SPECFLOW_WORK_ITEM_ID: event.workItemId,
689
+ SPECFLOW_PROJECT_ID: event.projectId,
690
+ SPECFLOW_SESSION_ID: sessionId,
691
+ });
692
+ const activeHooks = this.effectiveHooks();
693
+ const preparedWorkspace = await prepareWorkItemWorkspace({
694
+ baseCwd: cfg.cwd,
695
+ mode: cfg.workspaceMode,
696
+ ...(cfg.worktreeRoot === undefined ? {} : { worktreeRoot: cfg.worktreeRoot }),
697
+ workItemKey: event.workItemKey,
698
+ ...(activeHooks === undefined ? {} : { hooks: activeHooks }),
699
+ hookEnv,
700
+ onDiagnostic: this.deps.onDiagnostic,
701
+ });
702
+ run.workspacePath = preparedWorkspace.path;
703
+ if (activeHooks?.beforeRun !== undefined) {
704
+ await runLifecycleHook(activeHooks.beforeRun, preparedWorkspace.path, activeHooks.timeoutMs, hookEnv);
705
+ }
706
+ if (preparedWorkspace.path !== cfg.cwd) {
707
+ await this.deps.stateStore.upsertWorkItem({
708
+ workItemId: event.workItemId,
709
+ workItemKey: event.workItemKey,
710
+ projectId: event.projectId,
711
+ lastSessionId: sessionId,
712
+ activeSessionId: sessionId,
713
+ runnerKind: cfg.runner,
714
+ runnerThreadId: reusableThreadId ?? null,
715
+ workspacePath: preparedWorkspace.path,
716
+ pid: process.pid,
717
+ updatedAt: new Date().toISOString(),
718
+ });
719
+ }
720
+ this.deps.emitStatus({
721
+ runnerEvent: "session_started",
722
+ workItemKey: event.workItemKey,
723
+ sessionId,
724
+ runner: cfg.runner,
725
+ workspacePath: preparedWorkspace.path,
726
+ workspaceMode: preparedWorkspace.mode,
727
+ });
728
+ const adapter = this.deps.adapterFactory(cfg);
729
+ let currentPrompt = dispatch.overridePrompt ??
730
+ renderWorkItemPrompt(context, this.workflow, dispatch.isFollowUpMention);
731
+ let currentResumeThreadId = reusableThreadId;
732
+ let lastTurnResult = null;
733
+ const isRunStopped = () => run.stopRequested;
734
+ // Turn loop: runs the primary turn plus any steering messages queued while an adapter couldn't steer mid-turn.
735
+ try {
736
+ while (!isRunStopped() && !this.shuttingDown) {
737
+ const handle = await adapter.startTurn({
738
+ sessionId,
739
+ workItemKey: event.workItemKey,
740
+ workItemTitle: context.title,
741
+ cwd: preparedWorkspace.path,
742
+ prompt: currentPrompt,
743
+ ...(currentResumeThreadId === undefined
744
+ ? {}
745
+ : { resumeThreadId: currentResumeThreadId }),
746
+ ...(cfg.model === undefined ? {} : { model: cfg.model }),
747
+ sandbox: cfg.sandbox,
748
+ approval: cfg.approval,
749
+ extraArgs: cfg.extraArgs,
750
+ environment: this.deps.environment,
751
+ event,
752
+ callbacks: {
753
+ onThreadId: (tid) => {
754
+ run.runnerThreadId = tid;
755
+ currentResumeThreadId = tid;
756
+ void this.deps.stateStore.upsertWorkItem({
757
+ workItemId: event.workItemId,
758
+ workItemKey: event.workItemKey,
759
+ projectId: event.projectId,
760
+ lastSessionId: sessionId,
761
+ activeSessionId: sessionId,
762
+ runnerKind: cfg.runner,
763
+ runnerThreadId: tid,
764
+ workspacePath: preparedWorkspace.path,
765
+ pid: process.pid,
766
+ updatedAt: new Date().toISOString(),
767
+ });
768
+ },
769
+ onPlan: (steps, summary) => {
770
+ run.lastActivityAt = this.now();
771
+ return this.deps.telemetry.reportPlan(event.projectId, sessionId, steps, summary);
772
+ },
773
+ onThought: (body, title) => {
774
+ run.lastActivityAt = this.now();
775
+ return this.deps.telemetry.reportThought(event.projectId, sessionId, body, title);
776
+ },
777
+ onStep: (step) => {
778
+ run.lastActivityAt = this.now();
779
+ return this.deps.telemetry.reportStep(event.projectId, sessionId, step);
780
+ },
781
+ onAsk: (req) => this.awaitElicitation(run, req),
782
+ onAuthRequired: (scopeSummary, provider) => this.awaitAuth(run, scopeSummary, provider),
783
+ onActivity: () => {
784
+ run.lastActivityAt = this.now();
785
+ },
786
+ onDiagnostic: this.deps.onDiagnostic,
787
+ },
788
+ });
789
+ run.handle = handle;
790
+ if (this.isRunAborted(run)) {
791
+ if (run.stopReason === "stall_timeout") {
792
+ await handle.kill().catch(() => undefined);
793
+ }
794
+ else {
795
+ await handle.stop().catch(() => undefined);
796
+ }
797
+ }
798
+ const result = await handle.completion;
799
+ run.handle = null;
800
+ lastTurnResult = result;
801
+ if (result.runnerThreadId !== undefined) {
802
+ run.runnerThreadId = result.runnerThreadId;
803
+ currentResumeThreadId = result.runnerThreadId;
804
+ }
805
+ if (isRunStopped() || result.outcome !== "completed") {
806
+ break;
807
+ }
808
+ if (run.queuedSteerMessages.length === 0) {
809
+ break;
810
+ }
811
+ const followUps = run.queuedSteerMessages.splice(0, run.queuedSteerMessages.length);
812
+ currentPrompt = `Additional operator guidance received during execution:\n\n${followUps.join("\n\n")}\n\nPlease incorporate this guidance and provide your updated final summary.`;
813
+ }
814
+ }
815
+ finally {
816
+ run.turnLoopActive = false;
817
+ }
818
+ if (activeHooks?.afterRun !== undefined) {
819
+ await runLifecycleHook(activeHooks.afterRun, preparedWorkspace.path, activeHooks.timeoutMs, hookEnv).catch((error) => {
820
+ this.deps.onDiagnostic(`after_run hook warning: ${error instanceof Error ? error.message : String(error)}`);
821
+ });
822
+ }
823
+ if (isRunStopped() || lastTurnResult?.outcome === "interrupted") {
824
+ if (run.stopReason === "remote_stop") {
825
+ if (!run.stopAcknowledged) {
826
+ run.stopAcknowledged = true;
827
+ const rollbackSummary = await summarizeWorkspaceChanges(preparedWorkspace.path);
828
+ terminalEventAccepted = await this.deps.telemetry.acknowledgeStop(event.projectId, sessionId, "Stopped cleanly upon request.", rollbackSummary);
829
+ }
830
+ else {
831
+ terminalEventAccepted = true;
832
+ }
833
+ if (terminalEventAccepted) {
834
+ this.deps.emitStatus({
835
+ runnerEvent: "session_stopped",
836
+ workItemKey: event.workItemKey,
837
+ sessionId,
838
+ });
839
+ }
840
+ else {
841
+ this.deps.emitStatus({
842
+ runnerEvent: "session_failed",
843
+ workItemKey: event.workItemKey,
844
+ sessionId,
845
+ errorMessage: "Failed to acknowledge session stop; preserving recovery state.",
846
+ });
847
+ }
848
+ }
849
+ else {
850
+ const failureSpec = mapNonRemoteStopFailure(run.stopReason);
851
+ terminalEventAccepted = await this.deps.telemetry.failSession(event.projectId, sessionId, failureSpec.message, failureSpec.code);
852
+ this.deps.emitStatus({
853
+ runnerEvent: "session_failed",
854
+ workItemKey: event.workItemKey,
855
+ sessionId,
856
+ errorCode: failureSpec.code,
857
+ errorMessage: sanitizeAndClamp(failureSpec.message, 300),
858
+ });
859
+ }
860
+ }
861
+ else if (lastTurnResult === null || lastTurnResult.outcome === "failed") {
862
+ const message = lastTurnResult?.errorMessage ?? "Runner execution failed";
863
+ terminalEventAccepted = await this.deps.telemetry.failSession(event.projectId, sessionId, message, lastTurnResult?.errorCode);
864
+ this.deps.emitStatus({
865
+ runnerEvent: "session_failed",
866
+ workItemKey: event.workItemKey,
867
+ sessionId,
868
+ errorMessage: sanitizeAndClamp(message, 300),
869
+ });
870
+ }
871
+ else {
872
+ const finalText = lastTurnResult.finalMessage.trim();
873
+ const firstLine = finalText.split("\n")[0]?.trim() ?? "";
874
+ let resultCommentId = null;
875
+ if (cfg.commentMode === "final" && finalText.length > 0) {
876
+ resultCommentId = await this.deps.telemetry.postWorkItemComment(event.projectId, event.workItemKey, finalText);
877
+ }
878
+ terminalEventAccepted = await this.deps.telemetry.completeSession(event.projectId, sessionId, {
879
+ summary: lastTurnResult.summary ??
880
+ (firstLine.length > 0 ? firstLine : `Completed ${event.workItemKey}`),
881
+ resultCommentId,
882
+ ...(lastTurnResult.pullRequestUrl === undefined
883
+ ? {}
884
+ : { pullRequestUrl: lastTurnResult.pullRequestUrl }),
885
+ ...(lastTurnResult.pullRequestTitle === undefined
886
+ ? {}
887
+ : { pullRequestTitle: lastTurnResult.pullRequestTitle }),
888
+ ...(lastTurnResult.checksSummary === undefined
889
+ ? {}
890
+ : { checksSummary: lastTurnResult.checksSummary }),
891
+ });
892
+ if (terminalEventAccepted) {
893
+ this.deps.emitStatus({
894
+ runnerEvent: "session_completed",
895
+ workItemKey: event.workItemKey,
896
+ sessionId,
897
+ resultCommentId,
898
+ ...(lastTurnResult.pullRequestUrl === undefined
899
+ ? {}
900
+ : { pullRequestUrl: lastTurnResult.pullRequestUrl }),
901
+ });
902
+ }
903
+ else {
904
+ this.deps.emitStatus({
905
+ runnerEvent: "session_failed",
906
+ workItemKey: event.workItemKey,
907
+ sessionId,
908
+ errorMessage: "Failed to report session completion; preserving recovery state.",
909
+ });
910
+ }
911
+ }
912
+ }
913
+ catch (error) {
914
+ const message = error instanceof Error ? error.message : String(error);
915
+ this.deps.onDiagnostic(`Run failed for ${event.workItemKey}: ${message}`);
916
+ if (sessionId.length > 0 && !sessionId.startsWith("pending-")) {
917
+ terminalEventAccepted = await this.deps.telemetry
918
+ .failSession(event.projectId, sessionId, message, "RUNNER_ERROR")
919
+ .catch(() => false);
920
+ }
921
+ this.deps.emitStatus({
922
+ runnerEvent: "session_failed",
923
+ workItemKey: event.workItemKey,
924
+ sessionId: sessionId || null,
925
+ errorMessage: sanitizeAndClamp(message, 300),
926
+ });
927
+ }
928
+ finally {
929
+ run.turnLoopActive = false;
930
+ this.cancelRunWaiters(run);
931
+ if (sessionId.length > 0 && !sessionId.startsWith("pending-")) {
932
+ if (terminalEventAccepted) {
933
+ await this.deps.stateStore.markSessionEnded(event.workItemId, sessionId, run.runnerThreadId ?? null);
934
+ }
935
+ else {
936
+ this.deps.onDiagnostic(`Terminal event for session ${sessionId} (${event.workItemKey}) was not acknowledged; keeping recovery marker active.`);
937
+ }
938
+ }
939
+ }
940
+ }
941
+ enqueueInteraction(run, fn) {
942
+ const next = run.interactionQueue.then(fn, fn);
943
+ run.interactionQueue = next.then(() => undefined, () => undefined);
944
+ return next;
945
+ }
946
+ awaitElicitation(run, request) {
947
+ return this.enqueueInteraction(run, async () => {
948
+ if (this.isRunAborted(run)) {
949
+ return {
950
+ elicitationId: "",
951
+ selectedOptionId: null,
952
+ selectedOptionLabel: null,
953
+ freeText: null,
954
+ cancelled: true,
955
+ };
956
+ }
957
+ const elicitationId = await this.deps.telemetry.requestElicitation(run.projectId, run.sessionId, request);
958
+ if (elicitationId === null || this.isRunAborted(run)) {
959
+ return {
960
+ elicitationId: elicitationId ?? "",
961
+ selectedOptionId: null,
962
+ selectedOptionLabel: null,
963
+ freeText: null,
964
+ cancelled: true,
965
+ };
966
+ }
967
+ const bufferedAnswer = run.bufferedElicitationAnswers.get(elicitationId);
968
+ if (bufferedAnswer !== undefined) {
969
+ run.bufferedElicitationAnswers.delete(elicitationId);
970
+ run.lastActivityAt = this.now();
971
+ return bufferedAnswer;
972
+ }
973
+ let resolveWaiter;
974
+ const answerPromise = new Promise((resolve) => {
975
+ resolveWaiter = resolve;
976
+ });
977
+ const waiter = {
978
+ elicitationId,
979
+ options: request.options.map((o) => ({ id: o.id, label: o.label })),
980
+ resolve: resolveWaiter,
981
+ };
982
+ run.pendingElicitation = waiter;
983
+ try {
984
+ return await answerPromise;
985
+ }
986
+ finally {
987
+ if (run.pendingElicitation === waiter) {
988
+ run.pendingElicitation = null;
989
+ }
990
+ }
991
+ });
992
+ }
993
+ awaitAuth(run, scopeSummary, provider = "github") {
994
+ return this.enqueueInteraction(run, async () => {
995
+ if (this.isRunAborted(run)) {
996
+ return false;
997
+ }
998
+ let resolveWaiter;
999
+ const authPromise = new Promise((resolve) => {
1000
+ resolveWaiter = resolve;
1001
+ });
1002
+ const waiter = { resolve: resolveWaiter };
1003
+ run.pendingAuth = waiter;
1004
+ try {
1005
+ const posted = await this.deps.telemetry.requestAuth(run.projectId, run.sessionId, scopeSummary, provider);
1006
+ if (!posted || this.isRunAborted(run)) {
1007
+ return false;
1008
+ }
1009
+ return await authPromise;
1010
+ }
1011
+ finally {
1012
+ if (run.pendingAuth === waiter) {
1013
+ run.pendingAuth = null;
1014
+ }
1015
+ }
1016
+ });
1017
+ }
1018
+ async reconcileWaitingRun(run) {
1019
+ if (run.sessionId.length === 0 || run.sessionId.startsWith("pending-")) {
1020
+ return;
1021
+ }
1022
+ const read = await this.deps.telemetry.readSessionOutcome(run.projectId, run.sessionId);
1023
+ if (read.kind === "error") {
1024
+ return;
1025
+ }
1026
+ if (read.kind === "not_found") {
1027
+ run.stopRequested = true;
1028
+ run.stopReason ??= "stall_timeout";
1029
+ this.cancelRunWaiters(run);
1030
+ await run.handle?.kill();
1031
+ return;
1032
+ }
1033
+ const { detail } = read;
1034
+ const elicitation = detail.latestElicitation ?? null;
1035
+ if (run.pendingElicitation !== null &&
1036
+ elicitation !== null &&
1037
+ (run.pendingElicitation.elicitationId === null ||
1038
+ run.pendingElicitation.elicitationId === elicitation.id)) {
1039
+ if (elicitation.status === "answered") {
1040
+ const waiter = run.pendingElicitation;
1041
+ run.pendingElicitation = null;
1042
+ run.lastActivityAt = this.now();
1043
+ const selectedOpt = elicitation.selectedOptionId !== null
1044
+ ? elicitation.options.find((opt) => opt.id === elicitation.selectedOptionId)
1045
+ : undefined;
1046
+ waiter.resolve({
1047
+ elicitationId: elicitation.id,
1048
+ selectedOptionId: elicitation.selectedOptionId,
1049
+ selectedOptionLabel: selectedOpt?.label ?? null,
1050
+ freeText: elicitation.freeText,
1051
+ cancelled: false,
1052
+ });
1053
+ return;
1054
+ }
1055
+ if (elicitation.status === "expired" || elicitation.status === "cancelled") {
1056
+ const waiter = run.pendingElicitation;
1057
+ run.pendingElicitation = null;
1058
+ run.lastActivityAt = this.now();
1059
+ waiter.resolve({
1060
+ elicitationId: elicitation.id,
1061
+ selectedOptionId: null,
1062
+ selectedOptionLabel: null,
1063
+ freeText: null,
1064
+ cancelled: true,
1065
+ });
1066
+ }
1067
+ }
1068
+ if (detail.status === "stopping") {
1069
+ run.stopRequested = true;
1070
+ run.stopReason = "remote_stop";
1071
+ this.cancelRunWaiters(run);
1072
+ await run.handle?.stop();
1073
+ return;
1074
+ }
1075
+ if (detail.status === "stale" ||
1076
+ detail.status === "error" ||
1077
+ detail.status === "stopped" ||
1078
+ detail.status === "complete") {
1079
+ run.stopRequested = true;
1080
+ run.stopReason ??= "stall_timeout";
1081
+ this.cancelRunWaiters(run);
1082
+ this.deps.onDiagnostic(`Session ${run.sessionId} (${run.workItemKey}) became ${detail.status} remotely while awaiting input; releasing worker.`);
1083
+ await run.handle?.kill();
1084
+ }
1085
+ }
1086
+ async checkStalledRuns() {
1087
+ const timeoutMs = this.effectiveConfig().stallTimeoutMs;
1088
+ if (timeoutMs <= 0)
1089
+ return;
1090
+ const now = this.now();
1091
+ for (const run of this.activeByWorkItem.values()) {
1092
+ if (run.stopRequested) {
1093
+ continue;
1094
+ }
1095
+ if (run.pendingElicitation !== null || run.pendingAuth !== null) {
1096
+ await this.reconcileWaitingRun(run);
1097
+ continue;
1098
+ }
1099
+ if (now - run.lastActivityAt > timeoutMs && run.handle !== null) {
1100
+ run.stopRequested = true;
1101
+ run.stopReason ??= "stall_timeout";
1102
+ this.cancelRunWaiters(run);
1103
+ this.deps.onDiagnostic(`Session ${run.sessionId} (${run.workItemKey}) stalled after ${String(timeoutMs)}ms; terminating.`);
1104
+ await run.handle.kill();
1105
+ }
1106
+ }
1107
+ }
1108
+ async waitForIdle() {
1109
+ while (this.activeByWorkItem.size > 0 || this.pendingQueue.length > 0) {
1110
+ await this.drainQueue();
1111
+ const activePromises = [...this.activeByWorkItem.values()].map((r) => r.completionPromise);
1112
+ if (activePromises.length === 0)
1113
+ break;
1114
+ await Promise.allSettled(activePromises);
1115
+ }
1116
+ }
1117
+ shutdown() {
1118
+ if (this.shutdownPromise !== null) {
1119
+ return this.shutdownPromise;
1120
+ }
1121
+ this.shutdownPromise = (async () => {
1122
+ this.shuttingDown = true;
1123
+ if (this.stallTimer !== null) {
1124
+ clearInterval(this.stallTimer);
1125
+ this.stallTimer = null;
1126
+ }
1127
+ this.pendingQueue.length = 0;
1128
+ const runs = [...this.activeByWorkItem.values()];
1129
+ for (const run of runs) {
1130
+ run.stopRequested = true;
1131
+ run.stopReason ??= "local_shutdown";
1132
+ this.cancelRunWaiters(run);
1133
+ if (run.handle !== null) {
1134
+ await run.handle.stop().catch(() => undefined);
1135
+ }
1136
+ }
1137
+ await raceWithTimeout(Promise.allSettled(runs.map((r) => r.completionPromise)).then(() => undefined), 10_000, undefined);
1138
+ })();
1139
+ return this.shutdownPromise;
1140
+ }
1141
+ }
1142
+ function mapNonRemoteStopFailure(reason) {
1143
+ switch (reason) {
1144
+ case "unassigned":
1145
+ return {
1146
+ code: "WORK_ITEM_UNASSIGNED",
1147
+ message: "Work Item was unassigned from this Agent while running.",
1148
+ };
1149
+ case "stall_timeout":
1150
+ return {
1151
+ code: "STALL_TIMEOUT",
1152
+ message: "Runner turn exceeded the stall timeout and was terminated.",
1153
+ };
1154
+ case "local_shutdown":
1155
+ return {
1156
+ code: "RUNNER_SHUTDOWN",
1157
+ message: "Local SpecFlow runner shut down before completing this session.",
1158
+ };
1159
+ default:
1160
+ return {
1161
+ code: "RUNNER_INTERRUPTED",
1162
+ message: "Runner turn was interrupted unexpectedly.",
1163
+ };
1164
+ }
1165
+ }
1166
+ //# sourceMappingURL=orchestrator.js.map