@moxt-ai/mobius 0.0.458 → 0.0.460

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 (49) hide show
  1. package/dist/{chunk-TDFSYA4U.js → chunk-APGZM3B3.js} +782 -127
  2. package/dist/{chunk-TDFSYA4U.js.map → chunk-APGZM3B3.js.map} +4 -4
  3. package/dist/{chunk-BHWFDFZG.js → chunk-WOA2UFZO.js} +2 -2
  4. package/dist/{chunk-BHWFDFZG.js.map → chunk-WOA2UFZO.js.map} +1 -1
  5. package/dist/{cli-DHEOX6YM.js → cli-AYXN6EC5.js} +21 -4
  6. package/dist/cli-AYXN6EC5.js.map +7 -0
  7. package/dist/cli.js +2 -2
  8. package/dist/daemon/lifecycle/daemon.d.ts.map +1 -1
  9. package/dist/daemon/lifecycle/daemon.js +18 -1
  10. package/dist/daemon/lifecycle/daemon.js.map +1 -1
  11. package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/antigravity/agent-connection.js +208 -1
  13. package/dist/engine/acp/adapter/antigravity/agent-connection.js.map +1 -1
  14. package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts.map +1 -1
  15. package/dist/engine/acp/adapter/antigravity/background-wakeup.js +312 -25
  16. package/dist/engine/acp/adapter/antigravity/background-wakeup.js.map +1 -1
  17. package/dist/engine/agent/specification/vendors/antigravity-agent.d.ts +1 -1
  18. package/dist/engine/agent/specification/vendors/antigravity-agent.js +1 -1
  19. package/dist/engine/runtime/observability/diagnostic-log.d.ts.map +1 -1
  20. package/dist/engine/runtime/observability/diagnostic-log.js +3 -0
  21. package/dist/engine/runtime/observability/diagnostic-log.js.map +1 -1
  22. package/dist/engine/runtime/relay/connect.d.ts +4 -0
  23. package/dist/engine/runtime/relay/connect.d.ts.map +1 -1
  24. package/dist/engine/runtime/relay/connect.js +86 -11
  25. package/dist/engine/runtime/relay/connect.js.map +1 -1
  26. package/dist/engine/runtime/relay/diagnostics.d.ts +7 -1
  27. package/dist/engine/runtime/relay/diagnostics.d.ts.map +1 -1
  28. package/dist/engine/runtime/relay/diagnostics.js +8 -1
  29. package/dist/engine/runtime/relay/diagnostics.js.map +1 -1
  30. package/dist/engine/runtime/relay/liveness.d.ts +1 -0
  31. package/dist/engine/runtime/relay/liveness.d.ts.map +1 -1
  32. package/dist/engine/runtime/relay/liveness.js +21 -2
  33. package/dist/engine/runtime/relay/liveness.js.map +1 -1
  34. package/dist/engine/runtime/relay/run-relay-connection.d.ts.map +1 -1
  35. package/dist/engine/runtime/relay/run-relay-connection.js +33 -5
  36. package/dist/engine/runtime/relay/run-relay-connection.js.map +1 -1
  37. package/dist/engine/runtime/relay/runtime-revocation.d.ts +3 -0
  38. package/dist/engine/runtime/relay/runtime-revocation.d.ts.map +1 -1
  39. package/dist/engine/runtime/relay/runtime-revocation.js +6 -3
  40. package/dist/engine/runtime/relay/runtime-revocation.js.map +1 -1
  41. package/dist/engine/runtime/run.d.ts.map +1 -1
  42. package/dist/engine/runtime/run.js +15 -5
  43. package/dist/engine/runtime/run.js.map +1 -1
  44. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  45. package/dist/engine/session/live/agent-session.js +71 -12
  46. package/dist/engine/session/live/agent-session.js.map +1 -1
  47. package/dist/engine.js +2 -2
  48. package/package.json +1 -1
  49. package/dist/cli-DHEOX6YM.js.map +0 -7
@@ -5,7 +5,7 @@ import {
5
5
  __toESM,
6
6
  __using,
7
7
  package_default
8
- } from "./chunk-BHWFDFZG.js";
8
+ } from "./chunk-WOA2UFZO.js";
9
9
 
10
10
  // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
11
11
  var require_ignore = __commonJS({
@@ -808,8 +808,8 @@ var require_ignore = __commonJS({
808
808
  });
809
809
 
810
810
  // src/engine/runtime/relay/runtime-revocation.ts
811
- var runtimeRevocationCloseCode = 1008;
812
- var runtimeRevocationCloseReason = "Runtime revoked";
811
+ var RUNTIME_REVOCATION_CLOSE_CODE = 1008;
812
+ var RUNTIME_REVOCATION_CLOSE_REASON = "Runtime revoked";
813
813
  var RuntimeRelayRevokedError = class extends Error {
814
814
  code = "runtime_relay_revoked";
815
815
  closeCode;
@@ -821,8 +821,11 @@ var RuntimeRelayRevokedError = class extends Error {
821
821
  this.name = "RuntimeRelayRevokedError";
822
822
  }
823
823
  };
824
+ function createRuntimeRelayRevokedError(options = {}) {
825
+ return new RuntimeRelayRevokedError(RUNTIME_REVOCATION_CLOSE_CODE, RUNTIME_REVOCATION_CLOSE_REASON, options);
826
+ }
824
827
  function isRuntimeRelayRevocation(closeCode, closeReason) {
825
- return closeCode === runtimeRevocationCloseCode && closeReason === runtimeRevocationCloseReason;
828
+ return closeCode === RUNTIME_REVOCATION_CLOSE_CODE && closeReason === RUNTIME_REVOCATION_CLOSE_REASON;
826
829
  }
827
830
 
828
831
  // src/engine/runtime/engine.ts
@@ -27996,6 +27999,61 @@ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
27996
27999
  import { spawn as spawn2 } from "node:child_process";
27997
28000
  import { randomUUID as randomUUID3 } from "node:crypto";
27998
28001
 
28002
+ // src/engine/agent/discovery/agent-version.ts
28003
+ function parseVersion(value) {
28004
+ const match = /(?:^|[^0-9])v?(\d+(?:\.\d+)+)(?:-([0-9A-Za-z.-]+))?/u.exec(value);
28005
+ if (match?.[1] === void 0) {
28006
+ return null;
28007
+ }
28008
+ return {
28009
+ core: match[1].split(".").map(Number),
28010
+ prerelease: match[2]?.split(".") ?? []
28011
+ };
28012
+ }
28013
+ function comparePrerelease(left, right) {
28014
+ if (left.length === 0 || right.length === 0) {
28015
+ return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
28016
+ }
28017
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
28018
+ const leftPart = left[index2];
28019
+ const rightPart = right[index2];
28020
+ if (leftPart === void 0 || rightPart === void 0) {
28021
+ return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
28022
+ }
28023
+ if (leftPart === rightPart) {
28024
+ continue;
28025
+ }
28026
+ const leftNumber = /^\d+$/u.test(leftPart) ? Number(leftPart) : null;
28027
+ const rightNumber = /^\d+$/u.test(rightPart) ? Number(rightPart) : null;
28028
+ if (leftNumber !== null && rightNumber !== null) {
28029
+ return Math.sign(leftNumber - rightNumber);
28030
+ }
28031
+ if (leftNumber !== null || rightNumber !== null) {
28032
+ return leftNumber !== null ? -1 : 1;
28033
+ }
28034
+ return leftPart.localeCompare(rightPart);
28035
+ }
28036
+ return 0;
28037
+ }
28038
+ function compareAgentVersions(left, right) {
28039
+ const parsedLeft = parseVersion(left);
28040
+ const parsedRight = parseVersion(right);
28041
+ if (parsedLeft === null || parsedRight === null) {
28042
+ return null;
28043
+ }
28044
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
28045
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
28046
+ if (difference !== 0) {
28047
+ return Math.sign(difference);
28048
+ }
28049
+ }
28050
+ return comparePrerelease(parsedLeft.prerelease, parsedRight.prerelease);
28051
+ }
28052
+ function isAgentVersionSupported(reportedVersion, minimumSupportedVersion) {
28053
+ const comparison = compareAgentVersions(reportedVersion, minimumSupportedVersion);
28054
+ return comparison === null ? null : comparison >= 0;
28055
+ }
28056
+
27999
28057
  // src/engine/util/process/executable.ts
28000
28058
  import { spawn } from "node:child_process";
28001
28059
  import { stat as stat3 } from "node:fs/promises";
@@ -29007,8 +29065,10 @@ var SUBAGENT_CONVERSATION_ID_PATTERN = /"conversationId"\s*:\s*"([0-9a-f]{8}-[0-
29007
29065
  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;
29008
29066
  var AGENT_EXECUTOR_ERROR_PATTERN = /^\s*⚠ agent executor error:\s*(.+?)\s*$/su;
29009
29067
  var TASK_RESULT_SENDER_PATTERN = /\bsender=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(task-\d+)\b/giu;
29068
+ var BACKGROUND_TASK_CREATED_PATTERN = /\bTool is running as a background task with task id:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(task-\d+)\b/iu;
29010
29069
  var SUBAGENT_CREATED_MARKER = "Created the following subagent";
29011
29070
  var MAXIMUM_TOOL_DESCRIPTION_CHARS = 500;
29071
+ var MINIMUM_TRUNCATED_MATCH_CHARS = 16;
29012
29072
  var transcriptStepSchema = external_exports.object({
29013
29073
  content: external_exports.string().optional(),
29014
29074
  status: external_exports.string().optional(),
@@ -29209,15 +29269,80 @@ function inspectToolMetadata(update, previous) {
29209
29269
  }
29210
29270
  }
29211
29271
  }
29272
+ const matchText = readInputString(inputs, "CommandLine") ?? readInputString(inputs, "Prompt") ?? readInputString(inputs, "Description") ?? previous?.matchText;
29212
29273
  const description = readInputString(inputs, "toolSummary") ?? readInputString(inputs, "Description") ?? readInputString(inputs, "Role") ?? readInputString(inputs, "CommandLine") ?? readInputString(inputs, "Prompt") ?? readString3(update, "title") ?? previous?.description;
29213
29274
  return {
29214
29275
  category,
29215
29276
  description: description === void 0 ? void 0 : truncate(description, MAXIMUM_TOOL_DESCRIPTION_CHARS),
29216
29277
  isDaemon,
29278
+ matchText,
29217
29279
  subagentKillAll,
29218
29280
  subagentKillIds: [...subagentKillIds]
29219
29281
  };
29220
29282
  }
