@moxt-ai/mobius 0.0.453 → 0.0.455

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 (48) hide show
  1. package/dist/{chunk-PVKEDOVN.js → chunk-TPFOWHSZ.js} +749 -202
  2. package/dist/{chunk-PVKEDOVN.js.map → chunk-TPFOWHSZ.js.map} +4 -4
  3. package/dist/{chunk-2Q5CQHJI.js → chunk-ZNK44CJT.js} +2 -2
  4. package/dist/{chunk-2Q5CQHJI.js.map → chunk-ZNK44CJT.js.map} +1 -1
  5. package/dist/{cli-TZ354PVI.js → cli-LYAYRPGJ.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/acp-error.d.ts +5 -0
  8. package/dist/engine/acp/acp-error.d.ts.map +1 -1
  9. package/dist/engine/acp/acp-error.js +5 -0
  10. package/dist/engine/acp/acp-error.js.map +1 -1
  11. package/dist/engine/acp/adapter/antigravity/adapter.d.ts +1 -0
  12. package/dist/engine/acp/adapter/antigravity/adapter.d.ts.map +1 -1
  13. package/dist/engine/acp/adapter/antigravity/adapter.js +28 -2
  14. package/dist/engine/acp/adapter/antigravity/adapter.js.map +1 -1
  15. package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts +11 -1
  16. package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts.map +1 -1
  17. package/dist/engine/acp/adapter/antigravity/agent-connection.js +39 -4
  18. package/dist/engine/acp/adapter/antigravity/agent-connection.js.map +1 -1
  19. package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts +4 -0
  20. package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts.map +1 -1
  21. package/dist/engine/acp/adapter/antigravity/background-wakeup.js +453 -161
  22. package/dist/engine/acp/adapter/antigravity/background-wakeup.js.map +1 -1
  23. package/dist/engine/acp/adapter/antigravity/conversation-handoff.d.ts +7 -0
  24. package/dist/engine/acp/adapter/antigravity/conversation-handoff.d.ts.map +1 -0
  25. package/dist/engine/acp/adapter/antigravity/conversation-handoff.js +110 -0
  26. package/dist/engine/acp/adapter/antigravity/conversation-handoff.js.map +1 -0
  27. package/dist/engine/acp/native-history/preview-contract.d.ts +7 -0
  28. package/dist/engine/acp/native-history/preview-contract.d.ts.map +1 -1
  29. package/dist/engine/agent/specification/vendors/antigravity-agent.d.ts +5 -1
  30. package/dist/engine/agent/specification/vendors/antigravity-agent.d.ts.map +1 -1
  31. package/dist/engine/agent/specification/vendors/antigravity-agent.js +7 -2
  32. package/dist/engine/agent/specification/vendors/antigravity-agent.js.map +1 -1
  33. package/dist/engine/session/live/agent-session-restore.d.ts +1 -0
  34. package/dist/engine/session/live/agent-session-restore.d.ts.map +1 -1
  35. package/dist/engine/session/live/agent-session.d.ts +7 -1
  36. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  37. package/dist/engine/session/live/agent-session.js +14 -1
  38. package/dist/engine/session/live/agent-session.js.map +1 -1
  39. package/dist/engine/session/live/session-restore.d.ts +6 -0
  40. package/dist/engine/session/live/session-restore.d.ts.map +1 -1
  41. package/dist/engine/session/live/session-restore.js +26 -0
  42. package/dist/engine/session/live/session-restore.js.map +1 -1
  43. package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
  44. package/dist/engine/session/manager/session-manager.js +26 -1
  45. package/dist/engine/session/manager/session-manager.js.map +1 -1
  46. package/dist/engine.js +2 -2
  47. package/package.json +1 -1
  48. /package/dist/{cli-TZ354PVI.js.map → cli-LYAYRPGJ.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-2Q5CQHJI.js";
6
+ } from "./chunk-ZNK44CJT.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -26978,6 +26978,7 @@ function operationErrorMessage(error62) {
26978
26978
  }
26979
26979
 
26980
26980
  // src/engine/acp/acp-error.ts
