@moxt-ai/mobius 0.0.453 → 0.0.454

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.
@@ -8,11 +8,13 @@ import { isRecord, truncate } from "../../../util/value-utils.js";
8
8
  import { AGENT_TURN_META, BACKGROUND_TASKS_META, } from "../../agent/in-process-endpoint.js";
9
9
  const TRANSCRIPT_TAIL_BYTES = 65_536;
10
10
  const TRANSCRIPT_INITIAL_DELAY_MS = 40;
11
- const TRANSCRIPT_RETRY_DELAY_MS = 150;
12
- const WAKEUP_STREAM_FALLBACK_MS = 1_500;
13
- const WAKEUP_AWAITING_OUTPUT_MS = 60_000;
11
+ const TRANSCRIPT_POLL_INTERVAL_MS = 150;
12
+ export const WAKEUP_INACTIVITY_TIMEOUT_MS = 300_000;
14
13
  const SESSION_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
15
- const SUBAGENT_IDLE_PATTERN = /\bSubagent [0-9a-f-]+ has gone idle\b/u;
14
+ const SUBAGENT_CONVERSATION_ID_PATTERN = /"conversationId"\s*:\s*"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"/giu;
15
+ const SUBAGENT_IDLE_ID_PATTERN = /\bSubagent ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) (?:has gone|went) idle\b/giu;
16
+ const AGENT_EXECUTOR_ERROR_PATTERN = /^\s*⚠ agent executor error:\s*(.+?)\s*$/su;
17
+ const SUBAGENT_CREATED_MARKER = "Created the following subagent";
16
18
  const MAXIMUM_TOOL_DESCRIPTION_CHARS = 500;
17
19
  const transcriptStepSchema = z.object({
18
20
  content: z.string().optional(),
@@ -62,7 +64,7 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
62
64
  return null;
63
65
  }
64
66
  if (tail.bytes.byteLength === 0) {
65
- return { maxStepIndex: -1, settledWithoutToolCalls: false, steps: [] };
67
+ return { maxStepIndex: -1, settledStepIndex: null, steps: [] };
66
68
  }
67
69
  const text = new TextDecoder().decode(tail.bytes);
68
70
  const lines = text.split("\n");
@@ -85,36 +87,44 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
85
87
  steps.push(parsed.data);
86
88
  }
87
89
  }
88
- const lastStep = steps.at(-1);
89
- const maxStepIndex = lastStep?.step_index ?? -1;
90
- const settledWithoutToolCalls = lastStep !== undefined &&
91
- lastStep.step_index > baselineStepIndex &&
92
- lastStep.type === "PLANNER_RESPONSE" &&
93
- lastStep.status === "DONE" &&
94
- (lastStep.tool_calls === undefined || lastStep.tool_calls.length === 0);
95
- return { maxStepIndex, settledWithoutToolCalls, steps };
90
+ steps.sort((left, right) => left.step_index - right.step_index);
91
+ const maxStepIndex = steps.at(-1)?.step_index ?? -1;
92
+ const settledStep = steps.find((step) => step.step_index > baselineStepIndex &&
93
+ step.type === "PLANNER_RESPONSE" &&
94
+ step.status === "DONE" &&
95
+ (step.tool_calls === undefined || step.tool_calls.length === 0));
96
+ return {
97
+ maxStepIndex,
98
+ settledStepIndex: settledStep?.step_index ?? null,
99
+ steps,
100
+ };
96
101
  }