29283
+ function isBackgroundableCategory(category) {
29284
+ return category === "command" || category === "schedule" || category === "workflow";
29285
+ }
29286
+ function decodeTranscriptArg(value) {
29287
+ if (typeof value !== "string") {
29288
+ return value;
29289
+ }
29290
+ try {
29291
+ return JSON.parse(value);
29292
+ } catch {
29293
+ return value;
29294
+ }
29295
+ }
29296
+ function readTranscriptArgString(args, key) {
29297
+ const raw = args[key];
29298
+ if (raw === void 0) {
29299
+ return void 0;
29300
+ }
29301
+ const decoded = decodeTranscriptArg(raw);
29302
+ if (typeof decoded !== "string") {
29303
+ return void 0;
29304
+ }
29305
+ const stripped = typeof raw === "string" && decoded === raw && decoded.startsWith('"') ? decoded.slice(1) : decoded;
29306
+ const trimmed = stripped.trim();
29307
+ return trimmed.length > 0 ? trimmed : void 0;
29308
+ }
29309
+ function readTranscriptToolCallInfo(raw) {
29310
+ if (!isRecord5(raw)) {
29311
+ return null;
29312
+ }
29313
+ const name2 = readString3(raw, "name");
29314
+ const category = name2 === "run_command" ? "command" : name2 === "schedule" ? "schedule" : name2 === "run_workflow" ? "workflow" : null;
29315
+ const args = isRecord5(raw["args"]) ? raw["args"] : void 0;
29316
+ const isDaemon = args !== void 0 && (decodeTranscriptArg(args["IsDaemon"]) === true || readTranscriptArgString(args, "CronExpression") !== void 0);
29317
+ const matchText = args === void 0 ? void 0 : readTranscriptArgString(args, "CommandLine") ?? readTranscriptArgString(args, "Prompt") ?? readTranscriptArgString(args, "Description");
29318
+ return { category, isDaemon, matchText };
29319
+ }
29320
+ function matchesCandidateText(candidateText, transcriptText) {
29321
+ if (candidateText === void 0 || transcriptText === void 0) {
29322
+ return false;
29323
+ }
29324
+ if (candidateText === transcriptText) {
29325
+ return true;
29326
+ }
29327
+ const shorter = candidateText.length <= transcriptText.length ? candidateText : transcriptText;
29328
+ const longer = candidateText.length <= transcriptText.length ? transcriptText : candidateText;
29329
+ return shorter.length >= MINIMUM_TRUNCATED_MATCH_CHARS && longer.startsWith(shorter);
29330
+ }
29331
+ function extractTaskResultSenderIds(sessionId, steps, minStepExclusive, maxStepInclusive) {
29332
+ const targetSessionId = sessionId.toLowerCase();
29333
+ const received = /* @__PURE__ */ new Set();
29334
+ for (const step of steps) {
29335
+ if (step.step_index <= minStepExclusive || step.step_index > maxStepInclusive || step.type !== "SYSTEM_MESSAGE" || step.content === void 0) {
29336
+ continue;
29337
+ }
29338
+ for (const match of step.content.matchAll(TASK_RESULT_SENDER_PATTERN)) {
29339
+ if (match[1]?.toLowerCase() === targetSessionId && match[2] !== void 0) {
29340
+ received.add(match[2]);
29341
+ }
29342
+ }
29343
+ }
29344
+ return received;
29345
+ }
29221
29346
  function backgroundKindFor(category) {
29222
29347
  switch (category) {
29223
29348
  case "command":
@@ -29275,6 +29400,14 @@ var AntigravityBackgroundWakeup = class {
29275
29400
  }
29276
29401
  const created = {
29277
29402
  activeInteractions: 0,
29403
+ backgroundCorrelation: {
29404
+ boundCreationSteps: /* @__PURE__ */ new Set(),
29405
+ daemonNativeTaskIds: /* @__PURE__ */ new Set(),
29406
+ deliveredNativeTaskIds: /* @__PURE__ */ new Set(),
29407
+ nativeTaskIdByToolCallId: /* @__PURE__ */ new Map(),
29408
+ pendingCandidates: [],
29409
+ toolCallIdByNativeTaskId: /* @__PURE__ */ new Map()
29410
+ },
29278
29411
  backgroundTasks: /* @__PURE__ */ new Map(),
29279
29412
  baselineStepIndex: -1,
29280
29413
  lastEmittedBackgroundKey: "[]",
@@ -29287,8 +29420,9 @@ var AntigravityBackgroundWakeup = class {
29287
29420
  pendingToolCallIds: []
29288
29421
  },
29289
29422
  toolMetadata: /* @__PURE__ */ new Map(),
29423
+ wakeupCompletedOpenBgCandidates: /* @__PURE__ */ new Set(),
29290
29424
  wakeupGeneration: 0,
29291
- wakeupPendingTaskResults: 0,
29425
+ wakeupOwedToolCallIds: /* @__PURE__ */ new Set(),
29292
29426
  wakeupSettledStepIndex: null,
29293
29427
  wakeupStageSeq: 0
29294
29428
  };
@@ -29360,8 +29494,19 @@ var AntigravityBackgroundWakeup = class {
29360
29494
  }
29361
29495
  }
29362
29496
  };
29497
+ #deleteBackgroundTask = (session, toolCallId) => {
29498
+ session.backgroundTasks.delete(toolCallId);
29499
+ session.wakeupOwedToolCallIds.delete(toolCallId);
29500
+ session.wakeupCompletedOpenBgCandidates.delete(toolCallId);
29501
+ this.#removeBackgroundCandidate(session, toolCallId);
29502
+ session.backgroundCorrelation.nativeTaskIdByToolCallId.delete(toolCallId);
29503
+ };
29363
29504
  #clearAllBackgroundTasks = (session) => {
29364
29505
  session.backgroundTasks.clear();
29506
+ session.wakeupOwedToolCallIds.clear();
29507
+ session.wakeupCompletedOpenBgCandidates.clear();
29508
+ session.backgroundCorrelation.pendingCandidates.length = 0;
29509
+ session.backgroundCorrelation.nativeTaskIdByToolCallId.clear();
29365
29510
  session.subagents.conversationIdByToolCallId.clear();
29366
29511
  session.subagents.pendingToolCallIds.length = 0;
29367
29512
  };
@@ -29371,7 +29516,101 @@ var AntigravityBackgroundWakeup = class {
29371
29516
  if (task.kind === "subagent") {
29372
29517
  this.#deleteSubagentTask(session, taskId);
29373
29518
  } else {
29374
- session.backgroundTasks.delete(taskId);
29519
+ this.#deleteBackgroundTask(session, taskId);
29520
+ }
29521
+ }
29522
+ }
29523
+ };
29524
+ #recordBackgroundCandidate = (session, toolCallId, meta3) => {
29525
+ if (meta3.isDaemon || !isBackgroundableCategory(meta3.category)) {
29526
+ return;
29527
+ }
29528
+ if (session.backgroundCorrelation.nativeTaskIdByToolCallId.has(toolCallId)) {
29529
+ return;
29530
+ }
29531
+ const candidates = session.backgroundCorrelation.pendingCandidates;
29532
+ const existingIndex = candidates.findIndex((candidate) => candidate.toolCallId === toolCallId);
29533
+ if (existingIndex !== -1) {
29534
+ const existing = candidates[existingIndex];
29535
+ if (existing !== void 0 && existing.matchText === void 0 && meta3.matchText !== void 0) {
29536
+ candidates[existingIndex] = { ...existing, matchText: meta3.matchText };
29537
+ }
29538
+ return;
29539
+ }
29540
+ candidates.push({
29541
+ category: meta3.category,
29542
+ matchText: meta3.matchText,
29543
+ toolCallId
29544
+ });
29545
+ };
29546
+ #removeBackgroundCandidate = (session, toolCallId) => {
29547
+ const candidates = session.backgroundCorrelation.pendingCandidates;
29548
+ const index2 = candidates.findIndex((candidate) => candidate.toolCallId === toolCallId);
29549
+ if (index2 !== -1) {
29550
+ candidates.splice(index2, 1);
29551
+ }
29552
+ };
29553
+ #isActiveBackgroundCandidate = (session, toolCallId) => session.backgroundTasks.has(toolCallId) || session.phase.kind === "wakeup" && session.phase.openToolIds.has(toolCallId) || session.wakeupCompletedOpenBgCandidates.has(toolCallId) || session.wakeupOwedToolCallIds.has(toolCallId);
29554
+ #pruneInactiveCandidates = (session) => {
29555
+ const candidates = session.backgroundCorrelation.pendingCandidates;
29556
+ let writeIndex = 0;
29557
+ for (const candidate of candidates) {
29558
+ if (this.#isActiveBackgroundCandidate(session, candidate.toolCallId)) {
29559
+ candidates[writeIndex] = candidate;
29560
+ writeIndex += 1;
29561
+ }
29562
+ }
29563
+ candidates.length = writeIndex;
29564
+ };
29565
+ #syncBackgroundTaskCreations = (sessionId, session, steps) => {
29566
+ const correlation = session.backgroundCorrelation;
29567
+ const targetSessionId = sessionId.toLowerCase();
29568
+ let lastPlanner;
29569
+ for (const step of steps) {
29570
+ if (step.type === "PLANNER_RESPONSE" && step.tool_calls !== void 0 && step.tool_calls.length > 0) {
29571
+ lastPlanner = step;
29572
+ continue;
29573
+ }
29574
+ if (step.type !== "GENERIC" || step.status !== "RUNNING" || step.content === void 0 || correlation.boundCreationSteps.has(step.step_index)) {
29575
+ continue;
29576
+ }
29577
+ const match = BACKGROUND_TASK_CREATED_PATTERN.exec(step.content);
29578
+ if (match === null || match[1]?.toLowerCase() !== targetSessionId || match[2] === void 0) {
29579
+ continue;
29580
+ }
29581
+ const nativeTaskId = match[2];
29582
+ correlation.boundCreationSteps.add(step.step_index);
29583
+ const offset = lastPlanner === void 0 ? -1 : step.step_index - lastPlanner.step_index - 1;
29584
+ const rawToolCall = lastPlanner?.tool_calls !== void 0 && offset >= 0 && offset < lastPlanner.tool_calls.length ? lastPlanner.tool_calls[offset] : void 0;
29585
+ const info = readTranscriptToolCallInfo(rawToolCall);
29586
+ if (info?.isDaemon === true) {
29587
+ correlation.daemonNativeTaskIds.add(nativeTaskId);
29588
+ continue;
29589
+ }
29590
+ if (info !== null && info.category === null || step.step_index <= session.sessionOpenStepIndex) {
29591
+ continue;
29592
+ }
29593
+ const candidates = correlation.pendingCandidates;
29594
+ const categoryMatches = (candidate) => info === null || info.category === null || candidate.category === info.category;
29595
+ let matchedIndex = candidates.findIndex(
29596
+ (candidate) => this.#isActiveBackgroundCandidate(session, candidate.toolCallId) && categoryMatches(candidate) && matchesCandidateText(candidate.matchText, info?.matchText)
29597
+ );
29598
+ if (matchedIndex === -1) {
29599
+ matchedIndex = candidates.findIndex(
29600
+ (candidate) => this.#isActiveBackgroundCandidate(session, candidate.toolCallId) && categoryMatches(candidate)
29601
+ );
29602
+ }
29603
+ if (matchedIndex === -1 && info?.matchText !== void 0) {
29604
+ matchedIndex = candidates.findIndex(
29605
+ (candidate) => categoryMatches(candidate) && matchesCandidateText(candidate.matchText, info.matchText)
29606
+ );
29607
+ }
29608
+ if (matchedIndex !== -1) {
29609
+ const matched = candidates[matchedIndex];
29610
+ if (matched !== void 0) {
29611
+ candidates.splice(matchedIndex, 1);
29612
+ correlation.nativeTaskIdByToolCallId.set(matched.toolCallId, nativeTaskId);
29613
+ correlation.toolCallIdByNativeTaskId.set(nativeTaskId, matched.toolCallId);
29375
29614
  }
29376
29615
  }
29377
29616
  }