26981
+ var NATIVE_SESSION_UNUSABLE_ERROR_CODE = "native_session_unusable";
26981
26982
  var AcpExecutionError = class extends OperationError {
26982
26983
  constructor(message, options = {}, code = "acp_execution_failed") {
26983
26984
  super(code, message, options);
@@ -28014,11 +28015,13 @@ var systemTimer = new SystemTimer();
28014
28015
  // src/engine/acp/adapter/antigravity/background-wakeup.ts
28015
28016
  var TRANSCRIPT_TAIL_BYTES = 65536;
28016
28017
  var TRANSCRIPT_INITIAL_DELAY_MS = 40;
28017
- var TRANSCRIPT_RETRY_DELAY_MS = 150;
28018
- var WAKEUP_STREAM_FALLBACK_MS = 1500;
28019
- var WAKEUP_AWAITING_OUTPUT_MS = 6e4;
28018
+ var TRANSCRIPT_POLL_INTERVAL_MS = 150;
28019
+ var WAKEUP_INACTIVITY_TIMEOUT_MS = 3e5;
28020
28020
  var SESSION_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
28021
- var SUBAGENT_IDLE_PATTERN = /\bSubagent [0-9a-f-]+ has gone idle\b/u;
28021
+ var 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;
28022
+ var 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;
28023
+ var AGENT_EXECUTOR_ERROR_PATTERN = /^\s*⚠ agent executor error:\s*(.+?)\s*$/su;
28024
+ var SUBAGENT_CREATED_MARKER = "Created the following subagent";
28022
28025
  var MAXIMUM_TOOL_DESCRIPTION_CHARS = 500;
28023
28026
  var transcriptStepSchema = external_exports.object({
28024
28027
  content: external_exports.string().optional(),
@@ -28072,7 +28075,7 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
28072
28075
  return null;
28073
28076
  }
28074
28077
  if (tail.bytes.byteLength === 0) {
28075
- return { maxStepIndex: -1, settledWithoutToolCalls: false, steps: [] };
28078
+ return { maxStepIndex: -1, settledStepIndex: null, steps: [] };
28076
28079
  }
28077
28080
  const text2 = new TextDecoder().decode(tail.bytes);
28078
28081
  const lines = text2.split("\n");
@@ -28094,32 +28097,43 @@ async function readTranscriptTailState(launchEnvironment, sessionId, baselineSte
28094
28097
  steps.push(parsed.data);
28095
28098
  }
28096
28099
  }
28097
- const lastStep = steps.at(-1);
28098
- const maxStepIndex = lastStep?.step_index ?? -1;
28099
- const settledWithoutToolCalls = lastStep !== void 0 && lastStep.step_index > baselineStepIndex && lastStep.type === "PLANNER_RESPONSE" && lastStep.status === "DONE" && (lastStep.tool_calls === void 0 || lastStep.tool_calls.length === 0);
28100
- return { maxStepIndex, settledWithoutToolCalls, steps };
28100
+ steps.sort((left, right) => left.step_index - right.step_index);
28101
+ const maxStepIndex = steps.at(-1)?.step_index ?? -1;
28102
+ const settledStep = steps.find(
28103
+ (step) => step.step_index > baselineStepIndex && step.type === "PLANNER_RESPONSE" && step.status === "DONE" && (step.tool_calls === void 0 || step.tool_calls.length === 0)
28104
+ );
28105
+ return {
28106
+ maxStepIndex,
28107
+ settledStepIndex: settledStep?.step_index ?? null,
28108
+ steps
28109
+ };
28101
28110
  }
28102
- function countConsumedSubagentIdles(steps, afterStepIndex, throughStepIndex) {
28103
- const relevant = steps.filter((step) => step.step_index > afterStepIndex && step.step_index <= throughStepIndex);
28104
- let lastPlannerIndex = -1;
28105
- for (let index2 = relevant.length - 1; index2 >= 0; index2 -= 1) {
28106
- const step = relevant[index2];
28107
- if (step?.type === "PLANNER_RESPONSE") {
28108
- lastPlannerIndex = index2;
28109
- break;
28111
+ function extractUuidMatches(text2, pattern) {
28112
+ pattern.lastIndex = 0;
28113
+ const matches = [];
28114
+ for (const match of text2.matchAll(pattern)) {
28115
+ const captured = match[1]?.toLowerCase();
28116
+ if (captured !== void 0) {
28117
+ matches.push(captured);
28110
28118
  }
28111
28119
  }
28112
- if (lastPlannerIndex <= 0) {
28113
- return 0;
28120
+ return matches;
28121
+ }
28122
+ function extractExecutorError(updateKind, update) {
28123
+ if (updateKind !== "agent_message_chunk" && updateKind !== "agent_message") {
28124
+ return void 0;
28114
28125
  }
28115
- let count = 0;
28116
- for (let index2 = 0; index2 < lastPlannerIndex; index2 += 1) {
28117
- const step = relevant[index2];
28118
- if (step?.type === "SYSTEM_MESSAGE" && step.content !== void 0 && SUBAGENT_IDLE_PATTERN.test(step.content)) {
28119
- count += 1;
28120
- }
28126
+ const content = update["content"];
28127
+ if (!isRecord5(content) || content["type"] !== "text") {
28128
+ return void 0;
28121
28129
  }
28122
- return count;
28130
+ const text2 = readString3(content, "text");
28131
+ if (text2 === void 0) {
28132
+ return void 0;
28133
+ }
28134
+ const match = AGENT_EXECUTOR_ERROR_PATTERN.exec(text2);
28135
+ const message = match?.[1];
28136
+ return message === void 0 ? void 0 : truncate(message, MAXIMUM_TOOL_DESCRIPTION_CHARS);
28123
28137
  }
28124
28138
  function extractToolInputRecords(update) {
28125
28139
  const records = [];
@@ -28181,7 +28195,7 @@ function inspectToolMetadata(update, previous) {
28181
28195
  const inputs = extractToolInputRecords(update);
28182
28196
  const category = readToolCategory(update, inputs, previous);
28183
28197
  let isDaemon = previous?.isDaemon ?? false;
28184
- let subagentKillCount = previous?.subagentKillCount ?? 0;
28198
+ const subagentKillIds = new Set(previous?.subagentKillIds ?? []);
28185
28199
  let subagentKillAll = previous?.subagentKillAll ?? false;
28186
28200
  for (const record2 of inputs) {
28187
28201
  if (record2["IsDaemon"] === true) {
@@ -28196,7 +28210,14 @@ function inspectToolMetadata(update, previous) {
28196
28210
  if (action === "kill_all") {
28197
28211
  subagentKillAll = true;
28198
28212
  } else if (action === "kill" && Array.isArray(record2["ConversationIds"])) {
28199
- subagentKillCount = Math.max(subagentKillCount, record2["ConversationIds"].length);
28213
+ for (const rawId of record2["ConversationIds"]) {
28214
+ if (typeof rawId === "string") {
28215
+ const normalized = rawId.trim().toLowerCase();
28216
+ if (normalized.length > 0) {
28217
+ subagentKillIds.add(normalized);
28218
+ }
28219
+ }
28220
+ }
28200
28221
  }
28201
28222
  }
28202
28223
  }
@@ -28206,7 +28227,7 @@ function inspectToolMetadata(update, previous) {
28206
28227
  description: description === void 0 ? void 0 : truncate(description, MAXIMUM_TOOL_DESCRIPTION_CHARS),
28207
28228
  isDaemon,
28208
28229
  subagentKillAll,
28209
- subagentKillCount
28230
+ subagentKillIds: [...subagentKillIds]
28210
28231
  };
28211
28232
  }
28212
28233
  function backgroundKindFor(category) {
@@ -28270,8 +28291,16 @@ var AntigravityBackgroundWakeup = class {
28270
28291
  baselineStepIndex: -1,
28271
28292
  lastEmittedBackgroundKey: "[]",
28272
28293
  phase: { cancelRequested: false, kind: "idle" },
28294
+ sessionOpenStepIndex: -1,
28295
+ subagents: {
28296
+ boundCreationSteps: /* @__PURE__ */ new Set(),
28297
+ consumedIdleSteps: /* @__PURE__ */ new Set(),
28298
+ conversationIdByToolCallId: /* @__PURE__ */ new Map(),
28299
+ pendingToolCallIds: []
28300
+ },
28273
28301
  toolMetadata: /* @__PURE__ */ new Map(),
28274
- wakeupGeneration: 0
28302
+ wakeupGeneration: 0,
28303
+ wakeupStageSeq: 0
28275
28304
  };
28276
28305
  this.#sessions.set(sessionId, created);
28277
28306
  return created;
@@ -28283,12 +28312,14 @@ var AntigravityBackgroundWakeup = class {
28283
28312
  switch (phase.stage.kind) {
28284
28313
  case "awaiting-output":
28285
28314
  phase.stage.timeout.cancel();
28315
+ phase.stage.transcriptCheck.cancel();
28286
28316
  return;
28287
28317
  case "blocked-on-work":
28318
+ case "verifying-timeout":
28288
28319
  return;
28289
28320
  case "streaming":
28290
- phase.stage.transcriptCheck?.cancel();
28291
- phase.stage.fallbackTimeout.cancel();
28321
+ phase.stage.transcriptCheck.cancel();
28322
+ phase.stage.inactivityTimeout.cancel();
28292
28323
  return;
28293
28324
  default: {
28294
28325
  const unreachable2 = phase.stage;
@@ -28296,6 +28327,11 @@ var AntigravityBackgroundWakeup = class {
28296
28327
  }
28297
28328
  }
28298
28329
  };
28330
+ #emitNotifications = (notifications) => {
28331
+ for (const notification of notifications) {
28332
+ this.#emitMetaUpdate(notification);
28333
+ }
28334
+ };
28299
28335
  #takeBackgroundTasksUpdate = (sessionId, session) => {
28300
28336
  const tasks = [...session.backgroundTasks.values()];
28301
28337
  const serialized = JSON.stringify(tasks);
@@ -28305,26 +28341,48 @@ var AntigravityBackgroundWakeup = class {
28305
28341
  session.lastEmittedBackgroundKey = serialized;
28306
28342
  return makeMetaNotification(sessionId, BACKGROUND_TASKS_META, tasks);
28307
28343
  };
28308
- #removeSubagentTasks = (session, count) => {
28309
- if (count <= 0) {
28310
- return;
28344
+ #registerSubagentTask = (session, toolCallId, description) => {
28345
+ if (!session.backgroundTasks.has(toolCallId)) {
28346
+ session.backgroundTasks.set(toolCallId, {
28347
+ ...description === void 0 ? {} : { description },
28348
+ kind: "subagent",
28349
+ state: "running",
28350
+ taskId: toolCallId,
28351
+ toolUseId: toolCallId
28352
+ });
28311
28353
  }
28312
- let remaining = count;
28313
- for (const [taskId, task] of session.backgroundTasks) {
28314
- if (task.kind !== "subagent") {
28315
- continue;
28316
- }
28317
- session.backgroundTasks.delete(taskId);
28318
- remaining -= 1;
28319
- if (remaining === 0) {
28320
- break;
28354
+ if (!session.subagents.conversationIdByToolCallId.has(toolCallId) && !session.subagents.pendingToolCallIds.includes(toolCallId)) {
28355
+ session.subagents.pendingToolCallIds.push(toolCallId);
28356
+ }
28357
+ };
28358
+ #deleteSubagentTask = (session, toolCallId) => {
28359
+ session.backgroundTasks.delete(toolCallId);
28360
+ session.subagents.conversationIdByToolCallId.delete(toolCallId);
28361
+ const pendingIndex = session.subagents.pendingToolCallIds.indexOf(toolCallId);
28362
+ if (pendingIndex !== -1) {
28363
+ session.subagents.pendingToolCallIds.splice(pendingIndex, 1);
28364
+ }
28365
+ };
28366
+ #deleteAllSubagentTasks = (session) => {
28367
+ for (const [taskId, task] of [...session.backgroundTasks.entries()]) {
28368
+ if (task.kind === "subagent") {
28369
+ this.#deleteSubagentTask(session, taskId);
28321
28370
  }
28322
28371
  }
28323
28372
  };
28373
+ #clearAllBackgroundTasks = (session) => {
28374
+ session.backgroundTasks.clear();
28375
+ session.subagents.conversationIdByToolCallId.clear();
28376
+ session.subagents.pendingToolCallIds.length = 0;
28377
+ };
28324
28378
  #dropAwaitingResultTasks = (session) => {
28325
- for (const [taskId, task] of session.backgroundTasks) {
28379
+ for (const [taskId, task] of [...session.backgroundTasks.entries()]) {
28326
28380
  if (task.state === "awaiting-results") {
28327
- session.backgroundTasks.delete(taskId);
28381
+ if (task.kind === "subagent") {
28382
+ this.#deleteSubagentTask(session, taskId);
28383
+ } else {
28384
+ session.backgroundTasks.delete(taskId);
28385
+ }
28328
28386
  }
28329
28387
  }
28330
28388
  };
@@ -28336,49 +28394,183 @@ var AntigravityBackgroundWakeup = class {
28336
28394
  }
28337
28395
  return false;
28338
28396
  };
28339
- #oldestRunningSubagentId = (session) => {
28340
- for (const task of session.backgroundTasks.values()) {
28341
- if (task.kind === "subagent" && task.state === "running") {
28342
- return task.taskId;
28397
+ #syncSubagentCreations = (session, steps) => {
28398
+ if (session.subagents.pendingToolCallIds.length === 0) {
28399
+ return;
28400
+ }
28401
+ for (const step of steps) {
28402
+ if (step.step_index <= session.sessionOpenStepIndex || step.type !== "GENERIC" || step.status !== "DONE" || session.subagents.boundCreationSteps.has(step.step_index) || step.content === void 0 || !step.content.includes(SUBAGENT_CREATED_MARKER)) {
28403
+ continue;
28404
+ }
28405
+ const createdIds = extractUuidMatches(step.content, SUBAGENT_CONVERSATION_ID_PATTERN);
28406
+ if (createdIds.length === 0) {
28407
+ continue;
28408
+ }
28409
+ let boundAny = false;
28410
+ for (const conversationId of createdIds) {
28411
+ let nextToolCallId;
28412
+ while (session.subagents.pendingToolCallIds.length > 0) {
28413
+ const candidate = session.subagents.pendingToolCallIds.shift();
28414
+ if (candidate !== void 0 && session.backgroundTasks.has(candidate)) {
28415
+ nextToolCallId = candidate;
28416
+ break;
28417
+ }
28418
+ }
28419
+ if (nextToolCallId === void 0) {
28420
+ break;
28421
+ }
28422
+ session.subagents.conversationIdByToolCallId.set(nextToolCallId, conversationId);
28423
+ boundAny = true;
28424
+ }
28425
+ if (boundAny) {
28426
+ session.subagents.boundCreationSteps.add(step.step_index);
28427
+ }
28428
+ }
28429
+ };
28430
+ #findSubagentToolCallId = (session, conversationId) => {
28431
+ const targetId = conversationId.toLowerCase();
28432
+ for (const [toolCallId, mappedId] of session.subagents.conversationIdByToolCallId) {
28433
+ if (mappedId === targetId && session.backgroundTasks.has(toolCallId)) {
28434
+ return toolCallId;
28343
28435
  }
28344
28436
  }
28345
28437
  return void 0;
28346
28438
  };
28439
+ #processIdleSubagentMessages = (session, steps, maxStepExclusive, onMatchedToolCall) => {
28440
+ for (const step of steps) {
28441
+ if (step.step_index <= session.sessionOpenStepIndex || maxStepExclusive !== void 0 && step.step_index >= maxStepExclusive || step.type !== "SYSTEM_MESSAGE" || session.subagents.consumedIdleSteps.has(step.step_index) || step.content === void 0) {
28442
+ continue;
28443
+ }
28444
+ const idleIds = extractUuidMatches(step.content, SUBAGENT_IDLE_ID_PATTERN);
28445
+ if (idleIds.length === 0) {
28446
+ continue;
28447
+ }
28448
+ session.subagents.consumedIdleSteps.add(step.step_index);
28449
+ for (const conversationId of idleIds) {
28450
+ const toolCallId = this.#findSubagentToolCallId(session, conversationId);
28451
+ if (toolCallId !== void 0) {
28452
+ onMatchedToolCall(toolCallId);
28453
+ }
28454
+ }
28455
+ }
28456
+ };
28457
+ #markTriggeredSubagentIdles = (session, steps) => {
28458
+ const matched = /* @__PURE__ */ new Set();
28459
+ this.#processIdleSubagentMessages(session, steps, void 0, (toolCallId) => {
28460
+ const existing = session.backgroundTasks.get(toolCallId);
28461
+ if (existing !== void 0) {
28462
+ session.backgroundTasks.set(toolCallId, { ...existing, state: "awaiting-results" });
28463
+ matched.add(toolCallId);
28464
+ }
28465
+ });
28466
+ return [...matched];
28467
+ };
28468
+ #consumeSubagentIdlesThrough = (session, steps, plannerStepIndex) => {
28469
+ this.#processIdleSubagentMessages(session, steps, plannerStepIndex, (toolCallId) => {
28470
+ this.#deleteSubagentTask(session, toolCallId);
28471
+ });
28472
+ };
28473
+ #killSubagentsByMetadata = async (sessionId, session, meta3) => {
28474
+ if (meta3.subagentKillAll) {
28475
+ this.#deleteAllSubagentTasks(session);
28476
+ return true;
28477
+ }
28478
+ if (meta3.subagentKillIds.length === 0) {
28479
+ return true;
28480
+ }
28481
+ await this.#syncPendingSubagentCreations(sessionId, session);
28482
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
28483
+ return false;
28484
+ }
28485
+ for (const conversationId of meta3.subagentKillIds) {
28486
+ const targetToolCallId = this.#findSubagentToolCallId(session, conversationId);
28487
+ if (targetToolCallId !== void 0) {
28488
+ this.#deleteSubagentTask(session, targetToolCallId);
28489
+ }
28490
+ }
28491
+ return true;
28492
+ };
28493
+ #syncPendingSubagentCreations = async (sessionId, session) => {
28494
+ if (session.subagents.pendingToolCallIds.length === 0) {
28495
+ return;
28496
+ }
28497
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
28498
+ if (this.#disposed || this.#sessions.get(sessionId) !== session || tail === null) {
28499
+ return;
28500
+ }
28501
+ this.#syncSubagentCreations(session, tail.steps);
28502
+ };
28503
+ #scheduleTranscriptPoll = (sessionId, generation, stageEpoch, delayMs) => this.#timer.schedule(() => {
28504
+ void this.#checkWakeupTranscript(sessionId, generation, stageEpoch);
28505
+ }, delayMs);
28347
28506
  #setWakeupAwaitingOutput = (sessionId, session, generation, openToolIds) => {