97
- function countConsumedSubagentIdles(steps, afterStepIndex, throughStepIndex) {
98
- const relevant = steps.filter((step) => step.step_index > afterStepIndex && step.step_index <= throughStepIndex);
99
- let lastPlannerIndex = -1;
100
- for (let index = relevant.length - 1; index >= 0; index -= 1) {
101
- const step = relevant[index];
102
- if (step?.type === "PLANNER_RESPONSE") {
103
- lastPlannerIndex = index;
104
- break;
102
+ function extractUuidMatches(text, pattern) {
103
+ pattern.lastIndex = 0;
104
+ const matches = [];
105
+ for (const match of text.matchAll(pattern)) {
106
+ const captured = match[1]?.toLowerCase();
107
+ if (captured !== undefined) {
108
+ matches.push(captured);
105
109
  }
106
110
  }
107
- if (lastPlannerIndex <= 0) {
108
- return 0;
111
+ return matches;
112
+ }
113
+ function extractExecutorError(updateKind, update) {
114
+ if (updateKind !== "agent_message_chunk" && updateKind !== "agent_message") {
115
+ return undefined;
109
116
  }
110
- let count = 0;
111
- for (let index = 0; index < lastPlannerIndex; index += 1) {
112
- const step = relevant[index];
113
- if (step?.type === "SYSTEM_MESSAGE" && step.content !== undefined && SUBAGENT_IDLE_PATTERN.test(step.content)) {
114
- count += 1;
115
- }
117
+ const content = update["content"];
118
+ if (!isRecord(content) || content["type"] !== "text") {
119
+ return undefined;
116
120
  }
117
- return count;
121
+ const text = readString(content, "text");
122
+ if (text === undefined) {
123
+ return undefined;
124
+ }
125
+ const match = AGENT_EXECUTOR_ERROR_PATTERN.exec(text);
126
+ const message = match?.[1];
127
+ return message === undefined ? undefined : truncate(message, MAXIMUM_TOOL_DESCRIPTION_CHARS);
118
128
  }
119
129
  function extractToolInputRecords(update) {
120
130
  const records = [];
@@ -180,7 +190,7 @@ function inspectToolMetadata(update, previous) {
180
190
  const inputs = extractToolInputRecords(update);
181
191
  const category = readToolCategory(update, inputs, previous);
182
192
  let isDaemon = previous?.isDaemon ?? false;
183
- let subagentKillCount = previous?.subagentKillCount ?? 0;
193
+ const subagentKillIds = new Set(previous?.subagentKillIds ?? []);
184
194
  let subagentKillAll = previous?.subagentKillAll ?? false;
185
195
  for (const record of inputs) {
186
196
  if (record["IsDaemon"] === true) {
@@ -196,7 +206,14 @@ function inspectToolMetadata(update, previous) {
196
206
  subagentKillAll = true;
197
207
  }
198
208
  else if (action === "kill" && Array.isArray(record["ConversationIds"])) {
199
- subagentKillCount = Math.max(subagentKillCount, record["ConversationIds"].length);
209
+ for (const rawId of record["ConversationIds"]) {
210
+ if (typeof rawId === "string") {
211
+ const normalized = rawId.trim().toLowerCase();
212
+ if (normalized.length > 0) {
213
+ subagentKillIds.add(normalized);
214
+ }
215
+ }
216
+ }
200
217
  }
201
218
  }
202
219
  }
@@ -212,7 +229,7 @@ function inspectToolMetadata(update, previous) {
212
229
  description: description === undefined ? undefined : truncate(description, MAXIMUM_TOOL_DESCRIPTION_CHARS),
213
230
  isDaemon,
214
231
  subagentKillAll,
215
- subagentKillCount,
232
+ subagentKillIds: [...subagentKillIds],
216
233
  };
217
234
  }
218
235
  function backgroundKindFor(category) {
@@ -284,8 +301,16 @@ export class AntigravityBackgroundWakeup {
284
301
  baselineStepIndex: -1,
285
302
  lastEmittedBackgroundKey: "[]",
286
303
  phase: { cancelRequested: false, kind: "idle" },
304
+ sessionOpenStepIndex: -1,
305
+ subagents: {
306
+ boundCreationSteps: new Set(),
307
+ consumedIdleSteps: new Set(),
308
+ conversationIdByToolCallId: new Map(),
309
+ pendingToolCallIds: [],
310
+ },
287
311
  toolMetadata: new Map(),
288
312
  wakeupGeneration: 0,
313
+ wakeupStageSeq: 0,
289
314
  };
290
315
  this.#sessions.set(sessionId, created);
291
316
  return created;
@@ -297,12 +322,14 @@ export class AntigravityBackgroundWakeup {
297
322
  switch (phase.stage.kind) {
298
323
  case "awaiting-output":
299
324
  phase.stage.timeout.cancel();
325
+ phase.stage.transcriptCheck.cancel();
300
326
  return;
301
327
  case "blocked-on-work":
328
+ case "verifying-timeout":
302
329
  return;
303
330
  case "streaming":
304
- phase.stage.transcriptCheck?.cancel();
305
- phase.stage.fallbackTimeout.cancel();
331
+ phase.stage.transcriptCheck.cancel();
332
+ phase.stage.inactivityTimeout.cancel();
306
333
  return;
307
334
  default: {
308
335
  const unreachable = phase.stage;
@@ -310,6 +337,11 @@ export class AntigravityBackgroundWakeup {
310
337
  }
311
338
  }
312
339
  };
340
+ #emitNotifications = (notifications) => {
341
+ for (const notification of notifications) {
342
+ this.#emitMetaUpdate(notification);
343
+ }
344
+ };
313
345
  #takeBackgroundTasksUpdate = (sessionId, session) => {
314
346
  const tasks = [...session.backgroundTasks.values()];
315
347
  const serialized = JSON.stringify(tasks);
@@ -319,26 +351,50 @@ export class AntigravityBackgroundWakeup {
319
351
  session.lastEmittedBackgroundKey = serialized;
320
352
  return makeMetaNotification(sessionId, BACKGROUND_TASKS_META, tasks);
321
353
  };
322
- #removeSubagentTasks = (session, count) => {
323
- if (count <= 0) {
324
- return;
354
+ #registerSubagentTask = (session, toolCallId, description) => {
355
+ if (!session.backgroundTasks.has(toolCallId)) {
356
+ session.backgroundTasks.set(toolCallId, {
357
+ ...(description === undefined ? {} : { description }),
358
+ kind: "subagent",
359
+ state: "running",
360
+ taskId: toolCallId,
361
+ toolUseId: toolCallId,
362
+ });
325
363
  }
326
- let remaining = count;
327
- for (const [taskId, task] of session.backgroundTasks) {
328
- if (task.kind !== "subagent") {
329
- continue;
330
- }
331
- session.backgroundTasks.delete(taskId);
332
- remaining -= 1;
333
- if (remaining === 0) {
334
- break;
364
+ if (!session.subagents.conversationIdByToolCallId.has(toolCallId) &&
365
+ !session.subagents.pendingToolCallIds.includes(toolCallId)) {
366
+ session.subagents.pendingToolCallIds.push(toolCallId);
367
+ }
368
+ };
369
+ #deleteSubagentTask = (session, toolCallId) => {
370
+ session.backgroundTasks.delete(toolCallId);
371
+ session.subagents.conversationIdByToolCallId.delete(toolCallId);
372
+ const pendingIndex = session.subagents.pendingToolCallIds.indexOf(toolCallId);
373
+ if (pendingIndex !== -1) {
374
+ session.subagents.pendingToolCallIds.splice(pendingIndex, 1);
375
+ }
376
+ };
377
+ #deleteAllSubagentTasks = (session) => {
378
+ for (const [taskId, task] of [...session.backgroundTasks.entries()]) {
379
+ if (task.kind === "subagent") {
380
+ this.#deleteSubagentTask(session, taskId);
335
381
  }
336
382
  }
337
383
  };
384
+ #clearAllBackgroundTasks = (session) => {
385
+ session.backgroundTasks.clear();
386
+ session.subagents.conversationIdByToolCallId.clear();
387
+ session.subagents.pendingToolCallIds.length = 0;
388
+ };
338
389
  #dropAwaitingResultTasks = (session) => {
339
- for (const [taskId, task] of session.backgroundTasks) {
390
+ for (const [taskId, task] of [...session.backgroundTasks.entries()]) {
340
391
  if (task.state === "awaiting-results") {
341
- session.backgroundTasks.delete(taskId);
392
+ if (task.kind === "subagent") {
393
+ this.#deleteSubagentTask(session, taskId);
394
+ }
395
+ else {
396
+ session.backgroundTasks.delete(taskId);
397
+ }
342
398
  }
343
399
  }
344
400
  };
@@ -350,49 +406,176 @@ export class AntigravityBackgroundWakeup {
350
406
  }
351
407
  return false;
352
408
  };
353
- #oldestRunningSubagentId = (session) => {
354
- for (const task of session.backgroundTasks.values()) {
355
- if (task.kind === "subagent" && task.state === "running") {
356
- return task.taskId;
409
+ #syncSubagentCreations = (session, steps) => {
410
+ if (session.subagents.pendingToolCallIds.length === 0) {
411
+ return;
412
+ }
413
+ for (const step of steps) {
414
+ if (step.step_index <= session.sessionOpenStepIndex ||
415
+ step.type !== "GENERIC" ||
416
+ step.status !== "DONE" ||
417
+ session.subagents.boundCreationSteps.has(step.step_index) ||
418
+ step.content === undefined ||
419
+ !step.content.includes(SUBAGENT_CREATED_MARKER)) {
420
+ continue;
421
+ }
422
+ const createdIds = extractUuidMatches(step.content, SUBAGENT_CONVERSATION_ID_PATTERN);
423
+ if (createdIds.length === 0) {
424
+ continue;
425
+ }
426
+ let boundAny = false;
427
+ for (const conversationId of createdIds) {
428
+ let nextToolCallId;
429
+ while (session.subagents.pendingToolCallIds.length > 0) {
430
+ const candidate = session.subagents.pendingToolCallIds.shift();
431
+ if (candidate !== undefined && session.backgroundTasks.has(candidate)) {
432
+ nextToolCallId = candidate;
433
+ break;
434
+ }
435
+ }
436
+ if (nextToolCallId === undefined) {
437
+ break;
438
+ }
439
+ session.subagents.conversationIdByToolCallId.set(nextToolCallId, conversationId);
440
+ boundAny = true;
441
+ }
442
+ if (boundAny) {
443
+ session.subagents.boundCreationSteps.add(step.step_index);
444
+ }
445
+ }
446
+ };
447
+ #findSubagentToolCallId = (session, conversationId) => {
448
+ const targetId = conversationId.toLowerCase();
449
+ for (const [toolCallId, mappedId] of session.subagents.conversationIdByToolCallId) {
450
+ if (mappedId === targetId && session.backgroundTasks.has(toolCallId)) {
451
+ return toolCallId;
357
452
  }
358
453
  }
359
454
  return undefined;
360
455
  };
456
+ #processIdleSubagentMessages = (session, steps, maxStepExclusive, onMatchedToolCall) => {
457
+ for (const step of steps) {
458
+ if (step.step_index <= session.sessionOpenStepIndex ||
459
+ (maxStepExclusive !== undefined && step.step_index >= maxStepExclusive) ||
460
+ step.type !== "SYSTEM_MESSAGE" ||
461
+ session.subagents.consumedIdleSteps.has(step.step_index) ||
462
+ step.content === undefined) {
463
+ continue;
464
+ }
465
+ const idleIds = extractUuidMatches(step.content, SUBAGENT_IDLE_ID_PATTERN);
466
+ if (idleIds.length === 0) {
467
+ continue;
468
+ }
469
+ session.subagents.consumedIdleSteps.add(step.step_index);
470
+ for (const conversationId of idleIds) {
471
+ const toolCallId = this.#findSubagentToolCallId(session, conversationId);
472
+ if (toolCallId !== undefined) {
473
+ onMatchedToolCall(toolCallId);
474
+ }
475
+ }
476
+ }
477
+ };
478
+ #markTriggeredSubagentIdles = (session, steps) => {
479
+ const matched = new Set();
480
+ this.#processIdleSubagentMessages(session, steps, undefined, (toolCallId) => {
481
+ const existing = session.backgroundTasks.get(toolCallId);
482
+ if (existing !== undefined) {
483
+ session.backgroundTasks.set(toolCallId, { ...existing, state: "awaiting-results" });
484
+ matched.add(toolCallId);
485
+ }
486
+ });
487
+ return [...matched];
488
+ };
489
+ #consumeSubagentIdlesThrough = (session, steps, plannerStepIndex) => {
490
+ this.#processIdleSubagentMessages(session, steps, plannerStepIndex, (toolCallId) => {
491
+ this.#deleteSubagentTask(session, toolCallId);
492
+ });
493
+ };
494
+ #killSubagentsByMetadata = async (sessionId, session, meta) => {
495
+ if (meta.subagentKillAll) {
496
+ this.#deleteAllSubagentTasks(session);
497
+ return true;
498
+ }
499
+ if (meta.subagentKillIds.length === 0) {
500
+ return true;
501
+ }
502
+ await this.#syncPendingSubagentCreations(sessionId, session);
503
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
504
+ return false;
505
+ }
506
+ for (const conversationId of meta.subagentKillIds) {
507
+ const targetToolCallId = this.#findSubagentToolCallId(session, conversationId);
508
+ if (targetToolCallId !== undefined) {
509
+ this.#deleteSubagentTask(session, targetToolCallId);
510
+ }
511
+ }
512
+ return true;
513
+ };
514
+ #syncPendingSubagentCreations = async (sessionId, session) => {
515
+ if (session.subagents.pendingToolCallIds.length === 0) {
516
+ return;
517
+ }
518
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
519
+ if (this.#disposed || this.#sessions.get(sessionId) !== session || tail === null) {
520
+ return;
521
+ }
522
+ this.#syncSubagentCreations(session, tail.steps);
523
+ };
524
+ #scheduleTranscriptPoll = (sessionId, generation, stageEpoch, delayMs) => this.#timer.schedule(() => {
525
+ void this.#checkWakeupTranscript(sessionId, generation, stageEpoch);
526
+ }, delayMs);
361
527
  #setWakeupAwaitingOutput = (sessionId, session, generation, openToolIds) => {