@@ -29571,9 +29810,13 @@ var AntigravityBackgroundWakeup = class {
29571
29810
  }
29572
29811
  session.wakeupGeneration += 1;
29573
29812
  const generation = session.wakeupGeneration;
29574
- session.wakeupPendingTaskResults = [...session.backgroundTasks.values()].filter(
29575
- (task) => task.kind !== "subagent" && task.state === "awaiting-results"
29576
- ).length;
29813
+ session.wakeupOwedToolCallIds.clear();
29814
+ session.wakeupCompletedOpenBgCandidates.clear();
29815
+ for (const [toolCallId, task] of session.backgroundTasks) {
29816
+ if (task.kind !== "subagent" && task.state === "awaiting-results") {
29817
+ session.wakeupOwedToolCallIds.add(toolCallId);
29818
+ }
29819
+ }
29577
29820
  session.wakeupSettledStepIndex = null;
29578
29821
  this.#setWakeupAwaitingOutput(sessionId, session, generation, /* @__PURE__ */ new Set());
29579
29822
  notifications.push(
@@ -29591,6 +29834,8 @@ var AntigravityBackgroundWakeup = class {
29591
29834
  }
29592
29835
  this.#cancelWakeupTimers(session.phase);
29593
29836
  session.phase = { cancelRequested, kind: "idle" };
29837
+ session.wakeupOwedToolCallIds.clear();
29838
+ session.wakeupCompletedOpenBgCandidates.clear();
29594
29839
  this.#dropAwaitingResultTasks(session);
29595
29840
  const notifications = [];
29596
29841
  const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -29611,6 +29856,8 @@ var AntigravityBackgroundWakeup = class {
29611
29856
  }
29612
29857
  this.#cancelWakeupTimers(session.phase);
29613
29858
  session.phase = { cancelRequested: false, kind: "idle" };
29859
+ session.wakeupOwedToolCallIds.clear();
29860
+ session.wakeupCompletedOpenBgCandidates.clear();
29614
29861
  this.#dropAwaitingResultTasks(session);
29615
29862
  const notifications = [];
29616
29863
  const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -29674,11 +29921,16 @@ var AntigravityBackgroundWakeup = class {
29674
29921
  }
29675
29922
  if (tail !== null) {
29676
29923
  this.#syncSubagentCreations(current, tail.steps);
29924
+ this.#syncBackgroundTaskCreations(sessionId, current, tail.steps);
29677
29925
  }
29678
29926
  if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
29679
29927
  if (this.#settleWakeupReply(sessionId, current, tail, tail.settledStepIndex)) {
29680
29928
  this.#emitNotifications(this.#finishWakeup(sessionId, current, "end_turn", false));
29681
29929
  } else {
29930
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, current);
29931
+ if (bg2 !== null) {
29932
+ this.#emitMetaUpdate(bg2);
29933
+ }
29682
29934
  this.#setWakeupAwaitingOutput(sessionId, current, generation, current.phase.openToolIds);
29683
29935
  }
29684
29936
  return;
@@ -29693,9 +29945,10 @@ var AntigravityBackgroundWakeup = class {
29693
29945
  this.#rescheduleTranscriptCheck(sessionId, current, generation, stageEpoch, currentStage);
29694
29946
  };
29695
29947
  /**
29696
- * Records that the continuation's reply settled at `settledStepIndex` and counts the task results Antigravity
29697
- * handed to it up to there. Answers whether the continuation ends: it goes on while results are still owed, since
29698
- * Antigravity hands each to the run right after the reply it has, and the run continues from it.
29948
+ * Records that the continuation's reply settled at `settledStepIndex` and reconciles the task results Antigravity
29949
+ * handed to it up to there against the specific background tool calls still owed. Answers whether the continuation
29950
+ * ends: it goes on while any owed non-daemon result has not reached the transcript yet, since Antigravity hands
29951
+ * each to the run right after the reply it has, and the run continues from it.
29699
29952
  */
29700
29953
  #settleWakeupReply = (sessionId, session, tail, settledStepIndex) => {
29701
29954
  const sinceStepIndex = session.baselineStepIndex;