28348
28507
  this.#cancelWakeupTimers(session.phase);
28508
+ session.wakeupStageSeq += 1;
28509
+ const stageEpoch = session.wakeupStageSeq;
28510
+ const transcriptCheck = this.#scheduleTranscriptPoll(
28511
+ sessionId,
28512
+ generation,
28513
+ stageEpoch,
28514
+ TRANSCRIPT_INITIAL_DELAY_MS
28515
+ );
28349
28516
  const timeout = this.#timer.schedule(() => {
28350
- this.#finishWakeupFromTimer(sessionId, generation, "end_turn");
28351
- }, WAKEUP_AWAITING_OUTPUT_MS);
28517
+ void this.#handleWakeupTimeout(
28518
+ sessionId,
28519
+ generation,
28520
+ stageEpoch,
28521
+ "Antigravity continuation timed out waiting for output"
28522
+ );
28523
+ }, WAKEUP_INACTIVITY_TIMEOUT_MS);
28352
28524
  session.phase = {
28353
28525
  generation,
28354
28526
  kind: "wakeup",
28355
28527
  openToolIds,
28356
- stage: { kind: "awaiting-output", timeout }
28528
+ stage: { kind: "awaiting-output", stageEpoch, timeout, transcriptCheck }
28357
28529
  };
28358
28530
  };
28359
28531
  #setWakeupBlockedOnWork = (session, generation, openToolIds) => {
28360
28532
  this.#cancelWakeupTimers(session.phase);
28533
+ session.wakeupStageSeq += 1;
28534
+ const stageEpoch = session.wakeupStageSeq;
28361
28535
  session.phase = {
28362
28536
  generation,
28363
28537
  kind: "wakeup",
28364
28538
  openToolIds,
28365
- stage: { kind: "blocked-on-work" }
28539
+ stage: { kind: "blocked-on-work", stageEpoch }
28366
28540
  };
28367
28541
  };
28368
- #setWakeupStreaming = (sessionId, session, generation, openToolIds) => {
28542
+ #setWakeupStreaming = (sessionId, session, generation, openToolIds, incomingExecutorError) => {
28543
+ const previousExecutorError = session.phase.kind === "wakeup" && session.phase.generation === generation && session.phase.stage.kind === "streaming" ? session.phase.stage.executorError : void 0;
28544
+ const executorError = incomingExecutorError ?? previousExecutorError;
28369
28545
  this.#cancelWakeupTimers(session.phase);
28370
- const scheduleTranscriptCheck = (delayMs, allowRetry) => this.#timer.schedule(() => {
28371
- void this.#checkWakeupTranscript(sessionId, generation, allowRetry);
28372
- }, delayMs);
28373
- const fallbackTimeout = this.#timer.schedule(() => {
28374
- this.#finishWakeupFromTimer(sessionId, generation, "end_turn");
28375
- }, WAKEUP_STREAM_FALLBACK_MS);
28376
- const transcriptCheck = scheduleTranscriptCheck(TRANSCRIPT_INITIAL_DELAY_MS, true);
28546
+ session.wakeupStageSeq += 1;
28547
+ const stageEpoch = session.wakeupStageSeq;
28548
+ const transcriptCheck = this.#scheduleTranscriptPoll(
28549
+ sessionId,
28550
+ generation,
28551
+ stageEpoch,
28552
+ TRANSCRIPT_INITIAL_DELAY_MS
28553
+ );
28554
+ const inactivityTimeout = this.#timer.schedule(() => {
28555
+ void this.#handleWakeupTimeout(
28556
+ sessionId,
28557
+ generation,
28558
+ stageEpoch,
28559
+ "Antigravity continuation timed out while streaming"
28560
+ );
28561
+ }, WAKEUP_INACTIVITY_TIMEOUT_MS);
28377
28562
  session.phase = {
28378
28563
  generation,
28379
28564
  kind: "wakeup",
28380
28565
  openToolIds,
28381
- stage: { fallbackTimeout, kind: "streaming", transcriptCheck }
28566
+ stage: {
28567
+ executorError,
28568
+ executorErrorPolls: 0,
28569
+ inactivityTimeout,
28570
+ kind: "streaming",
28571
+ stageEpoch,
28572
+ transcriptCheck
28573
+ }
28382
28574
  };
28383
28575
  };
28384
28576
  #enterWakeup = (sessionId, session, taskIds) => {
@@ -28419,7 +28611,51 @@ var AntigravityBackgroundWakeup = class {
28419
28611
  );
28420
28612
  return notifications;
28421
28613
  };
28422
- #checkWakeupTranscript = async (sessionId, generation, allowRetry) => {
28614
+ #failWakeup = (sessionId, session, message) => {
28615
+ if (session.phase.kind !== "wakeup") {
28616
+ return [];
28617
+ }
28618
+ this.#cancelWakeupTimers(session.phase);
28619
+ session.phase = { cancelRequested: false, kind: "idle" };
28620
+ this.#dropAwaitingResultTasks(session);
28621
+ const notifications = [];
28622
+ const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
28623
+ if (bgNotification !== null) {
28624
+ notifications.push(bgNotification);
28625
+ }
28626
+ notifications.push(
28627
+ makeMetaNotification(sessionId, AGENT_TURN_META, {
28628
+ message,
28629
+ stage: "failed"
28630
+ })
28631
+ );
28632
+ return notifications;
28633
+ };
28634
+ #rescheduleTranscriptCheck = (sessionId, session, generation, stageEpoch, stage) => {
28635
+ if (session.phase.kind !== "wakeup") {
28636
+ return;
28637
+ }
28638
+ const nextCheck = this.#scheduleTranscriptPoll(sessionId, generation, stageEpoch, TRANSCRIPT_POLL_INTERVAL_MS);
28639
+ switch (stage.kind) {
28640
+ case "awaiting-output":
28641
+ session.phase = {
28642
+ ...session.phase,
28643
+ stage: { ...stage, transcriptCheck: nextCheck }
28644
+ };
28645
+ return;
28646
+ case "streaming":
28647
+ session.phase = {
28648
+ ...session.phase,
28649
+ stage: {
28650
+ ...stage,
28651
+ executorErrorPolls: stage.executorError === void 0 ? 0 : stage.executorErrorPolls + 1,
28652
+ transcriptCheck: nextCheck
28653
+ }
28654
+ };
28655
+ return;
28656
+ }
28657
+ };
28658
+ #checkWakeupTranscript = async (sessionId, generation, stageEpoch) => {
28423
28659
  if (this.#disposed) {
28424
28660
  return;
28425
28661
  }
@@ -28427,7 +28663,7 @@ var AntigravityBackgroundWakeup = class {
28427
28663
  if (session === void 0 || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
28428
28664
  return;
28429
28665
  }
28430
- if (session.phase.stage.kind !== "streaming") {
28666
+ if (session.phase.stage.stageEpoch !== stageEpoch || session.phase.stage.kind !== "streaming" && session.phase.stage.kind !== "awaiting-output") {
28431
28667
  return;
28432
28668
  }
28433
28669
  const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
@@ -28438,31 +28674,29 @@ var AntigravityBackgroundWakeup = class {
28438
28674
  if (current === void 0 || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
28439
28675
  return;
28440
28676
  }
28441
- if (current.phase.stage.kind !== "streaming") {
28677
+ const currentStage = current.phase.stage;
28678
+ if (currentStage.stageEpoch !== stageEpoch || currentStage.kind !== "streaming" && currentStage.kind !== "awaiting-output") {
28442
28679
  return;
28443
28680
  }
28444
- if (tail?.settledWithoutToolCalls) {
28445
- current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.maxStepIndex);
28446
- for (const notification of this.#finishWakeup(sessionId, current, "end_turn", false)) {
28447
- this.#emitMetaUpdate(notification);
28448
- }
28681
+ if (tail !== null) {
28682
+ this.#syncSubagentCreations(current, tail.steps);
28683
+ }
28684
+ if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
28685
+ current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.settledStepIndex);
28686
+ this.#consumeSubagentIdlesThrough(current, tail.steps, tail.settledStepIndex);
28687
+ this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
28449
28688
  return;
28450
28689
  }
28451
- if (allowRetry) {
28452
- const retryTask = this.#timer.schedule(() => {
28453
- void this.#checkWakeupTranscript(sessionId, generation, false);
28454
- }, TRANSCRIPT_RETRY_DELAY_MS);
28455
- current.phase = {
28456
- ...current.phase,
28457
- stage: {
28458
- fallbackTimeout: current.phase.stage.fallbackTimeout,
28459
- kind: "streaming",
28460
- transcriptCheck: retryTask
28461
- }
28462
- };
28690
+ if (currentStage.kind === "streaming" && currentStage.executorError !== void 0 && currentStage.executorErrorPolls >= 1) {
28691
+ if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
28692
+ current.baselineStepIndex = tail.maxStepIndex;
28693
+ }
28694
+ this.#emitNotifications(this.#failWakeup(sessionId, current, currentStage.executorError));
28695
+ return;
28463
28696
  }
28697
+ this.#rescheduleTranscriptCheck(sessionId, current, generation, stageEpoch, currentStage);
28464
28698
  };
28465
- #finishWakeupFromTimer = (sessionId, generation, stopReason) => {
28699
+ #handleWakeupTimeout = async (sessionId, generation, stageEpoch, message) => {
28466
28700
  if (this.#disposed) {
28467
28701
  return;
28468
28702
  }
@@ -28470,21 +28704,40 @@ var AntigravityBackgroundWakeup = class {
28470
28704
  if (session === void 0 || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
28471
28705
  return;
28472
28706
  }
28473
- void readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex).then((tail) => {
28474
- if (this.#disposed) {
28475
- return;
28476
- }
28477
- const current = this.#sessions.get(sessionId);
28478
- if (current === void 0 || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
28479
- return;
28480
- }
28481
- if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
28482
- current.baselineStepIndex = tail.maxStepIndex;
28483
- }
28484
- for (const notification of this.#finishWakeup(sessionId, current, stopReason, false)) {
28485
- this.#emitMetaUpdate(notification);
28486
- }
28487
- });
28707
+ if (session.phase.stage.stageEpoch !== stageEpoch || session.phase.stage.kind !== "awaiting-output" && session.phase.stage.kind !== "streaming") {
28708
+ return;
28709
+ }
28710
+ this.#cancelWakeupTimers(session.phase);
28711
+ session.wakeupStageSeq += 1;
28712
+ const timeoutEpoch = session.wakeupStageSeq;
28713
+ session.phase = {
28714
+ ...session.phase,
28715
+ stage: { kind: "verifying-timeout", message, stageEpoch: timeoutEpoch }
28716
+ };
28717
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
28718
+ if (this.#disposed) {
28719
+ return;
28720
+ }
28721
+ const current = this.#sessions.get(sessionId);
28722
+ if (current === void 0 || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
28723
+ return;
28724
+ }
28725
+ if (current.phase.stage.kind !== "verifying-timeout" || current.phase.stage.stageEpoch !== timeoutEpoch) {
28726
+ return;
28727
+ }
28728
+ if (tail !== null) {
28729
+ this.#syncSubagentCreations(current, tail.steps);
28730
+ }
28731
+ if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
28732
+ current.baselineStepIndex = Math.max(current.baselineStepIndex, tail.settledStepIndex);
28733
+ this.#consumeSubagentIdlesThrough(current, tail.steps, tail.settledStepIndex);
28734
+ this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
28735
+ return;
28736
+ }
28737
+ if (tail !== null && tail.maxStepIndex > current.baselineStepIndex) {
28738
+ current.baselineStepIndex = tail.maxStepIndex;
28739
+ }
28740
+ this.#emitNotifications(this.#failWakeup(sessionId, current, message));
28488
28741
  };