362
528
  this.#cancelWakeupTimers(session.phase);
529
+ session.wakeupStageSeq += 1;
530
+ const stageEpoch = session.wakeupStageSeq;
531
+ const transcriptCheck = this.#scheduleTranscriptPoll(sessionId, generation, stageEpoch, TRANSCRIPT_INITIAL_DELAY_MS);
363
532
  const timeout = this.#timer.schedule(() => {
364
- this.#finishWakeupFromTimer(sessionId, generation, "end_turn");
365
- }, WAKEUP_AWAITING_OUTPUT_MS);
533
+ void this.#handleWakeupTimeout(sessionId, generation, stageEpoch, "Antigravity continuation timed out waiting for output");
534
+ }, WAKEUP_INACTIVITY_TIMEOUT_MS);
366
535
  session.phase = {
367
536
  generation,
368
537
  kind: "wakeup",
369
538
  openToolIds,
370
- stage: { kind: "awaiting-output", timeout },
539
+ stage: { kind: "awaiting-output", stageEpoch, timeout, transcriptCheck },
371
540
  };
372
541
  };
373
542
  #setWakeupBlockedOnWork = (session, generation, openToolIds) => {
374
543
  this.#cancelWakeupTimers(session.phase);
544
+ session.wakeupStageSeq += 1;
545
+ const stageEpoch = session.wakeupStageSeq;
375
546
  session.phase = {
376
547
  generation,
377
548
  kind: "wakeup",
378
549
  openToolIds,
379
- stage: { kind: "blocked-on-work" },
550
+ stage: { kind: "blocked-on-work", stageEpoch },
380
551
  };