@@ -29703,22 +29956,60 @@ var AntigravityBackgroundWakeup = class {
29703
29956
  session.wakeupSettledStepIndex = settledStepIndex;
29704
29957
  this.#consumeSubagentIdlesThrough(session, tail.steps, settledStepIndex);
29705
29958
  if (tail.firstStepIndex > sinceStepIndex + 1) {
29706
- session.wakeupPendingTaskResults = 0;
29959
+ session.wakeupOwedToolCallIds.clear();
29960
+ session.wakeupCompletedOpenBgCandidates.clear();
29961
+ this.#pruneInactiveCandidates(session);
29707
29962
  return true;
29708
29963
  }
29709
- const received = /* @__PURE__ */ new Set();
29710
- for (const step of tail.steps) {
29711
- if (step.step_index <= sinceStepIndex || step.step_index > settledStepIndex || step.type !== "SYSTEM_MESSAGE" || step.content === void 0) {
29712
- continue;
29964
+ const correlation = session.backgroundCorrelation;
29965
+ const received = extractTaskResultSenderIds(sessionId, tail.steps, sinceStepIndex, settledStepIndex);
29966
+ for (const nativeTaskId of received) {
29967
+ correlation.deliveredNativeTaskIds.add(nativeTaskId);
29968
+ }
29969
+ for (const toolCallId of [...session.wakeupCompletedOpenBgCandidates]) {
29970
+ session.wakeupCompletedOpenBgCandidates.delete(toolCallId);
29971
+ const nativeTaskId = correlation.nativeTaskIdByToolCallId.get(toolCallId);
29972
+ if (nativeTaskId !== void 0 && !correlation.deliveredNativeTaskIds.has(nativeTaskId)) {
29973
+ session.wakeupOwedToolCallIds.add(toolCallId);
29974
+ if (!session.backgroundTasks.has(toolCallId)) {
29975
+ const meta3 = session.toolMetadata.get(toolCallId);
29976
+ const kind = backgroundKindFor(meta3?.category ?? null) ?? "shell";
29977
+ session.backgroundTasks.set(toolCallId, {
29978
+ ...meta3?.description === void 0 ? {} : { description: meta3.description },
29979
+ kind,
29980
+ state: "awaiting-results",
29981
+ taskId: toolCallId,
29982
+ toolUseId: toolCallId
29983
+ });
29984
+ }
29713
29985
  }
29714
- for (const match of step.content.matchAll(TASK_RESULT_SENDER_PATTERN)) {
29715
- if (match[1]?.toLowerCase() === sessionId.toLowerCase() && match[2] !== void 0) {
29716
- received.add(match[2]);
29986
+ }
29987
+ const consumedReceived = /* @__PURE__ */ new Set();
29988
+ const unboundOwed = [];
29989
+ for (const toolCallId of [...session.wakeupOwedToolCallIds]) {
29990
+ const nativeTaskId = correlation.nativeTaskIdByToolCallId.get(toolCallId);
29991
+ if (nativeTaskId !== void 0) {
29992
+ if (correlation.deliveredNativeTaskIds.has(nativeTaskId)) {
29993
+ session.wakeupOwedToolCallIds.delete(toolCallId);
29994
+ consumedReceived.add(nativeTaskId);
29717
29995
  }
29996
+ } else {
29997
+ unboundOwed.push(toolCallId);
29718
29998
  }
29719
29999
  }
29720
- session.wakeupPendingTaskResults = Math.max(0, session.wakeupPendingTaskResults - received.size);
29721
- return session.wakeupPendingTaskResults === 0;
30000
+ if (unboundOwed.length > 0) {
30001
+ let unmatchedReceived = 0;
30002
+ for (const nativeTaskId of received) {
30003
+ if (!consumedReceived.has(nativeTaskId) && !correlation.daemonNativeTaskIds.has(nativeTaskId) && !correlation.toolCallIdByNativeTaskId.has(nativeTaskId)) {
30004
+ unmatchedReceived += 1;
30005
+ }
30006
+ }
30007
+ for (const toolCallId of unboundOwed.slice(0, unmatchedReceived)) {
30008
+ session.wakeupOwedToolCallIds.delete(toolCallId);
30009
+ }
30010
+ }
30011
+ this.#pruneInactiveCandidates(session);
30012
+ return session.wakeupOwedToolCallIds.size === 0;
29722
30013
  };
29723
30014
  #handleWakeupTimeout = async (sessionId, generation, stageEpoch, message) => {
29724
30015
  if (this.#disposed) {
@@ -29751,6 +30042,7 @@ var AntigravityBackgroundWakeup = class {
29751
30042
  }
29752
30043
  if (tail !== null) {
29753
30044
  this.#syncSubagentCreations(current, tail.steps);
30045
+ this.#syncBackgroundTaskCreations(sessionId, current, tail.steps);
29754
30046
  }
29755
30047
  if (tail?.settledStepIndex !== null && tail?.settledStepIndex !== void 0) {
29756
30048
  this.#settleWakeupReply(sessionId, current, tail, tail.settledStepIndex);
@@ -29815,7 +30107,7 @@ var AntigravityBackgroundWakeup = class {
29815
30107
  const meta3 = inspectToolMetadata(update, session.toolMetadata.get(toolCallId));
29816
30108
  session.toolMetadata.set(toolCallId, meta3);
29817
30109
  if (meta3.isDaemon) {
29818
- session.backgroundTasks.delete(toolCallId);
30110
+ this.#deleteBackgroundTask(session, toolCallId);
29819
30111
  return;
29820
30112
  }
29821
30113
  if (meta3.category === "manage-subagents" && status === "completed") {
@@ -29834,6 +30126,7 @@ var AntigravityBackgroundWakeup = class {
29834
30126
  return;
29835
30127
  }
29836
30128
  if (!cancelled && status === "in_progress") {
30129
+ this.#recordBackgroundCandidate(session, toolCallId, meta3);
29837
30130
  session.backgroundTasks.set(toolCallId, {
29838
30131
  ...meta3.description === void 0 ? {} : { description: meta3.description },
29839
30132
  kind,
@@ -29845,6 +30138,9 @@ var AntigravityBackgroundWakeup = class {
29845
30138
  }
29846
30139
  if (status === "pending" || status === "completed" || status === "failed" || status === "cancelled") {
29847
30140
  session.backgroundTasks.delete(toolCallId);
30141
+ if (status !== "pending") {
30142
+ this.#removeBackgroundCandidate(session, toolCallId);
30143
+ }
29848
30144
  }
29849
30145
  };
29850
30146
  #applyWakeupToolUpdate = async (sessionId, session, update, notifications) => {
@@ -29863,7 +30159,7 @@ var AntigravityBackgroundWakeup = class {
29863
30159
  if (trackedExisting !== void 0) {
29864
30160
  if (status === "completed") {
29865
30161
  if (trackedExisting.kind !== "subagent" && trackedExisting.state !== "awaiting-results") {
29866
- session.wakeupPendingTaskResults += 1;
30162
+ session.wakeupOwedToolCallIds.add(toolCallId);
29867
30163
  }
29868
30164
  session.backgroundTasks.set(toolCallId, { ...trackedExisting, state: "awaiting-results" });
29869
30165
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
@@ -29882,7 +30178,7 @@ var AntigravityBackgroundWakeup = class {
29882
30178
  if (trackedExisting.kind === "subagent") {
29883
30179
  this.#deleteSubagentTask(session, toolCallId);
29884
30180
  } else {
29885
- session.backgroundTasks.delete(toolCallId);
30181
+ this.#deleteBackgroundTask(session, toolCallId);
29886
30182
  }
29887
30183
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
29888
30184
  if (bg2 !== null) {
@@ -29892,6 +30188,7 @@ var AntigravityBackgroundWakeup = class {
29892
30188
  return;
29893
30189
  }
29894
30190
  if (meta3.isDaemon) {
30191
+ this.#removeBackgroundCandidate(session, toolCallId);
29895
30192
  if (session.phase.openToolIds.has(toolCallId)) {
29896
30193
  const nextOpenToolIds = new Set(session.phase.openToolIds);
29897
30194
  nextOpenToolIds.delete(toolCallId);
@@ -29900,6 +30197,7 @@ var AntigravityBackgroundWakeup = class {
29900
30197
  return;
29901
30198
  }
29902
30199
  if (updateKind === "tool_call" && (status === "in_progress" || status === "pending")) {
30200
+ this.#recordBackgroundCandidate(session, toolCallId, meta3);
29903
30201
  if (!session.phase.openToolIds.has(toolCallId)) {
29904
30202
  const nextOpenToolIds = new Set(session.phase.openToolIds);
29905
30203
  nextOpenToolIds.add(toolCallId);
@@ -29908,12 +30206,24 @@ var AntigravityBackgroundWakeup = class {
29908
30206
  this.#pauseOrResumeWakeupTimers(sessionId, session);
29909
30207
  return;
29910
30208
  }
30209
+ if (status === "in_progress" || status === "pending") {
30210
+ this.#recordBackgroundCandidate(session, toolCallId, meta3);
30211
+ return;
30212
+ }
29911
30213
  if (status === "completed" || status === "failed" || status === "cancelled") {
29912
- if (session.phase.openToolIds.has(toolCallId)) {
30214
+ const wasOpenTool = session.phase.openToolIds.has(toolCallId);
30215
+ if (wasOpenTool) {
29913
30216
  const nextOpenToolIds = new Set(session.phase.openToolIds);
29914
30217
  nextOpenToolIds.delete(toolCallId);
29915
30218
  session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
29916
30219
  }
30220
+ const kind = backgroundKindFor(meta3.category);
30221
+ if (wasOpenTool && status === "completed" && (kind === "shell" || kind === "other")) {
30222
+ this.#recordBackgroundCandidate(session, toolCallId, meta3);
30223
+ session.wakeupCompletedOpenBgCandidates.add(toolCallId);
30224
+ } else if (status === "failed" || status === "cancelled") {
30225
+ this.#removeBackgroundCandidate(session, toolCallId);
30226
+ }
29917
30227
  if (meta3.category === "subagent" && status === "completed") {
29918
30228
  this.#registerSubagentTask(session, toolCallId, meta3.description);
29919
30229
  await this.#syncPendingSubagentCreations(sessionId, session);
@@ -30020,6 +30330,7 @@ var AntigravityBackgroundWakeup = class {
30020
30330
  if (tail2 !== null) {
30021
30331
  session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail2.maxStepIndex);
30022
30332
  session2.sessionOpenStepIndex = Math.max(session2.sessionOpenStepIndex, tail2.maxStepIndex);
30333
+ this.#syncBackgroundTaskCreations(tracked.sessionId, session2, tail2.steps);
30023
30334
  }
30024
30335
  if (tracked.kind === "load") {
30025
30336
  session2.phase = { cancelRequested: false, kind: "idle" };
@@ -30037,6 +30348,16 @@ var AntigravityBackgroundWakeup = class {
30037
30348
  if (tail !== null) {
30038
30349
  session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail.maxStepIndex);
30039
30350
  this.#syncSubagentCreations(session2, tail.steps);
30351
+ this.#syncBackgroundTaskCreations(tracked.sessionId, session2, tail.steps);
30352
+ for (const nativeTaskId of extractTaskResultSenderIds(
30353
+ tracked.sessionId,
30354
+ tail.steps,
30355
+ prePromptStepIndex,
30356
+ session2.baselineStepIndex
30357
+ )) {
30358
+ session2.backgroundCorrelation.deliveredNativeTaskIds.add(nativeTaskId);
30359
+ }
30360
+ this.#pruneInactiveCandidates(session2);
30040
30361
  if (!promptCancelled) {
30041
30362
  let lastPlannerStepIndex;
30042
30363
  for (let index2 = tail.steps.length - 1; index2 >= 0; index2 -= 1) {
@@ -30101,7 +30422,7 @@ var AntigravityBackgroundWakeup = class {
30101
30422
  if (existing.kind === "subagent") {
30102
30423
  this.#deleteSubagentTask(session, toolCallId);
30103
30424
  } else {
30104
- session.backgroundTasks.delete(toolCallId);
30425
+ this.#deleteBackgroundTask(session, toolCallId);
30105
30426
  }
30106
30427
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
30107
30428
  return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
@@ -30111,7 +30432,7 @@ var AntigravityBackgroundWakeup = class {
30111
30432
  if (existing.kind === "subagent") {
30112
30433
  this.#deleteSubagentTask(session, toolCallId);
30113
30434
  } else {
30114
- session.backgroundTasks.delete(toolCallId);
30435
+ this.#deleteBackgroundTask(session, toolCallId);
30115
30436
  }
30116
30437
  const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
30117
30438
  return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
@@ -30284,7 +30605,33 @@ var FULL_ACCESS_MODE_DESCRIPTION = "Never asks the user: approves file edits and
30284
30605
  var MAXIMUM_STDERR_TAIL_CHARACTERS = 2048;
30285
30606
  var MAXIMUM_PENDING_CONFIG_ECHOES = 16;
30286
30607
  var CANCEL_REQUEST_METHOD2 = "$/cancel_request";
30608
+ var STEERING_METHOD = "_session/steering";
30609
+ var PROMPT_STEERING_MINIMUM_VERSION = "1.5.0";
30610
+ var STEERING_PROMPT_ID_PREFIX = "mobius-antigravity-steering-";
30287
30611
  var INVALID_THINKING_SIGNATURE_PATTERN = /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/u;
30612
+ function addUsage(reports, latest) {
30613
+ const all = isRecord5(latest) ? [...reports, latest] : reports;
30614
+ if (all.length === 0) {
30615
+ return void 0;
30616
+ }
30617
+ const total = {};
30618
+ for (const report of all) {
30619
+ for (const [field, value] of Object.entries(report)) {
30620
+ const sum = total[field];
30621
+ if (typeof value === "number") {
30622
+ total[field] = (typeof sum === "number" ? sum : 0) + value;
30623
+ } else if (!(field in total)) {
30624
+ total[field] = value;
30625
+ }
30626
+ }
30627
+ }
30628
+ return total;
30629
+ }
30630
+ function steersWithPrompt(agentInfo) {
30631
+ const version3 = isRecord5(agentInfo) ? readStringProperty(agentInfo, "version") : void 0;
30632
+ const comparison = version3 === void 0 ? null : compareAgentVersions(version3, PROMPT_STEERING_MINIMUM_VERSION);
30633
+ return comparison !== null && comparison >= 0;
30634
+ }
30288
30635
  function readStringProperty(record2, key) {
30289
30636
  const value = record2[key];
30290
30637
  return typeof value === "string" ? value : void 0;
@@ -30426,6 +30773,12 @@ var AntigravityAgentConnection = class {
30426
30773
  #pendingConfigEchoes = [];
30427
30774
  /** Native sessions whose current prompt reported an unusable conversation. */
30428
30775
  #unusableSessions = /* @__PURE__ */ new Set();
30776
+ /** The client prompt each native session runs, while it runs. */
30777
+ #runningPrompts = /* @__PURE__ */ new Map();
30778
+ /** Every prompt sent to Antigravity whose answer has not arrived, by request id. */
30779
+ #promptsByKey = /* @__PURE__ */ new Map();
30780
+ /** Answers the proxy gives the client itself, ahead of any later message from Antigravity. */
30781
+ #answerClient;
30429
30782
  #latestPermissionMode = { kind: "native" };
30430
30783
  #sessionEstablished = false;
30431
30784
  #closePromise = null;
@@ -30698,6 +31051,22 @@ var AntigravityAgentConnection = class {
30698
31051
  if (targetKey !== void 0 && pending !== void 0 && (pending.kind === "mode_change" || pending.kind === "set_config_option") && !pending.cancelled) {
30699
31052
  this.#pendingRequests.set(targetKey, { ...pending, cancelled: true });
30700
31053
  }
31054
+ const steered = targetKey === void 0 ? void 0 : this.#promptsByKey.get(targetKey);
31055
+ if (steered !== void 0 && params2 !== void 0 && steered.clientKey === targetKey) {
31056
+ steered.cancelled = true;
31057
+ if (steered.currentKey !== targetKey) {
31058
+ return { ...message, params: { ...params2, requestId: steered.currentKey } };
31059
+ }
31060
+ }
31061
+ return message;
31062
+ }
31063
+ if (isNotificationMessage3(message) && message.method === methods.agent.session.cancel) {
31064
+ const params2 = isRecord5(message.params) ? message.params : void 0;
31065
+ const sessionId2 = params2 === void 0 ? void 0 : readStringProperty(params2, "sessionId");
31066
+ const running = sessionId2 === void 0 ? void 0 : this.#runningPrompts.get(sessionId2);
31067
+ if (running !== void 0) {
31068
+ running.cancelled = true;
31069
+ }
30701
31070
  return message;
30702
31071
  }
30703
31072
  if (!isRequestMessage3(message)) {
@@ -30707,10 +31076,29 @@ var AntigravityAgentConnection = class {
30707
31076
  const sessionId = params === void 0 ? void 0 : readStringProperty(params, "sessionId");
30708
31077
  const key = requestKeyOf2(message.id);
30709
31078
  switch (message.method) {
31079
+ case methods.agent.initialize: {
31080
+ if (key !== void 0) {
31081
+ this.#pendingRequests.set(key, { kind: "initialize" });
31082
+ }
31083
+ return message;
31084
+ }
30710
31085
  case methods.agent.session.prompt: {
30711
31086
  if (sessionId !== void 0) {
30712
31087
  this.#messageStreams.set(sessionId, { kind: "none" });
30713
31088
  this.#unusableSessions.delete(sessionId);
31089
+ if (key !== void 0) {
31090
+ const prompt = {
31091
+ cancelled: false,
31092
+ clientKey: key,
31093
+ currentKey: key,
31094
+ pendingSteer: void 0,
31095
+ sessionId,
31096
+ steering: Promise.resolve(),
31097
+ supersededUsage: []
31098
+ };
31099
+ this.#runningPrompts.set(sessionId, prompt);
31100
+ this.#promptsByKey.set(key, prompt);
31101
+ }
30714
31102
  }
30715
31103
  return message;
30716
31104
  }
@@ -30802,6 +31190,16 @@ var AntigravityAgentConnection = class {
30802
31190
  if (!isRecord5(message.result)) {
30803
31191
  return message;
30804
31192
  }
31193
+ if (tracked.kind === "initialize") {
31194
+ if (!steersWithPrompt(message.result["agentInfo"])) {
31195
+ return message;
31196
+ }
31197
+ const meta3 = isRecord5(message.result["_meta"]) ? message.result["_meta"] : {};
31198
+ return {
31199
+ ...message,
31200
+ result: { ...message.result, _meta: { ...meta3, steering: { supported: true } } }
31201
+ };
31202
+ }
30805
31203
  if (tracked.kind === "lifecycle") {
30806
31204
  const sessionId = readStringProperty(message.result, "sessionId");
30807
31205
  if (sessionId !== void 0) {
@@ -30862,17 +31260,130 @@ var AntigravityAgentConnection = class {
30862
31260
  }
30863
31261
  return message;
30864
31262
  };
31263
+ /**
31264
+ * Places the answer to a prompt in the client's prompt it belongs to. An earlier prompt of a steered run answers
31265
+ * as soon as it is steered and is dropped; the latest one answers for the client's prompt, with the usage of all.
31266
+ */
31267
+ #routePromptAnswer = (message) => {
31268
+ const key = requestKeyOf2(message.id);
31269
+ const prompt = key === void 0 ? void 0 : this.#promptsByKey.get(key);
31270
+ if (key === void 0 || prompt === void 0) {
31271
+ return message;
31272
+ }
31273
+ this.#promptsByKey.delete(key);
31274
+ const pending = prompt.pendingSteer;
31275
+ if (pending !== void 0 && key === pending.key && "error" in message) {
31276
+ prompt.pendingSteer = void 0;
31277
+ prompt.currentKey = pending.previousKey;
31278
+ pending.settle(false);
31279
+ return void 0;
31280
+ }
31281
+ if (pending !== void 0 && (key === pending.key || key === pending.previousKey)) {
31282
+ prompt.pendingSteer = void 0;
31283
+ pending.settle(true);
31284
+ }
31285
+ if (key !== prompt.currentKey) {
31286
+ if ("result" in message && isRecord5(message.result) && isRecord5(message.result["usage"])) {
31287
+ prompt.supersededUsage.push(message.result["usage"]);
31288
+ }
31289
+ return void 0;
31290
+ }
31291
+ if (this.#runningPrompts.get(prompt.sessionId) === prompt) {
31292
+ this.#runningPrompts.delete(prompt.sessionId);
31293
+ }
31294
+ if (key === prompt.clientKey) {
31295
+ return message;
31296
+ }
31297
+ if (!("result" in message) || !isRecord5(message.result)) {
31298
+ return { ...message, id: prompt.clientKey };
31299
+ }
31300
+ const usage = addUsage(prompt.supersededUsage, message.result["usage"]);
31301
+ return {
31302
+ ...message,
31303
+ id: prompt.clientKey,
31304
+ result: { ...message.result, ...usage === void 0 ? {} : { usage } }
31305
+ };
31306
+ };
31307
+ /**
31308
+ * Steers the running client prompt with another `session/prompt`, and answers once Antigravity has taken or
31309
+ * refused it. With no client prompt running, or one the client is stopping, the client sends its message as a
31310
+ * prompt of its own. It runs beside the client's later messages, such as the answer to a permission request that
31311
+ * Antigravity may need before it decides.
31312
+ */
31313
+ #steer = async (request, write) => {
31314
+ const params = isRecord5(request.params) ? request.params : {};
31315
+ const sessionId = readStringProperty(params, "sessionId");
31316
+ const answer = (result) => {
31317
+ this.#answerClient?.({ id: request.id, jsonrpc: "2.0", result });
31318
+ };
31319
+ const joinable = () => {
31320
+ const running2 = sessionId === void 0 ? void 0 : this.#runningPrompts.get(sessionId);
31321
+ return running2 === void 0 || running2.cancelled ? void 0 : running2;
31322
+ };
31323
+ const running = joinable();
31324
+ if (sessionId === void 0 || running === void 0) {
31325
+ answer({ outcome: "promptRequired", reason: "noRunningTurn" });
31326
+ return;
31327
+ }
31328
+ const previous = running.steering;
31329
+ const turn = Promise.withResolvers();
31330
+ running.steering = turn.promise;
31331
+ try {
31332
+ await previous;
31333
+ await this.#flushDeliveries();
31334
+ if (joinable() !== running) {
31335
+ answer({ outcome: "promptRequired", reason: "noRunningTurn" });
31336
+ return;
31337
+ }
31338
+ const key = `${STEERING_PROMPT_ID_PREFIX}${randomUUID3()}`;
31339
+ const verdict = Promise.withResolvers();
31340
+ running.pendingSteer = { key, previousKey: running.currentKey, settle: verdict.resolve };
31341
+ running.currentKey = key;
31342
+ this.#promptsByKey.set(key, running);
31343
+ this.#messageStreams.set(sessionId, { kind: "none" });
31344
+ await write({
31345
+ id: key,
31346
+ jsonrpc: "2.0",
31347
+ method: methods.agent.session.prompt,
31348
+ params: { prompt: params["prompt"], sessionId }
31349
+ });
31350
+ answer(await verdict.promise ? { outcome: "injected" } : { outcome: "failed" });
31351
+ } catch (cause) {
31352
+ this.#answerClient?.({
31353
+ error: { code: -32603, message: `Antigravity could not take the steering: ${String(cause)}` },
31354
+ id: request.id,
31355
+ jsonrpc: "2.0"
31356
+ });
31357
+ } finally {
31358
+ turn.resolve();
31359
+ }
31360
+ };
30865
31361
  #wrapStream = (rawStream) => {
30866
31362
  const writer = rawStream.writable.getWriter();
30867
31363
  const transformOutgoing = this.#transformOutgoing;
30868
31364
  const transformIncoming = this.#transformIncoming;
30869
31365
  const readable = rawStream.readable.pipeThrough(
30870
31366
  new TransformStream({
31367
+ start: (controller) => {
31368
+ this.#answerClient = (message) => {
31369
+ if (this.#closePromise !== null || this.#deliveryAbort.signal.aborted) {
31370
+ return;
31371
+ }
31372
+ try {
31373
+ controller.enqueue(message);
31374
+ } catch {
31375
+ }
31376
+ };
31377
+ },
30871
31378
  transform: async (chunk, controller) => {
30872
31379
  if (this.#closePromise !== null || this.#deliveryAbort.signal.aborted) {
30873
31380
  return;
30874
31381
  }
30875
- const transformed = transformIncoming(chunk);
31382
+ const routed = isResponseMessage3(chunk) ? this.#routePromptAnswer(chunk) : chunk;
31383
+ if (routed === void 0) {
31384
+ return;
31385
+ }
31386
+ const transformed = transformIncoming(routed);
30876
31387
  if (transformed === void 0) {
30877
31388
  return;
30878
31389
  }
@@ -30909,6 +31420,10 @@ var AntigravityAgentConnection = class {
30909
31420
  );
30910
31421
  const writable = new WritableStream({
30911
31422
  write: async (chunk) => {
31423
+ if (isRequestMessage3(chunk) && chunk.method === STEERING_METHOD) {
31424
+ void this.#steer(chunk, (message) => writer.write(message));
31425
+ return;
31426
+ }
30912
31427
  const outgoing = transformOutgoing(chunk);
30913
31428
  await this.#backgroundWakeup.onOutgoingMessage(outgoing);
30914
31429
  if (isRequestMessage3(outgoing) && outgoing.method === methods.agent.session.prompt) {
@@ -30998,7 +31513,7 @@ var AntigravityAgentSpecification = class extends InProcessAcpAgentSpecification
30998
31513
  id = "antigravity";
30999
31514
  label = "Antigravity";
31000
31515
  minimumSupportedAgentVersion = "1.5.1";
31001
- maximumTestedAgentVersion = "1.5.10";
31516
+ maximumTestedAgentVersion = "1.5.12";
31002
31517
  authenticationCommand = () => "agy acp --login";
31003
31518
  constructor(options) {
31004
31519
  super("MOBIUS_ANTIGRAVITY_PATH");
@@ -84837,61 +85352,6 @@ async function probeAcpReadiness(specification, agent2, environment, defaultWork
84837
85352
  }
84838
85353
  }
84839
85354
 
84840
- // src/engine/agent/discovery/agent-version.ts
84841
- function parseVersion(value) {
84842
- const match = /(?:^|[^0-9])v?(\d+(?:\.\d+)+)(?:-([0-9A-Za-z.-]+))?/u.exec(value);
84843
- if (match?.[1] === void 0) {
84844
- return null;
84845
- }
84846
- return {
84847
- core: match[1].split(".").map(Number),
84848
- prerelease: match[2]?.split(".") ?? []
84849
- };
84850
- }
84851
- function comparePrerelease(left, right) {
84852
- if (left.length === 0 || right.length === 0) {
84853
- return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
84854
- }
84855
- for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
84856
- const leftPart = left[index2];
84857
- const rightPart = right[index2];
84858
- if (leftPart === void 0 || rightPart === void 0) {
84859
- return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
84860
- }
84861
- if (leftPart === rightPart) {
84862
- continue;
84863
- }
84864
- const leftNumber = /^\d+$/u.test(leftPart) ? Number(leftPart) : null;
84865
- const rightNumber = /^\d+$/u.test(rightPart) ? Number(rightPart) : null;
84866
- if (leftNumber !== null && rightNumber !== null) {
84867
- return Math.sign(leftNumber - rightNumber);
84868
- }
84869
- if (leftNumber !== null || rightNumber !== null) {
84870
- return leftNumber !== null ? -1 : 1;
84871
- }
84872
- return leftPart.localeCompare(rightPart);
84873
- }
84874
- return 0;
84875
- }
84876
- function compareAgentVersions(left, right) {
84877
- const parsedLeft = parseVersion(left);
84878
- const parsedRight = parseVersion(right);
84879
- if (parsedLeft === null || parsedRight === null) {
84880
- return null;
84881
- }
84882
- for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
84883
- const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
84884
- if (difference !== 0) {
84885
- return Math.sign(difference);
84886
- }
84887
- }
84888
- return comparePrerelease(parsedLeft.prerelease, parsedRight.prerelease);
84889
- }
84890
- function isAgentVersionSupported(reportedVersion, minimumSupportedVersion) {
84891
- const comparison = compareAgentVersions(reportedVersion, minimumSupportedVersion);
84892
- return comparison === null ? null : comparison >= 0;
84893
- }
84894
-
84895
85355
  // src/engine/agent/discovery/executable-discovery.ts
84896
85356
  import { isAbsolute as isAbsolute14 } from "node:path";
84897
85357
  async function resolveSpecificationExecutables(executableName, overrideVariable2, resolveInstalled, context) {
@@ -88345,6 +88805,9 @@ var REMOTE_DIAGNOSTIC_FIELDS = [
88345
88805
  "operation",
88346
88806
  "runtimeId",
88347
88807
  "closeCode",
88808
+ "wasClean",
88809
+ "transportProtocol",
88810
+ "transportClosure",
88348
88811
  "timeoutMilliseconds",
88349
88812
  "attempt",
88350
88813
  "elapsedMilliseconds",
@@ -96763,7 +97226,13 @@ var AgentSession = class _AgentSession {
96763
97226
  const messageId = result._meta?.messageId;
96764
97227
  const completion = { ...messageId === void 0 ? {} : { messageId }, stopReason: result.stopReason };
96765
97228
  if (result.stopReason !== "cancelled" && this.#recordedBackground.length > 0) {
96766
- this.#hold(options.commandId, lifecycle.attemptId, completion);
97229
+ this.#hold(
97230
+ options.commandId,
97231
+ lifecycle.attemptId,
97232
+ completion,
97233
+ { kind: "all-background" },
97234
+ void 0
97235
+ );
96767
97236
  } else {
96768
97237
  await this.recordLifecycleEvent({
96769
97238
  payload: { commandId: options.commandId, kind: "prompt.completed", ...completion },
@@ -97043,20 +97512,35 @@ var AgentSession = class _AgentSession {
97043
97512
  this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
97044
97513
  };
97045
97514
  /** Keeps a command whose reply ended open for the background work still outstanding (see HeldCommand). */
97046
- #hold = (commandId, attemptId, completion) => {
97515
+ #hold = (commandId, attemptId, completion, scope, continues) => {
97047
97516
  this.#held = {
97048
97517
  attemptId,
97049
97518
  cancelled: false,
97050
97519
  commandId,
97051
97520
  completion,
97521
+ continues,
97052
97522
  limit: this.#timer.schedule(() => {
97053
97523
  void this.#releaseHeld().catch((error62) => {
97054
97524
  console.error("Mobius daemon could not end a command held for background work", error62);
97055
97525
  });
97056
- }, BACKGROUND_HOLD_LIMIT_MILLISECONDS)
97526
+ }, BACKGROUND_HOLD_LIMIT_MILLISECONDS),
97527
+ scope
97057
97528
  };
97058
97529
  this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, commandId);
97059
97530
  };
97531
+ #heldHasRemainingWork = (held) => {
97532
+ const scope = held.scope;
97533
+ switch (scope.kind) {
97534
+ case "all-background":
97535
+ return this.#recordedBackground.length > 0;
97536
+ case "started-tasks":
97537
+ return this.#recordedBackground.some((task) => scope.taskIds.has(task.taskId));
97538
+ default: {
97539
+ const unreachable2 = scope;
97540
+ throw new AcpExecutionError("Unexpected held command scope", { cause: unreachable2 });
97541
+ }
97542
+ }
97543
+ };
97060
97544
  /**
97061
97545
  * Records the end of the held command, if one is open: how its reply ended, unless it was stopped or `failure`
97062
97546
  * says its continuation failed. The Agent's continuation of it, if one runs, belongs to nothing after this.
@@ -97085,7 +97569,7 @@ var AgentSession = class _AgentSession {
97085
97569
  };
97086
97570
  /** Ends the held command once no background work is outstanding and no continuation of it is running. */
97087
97571
  #releaseHeldIfDone = async () => {
97088
- if (this.#held !== null && this.#agentTurn === null && this.#recordedBackground.length === 0) {
97572
+ if (this.#held !== null && this.#agentTurn === null && !this.#heldHasRemainingWork(this.#held)) {
97089
97573
  await this.#releaseHeld();
97090
97574
  }
97091
97575
  };
@@ -97122,14 +97606,20 @@ var AgentSession = class _AgentSession {
97122
97606
  }
97123
97607
  const held = this.#held;
97124
97608
  if (held !== null) {
97125
- this.#agentTurn = {
97126
- attemptId: held.attemptId,
97127
- cancelled: false,
97128
- commandId: held.commandId,
97129
- continues: void 0,
97130
- held: true
97131
- };
97132
- return;
97609
+ const heldScope = held.scope;
97610
+ if (heldScope.kind === "started-tasks" && report.taskIds.length > 0 && report.taskIds.every((taskId) => !heldScope.taskIds.has(taskId))) {
97611
+ await this.#releaseHeld();
97612
+ } else {
97613
+ this.#agentTurn = {
97614
+ attemptId: held.attemptId,
97615
+ cancelled: false,
97616
+ commandId: held.commandId,
97617
+ continues: held.continues,
97618
+ held: true,
97619
+ startedTaskIds: /* @__PURE__ */ new Set()
97620
+ };
97621
+ return;
97622
+ }
97133
97623
  }
97134
97624
  const continues = report.taskIds.flatMap((taskId) => {
97135
97625
  const commandId = this.#backgroundTaskCommands.get(taskId);
@@ -97140,7 +97630,8 @@ var AgentSession = class _AgentSession {
97140
97630
  cancelled: false,
97141
97631
  commandId: `agent-${randomUUID15()}`,
97142
97632
  continues,
97143
- held: false
97633
+ held: false,
97634
+ startedTaskIds: /* @__PURE__ */ new Set()
97144
97635
  };
97145
97636
  this.#agentTurn = agentTurn;
97146
97637
  await this.recordLifecycleEvent({
@@ -97176,6 +97667,21 @@ var AgentSession = class _AgentSession {
97176
97667
  await this.#releaseHeldIfDone();
97177
97668
  return;
97178
97669
  }
97670
+ if (!agentTurn.cancelled && report.stopReason !== "cancelled") {
97671
+ const remainingStarted = new Set(
97672
+ this.#recordedBackground.map((task) => task.taskId).filter((taskId) => agentTurn.startedTaskIds.has(taskId))
97673
+ );
97674
+ if (remainingStarted.size > 0) {
97675
+ this.#hold(
97676
+ agentTurn.commandId,
97677
+ agentTurn.attemptId,
97678
+ { stopReason: report.stopReason },
97679
+ { kind: "started-tasks", taskIds: remainingStarted },
97680
+ agentTurn.continues
97681
+ );
97682
+ return;
97683
+ }
97684
+ }
97179
97685
  await this.recordLifecycleEvent({
97180
97686
  payload: {
97181
97687
  commandId: agentTurn.commandId,
@@ -97203,13 +97709,18 @@ var AgentSession = class _AgentSession {
97203
97709
  */
97204
97710
  #recordBackgroundTasks = async (reports) => {
97205
97711
  const owner = this.#agentCommand() ?? this.#agentTurn?.continues ?? this.#lastClientCommandId;
97712
+ const previousTaskIds = new Set(this.#recordedBackground.map((task) => task.taskId));
97206
97713
  const current = new Set(reports.map((report) => report.taskId));
97207
97714
  for (const taskId of this.#backgroundTaskCommands.keys()) {
97208
97715
  if (!current.has(taskId)) {
97209
97716
  this.#backgroundTaskCommands.delete(taskId);
97210
97717
  }
97211
97718
  }
97719
+ const addedTaskIds = [];
97212
97720
  const tasks = reports.slice(0, SESSION_BACKGROUND_TASK_MAX_COUNT).map((report) => {
97721
+ if (!previousTaskIds.has(report.taskId)) {
97722
+ addedTaskIds.push(report.taskId);
97723
+ }
97213
97724
  if (owner !== void 0 && !this.#backgroundTaskCommands.has(report.taskId)) {
97214
97725
  this.#backgroundTaskCommands.set(report.taskId, owner);
97215
97726
  }
@@ -97223,6 +97734,21 @@ var AgentSession = class _AgentSession {
97223
97734
  ...report.description === void 0 ? {} : { description: truncate(report.description, 500) }
97224
97735
  };
97225
97736
  });
97737
+ if (addedTaskIds.length > 0) {
97738
+ if (this.#agentTurn !== null && !this.#agentTurn.held) {
97739
+ for (const taskId of addedTaskIds) {
97740
+ this.#agentTurn.startedTaskIds.add(taskId);
97741
+ }
97742
+ } else if (this.#agentTurn?.held === true && this.#held !== null && this.#held.scope.kind === "started-tasks") {
97743
+ this.#held = {
97744
+ ...this.#held,
97745
+ scope: {
97746
+ kind: "started-tasks",
97747
+ taskIds: /* @__PURE__ */ new Set([...this.#held.scope.taskIds, ...addedTaskIds])
97748
+ }
97749
+ };
97750
+ }
97751
+ }
97226
97752
  if (JSON.stringify(tasks) === JSON.stringify(this.#recordedBackground)) {
97227
97753
  return;
97228
97754
  }
@@ -100801,7 +101327,7 @@ var RelayConnectionDiagnostics = class {
100801
101327
  addFailureDetails(details, failure2);
100802
101328
  this.#record("agent_catalog_publish_failed", details, true);
100803
101329
  };
100804
- connectionClosed = (connectionEpoch, code, reason, source) => {
101330
+ connectionClosed = (connectionEpoch, code, reason, source, closeDetails = {}) => {
100805
101331
  if (this.#lastClosedEpoch === connectionEpoch) {
100806
101332
  return;
100807
101333
  }
@@ -100814,6 +101340,9 @@ var RelayConnectionDiagnostics = class {
100814
101340
  connectionEpoch: connectionEpoch.toString(),
100815
101341
  relayOrigin: this.#relayOrigin,
100816
101342
  source,
101343
+ ...closeDetails.transportClosure === void 0 ? {} : { transportClosure: closeDetails.transportClosure },
101344
+ ...closeDetails.transportProtocol === void 0 ? {} : { transportProtocol: closeDetails.transportProtocol },
101345
+ ...closeDetails.wasClean === void 0 ? {} : { wasClean: closeDetails.wasClean.toString() },
100817
101346
  ...this.#route
100818
101347
  },
100819
101348
  true
@@ -103724,8 +104253,25 @@ function createRuntimeCommandDispatcher(options) {
103724
104253
  }
103725
104254
 
103726
104255
  // src/engine/runtime/relay/connect.ts
104256
+ import { Socket } from "node:net";
104257
+ import { TLSSocket } from "node:tls";
103727
104258
  import { WebSocket as WebSocket9 } from "undici";
103728
104259
  var CONNECTION_TIMEOUT_MILLISECONDS = 6e4;
104260
+ var TCP_KEEPALIVE_INITIAL_DELAY_MILLISECONDS = 1e4;
104261
+ var MAX_HTTP1_ONLY_ORIGINS = 64;
104262
+ var http1OnlyWebSocketOrigins = /* @__PURE__ */ new Set();
104263
+ function rememberHttp1OnlyWebSocketOrigin(origin) {
104264
+ if (http1OnlyWebSocketOrigins.has(origin)) {
104265
+ return;
104266
+ }
104267
+ if (http1OnlyWebSocketOrigins.size >= MAX_HTTP1_ONLY_ORIGINS) {
104268
+ const oldest = http1OnlyWebSocketOrigins.values().next().value;
104269
+ if (oldest !== void 0) {
104270
+ http1OnlyWebSocketOrigins.delete(oldest);
104271
+ }
104272
+ }
104273
+ http1OnlyWebSocketOrigins.add(origin);
104274
+ }
103729
104275
  var RelayConnectionError = class extends Error {
103730
104276
  code;
103731
104277
  diagnosticDetails;
@@ -103741,7 +104287,10 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103741
104287
  return new Promise((resolve21, reject2) => {
103742
104288
  let releaseTransport = () => void 0;
103743
104289
  let removeTransportObserver = () => void 0;
104290
+ let transportProtocol = url2.protocol === "wss:" ? "http1" : "ws";
104291
+ let transportState = { kind: "open" };
103744
104292
  let released = false;
104293
+ let finished = false;
103745
104294
  const observeFailure = (failure2, source) => {
103746
104295
  if (!released && !signal.aborted) {
103747
104296
  transportFailed(failure2, source);
@@ -103749,42 +104298,76 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103749
104298
  };
103750
104299
  const observeHandshake = (statusCode, expectedStatus) => {
103751
104300
  if (statusCode !== expectedStatus) {
103752
- observeFailure(
103753
- Object.assign(new Error("Relay rejected the WebSocket handshake"), {
103754
- code: "relay_handshake_rejected",
103755
- statusCode
103756
- }),
103757
- "handshake"
103758
- );
104301
+ const handshakeFailure = Object.assign(new Error("Relay rejected the WebSocket handshake"), {
104302
+ code: "relay_handshake_rejected",
104303
+ statusCode
104304
+ });
104305
+ observeFailure(handshakeFailure, "handshake");
104306
+ if (statusCode === 401) {
104307
+ fail(createRuntimeRelayRevokedError({ cause: handshakeFailure }));
104308
+ }
103759
104309
  }
103760
104310
  };
104311
+ let retriedAsHttp1Only = false;
103761
104312
  const dispatcher = environmentProxyDispatcher.compose((dispatch) => (options, handler) => {
104313
+ const originKey = String(options.origin);
104314
+ const allowH2Option = Reflect.get(options, "allowH2");
104315
+ if (allowH2Option === false) {
104316
+ retriedAsHttp1Only = true;
104317
+ rememberHttp1OnlyWebSocketOrigin(originKey);
104318
+ }
104319
+ const dispatchOptions = options.upgrade === "websocket" && allowH2Option === void 0 && http1OnlyWebSocketOrigins.has(originKey) ? Object.assign({}, options, { allowH2: false }) : options;
103762
104320
  const trackedHandler = Object.create(handler);
103763
104321
  trackedHandler.onRequestStart = (controller, context) => {
103764
104322
  releaseTransport = (reason) => controller.abort(reason);
103765
104323
  handler.onRequestStart?.(controller, context);
103766
104324
  };
103767
104325
  trackedHandler.onResponseError = (controller, failure2) => {
103768
- observeFailure(failure2, "request");
104326
+ retriedAsHttp1Only = false;
103769
104327
  handler.onResponseError?.(controller, failure2);
104328
+ if (!retriedAsHttp1Only) {
104329
+ observeFailure(failure2, "request");
104330
+ }
103770
104331
  };
103771
104332
  trackedHandler.onResponseStart = (controller, statusCode, responseHeaders, statusMessage) => {
103772
104333
  observeHandshake(statusCode, 101);
103773
104334
  handler.onResponseStart?.(controller, statusCode, responseHeaders, statusMessage);
103774
104335
  };
103775
104336
  trackedHandler.onRequestUpgrade = (controller, statusCode, responseHeaders, transport) => {
103776
- observeHandshake(statusCode, Reflect.get(transport, "session") == null ? 101 : 200);
104337
+ const hasHttp2Session = Reflect.get(transport, "session") != null;
104338
+ transportProtocol = hasHttp2Session ? "h2" : transport instanceof TLSSocket ? "http1" : "ws";
104339
+ observeHandshake(statusCode, hasHttp2Session ? 200 : 101);
104340
+ if (transport instanceof Socket) {
104341
+ transport.setKeepAlive(true, TCP_KEEPALIVE_INITIAL_DELAY_MILLISECONDS);
104342
+ transport.setNoDelay(true);
104343
+ }
104344
+ const parentSocket = Reflect.get(transport, "_parent");
104345
+ if (parentSocket instanceof Socket) {
104346
+ parentSocket.setKeepAlive(true, TCP_KEEPALIVE_INITIAL_DELAY_MILLISECONDS);
104347
+ parentSocket.setNoDelay(true);
104348
+ }
104349
+ transportState = { kind: "open" };
103777
104350
  releaseTransport = (reason) => transport.destroy(reason);
103778
- const onTransportError = (failure2) => observeFailure(failure2, "socket");
104351
+ const onTransportEnd = () => {
104352
+ if (transportState.kind === "open") {
104353
+ transportState = { kind: "eof" };
104354
+ }
104355
+ };
104356
+ const onTransportError = (failure2) => {
104357
+ transportState = { kind: "socket_error" };
104358
+ observeFailure(failure2, "socket");
104359
+ };
103779
104360
  removeTransportObserver = () => {
104361
+ transport.off("end", onTransportEnd);
103780
104362
  transport.off("error", onTransportError);
103781
104363
  transport.off("close", removeTransportObserver);
103782
104364
  };
104365
+ transport.once("end", onTransportEnd);
103783
104366
  transport.on("error", onTransportError);
103784
104367
  transport.once("close", removeTransportObserver);
103785
104368
  return handler.onRequestUpgrade?.(controller, statusCode, responseHeaders, transport);
103786
104369
  };
103787
- return dispatch(options, trackedHandler);
104370
+ return dispatch(dispatchOptions, trackedHandler);
103788
104371
  });
103789
104372
  const endpoint = new URL(url2);
103790
104373
  const headers = relayAuthorization(endpoint);
@@ -103794,6 +104377,16 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103794
104377
  headers
103795
104378
  });
103796
104379
  socket.binaryType = "arraybuffer";
104380
+ const describeTransportClosure = () => {
104381
+ switch (transportState.kind) {
104382
+ case "open":
104383
+ return "open";
104384
+ case "eof":
104385
+ return "eof";
104386
+ case "socket_error":
104387
+ return "socket_error";
104388
+ }
104389
+ };
103797
104390
  const release2 = (reason) => {
103798
104391
  if (released) {
103799
104392
  return;
@@ -103802,7 +104395,6 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103802
104395
  removeTransportObserver();
103803
104396
  releaseTransport(reason);
103804
104397
  };
103805
- let finished = false;
103806
104398
  const timeout = setTimeout(onTimeout, CONNECTION_TIMEOUT_MILLISECONDS);
103807
104399
  const cleanup = () => {
103808
104400
  clearTimeout(timeout);
@@ -103811,7 +104403,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103811
104403
  socket.removeEventListener("error", onError);
103812
104404
  socket.removeEventListener("open", onOpen);
103813
104405
  };
103814
- const fail = (error62) => {
104406
+ function fail(error62) {
103815
104407
  if (finished) {
103816
104408
  return;
103817
104409
  }
@@ -103820,7 +104412,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103820
104412
  socket.close();
103821
104413
  release2(error62);
103822
104414
  reject2(error62);
103823
- };
104415
+ }
103824
104416
  const onAbort = () => {
103825
104417
  fail(
103826
104418
  new RelayConnectionError(
@@ -103862,7 +104454,12 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103862
104454
  }
103863
104455
  finished = true;
103864
104456
  cleanup();
103865
- resolve21({ release: release2, socket });
104457
+ resolve21({
104458
+ describeTransportClosure,
104459
+ release: release2,
104460
+ socket,
104461
+ transportProtocol
104462
+ });
103866
104463
  };
103867
104464
  function onTimeout() {
103868
104465
  fail(
@@ -103884,15 +104481,18 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
103884
104481
  // src/engine/runtime/relay/liveness.ts
103885
104482
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
103886
104483
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
104484
+ var MAX_INBOUND_ACK_EXTENSIONS = 5;
103887
104485
  var RelayLivenessState = class {
103888
104486
  };
103889
104487
  var NotStartedRelayLivenessState = class extends RelayLivenessState {
103890
104488
  };
103891
104489
  var AwaitingHeartbeatAckState = class extends RelayLivenessState {
103892
104490
  timeout;
103893
- constructor(timeout) {
104491
+ remainingExtensions;
104492
+ constructor(timeout, remainingExtensions) {
103894
104493
  super();
103895
104494
  this.timeout = timeout;
104495
+ this.remainingExtensions = remainingExtensions;
103896
104496
  }
103897
104497
  };
103898
104498
  var WaitingForHeartbeatState = class extends RelayLivenessState {
@@ -103921,6 +104521,23 @@ var RelayConnectionLiveness = class {
103921
104521
  this.#timer.schedule(this.#sendHeartbeat, HEARTBEAT_INTERVAL_MILLISECONDS)
103922
104522
  );
103923
104523
  };
104524
+ recordInboundActivity = () => {
104525
+ if (this.#state instanceof AwaitingHeartbeatAckState) {
104526
+ if (this.#state.remainingExtensions === 0) {
104527
+ return;
104528
+ }
104529
+ this.#state.timeout.cancel();
104530
+ this.#state = new AwaitingHeartbeatAckState(
104531
+ this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS),
104532
+ this.#state.remainingExtensions - 1
104533
+ );
104534
+ return;
104535
+ }
104536
+ if (this.#state instanceof WaitingForHeartbeatState || this.#state instanceof NotStartedRelayLivenessState || this.#state instanceof FinishedRelayLivenessState) {
104537
+ return;
104538
+ }
104539
+ throw new Error("Unknown relay liveness state");
104540
+ };
103924
104541
  close = () => {
103925
104542
  if (this.#state instanceof AwaitingHeartbeatAckState) {
103926
104543
  this.#state.timeout.cancel();
@@ -103965,7 +104582,8 @@ var RelayConnectionLiveness = class {
103965
104582
  throw new Error("Heartbeat was scheduled in an invalid state");
103966
104583
  }
103967
104584
  const awaiting = new AwaitingHeartbeatAckState(
103968
- this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
104585
+ this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS),
104586
+ MAX_INBOUND_ACK_EXTENSIONS
103969
104587
  );
103970
104588
  this.#state = awaiting;
103971
104589
  const sent = this.#transport.send({ kind: RUNTIME_HEARTBEAT_KIND });
@@ -104073,13 +104691,21 @@ async function runRelayConnection({
104073
104691
  };
104074
104692
  const stop = () => {
104075
104693
  publisher.flush();
104076
- diagnostics.connectionClosed(connectionEpoch, 1e3, "Daemon stopped", "daemon_stop");
104694
+ diagnostics.connectionClosed(connectionEpoch, 1e3, "Daemon stopped", "daemon_stop", {
104695
+ transportClosure: "local",
104696
+ transportProtocol: relay.transportProtocol,
104697
+ wasClean: true
104698
+ });
104077
104699
  closeRelaySocket(socket, 1e3, "Daemon stopped");
104078
104700
  resolveConnection();
104079
104701
  };
104080
104702
  const failAndClose = (failure2, code, reason, source) => {
104081
104703
  diagnostics.connectionFailed(connectionEpoch, failure2, source);
104082
- diagnostics.connectionClosed(connectionEpoch, code, reason, source);
104704
+ diagnostics.connectionClosed(connectionEpoch, code, reason, source, {
104705
+ transportClosure: "local",
104706
+ transportProtocol: relay.transportProtocol,
104707
+ wasClean: false
104708
+ });
104083
104709
  closeRelaySocket(socket, code, reason);
104084
104710
  rejectConnection(failure2);
104085
104711
  };
@@ -104104,7 +104730,12 @@ async function runRelayConnection({
104104
104730
  connectionEpoch,
104105
104731
  4001,
104106
104732
  "Relay liveness check timed out",
104107
- "heartbeat_timeout"
104733
+ "heartbeat_timeout",
104734
+ {
104735
+ transportClosure: "local",
104736
+ transportProtocol: relay.transportProtocol,
104737
+ wasClean: false
104738
+ }
104108
104739
  );
104109
104740
  closeRelaySocket(socket, 4001, "Relay liveness check timed out");
104110
104741
  resolveConnection();
@@ -104112,7 +104743,11 @@ async function runRelayConnection({
104112
104743
  });
104113
104744
  signal.addEventListener("abort", stop, { once: true });
104114
104745
  const handleClose = (event) => {
104115
- diagnostics.connectionClosed(connectionEpoch, event.code, event.reason, "relay");
104746
+ diagnostics.connectionClosed(connectionEpoch, event.code, event.reason, "relay", {
104747
+ transportClosure: relay.describeTransportClosure(),
104748
+ transportProtocol: relay.transportProtocol,
104749
+ wasClean: event.wasClean
104750
+ });
104116
104751
  if (isRuntimeRelayRevocation(event.code, event.reason)) {
104117
104752
  rejectConnection(new RuntimeRelayRevokedError(event.code, event.reason));
104118
104753
  return;
@@ -104124,10 +104759,17 @@ async function runRelayConnection({
104124
104759
  resolveConnection();
104125
104760
  return;
104126
104761
  }
104762
+ if (socket.readyState === WebSocket10.CLOSED) {
104763
+ return;
104764
+ }
104127
104765
  const cause = Reflect.get(event, "error");
104128
104766
  const failure2 = new Error("Relay WebSocket emitted an error", { cause: cause ?? event });
104129
104767
  diagnostics.connectionFailed(connectionEpoch, failure2, "socket_error");
104130
- diagnostics.connectionClosed(connectionEpoch, 1006, "WebSocket error", "socket_error");
104768
+ diagnostics.connectionClosed(connectionEpoch, 1006, "WebSocket error", "socket_error", {
104769
+ transportClosure: relay.describeTransportClosure(),
104770
+ transportProtocol: relay.transportProtocol,
104771
+ wasClean: false
104772
+ });
104131
104773
  rejectConnection(failure2);
104132
104774
  };
104133
104775
  const handleMessage = (event) => {
@@ -104135,6 +104777,7 @@ async function runRelayConnection({
104135
104777
  if (typeof encoded !== "string") {
104136
104778
  try {
104137
104779
  commands.dispatchChunk(encoded);
104780
+ connectionLiveness.recordInboundActivity();
104138
104781
  } catch (error62) {
104139
104782
  failAndClose(
104140
104783
  new Error("Relay sent an invalid content chunk", { cause: error62 }),
@@ -104148,6 +104791,7 @@ async function runRelayConnection({
104148
104791
  try {
104149
104792
  const message = decodeKnownServiceToDaemonMessage(encoded);
104150
104793
  if (message === null) {
104794
+ connectionLiveness.recordInboundActivity();
104151
104795
  diagnostics.daemonDiagnostic("protocol_message_discarded", "unknown", {
104152
104796
  reason: "unsupported_message"
104153
104797
  });
@@ -104168,6 +104812,7 @@ async function runRelayConnection({
104168
104812
  connectionLiveness.acknowledge();
104169
104813
  return;
104170
104814
  }
104815
+ connectionLiveness.recordInboundActivity();
104171
104816
  commands.dispatch(message);
104172
104817
  } catch (error62) {
104173
104818
  console.error("Mobius daemon rejected a message", error62);
@@ -104391,14 +105036,18 @@ var RuntimeSessionEventPublisher = class {
104391
105036
  };
104392
105037
 
104393
105038
  // src/engine/runtime/run.ts
104394
- var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
105039
+ var INITIAL_RELAY_RETRY_DELAY_MILLISECONDS = 500;
105040
+ var MAXIMUM_RELAY_RETRY_DELAY_MILLISECONDS = 6e4;
104395
105041
  var defaultReportUpgradeAvailability = () => Promise.resolve();
104396
- function waitForRelayRetry(signal, timer) {
105042
+ function relayRetryDelayMilliseconds(attempt) {
105043
+ return Math.min(MAXIMUM_RELAY_RETRY_DELAY_MILLISECONDS, INITIAL_RELAY_RETRY_DELAY_MILLISECONDS * 2 ** attempt);
105044
+ }
105045
+ function waitForRelayRetry(signal, timer, delayMilliseconds) {
104397
105046
  if (signal.aborted) {
104398
105047
  return Promise.resolve();
104399
105048
  }
104400
105049
  return new Promise((resolve21) => {
104401
- const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
105050
+ const retry = timer.schedule(finish, delayMilliseconds);
104402
105051
  function finish() {
104403
105052
  retry.cancel();
104404
105053
  signal.removeEventListener("abort", finish);
@@ -104417,8 +105066,10 @@ async function publishAgentCatalogUntilAvailable(config2, diagnostics, signal, t
104417
105066
  }
104418
105067
  diagnostics.catalogFailed(error62);
104419
105068
  }
105069
+ let retryAttempt = 0;
104420
105070
  while (!signal.aborted) {
104421
- await waitForRelayRetry(signal, timer);
105071
+ await waitForRelayRetry(signal, timer, relayRetryDelayMilliseconds(retryAttempt));
105072
+ retryAttempt += 1;
104422
105073
  try {
104423
105074
  await publishAgentCatalog(config2, signal);
104424
105075
  return;
@@ -104532,6 +105183,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
104532
105183
  announceReadiness();
104533
105184
  });
104534
105185
  const removeAgentProcesses = options.agentProcesses?.add(processes);
105186
+ let retryAttempt = 0;
104535
105187
  try {
104536
105188
  while (!signal.aborted) {
104537
105189
  connectionEpoch += 1;
@@ -104553,6 +105205,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
104553
105205
  reportUpgradeAvailability,
104554
105206
  diagnostics,
104555
105207
  onConnected: () => {
105208
+ retryAttempt = 0;
104556
105209
  if (catalogPublished) {
104557
105210
  options.onConnectionStatus?.("online");
104558
105211
  }
@@ -104570,8 +105223,10 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
104570
105223
  }
104571
105224
  diagnostics.connectionFailed(connectionEpoch, error62, "connection");
104572
105225
  }
105226
+ const retryDelayMilliseconds = relayRetryDelayMilliseconds(retryAttempt);
105227
+ retryAttempt += 1;
104573
105228
  options.onConnectionStatus?.("reconnecting");
104574
- await waitForRelayRetry(signal, timer);
105229
+ await waitForRelayRetry(signal, timer, retryDelayMilliseconds);
104575
105230
  }
104576
105231
  } finally {
104577
105232
  removeAgentProcesses?.();
@@ -104852,4 +105507,4 @@ export {
104852
105507
  * MIT Licensed
104853
105508
  *)
104854
105509
  */
104855
- //# sourceMappingURL=chunk-TDFSYA4U.js.map
105510
+ //# sourceMappingURL=chunk-APGZM3B3.js.map