28489
28742
  #promoteOpenWakeupToolsToBackground = (session) => {
28490
28743
  if (session.phase.kind !== "wakeup" || session.phase.openToolIds.size === 0) {
@@ -28519,12 +28772,14 @@ var AntigravityBackgroundWakeup = class {
28519
28772
  return;
28520
28773
  }
28521
28774
  if (session.phase.openToolIds.size > 0 || session.activeInteractions > 0) {
28522
- this.#setWakeupBlockedOnWork(session, session.phase.generation, session.phase.openToolIds);
28775
+ if (session.phase.stage.kind !== "blocked-on-work") {
28776
+ this.#setWakeupBlockedOnWork(session, session.phase.generation, session.phase.openToolIds);
28777
+ }
28523
28778
  } else if (session.phase.stage.kind === "blocked-on-work") {
28524
28779
  this.#setWakeupAwaitingOutput(sessionId, session, session.phase.generation, session.phase.openToolIds);
28525
28780
  }
28526
28781
  };
28527
- #applyClientPromptToolUpdate = (session, update, cancelled) => {
28782
+ #applyClientPromptToolUpdate = async (sessionId, session, update, cancelled) => {
28528
28783
  const toolCallId = readString3(update, "toolCallId");
28529
28784
  const status = readString3(update, "status");
28530
28785
  if (toolCallId === void 0 || status === void 0) {
@@ -28537,22 +28792,13 @@ var AntigravityBackgroundWakeup = class {
28537
28792
  return;
28538
28793
  }
28539
28794
  if (meta3.category === "manage-subagents" && status === "completed") {
28540
- if (meta3.subagentKillAll) {
28541
- this.#removeSubagentTasks(session, session.backgroundTasks.size);
28542
- } else {
28543
- this.#removeSubagentTasks(session, meta3.subagentKillCount);
28544
- }
28795
+ await this.#killSubagentsByMetadata(sessionId, session, meta3);
28545
28796
  return;
28546
28797
  }
28547
28798
  if (meta3.category === "subagent") {
28548
- if (!cancelled && status === "completed" && !session.backgroundTasks.has(toolCallId)) {
28549
- session.backgroundTasks.set(toolCallId, {
28550
- ...meta3.description === void 0 ? {} : { description: meta3.description },
28551
- kind: "subagent",
28552
- state: "running",
28553
- taskId: toolCallId,
28554
- toolUseId: toolCallId
28555
- });
28799
+ if (!cancelled && status === "completed") {
28800
+ this.#registerSubagentTask(session, toolCallId, meta3.description);
28801
+ await this.#syncPendingSubagentCreations(sessionId, session);
28556
28802
  }
28557
28803
  return;
28558
28804
  }
@@ -28574,7 +28820,7 @@ var AntigravityBackgroundWakeup = class {
28574
28820
  session.backgroundTasks.delete(toolCallId);
28575
28821
  }
28576
28822
  };
28577
- #applyWakeupToolUpdate = (sessionId, session, update, notifications) => {
28823
+ #applyWakeupToolUpdate = async (sessionId, session, update, notifications) => {
28578
28824
  if (session.phase.kind !== "wakeup") {
28579
28825
  return;
28580
28826
  }
@@ -28603,7 +28849,11 @@ var AntigravityBackgroundWakeup = class {
28603
28849
  );
28604
28850
  }