381
552
  };
382
- #setWakeupStreaming = (sessionId, session, generation, openToolIds) => {
553
+ #setWakeupStreaming = (sessionId, session, generation, openToolIds, incomingExecutorError) => {
554
+ const previousExecutorError = session.phase.kind === "wakeup" &&
555
+ session.phase.generation === generation &&
556
+ session.phase.stage.kind === "streaming"
557
+ ? session.phase.stage.executorError
558
+ : undefined;
559
+ const executorError = incomingExecutorError ?? previousExecutorError;
383
560
  this.#cancelWakeupTimers(session.phase);
384
- const scheduleTranscriptCheck = (delayMs, allowRetry) => this.#timer.schedule(() => {
385
- void this.#checkWakeupTranscript(sessionId, generation, allowRetry);
386
- }, delayMs);
387
- const fallbackTimeout = this.#timer.schedule(() => {
388
- this.#finishWakeupFromTimer(sessionId, generation, "end_turn");
389
- }, WAKEUP_STREAM_FALLBACK_MS);
390
- const transcriptCheck = scheduleTranscriptCheck(TRANSCRIPT_INITIAL_DELAY_MS, true);
561
+ session.wakeupStageSeq += 1;
562
+ const stageEpoch = session.wakeupStageSeq;
563
+ const transcriptCheck = this.#scheduleTranscriptPoll(sessionId, generation, stageEpoch, TRANSCRIPT_INITIAL_DELAY_MS);
564
+ const inactivityTimeout = this.#timer.schedule(() => {
565
+ void this.#handleWakeupTimeout(sessionId, generation, stageEpoch, "Antigravity continuation timed out while streaming");
566
+ }, WAKEUP_INACTIVITY_TIMEOUT_MS);
391
567
  session.phase = {
392
568
  generation,
393
569
  kind: "wakeup",
394
570
  openToolIds,
395
- stage: { fallbackTimeout, kind: "streaming", transcriptCheck },
571
+ stage: {
572
+ executorError,
573
+ executorErrorPolls: 0,
574
+ inactivityTimeout,
575
+ kind: "streaming",
576
+ stageEpoch,
577
+ transcriptCheck,
578
+ },
396
579
  };
397
580
  };
398
581
  #enterWakeup = (sessionId, session, taskIds) => {
@@ -429,7 +612,49 @@ export class AntigravityBackgroundWakeup {
429
612
  }));
430
613
  return notifications;
431
614
  };
432
- #checkWakeupTranscript = async (sessionId, generation, allowRetry) => {
615
+ #failWakeup = (sessionId, session, message) => {
616
+ if (session.phase.kind !== "wakeup") {
617
+ return [];
618
+ }
619
+ this.#cancelWakeupTimers(session.phase);
620
+ session.phase = { cancelRequested: false, kind: "idle" };
621
+ this.#dropAwaitingResultTasks(session);
622
+ const notifications = [];
623
+ const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
624
+ if (bgNotification !== null) {
625
+ notifications.push(bgNotification);
626
+ }
627
+ notifications.push(makeMetaNotification(sessionId, AGENT_TURN_META, {
628
+ message,
629
+ stage: "failed",
630
+ }));
631
+ return notifications;
632
+ };
633
+ #rescheduleTranscriptCheck = (sessionId, session, generation, stageEpoch, stage) => {
634
+ if (session.phase.kind !== "wakeup") {
635
+ return;
636
+ }
637
+ const nextCheck = this.#scheduleTranscriptPoll(sessionId, generation, stageEpoch, TRANSCRIPT_POLL_INTERVAL_MS);
638
+ switch (stage.kind) {
639
+ case "awaiting-output":
640
+ session.phase = {
641
+ ...session.phase,
642
+ stage: { ...stage, transcriptCheck: nextCheck },
643
+ };
644
+ return;
645
+ case "streaming":
646
+ session.phase = {
647
+ ...session.phase,
648
+ stage: {
649
+ ...stage,
650
+ executorErrorPolls: stage.executorError === undefined ? 0 : stage.executorErrorPolls + 1,
651
+ transcriptCheck: nextCheck,
652
+ },
653
+ };
654
+ return;
655
+ }
656
+ };
657
+ #checkWakeupTranscript = async (sessionId, generation, stageEpoch) => {
433
658
  if (this.#disposed) {
434
659
  return;
435
660
  }