28605
28851
  } else if (status === "failed" || status === "cancelled") {
28606
- session.backgroundTasks.delete(toolCallId);
28852
+ if (trackedExisting.kind === "subagent") {
28853
+ this.#deleteSubagentTask(session, toolCallId);
28854
+ } else {
28855
+ session.backgroundTasks.delete(toolCallId);
28856
+ }
28607
28857
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28608
28858
  if (bg2 !== null) {
28609
28859
  notifications.push(bg2);
@@ -28635,22 +28885,19 @@ var AntigravityBackgroundWakeup = class {
28635
28885
  session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
28636
28886
  }
28637
28887
  if (meta3.category === "subagent" && status === "completed") {
28638
- session.backgroundTasks.set(toolCallId, {
28639
- ...meta3.description === void 0 ? {} : { description: meta3.description },
28640
- kind: "subagent",
28641
- state: "running",
28642
- taskId: toolCallId,
28643
- toolUseId: toolCallId
28644
- });
28888
+ this.#registerSubagentTask(session, toolCallId, meta3.description);
28889
+ await this.#syncPendingSubagentCreations(sessionId, session);
28890
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
28891
+ return;
28892
+ }
28645
28893
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28646
28894
  if (bg2 !== null) {
28647
28895
  notifications.push(bg2);
28648
28896
  }
28649
28897
  } else if (meta3.category === "manage-subagents" && status === "completed") {
28650
- if (meta3.subagentKillAll) {
28651
- this.#removeSubagentTasks(session, session.backgroundTasks.size);
28652
- } else {
28653
- this.#removeSubagentTasks(session, meta3.subagentKillCount);
28898
+ const active = await this.#killSubagentsByMetadata(sessionId, session, meta3);
28899
+ if (!active) {
28900
+ return;
28654
28901
  }
28655
28902
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28656
28903
  if (bg2 !== null) {
@@ -28693,9 +28940,7 @@ var AntigravityBackgroundWakeup = class {
28693
28940
  }
28694
28941
  const session = this.#ensureSession(sessionId);
28695
28942
  if (session.phase.kind === "wakeup") {
28696
- for (const notification of this.#finishWakeup(sessionId, session, "end_turn", false)) {
28697
- this.#emitMetaUpdate(notification);
28698
- }
28943
+ this.#emitNotifications(this.#finishWakeup(sessionId, session, "end_turn", false));
28699
28944
  }
28700
28945
  const tail = await readTranscriptTailState(
28701
28946
  this.#launchEnvironment,
@@ -28721,6 +28966,9 @@ var AntigravityBackgroundWakeup = class {
28721
28966
  };
28722
28967
  onIncomingMessage = async (message) => {
28723
28968
  if (this.#disposed) {
28969
+ if (isResponseMessage2(message) && "result" in message && isRecord5(message.result) && readString3(message.result, "stopReason") !== "cancelled") {
28970
+ return { afterUpdates: [], beforeUpdates: [], rewritePromptCancelled: true };
28971
+ }
28724
28972
  return EMPTY_INCOMING_OUTCOME;
28725
28973
  }
28726
28974
  if (isResponseMessage2(message)) {
@@ -28741,6 +28989,7 @@ var AntigravityBackgroundWakeup = class {
28741
28989
  );
28742
28990
  if (tail2 !== null) {
28743
28991
  session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail2.maxStepIndex);
28992
+ session2.sessionOpenStepIndex = Math.max(session2.sessionOpenStepIndex, tail2.maxStepIndex);
28744
28993
  }
28745
28994
  if (tracked.kind === "load") {
28746
28995
  session2.phase = { cancelRequested: false, kind: "idle" };
@@ -28748,29 +28997,45 @@ var AntigravityBackgroundWakeup = class {
28748
28997
  return EMPTY_INCOMING_OUTCOME;
28749
28998
  }
28750
28999
  const prePromptStepIndex = session2.phase.kind === "client-prompt" ? session2.phase.prePromptStepIndex : session2.baselineStepIndex;
28751
- const promptCancelled = session2.phase.kind === "client-prompt" && session2.phase.cancelled || "result" in message && isRecord5(message.result) && readString3(message.result, "stopReason") === "cancelled";
29000
+ const responseStopReason = "result" in message && isRecord5(message.result) ? readString3(message.result, "stopReason") : void 0;
28752
29001
  const tail = await readTranscriptTailState(
28753
29002
  this.#launchEnvironment,
28754
29003
  tracked.sessionId,
28755
29004
  session2.baselineStepIndex
28756
29005
  );
29006
+ const promptCancelled = this.#disposed || session2.phase.kind === "client-prompt" && session2.phase.cancelled || session2.phase.kind === "idle" && session2.phase.cancelRequested || responseStopReason === "cancelled";
28757
29007
  if (tail !== null) {
28758
29008
  session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail.maxStepIndex);
29009
+ this.#syncSubagentCreations(session2, tail.steps);
28759
29010
  if (!promptCancelled) {
28760
- const consumedSubagents = countConsumedSubagentIdles(
28761
- tail.steps,
28762
- prePromptStepIndex,
28763
- session2.baselineStepIndex
28764
- );
28765
- this.#removeSubagentTasks(session2, consumedSubagents);
29011
+ let lastPlannerStepIndex;
29012
+ for (let index2 = tail.steps.length - 1; index2 >= 0; index2 -= 1) {
29013
+ const step = tail.steps[index2];
29014
+ if (step !== void 0 && step.step_index > prePromptStepIndex && step.step_index <= session2.baselineStepIndex && step.type === "PLANNER_RESPONSE") {
29015
+ lastPlannerStepIndex = step.step_index;
29016
+ break;
29017
+ }
29018
+ }
29019
+ if (lastPlannerStepIndex !== void 0) {
29020
+ this.#consumeSubagentIdlesThrough(session2, tail.steps, lastPlannerStepIndex);
29021
+ }
28766
29022
  }
28767
29023
  }
28768
29024
  if (promptCancelled) {
28769
- session2.backgroundTasks.clear();
29025
+ this.#clearAllBackgroundTasks(session2);
28770
29026
  }
28771
29027
  session2.phase = { cancelRequested: promptCancelled, kind: "idle" };
28772
29028
  const bg2 = this.#takeBackgroundTasksUpdate(tracked.sessionId, session2);
28773
- return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates: [bg2] };
29029
+ const rewritePromptCancelled = promptCancelled && "result" in message && isRecord5(message.result) && responseStopReason !== "cancelled";
29030
+ const beforeUpdates = bg2 === null ? [] : [bg2];
29031
+ if (beforeUpdates.length === 0 && !rewritePromptCancelled) {
29032
+ return EMPTY_INCOMING_OUTCOME;
29033
+ }
29034
+ return {
29035
+ afterUpdates: [],
29036
+ beforeUpdates,
29037
+ ...rewritePromptCancelled ? { rewritePromptCancelled: true } : {}
29038
+ };
28774
29039
  }
28775
29040
  if (!isNotificationMessage2(message) || message.method !== methods.client.session.update) {
28776
29041
  return EMPTY_INCOMING_OUTCOME;
@@ -28791,7 +29056,7 @@ var AntigravityBackgroundWakeup = class {
28791
29056
  return EMPTY_INCOMING_OUTCOME;
28792
29057
  case "client-prompt": {
28793
29058
  if (updateKind === "tool_call" || updateKind === "tool_call_update") {
28794
- this.#applyClientPromptToolUpdate(session, update, session.phase.cancelled);
29059
+ await this.#applyClientPromptToolUpdate(sessionId, session, update, session.phase.cancelled);
28795
29060
  }
28796
29061
  return EMPTY_INCOMING_OUTCOME;
28797
29062
  }
@@ -28803,13 +29068,21 @@ var AntigravityBackgroundWakeup = class {
28803
29068
  const existing = session.backgroundTasks.get(toolCallId);
28804
29069
  if (existing !== void 0) {
28805
29070
  if (status === "failed" || status === "cancelled") {
28806
- session.backgroundTasks.delete(toolCallId);
29071
+ if (existing.kind === "subagent") {
29072
+ this.#deleteSubagentTask(session, toolCallId);
29073
+ } else {
29074
+ session.backgroundTasks.delete(toolCallId);
29075
+ }
28807
29076
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28808
29077
  return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
28809
29078
  }
28810
29079
  if (status === "completed") {
28811
29080
  if (session.phase.cancelRequested) {
28812
- session.backgroundTasks.delete(toolCallId);
29081
+ if (existing.kind === "subagent") {
29082
+ this.#deleteSubagentTask(session, toolCallId);
29083
+ } else {
29084
+ session.backgroundTasks.delete(toolCallId);
29085
+ }
28813
29086
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28814
29087
  return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
28815
29088
  }
@@ -28835,20 +29108,27 @@ var AntigravityBackgroundWakeup = class {
28835
29108
  return EMPTY_INCOMING_OUTCOME;
28836
29109
  }
28837
29110
  }
28838
- const subagentTaskId = this.#oldestRunningSubagentId(session);
28839
- if (subagentTaskId !== void 0) {
28840
- const existing = session.backgroundTasks.get(subagentTaskId);
28841
- if (existing !== void 0) {
28842
- session.backgroundTasks.set(subagentTaskId, { ...existing, state: "awaiting-results" });
29111
+ let matchedTaskIds = [];
29112
+ if (this.#hasSubagentTasks(session)) {
29113
+ const tail = await readTranscriptTailState(
29114
+ this.#launchEnvironment,
29115
+ sessionId,
29116
+ session.baselineStepIndex
29117
+ );
29118
+ if (this.#disposed || this.#sessions.get(sessionId) !== session) {
29119
+ return EMPTY_INCOMING_OUTCOME;
29120
+ }
29121
+ if (session.phase.kind !== "idle" || session.phase.cancelRequested) {
29122
+ return EMPTY_INCOMING_OUTCOME;
29123
+ }
29124
+ if (tail !== null) {
29125
+ this.#syncSubagentCreations(session, tail.steps);
29126
+ matchedTaskIds = this.#markTriggeredSubagentIdles(session, tail.steps);
28843
29127
  }
28844
29128
  }
28845
- const startedNotifications = this.#enterWakeup(
28846
- sessionId,
28847
- session,
28848
- subagentTaskId === void 0 ? [] : [subagentTaskId]
28849
- );
29129
+ const startedNotifications = this.#enterWakeup(sessionId, session, matchedTaskIds);
28850
29130
  const extraWakeup = [];
28851
- this.#handleWakeupUpdate(sessionId, session, updateKind, update, extraWakeup);
29131
+ await this.#handleWakeupUpdate(sessionId, session, updateKind, update, extraWakeup);
28852
29132
  return {
28853
29133
  afterUpdates: [],
28854
29134
  beforeUpdates: [...startedNotifications, ...extraWakeup]
@@ -28856,7 +29136,7 @@ var AntigravityBackgroundWakeup = class {
28856
29136
  }
28857
29137
  case "wakeup": {
28858
29138
  const beforeUpdates = [];
28859
- this.#handleWakeupUpdate(sessionId, session, updateKind, update, beforeUpdates);
29139
+ await this.#handleWakeupUpdate(sessionId, session, updateKind, update, beforeUpdates);
28860
29140
  return beforeUpdates.length === 0 ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates };
28861
29141
  }
28862
29142
  default: {
@@ -28865,22 +29145,29 @@ var AntigravityBackgroundWakeup = class {
28865
29145
  }
28866
29146
  }
28867
29147
  };
28868
- #handleWakeupUpdate = (sessionId, session, updateKind, update, beforeUpdates) => {
29148
+ #handleWakeupUpdate = async (sessionId, session, updateKind, update, beforeUpdates) => {
28869
29149
  if (session.phase.kind !== "wakeup") {
28870
29150
  return;
28871
29151
  }
28872
29152
  if (updateKind === "tool_call" || updateKind === "tool_call_update") {
28873
- this.#applyWakeupToolUpdate(sessionId, session, update, beforeUpdates);
29153
+ await this.#applyWakeupToolUpdate(sessionId, session, update, beforeUpdates);
28874
29154
  return;
28875
29155
  }
28876
29156
  if (isWakeupChunkUpdateKind(updateKind)) {
29157
+ const executorError = extractExecutorError(updateKind, update);
28877
29158
  this.#promoteOpenWakeupToolsToBackground(session);
28878
29159
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28879
29160
  if (bg2 !== null) {
28880
29161
  beforeUpdates.push(bg2);
28881
29162
  }
28882
29163
  if (session.phase.openToolIds.size === 0 && session.activeInteractions === 0) {
28883
- this.#setWakeupStreaming(sessionId, session, session.phase.generation, session.phase.openToolIds);
29164
+ this.#setWakeupStreaming(
29165
+ sessionId,
29166
+ session,
29167
+ session.phase.generation,
29168
+ session.phase.openToolIds,
29169
+ executorError
29170
+ );
28884
29171
  }
28885
29172
  }
28886
29173
  };
@@ -28911,8 +29198,8 @@ var AntigravityBackgroundWakeup = class {
28911
29198
  const mustClose = session.phase.kind === "wakeup" || this.#hasSubagentTasks(session);
28912
29199
  if (mustClose) {
28913
29200
  this.#cancelWakeupTimers(session.phase);
28914
- session.backgroundTasks.clear();
28915
- session.phase = { cancelRequested: true, kind: "idle" };
29201
+ this.#clearAllBackgroundTasks(session);
29202
+ session.phase = session.phase.kind === "client-prompt" ? { ...session.phase, cancelled: true } : { cancelRequested: true, kind: "idle" };
28916
29203
  return "close";
28917
29204
  }
28918
29205
  if (session.phase.kind === "client-prompt") {
@@ -28929,7 +29216,7 @@ var AntigravityBackgroundWakeup = class {
28929
29216
  for (const [sessionId, session] of this.#sessions) {
28930
29217
  const wasWakeup = session.phase.kind === "wakeup";
28931
29218
  this.#cancelWakeupTimers(session.phase);
28932
- session.backgroundTasks.clear();
29219
+ this.#clearAllBackgroundTasks(session);
28933
29220
  if (wasWakeup) {
28934
29221
  session.phase = { cancelRequested: false, kind: "idle" };
28935
29222
  this.#emitMetaUpdate(
@@ -28967,6 +29254,7 @@ var FULL_ACCESS_MODE_DESCRIPTION = "Never asks the user: approves file edits and
28967
29254
  var MAXIMUM_STDERR_TAIL_CHARACTERS = 2048;
28968
29255
  var MAXIMUM_PENDING_CONFIG_ECHOES = 16;
28969
29256
  var CANCEL_REQUEST_METHOD2 = "$/cancel_request";
29257
+ var INVALID_THINKING_SIGNATURE_PATTERN = /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/u;
28970
29258
  function readStringProperty(record2, key) {
28971
29259
  const value = record2[key];
28972
29260
  return typeof value === "string" ? value : void 0;
@@ -29090,6 +29378,9 @@ async function prepareAntigravitySessionCancel(clientConnection2, sessionId) {
29090
29378
  }
29091
29379
  return await owner.prepareSessionCancel(sessionId);
29092
29380
  }
29381
+ function takeAntigravityUnusableNativeSession(clientConnection2, sessionId) {
29382
+ return activeConnectionsByClient.get(clientConnection2)?.takeUnusableNativeSession(sessionId) ?? false;
29383
+ }
29093
29384
  var AntigravityAgentConnection = class {
29094
29385
  connection;
29095
29386
  termination;
@@ -29103,6 +29394,8 @@ var AntigravityAgentConnection = class {
29103
29394
  #messageStreams = /* @__PURE__ */ new Map();
29104
29395
  #pendingRequests = /* @__PURE__ */ new Map();
29105
29396
  #pendingConfigEchoes = [];
29397
+ /** Native sessions whose current prompt reported an unusable conversation. */
29398
+ #unusableSessions = /* @__PURE__ */ new Set();
29106
29399
  #latestPermissionMode = { kind: "native" };
29107
29400
  #sessionEstablished = false;
29108
29401
  #closePromise = null;
@@ -29117,7 +29410,8 @@ var AntigravityAgentConnection = class {
29117
29410
  emitMetaUpdate: (notification) => {
29118
29411
  this.#queueMetaUpdate(notification);
29119
29412
  },
29120
- launchEnvironment
29413
+ launchEnvironment,
29414
+ ...options.timer === void 0 ? {} : { timer: options.timer }
29121
29415
  });
29122
29416
  const launch = executableLaunch2(options.command, ["acp"]);
29123
29417
  const child = spawn2(launch.command, [...launch.arguments], {
@@ -29275,6 +29569,7 @@ var AntigravityAgentConnection = class {
29275
29569
  await this.#flushDeliveries();
29276
29570
  return disposition;
29277
29571
  };
29572
+ takeUnusableNativeSession = (sessionId) => this.#unusableSessions.delete(sessionId);
29278
29573
  initialize = async (signal) => {
29279
29574
  signal.throwIfAborted();
29280
29575
  };
@@ -29282,10 +29577,11 @@ var AntigravityAgentConnection = class {
29282
29577
  closeProcess = () => {
29283
29578
  this.#closePromise ??= (async () => {
29284
29579
  try {
29285
- this.#backgroundWakeup.dispose();
29580
+ this.#child.stdout?.pause();
29286
29581
  this.#deliveryAbort.abort(new DOMException("Antigravity ACP connection closed", "AbortError"));
29287
- const captured = await captureProcessTree(this.#child);
29288
29582
  this.connection.close();
29583
+ this.#backgroundWakeup.dispose();
29584
+ const captured = await captureProcessTree(this.#child);
29289
29585
  this.#child.stdin?.end();
29290
29586
  await stopProcessTree(this.#child, captured);
29291
29587
  } finally {
@@ -29384,6 +29680,7 @@ var AntigravityAgentConnection = class {
29384
29680
  case methods.agent.session.prompt: {
29385
29681
  if (sessionId !== void 0) {
29386
29682
  this.#messageStreams.set(sessionId, { kind: "none" });
29683
+ this.#unusableSessions.delete(sessionId);
29387
29684
  }
29388
29685
  return message;
29389
29686
  }
@@ -29507,6 +29804,10 @@ var AntigravityAgentConnection = class {
29507
29804
  }
29508
29805
  const modeState = this.#permissionModes.get(sessionId) ?? { kind: "native" };
29509
29806
  const updateKind = readStringProperty(update, "sessionUpdate");
29807
+ const executorError = updateKind === void 0 ? void 0 : extractExecutorError(updateKind, update);
29808
+ if (executorError !== void 0 && INVALID_THINKING_SIGNATURE_PATTERN.test(executorError)) {
29809
+ this.#unusableSessions.add(sessionId);
29810
+ }
29510
29811
  if (updateKind === "config_option_update") {
29511
29812
  if (this.#consumeConfigEcho(sessionId, update["configOptions"])) {
29512
29813
  return void 0;
@@ -29538,11 +29839,17 @@ var AntigravityAgentConnection = class {
29538
29839
  const readable = rawStream.readable.pipeThrough(
29539
29840
  new TransformStream({
29540
29841
  transform: async (chunk, controller) => {
29842
+ if (this.#closePromise !== null || this.#deliveryAbort.signal.aborted) {
29843
+ return;
29844
+ }
29541
29845
  const transformed = transformIncoming(chunk);
29542
29846
  if (transformed === void 0) {
29543
29847
  return;
29544
29848
  }
29545
29849
  const outcome = await this.#backgroundWakeup.onIncomingMessage(transformed);
29850
+ if (this.#closePromise !== null || this.#deliveryAbort.signal.aborted) {
29851
+ return;
29852
+ }
29546
29853
  if (isResponseMessage3(transformed)) {
29547
29854
  for (const metaUpdate of outcome.beforeUpdates) {
29548
29855
  this.#queueMetaUpdate(metaUpdate);
@@ -29550,7 +29857,11 @@ var AntigravityAgentConnection = class {
29550
29857
  if (outcome.beforeUpdates.length > 0) {
29551
29858
  await this.#flushDeliveries();
29552
29859
  }
29553
- controller.enqueue(transformed);
29860
+ const outgoingResponse = outcome.rewritePromptCancelled === true && "result" in transformed && isRecord5(transformed.result) ? {
29861
+ ...transformed,
29862
+ result: { ...transformed.result, stopReason: "cancelled" }
29863
+ } : transformed;
29864
+ controller.enqueue(outgoingResponse);
29554
29865
  for (const metaUpdate of outcome.afterUpdates) {
29555
29866
  this.#queueMetaUpdate(metaUpdate);
29556
29867
  }
@@ -29649,14 +29960,19 @@ var AntigravityAgentSpecification = class extends InProcessAcpAgentSpecification
29649
29960
  acpProbeTimeoutMilliseconds = ACP_PROBE_TIMEOUT_MILLISECONDS2;
29650
29961
  adapterVersionArguments = Object.freeze([]);
29651
29962
  agentExecutable = "agy";
29652
- createConnection = (options) => new AntigravityAgentConnection(options);
29963
+ #timer;
29964
+ createConnection = (options) => new AntigravityAgentConnection({
29965
+ ...options,
29966
+ ...this.#timer === void 0 ? {} : { timer: this.#timer }
29967
+ });
29653
29968
  id = "antigravity";
29654
29969
  label = "Antigravity";
29655
29970
  minimumSupportedAgentVersion = "1.5.1";
29656
29971
  maximumTestedAgentVersion = "1.5.10";
29657
29972
  authenticationCommand = () => "agy acp --login";
29658
- constructor() {
29973
+ constructor(options) {
29659
29974
  super("MOBIUS_ANTIGRAVITY_PATH");
29975
+ this.#timer = options?.timer;
29660
29976
  }
29661
29977
  resolveInstalledAgentExecutables = async (context) => {
29662
29978
  context.signal.throwIfAborted();
@@ -84121,7 +84437,115 @@ var AgentQueryProcesses = class {
84121
84437
  };
84122
84438
  };
84123
84439
 
84440
+ // src/engine/acp/adapter/antigravity/conversation-handoff.ts
84441
+ import { join as join24 } from "node:path";
84442
+ var TRANSCRIPT_TAIL_BYTES2 = 1048576;
84443
+ var MAXIMUM_HANDOFF_CHARACTERS = 32e3;
84444
+ var MAXIMUM_MESSAGE_CHARACTERS = 4e3;
84445
+ var SESSION_UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
84446
+ var USER_REQUEST_PATTERN = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/u;
84447
+ var HANDOFF_TAG = "previous_conversation";
84448
+ var transcriptStepSchema2 = external_exports.object({
84449
+ content: external_exports.string().optional(),
84450
+ step_index: external_exports.number().int().nonnegative(),
84451
+ type: external_exports.string()
84452
+ });
84453
+ function messageFromStep(step) {
84454
+ const content = step.content?.trim();
84455
+ if (content === void 0 || content.length === 0) {
84456
+ return void 0;
84457
+ }
84458
+ switch (step.type) {
84459
+ case "USER_INPUT": {
84460
+ const request = USER_REQUEST_PATTERN.exec(content)?.[1]?.trim();
84461
+ return request === void 0 || request.length === 0 ? void 0 : { role: "user", text: request };
84462
+ }
84463
+ case "PLANNER_RESPONSE":
84464
+ return { role: "assistant", text: content };
84465
+ default:
84466
+ return void 0;
84467
+ }
84468
+ }
84469
+ async function readConversationMessages(launchEnvironment, nativeSessionId) {
84470
+ const geminiHome = resolveGeminiHome(launchEnvironment);
84471
+ if (geminiHome === void 0 || !SESSION_UUID_PATTERN2.test(nativeSessionId)) {
84472
+ return null;
84473
+ }
84474
+ const tail = await readScopedFileTail(
84475
+ geminiHome,
84476
+ join24("antigravity-cli", "brain", nativeSessionId, ".system_generated", "logs", "transcript.jsonl"),
84477
+ TRANSCRIPT_TAIL_BYTES2
84478
+ );
84479
+ if (tail === null) {
84480
+ return null;
84481
+ }
84482
+ const lines = new TextDecoder().decode(tail.bytes).split("\n");
84483
+ const steps = [];
84484
+ for (const line of lines.slice(tail.offset > 0 ? 1 : 0)) {
84485
+ if (line.trim().length === 0) {
84486
+ continue;
84487
+ }
84488
+ let decoded;
84489
+ try {
84490
+ decoded = JSON.parse(line);
84491
+ } catch {
84492
+ continue;
84493
+ }
84494
+ const parsed = transcriptStepSchema2.safeParse(decoded);
84495
+ if (parsed.success) {
84496
+ steps.push(parsed.data);
84497
+ }
84498
+ }
84499
+ steps.sort((left, right) => left.step_index - right.step_index);
84500
+ const messages = steps.flatMap((step) => {
84501
+ const message = messageFromStep(step);
84502
+ return message === void 0 ? [] : [message];
84503
+ });
84504
+ return { messages, complete: tail.offset === 0 };
84505
+ }
84506
+ async function antigravityConversationHandoff(launchEnvironment, unusableNativeSessionId) {
84507
+ const conversation = await readConversationMessages(launchEnvironment, unusableNativeSessionId);
84508
+ const introduction = "This conversation continues an earlier one that could no longer be sent to the model. Treat the earlier messages below as what the user and you have already said; continue from them without repeating finished work unless the user asks.";
84509
+ if (conversation === null || conversation.messages.length === 0) {
84510
+ return `<${HANDOFF_TAG}>
84511
+ ${introduction}
84512
+ The earlier messages could not be read.
84513
+ </${HANDOFF_TAG}>`;
84514
+ }
84515
+ const entries = [];
84516
+ let length = 0;
84517
+ let omitted = 0;
84518
+ for (let index2 = conversation.messages.length - 1; index2 >= 0; index2 -= 1) {
84519
+ const message = conversation.messages[index2];
84520
+ if (message === void 0) {
84521
+ continue;
84522
+ }
84523
+ const text2 = truncate(message.text, MAXIMUM_MESSAGE_CHARACTERS).replaceAll(
84524
+ `</${HANDOFF_TAG}>`,
84525
+ `</ ${HANDOFF_TAG}>`
84526
+ );
84527
+ const entry = `[${message.role}]
84528
+ ${text2}`;
84529
+ if (length + entry.length > MAXIMUM_HANDOFF_CHARACTERS) {
84530
+ omitted = index2 + 1;
84531
+ break;
84532
+ }
84533
+ entries.unshift(entry);
84534
+ length += entry.length;
84535
+ }
84536
+ const earlierOmitted = omitted > 0 || !conversation.complete;
84537
+ return [
84538
+ `<${HANDOFF_TAG}>`,
84539
+ introduction,
84540
+ ...earlierOmitted ? ["Earlier messages are omitted; the ones below are the most recent."] : [],
84541
+ "",
84542
+ entries.join("\n\n"),
84543
+ `</${HANDOFF_TAG}>`
84544
+ ].join("\n");
84545
+ }
84546
+
84124
84547
  // src/engine/acp/adapter/antigravity/adapter.ts
84548
+ var UNUSABLE_NATIVE_SESSION_MESSAGE = "Antigravity can no longer send this conversation's saved history to the model. Your next message continues in a new Antigravity conversation that carries this conversation's context.";
84125
84549
  var AntigravityAdapter = class {
84126
84550
  #queryProcesses;
84127
84551
  #connector;
@@ -84146,6 +84570,30 @@ var AntigravityAdapter = class {
84146
84570
  this.#executionConnections.bind(execution, nativeSessionId);
84147
84571
  return normalizeOpenedSession(execution, nativeSessionId, response, signal);
84148
84572
  });
84573
+ // `agy acp` adds `systemPrompt.append` to the new conversation's system prompt and keeps it with the conversation.
84574
+ continueInNewSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
84575
+ const { connection } = execution;
84576
+ const handoff2 = await antigravityConversationHandoff(
84577
+ { ...process.env, ...params.scope.agent.environment },
84578
+ params.unusableNativeSessionId
84579
+ );
84580
+ signal.throwIfAborted();
84581
+ const response = await connection.race(
84582
+ connection.connection.agent.request(
84583
+ methods.agent.session.new,
84584
+ {
84585
+ ...sessionWorkspace(params.scope),
84586
+ _meta: { antigravity: { systemPrompt: { append: handoff2 } } }
84587
+ },
84588
+ { cancellationSignal: signal }
84589
+ ),
84590
+ "ACP agent exited while starting a session",
84591
+ signal
84592
+ );
84593
+ const nativeSessionId = createdNativeSessionId(response);
84594
+ this.#executionConnections.bind(execution, nativeSessionId);
84595
+ return normalizeOpenedSession(execution, nativeSessionId, response, signal);
84596
+ });
84149
84597
  openSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
84150
84598
  const { connection } = execution;
84151
84599
  const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
@@ -84191,7 +84639,14 @@ var AntigravityAdapter = class {
84191
84639
  closeSession = (...args) => this.#executionConnections.closeSession(...args);
84192
84640
  releaseSession = (params) => this.#executionConnections.releaseSession(params);
84193
84641
  readNativeHistoryRevision = (params) => this.#executionConnections.readNativeHistoryRevision(params);
84194
- prompt = (...args) => this.#executionConnections.prompt(...args);
84642
+ prompt = async (params) => {
84643
+ const result = await this.#executionConnections.prompt(params);
84644
+ const connection = this.#executionConnections.connection(params);
84645
+ if (connection !== void 0 && takeAntigravityUnusableNativeSession(connection.connection, params.nativeSessionId) && result.stopReason !== "cancelled") {
84646
+ throw new AcpExecutionError(UNUSABLE_NATIVE_SESSION_MESSAGE, {}, NATIVE_SESSION_UNUSABLE_ERROR_CODE);
84647
+ }
84648
+ return result;
84649
+ };
84195
84650
  steer = (...args) => this.#executionConnections.steer(...args);
84196
84651
  renameSession = (...args) => this.#executionConnections.renameSession(...args);
84197
84652
  configureSession = (...args) => this.#executionConnections.configureSession(...args);
@@ -84908,11 +85363,11 @@ function describeEnvironmentProxyRoute(target) {
84908
85363
  }
84909
85364
 
84910
85365
  // src/engine/runtime/observability/diagnostic-log.ts
84911
- import { join as join26 } from "node:path";
85366
+ import { join as join27 } from "node:path";
84912
85367
 
84913
85368
  // src/engine/storage/logs/bounded-log.ts
84914
85369
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
84915
- import { join as join24 } from "node:path";
85370
+ import { join as join25 } from "node:path";
84916
85371
  var BoundedLineLog = class {
84917
85372
  #path;
84918
85373
  #maximumBytes;
@@ -84921,7 +85376,7 @@ var BoundedLineLog = class {
84921
85376
  #onWriteFailure;
84922
85377
  constructor(directory, filename, maximumBytes, onWriteFailure = () => void 0) {
84923
85378
  this.#directory = directory;
84924
- this.#path = join24(directory, filename);
85379
+ this.#path = join25(directory, filename);
84925
85380
  this.#maximumBytes = maximumBytes;
84926
85381
  this.#onWriteFailure = onWriteFailure;
84927
85382
  }
@@ -84972,21 +85427,21 @@ var BoundedLineLog = class {
84972
85427
 
84973
85428
  // src/engine/storage/logs/log-files.ts
84974
85429
  import { readFileSync as readFileSync11 } from "node:fs";
84975
- import { join as join25 } from "node:path";
85430
+ import { join as join26 } from "node:path";
84976
85431
  var DAEMON_LOG_FILENAME = "daemon.log";
84977
85432
  var WORKER_LIFECYCLE_LOG_FILENAME = "worker-lifecycle.log";
84978
85433
  function unhandledRejectionLogFilename(role) {
84979
85434
  return `unhandled-rejections-${role}.log`;
84980
85435
  }
84981
85436
  function logDirectory(dataDirectory) {
84982
- return join25(dataDirectory, "logs");
85437
+ return join26(dataDirectory, "logs");
84983
85438
  }
84984
85439
  function processLogPaths(dataDirectory) {
84985
85440
  return [
84986
85441
  WORKER_LIFECYCLE_LOG_FILENAME,
84987
85442
  unhandledRejectionLogFilename("manager"),
84988
85443
  unhandledRejectionLogFilename("worker")
84989
- ].map((filename) => join25(logDirectory(dataDirectory), filename));
85444
+ ].map((filename) => join26(logDirectory(dataDirectory), filename));
84990
85445
  }
84991
85446
  function readLogText(path6) {
84992
85447
  try {
@@ -85061,7 +85516,7 @@ var RuntimeDiagnosticLog = class {
85061
85516
  this.#maximumBytes = maximumBytes;
85062
85517
  const processLogsDirectory = options.processLogsDirectory;
85063
85518
  this.#sources = [
85064
- { maximumBytes, path: join26(directory, DAEMON_LOG_FILENAME) },
85519
+ { maximumBytes, path: join27(directory, DAEMON_LOG_FILENAME) },
85065
85520
  // The process logs a Runtime does not own, but must read to explain its own deaths.
85066
85521
  ...processLogsDirectory === void 0 ? [] : processLogPaths(processLogsDirectory).map((path6) => ({ maximumBytes: null, path: path6 }))
85067
85522
  ];
@@ -86196,7 +86651,7 @@ function sql(strings, ...params) {
86196
86651
  return new SQL([new StringChunk(str)]);
86197
86652
  }
86198
86653
  _sql.raw = raw;
86199
- function join33(chunks, separator) {
86654
+ function join34(chunks, separator) {
86200
86655
  const result = [];
86201
86656
  for (const [i, chunk] of chunks.entries()) {
86202
86657
  if (i > 0 && separator !== void 0) result.push(separator);
@@ -86204,7 +86659,7 @@ function sql(strings, ...params) {
86204
86659
  }
86205
86660
  return new SQL(result);
86206
86661
  }
86207
- _sql.join = join33;
86662
+ _sql.join = join34;
86208
86663
  function identifier2(value) {
86209
86664
  return new Name(value);
86210
86665
  }
@@ -88349,7 +88804,7 @@ var SQLiteSelectBase = class extends TypedQueryBuilder {
88349
88804
  const baseTableName = this.tableName;
88350
88805
  const tableName = getTableLikeName(table);
88351
88806
  for (const item of extractUsedTable(table)) this.usedTables.add(item);
88352
- if (typeof tableName === "string" && this.config.joins?.some((join33) => join33.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
88807
+ if (typeof tableName === "string" && this.config.joins?.some((join34) => join34.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
88353
88808
  if (!this.isPartialSelect) {
88354
88809
  if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
88355
88810
  if (typeof tableName === "string" && !is(table, SQL)) {
@@ -89188,7 +89643,7 @@ var SQLiteDialect = class {
89188
89643
  if (!joins2) return;
89189
89644
  const withEntries = Object.entries(joins2).filter(([_, v]) => v);
89190
89645
  if (!withEntries.length) return;
89191
- return sql.join(withEntries.map(([k2, join33]) => {
89646
+ return sql.join(withEntries.map(([k2, join34]) => {
89192
89647
  const relation = tableConfig.relations[k2];
89193
89648
  const isSingle2 = is(relation, One2);
89194
89649
  const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
@@ -89199,7 +89654,7 @@ var SQLiteDialect = class {
89199
89654
  table: targetTable,
89200
89655
  mode: isSingle2 ? "first" : "many",
89201
89656
  schema,
89202
- queryConfig: join33,
89657
+ queryConfig: join34,
89203
89658
  tableConfig: schema[relation.targetTableName],
89204
89659
  relationWhere: filter,
89205
89660
  isNested: true,
@@ -89213,7 +89668,7 @@ var SQLiteDialect = class {
89213
89668
  key: k2,
89214
89669
  selection: innerQuery.selection,
89215
89670
  isArray: !isSingle2,
89216
- isOptional: (relation.optional ?? false) || join33 !== true && !!join33.where
89671
+ isOptional: (relation.optional ?? false) || join34 !== true && !!join34.where
89217
89672
  });
89218
89673
  const jsonColumns = sql.join(innerQuery.selection.map((s) => {
89219
89674
  return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
@@ -89829,7 +90284,7 @@ var SQLiteUpdateBase = class {
89829
90284
  createJoin(joinType) {
89830
90285
  return ((table, on2) => {
89831
90286
  const tableName = getTableLikeName(table);
89832
- if (typeof tableName === "string" && this.config.joins.some((join33) => join33.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
90287
+ if (typeof tableName === "string" && this.config.joins.some((join34) => join34.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
89833
90288
  if (typeof on2 === "function") {
89834
90289
  const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
89835
90290
  on2 = on2(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
@@ -90783,7 +91238,7 @@ var SessionEventCacheTable = class {
90783
91238
  // src/engine/storage/sqlite/local-databases.ts
90784
91239
  import { createHash as createHash4 } from "node:crypto";
90785
91240
  import { existsSync as existsSync9 } from "node:fs";
90786
- import { join as join27 } from "node:path";
91241
+ import { join as join28 } from "node:path";
90787
91242
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
90788
91243
 
90789
91244
  // src/engine/generated/acp-session-store-migrations.ts
@@ -91036,9 +91491,9 @@ var LocalSqliteDatabase = class {
91036
91491
  function channelSessionDatabasePaths(stateDirectory, channelId) {
91037
91492
  const channelHash = createHash4("sha256").update(channelId).digest("hex");
91038
91493
  return {
91039
- cancellations: join27(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
91040
- events: join27(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
91041
- sessions: join27(stateDirectory, "sessions", `${channelHash}.sqlite`)
91494
+ cancellations: join28(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
91495
+ events: join28(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
91496
+ sessions: join28(stateDirectory, "sessions", `${channelHash}.sqlite`)
91042
91497
  };
91043
91498
  }
91044
91499
  function recordAppliedAdmissionOrder(path6) {
@@ -92793,6 +93248,30 @@ async function restoreSession(session, signal, recovery) {
92793
93248
  conversation !== void 0 && session.restored ? conversation.updatedAt : (/* @__PURE__ */ new Date()).toISOString()
92794
93249
  );
92795
93250
  }
93251
+ async function continueInNewNativeSession(session, signal, unusableNativeSessionId) {
93252
+ const stored = session.metrics.measureSync("session-state-read", () => session.store.read(session.sessionId));
93253
+ const conversation = stored instanceof FoundStoredSession ? stored.session : void 0;
93254
+ if (conversation === void 0 || conversation.nativeSessionId !== unusableNativeSessionId || conversation.agentId !== session.agentId || conversation.cwd !== session.cwd || !arraysEqual(conversation.additionalDirectories, session.additionalDirectories)) {
93255
+ throw new AcpExecutionError(
93256
+ "The Session no longer continues the native conversation that failed",
93257
+ {},
93258
+ "session_identity_mismatch"
93259
+ );
93260
+ }
93261
+ const opened = await session.metrics.measure(
93262
+ "session-new",
93263
+ async () => await session.continueSession(unusableNativeSessionId, signal)
93264
+ );
93265
+ session.selectNativeSession(opened.nativeSessionId);
93266
+ session.setPrompted(true);
93267
+ session.setSessionTitle(conversation.title);
93268
+ session.setRestored(true);
93269
+ session.startExecutionOnlyCapture();
93270
+ session.applySessionOpened(opened);
93271
+ await session.restoreStoredConfigurations(conversation, signal);
93272
+ signal.throwIfAborted();
93273
+ session.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
93274
+ }
92796
93275
 
92797
93276
  // src/engine/session/live/agent-session.ts
92798
93277
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -93013,6 +93492,23 @@ var AgentSession = class _AgentSession {
93013
93492
  promptSuggestions,
93014
93493
  timer
93015
93494
  );
93495
+ /**
93496
+ * Starts a process that continues the Session in a new native conversation, in place of the stored one whose
93497
+ * prompts failed with `native_session_unusable`.
93498
+ */
93499
+ static continueUnusable = async (options, unusableNativeSessionId, getObserver, agentCommand, store, adapter, promptSuggestions, timer) => await _AgentSession.#start(
93500
+ options,
93501
+ getObserver,
93502
+ agentCommand,
93503
+ store,
93504
+ async (runtime) => await runtime.#writeNativeHistory(
93505
+ async () => await continueInNewNativeSession(runtime, options.signal, unusableNativeSessionId)
93506
+ ),
93507
+ unmeasuredOperationMetrics,
93508
+ adapter,
93509
+ promptSuggestions,
93510
+ timer
93511
+ );
93016
93512
  belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId && this.#cwd === cwd && arraysEqual(this.#additionalDirectories, additionalDirectories);
93017
93513
  usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
93018
93514
  writeStoredSession = (updatedAt) => {
@@ -93861,6 +94357,17 @@ var AgentSession = class _AgentSession {
93861
94357
  generateTitle: this.#generateTitle
93862
94358
  });
93863
94359
  createSession = (signal) => this.#adapter.createSession(this.#sessionParams(signal));
94360
+ continueSession = async (unusableNativeSessionId, signal) => {
94361
+ const continueInNewSession = this.#adapter.continueInNewSession;
94362
+ if (continueInNewSession === void 0) {
94363
+ throw new AcpExecutionError(
94364
+ "This Agent cannot continue a conversation in a new native conversation",
94365
+ {},
94366
+ "session_restore_unsupported"
94367
+ );
94368
+ }
94369
+ return await continueInNewSession({ ...this.#sessionParams(signal), unusableNativeSessionId });
94370
+ };
93864
94371
  openSession = (signal) => this.#adapter.openSession({ ...this.#sessionParams(signal), nativeSessionId: this.nativeSessionId() });
93865
94372
  openSessionWithReplay = async (signal) => (await this.#loadSession(signal)).opened;
93866
94373
  setConfigOptions(options) {
@@ -94643,6 +95150,7 @@ var SessionManager2 = class {
94643
95150
  }
94644
95151
  } catch (error62) {
94645
95152
  const failedRuntime = this.#executionProcesses.get(options2.sessionId);
95153
+ const unusableNativeSessionId = error62 instanceof AcpExecutionError && error62.code === NATIVE_SESSION_UNUSABLE_ERROR_CODE ? failedRuntime?.nativeSessionId() : void 0;
94646
95154
  if (failedRuntime !== void 0) {
94647
95155
  await this.#retireSessionProcess(
94648
95156
  options2.sessionId,
@@ -94653,6 +95161,9 @@ var SessionManager2 = class {
94653
95161
  if (cancelled()) {
94654
95162
  return { stopReason: "cancelled" };
94655
95163
  }
95164
+ if (unusableNativeSessionId !== void 0 && unusableNativeSessionId.length > 0) {
95165
+ await this.#continueInNewNativeSession(options2, unusableNativeSessionId);
95166
+ }
94656
95167
  if (error62 instanceof AcpExecutionError) {
94657
95168
  throw error62;
94658
95169
  }
@@ -94669,6 +95180,42 @@ var SessionManager2 = class {
94669
95180
  }
94670
95181
  }
94671
95182
  });
95183
+ /**
95184
+ * Moves a Session off a native conversation the Agent can no longer continue before its failed prompt settles,
95185
+ * so the member's next prompt reaches a conversation that works. When this fails, the next prompt fails the same
95186
+ * way and tries again.
95187
+ */
95188
+ async #continueInNewNativeSession(options, unusableNativeSessionId) {
95189
+ if (options.adapter.continueInNewSession === void 0) {
95190
+ return;
95191
+ }
95192
+ try {
95193
+ await this.#executionProcesses.prepare(
95194
+ options.sessionId,
95195
+ async () => this.#startRetainedSessionProcess(
95196
+ options,
95197
+ async () => await AgentSession.continueUnusable(
95198
+ options,
95199
+ unusableNativeSessionId,
95200
+ () => this.#runtimeObserver,
95201
+ this.#executions.agentCommand,
95202
+ this.#store,
95203
+ options.adapter,
95204
+ this.promptSuggestions,
95205
+ this.#timer
95206
+ )
95207
+ )
95208
+ );
95209
+ } catch (error62) {
95210
+ if (options.signal.aborted) {
95211
+ return;
95212
+ }
95213
+ console.warn(
95214
+ `[${options.agent.id}-acp] The Session could not continue in a new native conversation`,
95215
+ error62
95216
+ );
95217
+ }
95218
+ }
94672
95219
  respondPermission = async (options) => {
94673
95220
  this.#assertOpen(options.sessionId);
94674
95221
  const runtime = this.#executionProcesses.get(options.sessionId);
@@ -96051,7 +96598,7 @@ var SessionTurns = class {
96051
96598
 
96052
96599
  // src/engine/session/workspace/workspace-directory.ts
96053
96600
  import { homedir as homedir4 } from "node:os";
96054
- import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute16, join as join28, normalize as normalize2, relative as relative3 } from "node:path";
96601
+ import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute16, join as join29, normalize as normalize2, relative as relative3 } from "node:path";
96055
96602
 
96056
96603
  // src/engine/session/workspace/local-authorization-error.ts
96057
96604
  var LocalAuthorizationError = class extends OperationError {
@@ -96197,7 +96744,7 @@ var WorkspaceDirectoryService = class {
96197
96744
  continue;
96198
96745
  }
96199
96746
  try {
96200
- const path6 = await this.resolvePath(join28(target, child.name), signal);
96747
+ const path6 = await this.resolvePath(join29(target, child.name), signal);
96201
96748
  entries.push({ directoryId: encodePath(path6), name: child.name });
96202
96749
  } catch (cause) {
96203
96750
  signal.throwIfAborted();
@@ -96382,13 +96929,13 @@ function buildSessionLayer(options) {
96382
96929
 
96383
96930
  // src/engine/session/content/external-content-store.ts
96384
96931
  import { createHash as createHash8 } from "node:crypto";
96385
- import { extname as extname2, join as join30 } from "node:path";
96932
+ import { extname as extname2, join as join31 } from "node:path";
96386
96933
  import { pathToFileURL as pathToFileURL3 } from "node:url";
96387
96934
 
96388
96935
  // src/engine/storage/files/scratch-directory.ts
96389
96936
  import { randomUUID as randomUUID18 } from "node:crypto";
96390
96937
  import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as readFile7, realpath as realpath7, rename as rename4, rm as rm5, stat as stat6, utimes, writeFile as writeFile2 } from "node:fs/promises";
96391
- import { dirname as dirname11, join as join29 } from "node:path";
96938
+ import { dirname as dirname11, join as join30 } from "node:path";
96392
96939
  async function atomicWrite(path6, bytes, signal) {
96393
96940
  const temporary = `${path6}.${randomUUID18()}.tmp`;
96394
96941
  try {
@@ -96402,7 +96949,7 @@ async function atomicWrite(path6, bytes, signal) {
96402
96949
  var ScratchDirectory = class {
96403
96950
  #root;
96404
96951
  constructor(parent) {
96405
- this.#root = join29(parent, randomUUID18());
96952
+ this.#root = join30(parent, randomUUID18());
96406
96953
  }
96407
96954
  /** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
96408
96955
  refreshLease = async (leaseMilliseconds) => {
@@ -96413,7 +96960,7 @@ var ScratchDirectory = class {
96413
96960
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
96414
96961
  continue;
96415
96962
  }
96416
- const path6 = join29(dirname11(this.#root), directory.name);
96963
+ const path6 = join30(dirname11(this.#root), directory.name);
96417
96964
  if (path6 === this.#root) {
96418
96965
  continue;
96419
96966
  }
@@ -96428,10 +96975,10 @@ var ScratchDirectory = class {
96428
96975
  };
96429
96976
  /** Writes `bytes` atomically to `<group>/<name>` with owner-only permissions and returns the path. */
96430
96977
  write = async (group, name2, bytes, signal) => {
96431
- const directory = join29(this.#root, group);
96978
+ const directory = join30(this.#root, group);
96432
96979
  await mkdir5(directory, { mode: 448, recursive: true });
96433
96980
  signal.throwIfAborted();
96434
- const path6 = join29(directory, name2);
96981
+ const path6 = join30(directory, name2);
96435
96982
  await atomicWrite(path6, bytes, signal);
96436
96983
  return path6;
96437
96984
  };
@@ -96482,7 +97029,7 @@ var LocalExternalContentStore = class {
96482
97029
  #expirationTimer;
96483
97030
  #cleanup = Promise.resolve();
96484
97031
  constructor(stateDirectory) {
96485
- this.#scratch = new ScratchDirectory(join30(stateDirectory, "tmp", "session-content"));
97032
+ this.#scratch = new ScratchDirectory(join31(stateDirectory, "tmp", "session-content"));
96486
97033
  this.#expirationTimer = setInterval(() => {
96487
97034
  void this.#expire().catch(() => void 0);
96488
97035
  }, 6e4);
@@ -96890,7 +97437,7 @@ var AgentProcessPool = class {
96890
97437
 
96891
97438
  // src/engine/session/settings/agent-settings-cache.ts
96892
97439
  import { createHash as createHash9, randomUUID as randomUUID19 } from "node:crypto";
96893
- import { join as join31 } from "node:path";
97440
+ import { join as join32 } from "node:path";
96894
97441
  var CACHE_FILE_LIMIT = 32 * 1024 * 1024;
96895
97442
  var CACHE_FORMAT = 1;
96896
97443
  var generationSchema = external_exports.union([external_exports.literal("initial"), external_exports.uuid()]);
@@ -96955,8 +97502,8 @@ var AgentSettingsCache = class {
96955
97502
  #generationPath;
96956
97503
  #generation = 0;
96957
97504
  constructor(stateDirectory) {
96958
- this.#directory = join31(stateDirectory, "agent-settings");
96959
- this.#generationPath = join31(this.#directory, "generation");
97505
+ this.#directory = join32(stateDirectory, "agent-settings");
97506
+ this.#generationPath = join32(this.#directory, "generation");
96960
97507
  }
96961
97508
  get generation() {
96962
97509
  return this.#generation;
@@ -96967,7 +97514,7 @@ var AgentSettingsCache = class {
96967
97514
  };
96968
97515
  open = async (agent2, signal) => {
96969
97516
  const inspections = /* @__PURE__ */ new Map();
96970
- const path6 = join31(this.#directory, `${hash2(agent2.id)}.json`);
97517
+ const path6 = join32(this.#directory, `${hash2(agent2.id)}.json`);
96971
97518
  const fingerprint = hash2([
96972
97519
  agent2.agentVersion,
96973
97520
  agent2.adapterVersion,
@@ -97992,7 +98539,7 @@ function createContentWriteCommands(context) {
97992
98539
  import { WebSocket as WebSocket5 } from "undici";
97993
98540
 
97994
98541
  // src/engine/session/content/session-files.ts
97995
- import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as join32, normalize as normalize3, resolve as resolve17 } from "node:path";
98542
+ import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as join33, normalize as normalize3, resolve as resolve17 } from "node:path";
97996
98543
  import { fileURLToPath as fileURLToPath2 } from "node:url";
97997
98544
  function requestedPath(value) {
97998
98545
  if (value.includes("\0")) {
@@ -98016,7 +98563,7 @@ async function resolveFile(value, workingDirectory, signal) {
98016
98563
  if (isAbsolute17(requested.path) && normalize3(requested.path) !== requested.path) {
98017
98564
  return null;
98018
98565
  }
98019
- const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [join32(workingDirectory, requested.path), requested.path] : [resolve17(workingDirectory, requested.path)];
98566
+ const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [join33(workingDirectory, requested.path), requested.path] : [resolve17(workingDirectory, requested.path)];
98020
98567
  for (const candidate of candidates) {
98021
98568
  if (!isAbsolute17(candidate) || normalize3(candidate) !== candidate) {
98022
98569
  continue;
@@ -100593,4 +101140,4 @@ export {
100593
101140
  * MIT Licensed
100594
101141
  *)
100595
101142
  */
100596
- //# sourceMappingURL=chunk-PVKEDOVN.js.map
101143
+ //# sourceMappingURL=chunk-TPFOWHSZ.js.map