@@ -437,7 +662,8 @@ export class AntigravityBackgroundWakeup {
437
662
  if (session === undefined || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
438
663
  return;
439
664
  }
440
- if (session.phase.stage.kind !== "streaming") {
665
+ if (session.phase.stage.stageEpoch !== stageEpoch ||
666
+ (session.phase.stage.kind !== "streaming" && session.phase.stage.kind !== "awaiting-output")) {
441
667
  return;
442
668
  }
443
669
  const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
@@ -448,31 +674,32 @@ export class AntigravityBackgroundWakeup {
448
674
  if (current === undefined || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
449
675
  return;
450
676
  }
451
- if (current.phase.stage.kind !== "streaming") {
677
+ const currentStage = current.phase.stage;
678
+ if (currentStage.stageEpoch !== stageEpoch ||
679
+ (currentStage.kind !== "streaming" && currentStage.kind !== "awaiting-output")) {
452
680
  return;
453
681
  }
454
- if (tail?.settledWithoutToolCalls) {
455
- current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.maxStepIndex);
456
- for (const notification of this.#finishWakeup(sessionId, current, "end_turn", false)) {
457
- this.#emitMetaUpdate(notification);
458
- }
682
+ if (tail !== null) {
683
+ this.#syncSubagentCreations(current, tail.steps);
684
+ }
685
+ if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== undefined) {
686
+ current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.settledStepIndex);
687
+ this.#consumeSubagentIdlesThrough(current, tail.steps, tail.settledStepIndex);
688
+ this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
459
689
  return;
460
690
  }
461
- if (allowRetry) {
462
- const retryTask = this.#timer.schedule(() => {
463
- void this.#checkWakeupTranscript(sessionId, generation, false);
464
- }, TRANSCRIPT_RETRY_DELAY_MS);
465
- current.phase = {
466
- ...current.phase,
467
- stage: {
468
- fallbackTimeout: current.phase.stage.fallbackTimeout,
469
- kind: "streaming",
470
- transcriptCheck: retryTask,
471
- },
472
- };
691
+ if (currentStage.kind === "streaming" &&
692
+ currentStage.executorError !== undefined &&
693
+ currentStage.executorErrorPolls >= 1) {
694
+ if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
695
+ current.baselineStepIndex = tail.maxStepIndex;
696
+ }
697
+ this.#emitNotifications(this.#failWakeup(sessionId, current, currentStage.executorError));
698
+ return;
473
699
  }
700
+ this.#rescheduleTranscriptCheck(sessionId, current, generation, stageEpoch, currentStage);
474
701
  };
475
- #finishWakeupFromTimer = (sessionId, generation, stopReason) => {
702
+ #handleWakeupTimeout = async (sessionId, generation, stageEpoch, message) => {
476
703
  if (this.#disposed) {
477
704
  return;
478
705
  }
@@ -480,21 +707,41 @@ export class AntigravityBackgroundWakeup {
480
707
  if (session === undefined || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
481
708
  return;
482
709
  }
483
- void readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex).then((tail) => {
484
- if (this.#disposed) {
485
- return;
486
- }
487
- const current = this.#sessions.get(sessionId);
488
- if (current === undefined || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
489
- return;
490
- }
491
- if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
492
- current.baselineStepIndex = tail.maxStepIndex;
493
- }
494
- for (const notification of this.#finishWakeup(sessionId, current, stopReason, false)) {
495
- this.#emitMetaUpdate(notification);
496
- }
497
- });
710
+ if (session.phase.stage.stageEpoch !== stageEpoch ||
711
+ (session.phase.stage.kind !== "awaiting-output" && session.phase.stage.kind !== "streaming")) {
712
+ return;
713
+ }
714
+ this.#cancelWakeupTimers(session.phase);
715
+ session.wakeupStageSeq += 1;
716
+ const timeoutEpoch = session.wakeupStageSeq;
717
+ session.phase = {
718
+ ...session.phase,
719
+ stage: { kind: "verifying-timeout", message, stageEpoch: timeoutEpoch },
720
+ };
721
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
722
+ if (this.#disposed) {
723
+ return;
724
+ }
725
+ const current = this.#sessions.get(sessionId);
726
+ if (current === undefined || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
727
+ return;
728
+ }
729
+ if (current.phase.stage.kind !== "verifying-timeout" || current.phase.stage.stageEpoch !== timeoutEpoch) {
730
+ return;
731
+ }
732
+ if (tail !== null) {
733
+ this.#syncSubagentCreations(current, tail.steps);
734
+ }
735
+ if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== undefined) {
736
+ current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.settledStepIndex);
737
+ this.#consumeSubagentIdlesThrough(current, tail.steps, tail.settledStepIndex);
738
+ this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
739
+ return;
740
+ }
741
+ if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
742
+ current.baselineStepIndex = tail.maxStepIndex;
743
+ }
744
+ this.#emitNotifications(this.#failWakeup(sessionId, current, message));
498
745
  };
499
746
  #promoteOpenWakeupToolsToBackground = (session) => {
500
747
  if (session.phase.kind !== "wakeup" || session.phase.openToolIds.size === 0) {
@@ -529,13 +776,15 @@ export class AntigravityBackgroundWakeup {
529
776
  return;
530
777
  }
531
778
  if (session.phase.openToolIds.size > 0 || session.activeInteractions > 0) {
532
- this.#setWakeupBlockedOnWork(session, session.phase.generation, session.phase.openToolIds);
779
+ if (session.phase.stage.kind !== "blocked-on-work") {
780
+ this.#setWakeupBlockedOnWork(session, session.phase.generation, session.phase.openToolIds);
781
+ }
533
782
  }
534
783
  else if (session.phase.stage.kind === "blocked-on-work") {
535
784
  this.#setWakeupAwaitingOutput(sessionId, session, session.phase.generation, session.phase.openToolIds);
536
785
  }
537
786
  };
538
- #applyClientPromptToolUpdate = (session, update, cancelled) => {
787
+ #applyClientPromptToolUpdate = async (sessionId, session, update, cancelled) => {
539
788
  const toolCallId = readString(update, "toolCallId");
540
789
  const status = readString(update, "status");
541
790
  if (toolCallId === undefined || status === undefined) {
@@ -548,23 +797,13 @@ export class AntigravityBackgroundWakeup {
548
797
  return;
549
798
  }
550
799
  if (meta.category === "manage-subagents" && status === "completed") {
551
- if (meta.subagentKillAll) {
552
- this.#removeSubagentTasks(session, session.backgroundTasks.size);
553
- }
554
- else {
555
- this.#removeSubagentTasks(session, meta.subagentKillCount);
556
- }
800
+ await this.#killSubagentsByMetadata(sessionId, session, meta);
557
801
  return;
558
802
  }
559
803
  if (meta.category === "subagent") {
560
- if (!cancelled && status === "completed" && !session.backgroundTasks.has(toolCallId)) {
561
- session.backgroundTasks.set(toolCallId, {
562
- ...(meta.description === undefined ? {} : { description: meta.description }),
563
- kind: "subagent",
564
- state: "running",
565
- taskId: toolCallId,
566
- toolUseId: toolCallId,
567
- });
804
+ if (!cancelled && status === "completed") {
805
+ this.#registerSubagentTask(session, toolCallId, meta.description);
806
+ await this.#syncPendingSubagentCreations(sessionId, session);
568
807
  }
569
808
  return;
570
809
  }
@@ -586,7 +825,7 @@ export class AntigravityBackgroundWakeup {
586
825
  session.backgroundTasks.delete(toolCallId);
587
826
  }
588
827
  };
589
- #applyWakeupToolUpdate = (sessionId, session, update, notifications) => {
828
+ #applyWakeupToolUpdate = async (sessionId, session, update, notifications) => {
590
829
  if (session.phase.kind !== "wakeup") {
591
830
  return;
592
831
  }
@@ -611,7 +850,12 @@ export class AntigravityBackgroundWakeup {
611
850
  }
612
851
  }
613
852
  else if (status === "failed" || status === "cancelled") {
614
- session.backgroundTasks.delete(toolCallId);
853
+ if (trackedExisting.kind === "subagent") {
854
+ this.#deleteSubagentTask(session, toolCallId);
855
+ }
856
+ else {
857
+ session.backgroundTasks.delete(toolCallId);
858
+ }
615
859
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
616
860
  if (bg !== null) {
617
861
  notifications.push(bg);
@@ -643,24 +887,20 @@ export class AntigravityBackgroundWakeup {
643
887
  session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
644
888
  }
645
889
  if (meta.category === "subagent" && status === "completed") {
646
- session.backgroundTasks.set(toolCallId, {
647
- ...(meta.description === undefined ? {} : { description: meta.description }),
648
- kind: "subagent",
649
- state: "running",
650
- taskId: toolCallId,
651
- toolUseId: toolCallId,
652
- });
890
+ this.#registerSubagentTask(session, toolCallId, meta.description);
891
+ await this.#syncPendingSubagentCreations(sessionId, session);
892
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
893
+ return;
894
+ }
653
895
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
654
896
  if (bg !== null) {
655
897
  notifications.push(bg);
656
898
  }
657
899
  }
658
900
  else if (meta.category === "manage-subagents" && status === "completed") {
659
- if (meta.subagentKillAll) {
660
- this.#removeSubagentTasks(session, session.backgroundTasks.size);
661
- }
662
- else {
663
- this.#removeSubagentTasks(session, meta.subagentKillCount);
901
+ const active = await this.#killSubagentsByMetadata(sessionId, session, meta);
902
+ if (!active) {
903
+ return;
664
904
  }
665
905
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
666
906
  if (bg !== null) {
@@ -703,9 +943,7 @@ export class AntigravityBackgroundWakeup {
703
943
  }
704
944
  const session = this.#ensureSession(sessionId);
705
945
  if (session.phase.kind === "wakeup") {
706
- for (const notification of this.#finishWakeup(sessionId, session, "end_turn", false)) {
707
- this.#emitMetaUpdate(notification);
708
- }
946
+ this.#emitNotifications(this.#finishWakeup(sessionId, session, "end_turn", false));
709
947
  }
710
948
  const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
711
949
  const prePromptStepIndex = Math.max(session.baselineStepIndex, tail?.maxStepIndex ?? -1);
@@ -727,6 +965,12 @@ export class AntigravityBackgroundWakeup {
727
965
  };
728
966
  onIncomingMessage = async (message) => {
729
967
  if (this.#disposed) {
968
+ if (isResponseMessage(message) &&
969
+ "result" in message &&
970
+ isRecord(message.result) &&
971
+ readString(message.result, "stopReason") !== "cancelled") {
972
+ return { afterUpdates: [], beforeUpdates: [], rewritePromptCancelled: true };
973
+ }
730
974
  return EMPTY_INCOMING_OUTCOME;
731
975
  }
732
976
  if (isResponseMessage(message)) {
@@ -743,6 +987,7 @@ export class AntigravityBackgroundWakeup {
743
987
  const tail = await readTranscriptTailState(this.#launchEnvironment, tracked.sessionId, session.baselineStepIndex);
744
988
  if (tail !== null) {
745
989
  session.baselineStepIndex = Math.max(session.baselineStepIndex, tail.maxStepIndex);
990
+ session.sessionOpenStepIndex = Math.max(session.sessionOpenStepIndex, tail.maxStepIndex);
746
991
  }
747
992
  if (tracked.kind === "load") {
748
993
  session.phase = { cancelRequested: false, kind: "idle" };
@@ -750,24 +995,50 @@ export class AntigravityBackgroundWakeup {
750
995
  return EMPTY_INCOMING_OUTCOME;
751
996
  }
752
997
  const prePromptStepIndex = session.phase.kind === "client-prompt" ? session.phase.prePromptStepIndex : session.baselineStepIndex;
753
- const promptCancelled = (session.phase.kind === "client-prompt" && session.phase.cancelled) ||
754
- ("result" in message &&
755
- isRecord(message.result) &&
756
- readString(message.result, "stopReason") === "cancelled");
998
+ const responseStopReason = "result" in message && isRecord(message.result) ? readString(message.result, "stopReason") : undefined;
757
999
  const tail = await readTranscriptTailState(this.#launchEnvironment, tracked.sessionId, session.baselineStepIndex);
1000
+ const promptCancelled = this.#disposed ||
1001
+ (session.phase.kind === "client-prompt" && session.phase.cancelled) ||
1002
+ (session.phase.kind === "idle" && session.phase.cancelRequested) ||
1003
+ responseStopReason === "cancelled";
758
1004
  if (tail !== null) {
759
1005
  session.baselineStepIndex = Math.max(session.baselineStepIndex, tail.maxStepIndex);
1006
+ this.#syncSubagentCreations(session, tail.steps);
760
1007
  if (!promptCancelled) {
761
- const consumedSubagents = countConsumedSubagentIdles(tail.steps, prePromptStepIndex, session.baselineStepIndex);
762
- this.#removeSubagentTasks(session, consumedSubagents);
1008
+ let lastPlannerStepIndex;
1009
+ for (let index = tail.steps.length - 1; index >= 0; index -= 1) {
1010
+ const step = tail.steps[index];
1011
+ if (step !== undefined &&
1012
+ step.step_index > prePromptStepIndex &&
1013
+ step.step_index <= session.baselineStepIndex &&
1014
+ step.type === "PLANNER_RESPONSE") {
1015
+ lastPlannerStepIndex = step.step_index;
1016
+ break;
1017
+ }
1018
+ }
1019
+ if (lastPlannerStepIndex !== undefined) {
1020
+ this.#consumeSubagentIdlesThrough(session, tail.steps, lastPlannerStepIndex);
1021
+ }
763
1022
  }
764
1023
  }
765
1024
  if (promptCancelled) {
766
- session.backgroundTasks.clear();
1025
+ this.#clearAllBackgroundTasks(session);
767
1026
  }
768
1027
  session.phase = { cancelRequested: promptCancelled, kind: "idle" };
769
1028
  const bg = this.#takeBackgroundTasksUpdate(tracked.sessionId, session);
770
- return bg === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates: [bg] };
1029
+ const rewritePromptCancelled = promptCancelled &&
1030
+ "result" in message &&
1031
+ isRecord(message.result) &&
1032
+ responseStopReason !== "cancelled";
1033
+ const beforeUpdates = bg === null ? [] : [bg];
1034
+ if (beforeUpdates.length === 0 && !rewritePromptCancelled) {
1035
+ return EMPTY_INCOMING_OUTCOME;
1036
+ }
1037
+ return {
1038
+ afterUpdates: [],
1039
+ beforeUpdates,
1040
+ ...(rewritePromptCancelled ? { rewritePromptCancelled: true } : {}),
1041
+ };
771
1042
  }
772
1043
  if (!isNotificationMessage(message) || message.method !== methods.client.session.update) {
773
1044
  return EMPTY_INCOMING_OUTCOME;
@@ -788,7 +1059,7 @@ export class AntigravityBackgroundWakeup {
788
1059
  return EMPTY_INCOMING_OUTCOME;
789
1060
  case "client-prompt": {
790
1061
  if (updateKind === "tool_call" || updateKind === "tool_call_update") {
791
- this.#applyClientPromptToolUpdate(session, update, session.phase.cancelled);
1062
+ await this.#applyClientPromptToolUpdate(sessionId, session, update, session.phase.cancelled);
792
1063
  }
793
1064
  return EMPTY_INCOMING_OUTCOME;
794
1065
  }
@@ -800,13 +1071,23 @@ export class AntigravityBackgroundWakeup {
800
1071
  const existing = session.backgroundTasks.get(toolCallId);
801
1072
  if (existing !== undefined) {
802
1073
  if (status === "failed" || status === "cancelled") {
803
- session.backgroundTasks.delete(toolCallId);
1074
+ if (existing.kind === "subagent") {
1075
+ this.#deleteSubagentTask(session, toolCallId);
1076
+ }
1077
+ else {
1078
+ session.backgroundTasks.delete(toolCallId);
1079
+ }
804
1080
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
805
1081
  return bg === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg], beforeUpdates: [] };
806
1082
  }
807
1083
  if (status === "completed") {
808
1084
  if (session.phase.cancelRequested) {
809
- session.backgroundTasks.delete(toolCallId);
1085
+ if (existing.kind === "subagent") {
1086
+ this.#deleteSubagentTask(session, toolCallId);
1087
+ }
1088
+ else {
1089
+ session.backgroundTasks.delete(toolCallId);
1090
+ }
810
1091
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
811
1092
  return bg === null
812
1093
  ? EMPTY_INCOMING_OUTCOME
@@ -834,16 +1115,23 @@ export class AntigravityBackgroundWakeup {
834
1115
  return EMPTY_INCOMING_OUTCOME;
835
1116
  }
836
1117
  }
837
- const subagentTaskId = this.#oldestRunningSubagentId(session);
838
- if (subagentTaskId !== undefined) {
839
- const existing = session.backgroundTasks.get(subagentTaskId);
840
- if (existing !== undefined) {
841
- session.backgroundTasks.set(subagentTaskId, { ...existing, state: "awaiting-results" });
1118
+ let matchedTaskIds = [];
1119
+ if (this.#hasSubagentTasks(session)) {
1120
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
1121
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
1122
+ return EMPTY_INCOMING_OUTCOME;
1123
+ }
1124
+ if (session.phase.kind !== "idle" || session.phase.cancelRequested) {
1125
+ return EMPTY_INCOMING_OUTCOME;
1126
+ }
1127
+ if (tail !== null) {
1128
+ this.#syncSubagentCreations(session, tail.steps);
1129
+ matchedTaskIds = this.#markTriggeredSubagentIdles(session, tail.steps);
842
1130
  }
843
1131
  }
844
- const startedNotifications = this.#enterWakeup(sessionId, session, subagentTaskId === undefined ? [] : [subagentTaskId]);
1132
+ const startedNotifications = this.#enterWakeup(sessionId, session, matchedTaskIds);
845
1133
  const extraWakeup = [];
846
- this.#handleWakeupUpdate(sessionId, session, updateKind, update, extraWakeup);
1134
+ await this.#handleWakeupUpdate(sessionId, session, updateKind, update, extraWakeup);
847
1135
  return {
848
1136
  afterUpdates: [],
849
1137
  beforeUpdates: [...startedNotifications, ...extraWakeup],
@@ -851,7 +1139,7 @@ export class AntigravityBackgroundWakeup {
851
1139
  }
852
1140
  case "wakeup": {
853
1141
  const beforeUpdates = [];
854
- this.#handleWakeupUpdate(sessionId, session, updateKind, update, beforeUpdates);
1142
+ await this.#handleWakeupUpdate(sessionId, session, updateKind, update, beforeUpdates);
855
1143
  return beforeUpdates.length === 0 ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates };
856
1144
  }
857
1145
  default: {
@@ -860,22 +1148,23 @@ export class AntigravityBackgroundWakeup {
860
1148
  }
861
1149
  }
862
1150
  };
863
- #handleWakeupUpdate = (sessionId, session, updateKind, update, beforeUpdates) => {
1151
+ #handleWakeupUpdate = async (sessionId, session, updateKind, update, beforeUpdates) => {
864
1152
  if (session.phase.kind !== "wakeup") {
865
1153
  return;
866
1154
  }
867
1155
  if (updateKind === "tool_call" || updateKind === "tool_call_update") {
868
- this.#applyWakeupToolUpdate(sessionId, session, update, beforeUpdates);
1156
+ await this.#applyWakeupToolUpdate(sessionId, session, update, beforeUpdates);
869
1157
  return;
870
1158
  }
871
1159
  if (isWakeupChunkUpdateKind(updateKind)) {
1160
+ const executorError = extractExecutorError(updateKind, update);
872
1161
  this.#promoteOpenWakeupToolsToBackground(session);
873
1162
  const bg = this.#takeBackgroundTasksUpdate(sessionId, session);
874
1163
  if (bg !== null) {
875
1164
  beforeUpdates.push(bg);
876
1165
  }
877
1166
  if (session.phase.openToolIds.size === 0 && session.activeInteractions === 0) {
878
- this.#setWakeupStreaming(sessionId, session, session.phase.generation, session.phase.openToolIds);
1167
+ this.#setWakeupStreaming(sessionId, session, session.phase.generation, session.phase.openToolIds, executorError);
879
1168
  }
880
1169
  }
881
1170
  };
@@ -908,8 +1197,11 @@ export class AntigravityBackgroundWakeup {
908
1197
  // Process teardown in AgentSession.#endAgentWork owns emitting terminal
909
1198
  // lifecycle events after SessionManager detaches the closing runtime.
910
1199
  this.#cancelWakeupTimers(session.phase);
911
- session.backgroundTasks.clear();
912
- session.phase = { cancelRequested: true, kind: "idle" };
1200
+ this.#clearAllBackgroundTasks(session);
1201
+ session.phase =
1202
+ session.phase.kind === "client-prompt"
1203
+ ? { ...session.phase, cancelled: true }
1204
+ : { cancelRequested: true, kind: "idle" };
913
1205
  return "close";
914
1206
  }
915
1207
  if (session.phase.kind === "client-prompt") {
@@ -927,7 +1219,7 @@ export class AntigravityBackgroundWakeup {
927
1219
  for (const [sessionId, session] of this.#sessions) {
928
1220
  const wasWakeup = session.phase.kind === "wakeup";
929
1221
  this.#cancelWakeupTimers(session.phase);
930
- session.backgroundTasks.clear();
1222
+ this.#clearAllBackgroundTasks(session);
931
1223
  if (wasWakeup) {
932
1224
  session.phase = { cancelRequested: false, kind: "idle" };
933
1225
  this.#emitMetaUpdate(makeMetaNotification(sessionId, AGENT_TURN_META, {