@moxt-ai/mobius 0.0.452 → 0.0.453

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 (34) hide show
  1. package/dist/{chunk-TZJRGEU4.js → chunk-2Q5CQHJI.js} +2 -2
  2. package/dist/{chunk-TZJRGEU4.js.map → chunk-2Q5CQHJI.js.map} +1 -1
  3. package/dist/{chunk-DVSY3FDV.js → chunk-PVKEDOVN.js} +1335 -156
  4. package/dist/{chunk-DVSY3FDV.js.map → chunk-PVKEDOVN.js.map} +4 -4
  5. package/dist/{cli-NQKQR32P.js → cli-TZ354PVI.js} +3 -3
  6. package/dist/cli.js +2 -2
  7. package/dist/engine/acp/adapter/antigravity/adapter.d.ts.map +1 -1
  8. package/dist/engine/acp/adapter/antigravity/adapter.js +12 -1
  9. package/dist/engine/acp/adapter/antigravity/adapter.js.map +1 -1
  10. package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts +5 -2
  11. package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts.map +1 -1
  12. package/dist/engine/acp/adapter/antigravity/agent-connection.js +172 -22
  13. package/dist/engine/acp/adapter/antigravity/agent-connection.js.map +1 -1
  14. package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts +35 -0
  15. package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts.map +1 -0
  16. package/dist/engine/acp/adapter/antigravity/background-wakeup.js +959 -0
  17. package/dist/engine/acp/adapter/antigravity/background-wakeup.js.map +1 -0
  18. package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -1
  19. package/dist/engine/acp/adapter/execution-connections.js +4 -1
  20. package/dist/engine/acp/adapter/execution-connections.js.map +1 -1
  21. package/dist/engine/session/live/agent-session.d.ts +1 -1
  22. package/dist/engine/session/live/agent-session.d.ts.map +1 -1
  23. package/dist/engine/session/live/agent-session.js +34 -8
  24. package/dist/engine/session/live/agent-session.js.map +1 -1
  25. package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
  26. package/dist/engine/session/manager/session-manager.js +16 -1
  27. package/dist/engine/session/manager/session-manager.js.map +1 -1
  28. package/dist/engine/storage/files/local-files.d.ts +5 -0
  29. package/dist/engine/storage/files/local-files.d.ts.map +1 -1
  30. package/dist/engine/storage/files/local-files.js +38 -0
  31. package/dist/engine/storage/files/local-files.js.map +1 -1
  32. package/dist/engine.js +2 -2
  33. package/package.json +1 -1
  34. /package/dist/{cli-NQKQR32P.js.map → cli-TZ354PVI.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  __export,
4
4
  __using,
5
5
  package_default
6
- } from "./chunk-TZJRGEU4.js";
6
+ } from "./chunk-2Q5CQHJI.js";
7
7
 
8
8
  // src/engine/runtime/relay/runtime-revocation.ts
9
9
  var runtimeRevocationCloseCode = 1008;
@@ -22275,6 +22275,41 @@ async function readFileStart(path6, byteLength) {
22275
22275
  }
22276
22276
  return bytes;
22277
22277
  }
22278
+ async function readScopedFileTail(baseDirectory, requestedRelativePath, maximumBytes) {
22279
+ if (requestedRelativePath.length === 0 || isAbsolute(requestedRelativePath)) {
22280
+ return null;
22281
+ }
22282
+ try {
22283
+ const directory = await canonicalPath(resolve(baseDirectory));
22284
+ const candidate = resolve(directory, requestedRelativePath);
22285
+ if (!withinDirectory(directory, candidate)) {
22286
+ return null;
22287
+ }
22288
+ const target = await canonicalPath(candidate);
22289
+ if (!withinDirectory(directory, target)) {
22290
+ return null;
22291
+ }
22292
+ const handle = await open2(target, constants.O_RDONLY | constants.O_NOFOLLOW);
22293
+ try {
22294
+ const metadata = await handle.stat();
22295
+ if (!metadata.isFile()) {
22296
+ return null;
22297
+ }
22298
+ if (metadata.size === 0 || maximumBytes <= 0) {
22299
+ return { bytes: new Uint8Array(0), offset: 0 };
22300
+ }
22301
+ const offset = Math.max(0, metadata.size - maximumBytes);
22302
+ const length = metadata.size - offset;
22303
+ const buffer = new Uint8Array(length);
22304
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
22305
+ return { bytes: buffer.subarray(0, bytesRead), offset };
22306
+ } finally {
22307
+ await handle.close();
22308
+ }
22309
+ } catch {
22310
+ return null;
22311
+ }
22312
+ }
22278
22313
  async function readFileBytes(path6) {
22279
22314
  return await readFile(path6);
22280
22315
  }
@@ -27675,6 +27710,20 @@ function executableLaunch2(command, args) {
27675
27710
  }
27676
27711
  var platformSpawnOptions = hostPlatform.spawnOptions;
27677
27712
 
27713
+ // src/engine/util/serial-task-queue.ts
27714
+ var SerialTaskQueue = class {
27715
+ #tail = Promise.resolve();
27716
+ run = async (task, signal) => {
27717
+ signal.throwIfAborted();
27718
+ const result = this.#tail.then(() => {
27719
+ signal.throwIfAborted();
27720
+ return task(signal);
27721
+ });
27722
+ this.#tail = result.catch(() => void 0);
27723
+ return await result;
27724
+ };
27725
+ };
27726
+
27678
27727
  // src/engine/util/value-utils.ts
27679
27728
  function truncate(value, maximumLength) {
27680
27729
  return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
@@ -27945,6 +27994,972 @@ function createWritableAcpStream(output2) {
27945
27994
  });
27946
27995
  }
27947
27996
 
27997
+ // src/engine/acp/adapter/antigravity/background-wakeup.ts
27998
+ import { homedir } from "node:os";
27999
+ import { join as join11 } from "node:path";
28000
+
28001
+ // src/engine/util/timer.ts
28002
+ var SystemTimer = class {
28003
+ schedule = (callback, milliseconds) => {
28004
+ const timeout = setTimeout(callback, milliseconds);
28005
+ return {
28006
+ cancel: () => {
28007
+ clearTimeout(timeout);
28008
+ }
28009
+ };
28010
+ };
28011
+ };
28012
+ var systemTimer = new SystemTimer();
28013
+
28014
+ // src/engine/acp/adapter/antigravity/background-wakeup.ts
28015
+ var TRANSCRIPT_TAIL_BYTES = 65536;
28016
+ 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;
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;
28022
+ var MAXIMUM_TOOL_DESCRIPTION_CHARS = 500;
28023
+ var transcriptStepSchema = external_exports.object({
28024
+ content: external_exports.string().optional(),
28025
+ status: external_exports.string().optional(),
28026
+ step_index: external_exports.number().int().nonnegative(),
28027
+ tool_calls: external_exports.array(external_exports.unknown()).optional(),
28028
+ type: external_exports.string()
28029
+ });
28030
+ var EMPTY_INCOMING_OUTCOME = {
28031
+ afterUpdates: [],
28032
+ beforeUpdates: []
28033
+ };
28034
+ function readString3(record2, key) {
28035
+ const value = record2[key];
28036
+ return typeof value === "string" ? value : void 0;
28037
+ }
28038
+ function requestKeyOf(id) {
28039
+ return typeof id === "string" || typeof id === "number" ? id : void 0;
28040
+ }
28041
+ function isRequestMessage2(message) {
28042
+ return "method" in message && "id" in message;
28043
+ }
28044
+ function isNotificationMessage2(message) {
28045
+ return "method" in message && !("id" in message);
28046
+ }
28047
+ function isResponseMessage2(message) {
28048
+ return "id" in message && !("method" in message);
28049
+ }
28050
+ function resolveGeminiHome(launchEnvironment) {
28051
+ const configured = launchEnvironment["GEMINI_HOME"]?.trim();
28052
+ if (configured !== void 0 && configured.length > 0) {
28053
+ return configured;
28054
+ }
28055
+ const home = launchEnvironment["HOME"]?.trim() || launchEnvironment["USERPROFILE"]?.trim() || homedir();
28056
+ return home.length > 0 ? join11(home, ".gemini") : void 0;
28057
+ }
28058
+ async function readTranscriptTailState(launchEnvironment, sessionId, baselineStepIndex) {
28059
+ if (!SESSION_UUID_PATTERN.test(sessionId)) {
28060
+ return null;
28061
+ }
28062
+ const geminiHome = resolveGeminiHome(launchEnvironment);
28063
+ if (geminiHome === void 0) {
28064
+ return null;
28065
+ }
28066
+ const tail = await readScopedFileTail(
28067
+ geminiHome,
28068
+ join11("antigravity-cli", "brain", sessionId, ".system_generated", "logs", "transcript.jsonl"),
28069
+ TRANSCRIPT_TAIL_BYTES
28070
+ );
28071
+ if (tail === null) {
28072
+ return null;
28073
+ }
28074
+ if (tail.bytes.byteLength === 0) {
28075
+ return { maxStepIndex: -1, settledWithoutToolCalls: false, steps: [] };
28076
+ }
28077
+ const text2 = new TextDecoder().decode(tail.bytes);
28078
+ const lines = text2.split("\n");
28079
+ const startIndex = tail.offset > 0 ? 1 : 0;
28080
+ const steps = [];
28081
+ for (const rawLine of lines.slice(startIndex)) {
28082
+ const trimmed = rawLine.trim();
28083
+ if (trimmed.length === 0) {
28084
+ continue;
28085
+ }
28086
+ let parsedJson;
28087
+ try {
28088
+ parsedJson = JSON.parse(trimmed);
28089
+ } catch {
28090
+ continue;
28091
+ }
28092
+ const parsed = transcriptStepSchema.safeParse(parsedJson);
28093
+ if (parsed.success) {
28094
+ steps.push(parsed.data);
28095
+ }
28096
+ }
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 };
28101
+ }
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;
28110
+ }
28111
+ }
28112
+ if (lastPlannerIndex <= 0) {
28113
+ return 0;
28114
+ }
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
+ }
28121
+ }
28122
+ return count;
28123
+ }
28124
+ function extractToolInputRecords(update) {
28125
+ const records = [];
28126
+ const args = update["args"];
28127
+ if (isRecord5(args)) {
28128
+ records.push(args);
28129
+ }
28130
+ const rawInput = update["rawInput"];
28131
+ if (isRecord5(rawInput)) {
28132
+ records.push(rawInput);
28133
+ }
28134
+ return records;
28135
+ }
28136
+ function readInputString(records, key) {
28137
+ for (const record2 of records) {
28138
+ const value = readString3(record2, key)?.trim();
28139
+ if (value !== void 0 && value.length > 0) {
28140
+ return value;
28141
+ }
28142
+ }
28143
+ return void 0;
28144
+ }
28145
+ function readToolCategory(update, inputs, previous) {
28146
+ const name2 = readString3(update, "name");
28147
+ if (name2 === "run_command") {
28148
+ return "command";
28149
+ }
28150
+ if (name2 === "schedule") {
28151
+ return "schedule";
28152
+ }
28153
+ if (name2 === "run_workflow") {
28154
+ return "workflow";
28155
+ }
28156
+ if (name2 === "invoke_subagent") {
28157
+ return "subagent";
28158
+ }
28159
+ if (name2 === "manage_subagents") {
28160
+ return "manage-subagents";
28161
+ }
28162
+ const title = readString3(update, "title");
28163
+ if (title === "Run invoke_subagent" || title === "Running invoke_subagent" || title === "Run invoke_subagent?" || title === "Running start_subagent" || title === "Run start_subagent?") {
28164
+ return "subagent";
28165
+ }
28166
+ if (title === "Run schedule" || title === "Running schedule") {
28167
+ return "schedule";
28168
+ }
28169
+ if (title === "Run manage_subagents") {
28170
+ return "manage-subagents";
28171
+ }
28172
+ if (previous?.category !== void 0 && previous.category !== null) {
28173
+ return previous.category;
28174
+ }
28175
+ if (readInputString(inputs, "CommandLine") !== void 0) {
28176
+ return "command";
28177
+ }
28178
+ return null;
28179
+ }
28180
+ function inspectToolMetadata(update, previous) {
28181
+ const inputs = extractToolInputRecords(update);
28182
+ const category = readToolCategory(update, inputs, previous);
28183
+ let isDaemon = previous?.isDaemon ?? false;
28184
+ let subagentKillCount = previous?.subagentKillCount ?? 0;
28185
+ let subagentKillAll = previous?.subagentKillAll ?? false;
28186
+ for (const record2 of inputs) {
28187
+ if (record2["IsDaemon"] === true) {
28188
+ isDaemon = true;
28189
+ }
28190
+ const cron = readString3(record2, "CronExpression")?.trim();
28191
+ if (cron !== void 0 && cron.length > 0) {
28192
+ isDaemon = true;
28193
+ }
28194
+ if (category === "manage-subagents") {
28195
+ const action = readString3(record2, "Action");
28196
+ if (action === "kill_all") {
28197
+ subagentKillAll = true;
28198
+ } else if (action === "kill" && Array.isArray(record2["ConversationIds"])) {
28199
+ subagentKillCount = Math.max(subagentKillCount, record2["ConversationIds"].length);
28200
+ }
28201
+ }
28202
+ }
28203
+ const description = readInputString(inputs, "toolSummary") ?? readInputString(inputs, "Description") ?? readInputString(inputs, "Role") ?? readInputString(inputs, "CommandLine") ?? readInputString(inputs, "Prompt") ?? readString3(update, "title") ?? previous?.description;
28204
+ return {
28205
+ category,
28206
+ description: description === void 0 ? void 0 : truncate(description, MAXIMUM_TOOL_DESCRIPTION_CHARS),
28207
+ isDaemon,
28208
+ subagentKillAll,
28209
+ subagentKillCount
28210
+ };
28211
+ }
28212
+ function backgroundKindFor(category) {
28213
+ switch (category) {
28214
+ case "command":
28215
+ return "shell";
28216
+ case "subagent":
28217
+ return "subagent";
28218
+ case "schedule":
28219
+ case "workflow":
28220
+ return "other";
28221
+ case "manage-subagents":
28222
+ case null:
28223
+ return null;
28224
+ }
28225
+ }
28226
+ function makeMetaNotification(sessionId, metaKey, payload) {
28227
+ return {
28228
+ sessionId,
28229
+ update: {
28230
+ _meta: { [metaKey]: payload },
28231
+ sessionUpdate: "session_info_update"
28232
+ }
28233
+ };
28234
+ }
28235
+ function isWakeupStartUpdateKind(updateKind) {
28236
+ switch (updateKind) {
28237
+ case "agent_message_chunk":
28238
+ case "agent_thought_chunk":
28239
+ case "agent_message":
28240
+ case "agent_thought":
28241
+ case "tool_call":
28242
+ return true;
28243
+ default:
28244
+ return false;
28245
+ }
28246
+ }
28247
+ function isWakeupChunkUpdateKind(updateKind) {
28248
+ return updateKind === "agent_message_chunk" || updateKind === "agent_thought_chunk" || updateKind === "agent_message" || updateKind === "agent_thought";
28249
+ }
28250
+ var AntigravityBackgroundWakeup = class {
28251
+ #emitMetaUpdate;
28252
+ #launchEnvironment;
28253
+ #timer;
28254
+ #sessions = /* @__PURE__ */ new Map();
28255
+ #pendingRequests = /* @__PURE__ */ new Map();
28256
+ #disposed = false;
28257
+ constructor(options) {
28258
+ this.#emitMetaUpdate = options.emitMetaUpdate;
28259
+ this.#launchEnvironment = options.launchEnvironment;
28260
+ this.#timer = options.timer ?? systemTimer;
28261
+ }
28262
+ #ensureSession = (sessionId) => {
28263
+ const existing = this.#sessions.get(sessionId);
28264
+ if (existing !== void 0) {
28265
+ return existing;
28266
+ }
28267
+ const created = {
28268
+ activeInteractions: 0,
28269
+ backgroundTasks: /* @__PURE__ */ new Map(),
28270
+ baselineStepIndex: -1,
28271
+ lastEmittedBackgroundKey: "[]",
28272
+ phase: { cancelRequested: false, kind: "idle" },
28273
+ toolMetadata: /* @__PURE__ */ new Map(),
28274
+ wakeupGeneration: 0
28275
+ };
28276
+ this.#sessions.set(sessionId, created);
28277
+ return created;
28278
+ };
28279
+ #cancelWakeupTimers = (phase) => {
28280
+ if (phase.kind !== "wakeup") {
28281
+ return;
28282
+ }
28283
+ switch (phase.stage.kind) {
28284
+ case "awaiting-output":
28285
+ phase.stage.timeout.cancel();
28286
+ return;
28287
+ case "blocked-on-work":
28288
+ return;
28289
+ case "streaming":
28290
+ phase.stage.transcriptCheck?.cancel();
28291
+ phase.stage.fallbackTimeout.cancel();
28292
+ return;
28293
+ default: {
28294
+ const unreachable2 = phase.stage;
28295
+ throw new Error(`Unexpected wakeup stage: ${String(unreachable2)}`);
28296
+ }
28297
+ }
28298
+ };
28299
+ #takeBackgroundTasksUpdate = (sessionId, session) => {
28300
+ const tasks = [...session.backgroundTasks.values()];
28301
+ const serialized = JSON.stringify(tasks);
28302
+ if (serialized === session.lastEmittedBackgroundKey) {
28303
+ return null;
28304
+ }
28305
+ session.lastEmittedBackgroundKey = serialized;
28306
+ return makeMetaNotification(sessionId, BACKGROUND_TASKS_META, tasks);
28307
+ };
28308
+ #removeSubagentTasks = (session, count) => {
28309
+ if (count <= 0) {
28310
+ return;
28311
+ }
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;
28321
+ }
28322
+ }
28323
+ };
28324
+ #dropAwaitingResultTasks = (session) => {
28325
+ for (const [taskId, task] of session.backgroundTasks) {
28326
+ if (task.state === "awaiting-results") {
28327
+ session.backgroundTasks.delete(taskId);
28328
+ }
28329
+ }
28330
+ };
28331
+ #hasSubagentTasks = (session) => {
28332
+ for (const task of session.backgroundTasks.values()) {
28333
+ if (task.kind === "subagent") {
28334
+ return true;
28335
+ }
28336
+ }
28337
+ return false;
28338
+ };
28339
+ #oldestRunningSubagentId = (session) => {
28340
+ for (const task of session.backgroundTasks.values()) {
28341
+ if (task.kind === "subagent" && task.state === "running") {
28342
+ return task.taskId;
28343
+ }
28344
+ }
28345
+ return void 0;
28346
+ };
28347
+ #setWakeupAwaitingOutput = (sessionId, session, generation, openToolIds) => {
28348
+ this.#cancelWakeupTimers(session.phase);
28349
+ const timeout = this.#timer.schedule(() => {
28350
+ this.#finishWakeupFromTimer(sessionId, generation, "end_turn");
28351
+ }, WAKEUP_AWAITING_OUTPUT_MS);
28352
+ session.phase = {
28353
+ generation,
28354
+ kind: "wakeup",
28355
+ openToolIds,
28356
+ stage: { kind: "awaiting-output", timeout }
28357
+ };
28358
+ };
28359
+ #setWakeupBlockedOnWork = (session, generation, openToolIds) => {
28360
+ this.#cancelWakeupTimers(session.phase);
28361
+ session.phase = {
28362
+ generation,
28363
+ kind: "wakeup",
28364
+ openToolIds,
28365
+ stage: { kind: "blocked-on-work" }
28366
+ };
28367
+ };
28368
+ #setWakeupStreaming = (sessionId, session, generation, openToolIds) => {
28369
+ 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);
28377
+ session.phase = {
28378
+ generation,
28379
+ kind: "wakeup",
28380
+ openToolIds,
28381
+ stage: { fallbackTimeout, kind: "streaming", transcriptCheck }
28382
+ };
28383
+ };
28384
+ #enterWakeup = (sessionId, session, taskIds) => {
28385
+ const notifications = [];
28386
+ const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
28387
+ if (bgNotification !== null) {
28388
+ notifications.push(bgNotification);
28389
+ }
28390
+ session.wakeupGeneration += 1;
28391
+ const generation = session.wakeupGeneration;
28392
+ this.#setWakeupAwaitingOutput(sessionId, session, generation, /* @__PURE__ */ new Set());
28393
+ notifications.push(
28394
+ makeMetaNotification(sessionId, AGENT_TURN_META, {
28395
+ reason: "background-task",
28396
+ stage: "started",
28397
+ taskIds: [...taskIds]
28398
+ })
28399
+ );
28400
+ return notifications;
28401
+ };
28402
+ #finishWakeup = (sessionId, session, stopReason, cancelRequested) => {
28403
+ if (session.phase.kind !== "wakeup") {
28404
+ return [];
28405
+ }
28406
+ this.#cancelWakeupTimers(session.phase);
28407
+ session.phase = { cancelRequested, kind: "idle" };
28408
+ this.#dropAwaitingResultTasks(session);
28409
+ const notifications = [];
28410
+ const bgNotification = this.#takeBackgroundTasksUpdate(sessionId, session);
28411
+ if (bgNotification !== null) {
28412
+ notifications.push(bgNotification);
28413
+ }
28414
+ notifications.push(
28415
+ makeMetaNotification(sessionId, AGENT_TURN_META, {
28416
+ stage: "ended",
28417
+ stopReason
28418
+ })
28419
+ );
28420
+ return notifications;
28421
+ };
28422
+ #checkWakeupTranscript = async (sessionId, generation, allowRetry) => {
28423
+ if (this.#disposed) {
28424
+ return;
28425
+ }
28426
+ const session = this.#sessions.get(sessionId);
28427
+ if (session === void 0 || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
28428
+ return;
28429
+ }
28430
+ if (session.phase.stage.kind !== "streaming") {
28431
+ return;
28432
+ }
28433
+ const tail = await readTranscriptTailState(this.#launchEnvironment, sessionId, session.baselineStepIndex);
28434
+ if (this.#disposed) {
28435
+ return;
28436
+ }
28437
+ const current = this.#sessions.get(sessionId);
28438
+ if (current === void 0 || current.phase.kind !== "wakeup" || current.phase.generation !== generation) {
28439
+ return;
28440
+ }
28441
+ if (current.phase.stage.kind !== "streaming") {
28442
+ return;
28443
+ }
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
+ }
28449
+ return;
28450
+ }
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
+ };
28463
+ }
28464
+ };
28465
+ #finishWakeupFromTimer = (sessionId, generation, stopReason) => {
28466
+ if (this.#disposed) {
28467
+ return;
28468
+ }
28469
+ const session = this.#sessions.get(sessionId);
28470
+ if (session === void 0 || session.phase.kind !== "wakeup" || session.phase.generation !== generation) {
28471
+ return;
28472
+ }
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
+ });
28488
+ };
28489
+ #promoteOpenWakeupToolsToBackground = (session) => {
28490
+ if (session.phase.kind !== "wakeup" || session.phase.openToolIds.size === 0) {
28491
+ return;
28492
+ }
28493
+ const remainingOpenToolIds = new Set(session.phase.openToolIds);
28494
+ let changed = false;
28495
+ for (const toolCallId of session.phase.openToolIds) {
28496
+ const meta3 = session.toolMetadata.get(toolCallId);
28497
+ if (meta3 === void 0 || meta3.isDaemon) {
28498
+ continue;
28499
+ }
28500
+ const kind = backgroundKindFor(meta3.category);
28501
+ if (kind === "shell" || kind === "other") {
28502
+ remainingOpenToolIds.delete(toolCallId);
28503
+ changed = true;
28504
+ session.backgroundTasks.set(toolCallId, {
28505
+ ...meta3.description === void 0 ? {} : { description: meta3.description },
28506
+ kind,
28507
+ state: "running",
28508
+ taskId: toolCallId,
28509
+ toolUseId: toolCallId
28510
+ });
28511
+ }
28512
+ }
28513
+ if (changed) {
28514
+ session.phase = { ...session.phase, openToolIds: remainingOpenToolIds };
28515
+ }
28516
+ };
28517
+ #pauseOrResumeWakeupTimers = (sessionId, session) => {
28518
+ if (session.phase.kind !== "wakeup") {
28519
+ return;
28520
+ }
28521
+ if (session.phase.openToolIds.size > 0 || session.activeInteractions > 0) {
28522
+ this.#setWakeupBlockedOnWork(session, session.phase.generation, session.phase.openToolIds);
28523
+ } else if (session.phase.stage.kind === "blocked-on-work") {
28524
+ this.#setWakeupAwaitingOutput(sessionId, session, session.phase.generation, session.phase.openToolIds);
28525
+ }
28526
+ };
28527
+ #applyClientPromptToolUpdate = (session, update, cancelled) => {
28528
+ const toolCallId = readString3(update, "toolCallId");
28529
+ const status = readString3(update, "status");
28530
+ if (toolCallId === void 0 || status === void 0) {
28531
+ return;
28532
+ }
28533
+ const meta3 = inspectToolMetadata(update, session.toolMetadata.get(toolCallId));
28534
+ session.toolMetadata.set(toolCallId, meta3);
28535
+ if (meta3.isDaemon) {
28536
+ session.backgroundTasks.delete(toolCallId);
28537
+ return;
28538
+ }
28539
+ 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
+ }
28545
+ return;
28546
+ }
28547
+ 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
+ });
28556
+ }
28557
+ return;
28558
+ }
28559
+ const kind = backgroundKindFor(meta3.category);
28560
+ if (kind === null) {
28561
+ return;
28562
+ }
28563
+ if (!cancelled && status === "in_progress") {
28564
+ session.backgroundTasks.set(toolCallId, {
28565
+ ...meta3.description === void 0 ? {} : { description: meta3.description },
28566
+ kind,
28567
+ state: "running",
28568
+ taskId: toolCallId,
28569
+ toolUseId: toolCallId
28570
+ });
28571
+ return;
28572
+ }
28573
+ if (status === "pending" || status === "completed" || status === "failed" || status === "cancelled") {
28574
+ session.backgroundTasks.delete(toolCallId);
28575
+ }
28576
+ };
28577
+ #applyWakeupToolUpdate = (sessionId, session, update, notifications) => {
28578
+ if (session.phase.kind !== "wakeup") {
28579
+ return;
28580
+ }
28581
+ const toolCallId = readString3(update, "toolCallId");
28582
+ const status = readString3(update, "status");
28583
+ const updateKind = readString3(update, "sessionUpdate");
28584
+ if (toolCallId === void 0 || status === void 0 || updateKind === void 0) {
28585
+ return;
28586
+ }
28587
+ const meta3 = inspectToolMetadata(update, session.toolMetadata.get(toolCallId));
28588
+ session.toolMetadata.set(toolCallId, meta3);
28589
+ const trackedExisting = session.backgroundTasks.get(toolCallId);
28590
+ if (trackedExisting !== void 0) {
28591
+ if (status === "completed") {
28592
+ session.backgroundTasks.set(toolCallId, { ...trackedExisting, state: "awaiting-results" });
28593
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28594
+ if (bg2 !== null) {
28595
+ notifications.push(bg2);
28596
+ }
28597
+ if (session.phase.stage.kind === "streaming") {
28598
+ this.#setWakeupAwaitingOutput(
28599
+ sessionId,
28600
+ session,
28601
+ session.phase.generation,
28602
+ session.phase.openToolIds
28603
+ );
28604
+ }
28605
+ } else if (status === "failed" || status === "cancelled") {
28606
+ session.backgroundTasks.delete(toolCallId);
28607
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28608
+ if (bg2 !== null) {
28609
+ notifications.push(bg2);
28610
+ }
28611
+ }
28612
+ return;
28613
+ }
28614
+ if (meta3.isDaemon) {
28615
+ if (session.phase.openToolIds.has(toolCallId)) {
28616
+ const nextOpenToolIds = new Set(session.phase.openToolIds);
28617
+ nextOpenToolIds.delete(toolCallId);
28618
+ session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
28619
+ }
28620
+ return;
28621
+ }
28622
+ if (updateKind === "tool_call" && (status === "in_progress" || status === "pending")) {
28623
+ if (!session.phase.openToolIds.has(toolCallId)) {
28624
+ const nextOpenToolIds = new Set(session.phase.openToolIds);
28625
+ nextOpenToolIds.add(toolCallId);
28626
+ session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
28627
+ }
28628
+ this.#pauseOrResumeWakeupTimers(sessionId, session);
28629
+ return;
28630
+ }
28631
+ if (status === "completed" || status === "failed" || status === "cancelled") {
28632
+ if (session.phase.openToolIds.has(toolCallId)) {
28633
+ const nextOpenToolIds = new Set(session.phase.openToolIds);
28634
+ nextOpenToolIds.delete(toolCallId);
28635
+ session.phase = { ...session.phase, openToolIds: nextOpenToolIds };
28636
+ }
28637
+ 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
+ });
28645
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28646
+ if (bg2 !== null) {
28647
+ notifications.push(bg2);
28648
+ }
28649
+ } 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);
28654
+ }
28655
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28656
+ if (bg2 !== null) {
28657
+ notifications.push(bg2);
28658
+ }
28659
+ }
28660
+ this.#pauseOrResumeWakeupTimers(sessionId, session);
28661
+ }
28662
+ };
28663
+ onOutgoingMessage = async (message) => {
28664
+ if (this.#disposed || !isRequestMessage2(message)) {
28665
+ return;
28666
+ }
28667
+ const key = requestKeyOf(message.id);
28668
+ const params = isRecord5(message.params) ? message.params : void 0;
28669
+ const sessionId = params === void 0 ? void 0 : readString3(params, "sessionId");
28670
+ switch (message.method) {
28671
+ case methods.agent.session.load: {
28672
+ if (sessionId === void 0) {
28673
+ return;
28674
+ }
28675
+ const session = this.#ensureSession(sessionId);
28676
+ this.#cancelWakeupTimers(session.phase);
28677
+ session.phase = { kind: "loading", requestKey: key };
28678
+ if (key !== void 0) {
28679
+ this.#pendingRequests.set(key, { kind: "load", sessionId });
28680
+ }
28681
+ return;
28682
+ }
28683
+ case methods.agent.session.new:
28684
+ case methods.agent.session.resume: {
28685
+ if (sessionId !== void 0 && key !== void 0) {
28686
+ this.#pendingRequests.set(key, { kind: "session-open", sessionId });
28687
+ }
28688
+ return;
28689
+ }
28690
+ case methods.agent.session.prompt: {
28691
+ if (sessionId === void 0) {
28692
+ return;
28693
+ }
28694
+ const session = this.#ensureSession(sessionId);
28695
+ if (session.phase.kind === "wakeup") {
28696
+ for (const notification of this.#finishWakeup(sessionId, session, "end_turn", false)) {
28697
+ this.#emitMetaUpdate(notification);
28698
+ }
28699
+ }
28700
+ const tail = await readTranscriptTailState(
28701
+ this.#launchEnvironment,
28702
+ sessionId,
28703
+ session.baselineStepIndex
28704
+ );
28705
+ const prePromptStepIndex = Math.max(session.baselineStepIndex, tail?.maxStepIndex ?? -1);
28706
+ session.baselineStepIndex = prePromptStepIndex;
28707
+ session.phase = {
28708
+ cancelled: false,
28709
+ kind: "client-prompt",
28710
+ prePromptStepIndex,
28711
+ requestKey: key
28712
+ };
28713
+ if (key !== void 0) {
28714
+ this.#pendingRequests.set(key, { kind: "prompt", sessionId });
28715
+ }
28716
+ return;
28717
+ }
28718
+ default:
28719
+ return;
28720
+ }
28721
+ };
28722
+ onIncomingMessage = async (message) => {
28723
+ if (this.#disposed) {
28724
+ return EMPTY_INCOMING_OUTCOME;
28725
+ }
28726
+ if (isResponseMessage2(message)) {
28727
+ const key = requestKeyOf(message.id);
28728
+ const tracked = key === void 0 ? void 0 : this.#pendingRequests.get(key);
28729
+ if (key !== void 0) {
28730
+ this.#pendingRequests.delete(key);
28731
+ }
28732
+ if (tracked === void 0) {
28733
+ return EMPTY_INCOMING_OUTCOME;
28734
+ }
28735
+ const session2 = this.#ensureSession(tracked.sessionId);
28736
+ if (tracked.kind === "load" || tracked.kind === "session-open") {
28737
+ const tail2 = await readTranscriptTailState(
28738
+ this.#launchEnvironment,
28739
+ tracked.sessionId,
28740
+ session2.baselineStepIndex
28741
+ );
28742
+ if (tail2 !== null) {
28743
+ session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail2.maxStepIndex);
28744
+ }
28745
+ if (tracked.kind === "load") {
28746
+ session2.phase = { cancelRequested: false, kind: "idle" };
28747
+ }
28748
+ return EMPTY_INCOMING_OUTCOME;
28749
+ }
28750
+ 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";
28752
+ const tail = await readTranscriptTailState(
28753
+ this.#launchEnvironment,
28754
+ tracked.sessionId,
28755
+ session2.baselineStepIndex
28756
+ );
28757
+ if (tail !== null) {
28758
+ session2.baselineStepIndex = Math.max(session2.baselineStepIndex, tail.maxStepIndex);
28759
+ if (!promptCancelled) {
28760
+ const consumedSubagents = countConsumedSubagentIdles(
28761
+ tail.steps,
28762
+ prePromptStepIndex,
28763
+ session2.baselineStepIndex
28764
+ );
28765
+ this.#removeSubagentTasks(session2, consumedSubagents);
28766
+ }
28767
+ }
28768
+ if (promptCancelled) {
28769
+ session2.backgroundTasks.clear();
28770
+ }
28771
+ session2.phase = { cancelRequested: promptCancelled, kind: "idle" };
28772
+ const bg2 = this.#takeBackgroundTasksUpdate(tracked.sessionId, session2);
28773
+ return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates: [bg2] };
28774
+ }
28775
+ if (!isNotificationMessage2(message) || message.method !== methods.client.session.update) {
28776
+ return EMPTY_INCOMING_OUTCOME;
28777
+ }
28778
+ const params = isRecord5(message.params) ? message.params : void 0;
28779
+ const sessionId = params === void 0 ? void 0 : readString3(params, "sessionId");
28780
+ const update = params === void 0 ? void 0 : params["update"];
28781
+ if (sessionId === void 0 || !isRecord5(update)) {
28782
+ return EMPTY_INCOMING_OUTCOME;
28783
+ }
28784
+ const updateKind = readString3(update, "sessionUpdate");
28785
+ if (updateKind === void 0) {
28786
+ return EMPTY_INCOMING_OUTCOME;
28787
+ }
28788
+ const session = this.#ensureSession(sessionId);
28789
+ switch (session.phase.kind) {
28790
+ case "loading":
28791
+ return EMPTY_INCOMING_OUTCOME;
28792
+ case "client-prompt": {
28793
+ if (updateKind === "tool_call" || updateKind === "tool_call_update") {
28794
+ this.#applyClientPromptToolUpdate(session, update, session.phase.cancelled);
28795
+ }
28796
+ return EMPTY_INCOMING_OUTCOME;
28797
+ }
28798
+ case "idle": {
28799
+ if (updateKind === "tool_call_update") {
28800
+ const toolCallId = readString3(update, "toolCallId");
28801
+ const status = readString3(update, "status");
28802
+ if (toolCallId !== void 0 && status !== void 0) {
28803
+ const existing = session.backgroundTasks.get(toolCallId);
28804
+ if (existing !== void 0) {
28805
+ if (status === "failed" || status === "cancelled") {
28806
+ session.backgroundTasks.delete(toolCallId);
28807
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28808
+ return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
28809
+ }
28810
+ if (status === "completed") {
28811
+ if (session.phase.cancelRequested) {
28812
+ session.backgroundTasks.delete(toolCallId);
28813
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28814
+ return bg2 === null ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [bg2], beforeUpdates: [] };
28815
+ }
28816
+ session.backgroundTasks.set(toolCallId, {
28817
+ ...existing,
28818
+ state: "awaiting-results"
28819
+ });
28820
+ return {
28821
+ afterUpdates: [],
28822
+ beforeUpdates: this.#enterWakeup(sessionId, session, [toolCallId])
28823
+ };
28824
+ }
28825
+ }
28826
+ }
28827
+ return EMPTY_INCOMING_OUTCOME;
28828
+ }
28829
+ if (session.phase.cancelRequested || !isWakeupStartUpdateKind(updateKind)) {
28830
+ return EMPTY_INCOMING_OUTCOME;
28831
+ }
28832
+ if (updateKind === "tool_call") {
28833
+ const meta3 = inspectToolMetadata(update, void 0);
28834
+ if (meta3.isDaemon) {
28835
+ return EMPTY_INCOMING_OUTCOME;
28836
+ }
28837
+ }
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" });
28843
+ }
28844
+ }
28845
+ const startedNotifications = this.#enterWakeup(
28846
+ sessionId,
28847
+ session,
28848
+ subagentTaskId === void 0 ? [] : [subagentTaskId]
28849
+ );
28850
+ const extraWakeup = [];
28851
+ this.#handleWakeupUpdate(sessionId, session, updateKind, update, extraWakeup);
28852
+ return {
28853
+ afterUpdates: [],
28854
+ beforeUpdates: [...startedNotifications, ...extraWakeup]
28855
+ };
28856
+ }
28857
+ case "wakeup": {
28858
+ const beforeUpdates = [];
28859
+ this.#handleWakeupUpdate(sessionId, session, updateKind, update, beforeUpdates);
28860
+ return beforeUpdates.length === 0 ? EMPTY_INCOMING_OUTCOME : { afterUpdates: [], beforeUpdates };
28861
+ }
28862
+ default: {
28863
+ const unreachable2 = session.phase;
28864
+ throw new Error(`Unexpected Antigravity session phase: ${String(unreachable2)}`);
28865
+ }
28866
+ }
28867
+ };
28868
+ #handleWakeupUpdate = (sessionId, session, updateKind, update, beforeUpdates) => {
28869
+ if (session.phase.kind !== "wakeup") {
28870
+ return;
28871
+ }
28872
+ if (updateKind === "tool_call" || updateKind === "tool_call_update") {
28873
+ this.#applyWakeupToolUpdate(sessionId, session, update, beforeUpdates);
28874
+ return;
28875
+ }
28876
+ if (isWakeupChunkUpdateKind(updateKind)) {
28877
+ this.#promoteOpenWakeupToolsToBackground(session);
28878
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28879
+ if (bg2 !== null) {
28880
+ beforeUpdates.push(bg2);
28881
+ }
28882
+ if (session.phase.openToolIds.size === 0 && session.activeInteractions === 0) {
28883
+ this.#setWakeupStreaming(sessionId, session, session.phase.generation, session.phase.openToolIds);
28884
+ }
28885
+ }
28886
+ };
28887
+ beginInteraction = (sessionId) => {
28888
+ if (this.#disposed) {
28889
+ return;
28890
+ }
28891
+ const session = this.#ensureSession(sessionId);
28892
+ session.activeInteractions += 1;
28893
+ this.#pauseOrResumeWakeupTimers(sessionId, session);
28894
+ };
28895
+ endInteraction = (sessionId) => {
28896
+ if (this.#disposed) {
28897
+ return;
28898
+ }
28899
+ const session = this.#sessions.get(sessionId);
28900
+ if (session === void 0) {
28901
+ return;
28902
+ }
28903
+ session.activeInteractions = Math.max(0, session.activeInteractions - 1);
28904
+ this.#pauseOrResumeWakeupTimers(sessionId, session);
28905
+ };
28906
+ cancelSession = (sessionId) => {
28907
+ if (this.#disposed) {
28908
+ return "retain";
28909
+ }
28910
+ const session = this.#ensureSession(sessionId);
28911
+ const mustClose = session.phase.kind === "wakeup" || this.#hasSubagentTasks(session);
28912
+ if (mustClose) {
28913
+ this.#cancelWakeupTimers(session.phase);
28914
+ session.backgroundTasks.clear();
28915
+ session.phase = { cancelRequested: true, kind: "idle" };
28916
+ return "close";
28917
+ }
28918
+ if (session.phase.kind === "client-prompt") {
28919
+ session.phase = { ...session.phase, cancelled: true };
28920
+ } else if (session.phase.kind === "idle") {
28921
+ session.phase = { cancelRequested: true, kind: "idle" };
28922
+ }
28923
+ return "retain";
28924
+ };
28925
+ onUnexpectedProcessExit = (message) => {
28926
+ if (this.#disposed) {
28927
+ return;
28928
+ }
28929
+ for (const [sessionId, session] of this.#sessions) {
28930
+ const wasWakeup = session.phase.kind === "wakeup";
28931
+ this.#cancelWakeupTimers(session.phase);
28932
+ session.backgroundTasks.clear();
28933
+ if (wasWakeup) {
28934
+ session.phase = { cancelRequested: false, kind: "idle" };
28935
+ this.#emitMetaUpdate(
28936
+ makeMetaNotification(sessionId, AGENT_TURN_META, {
28937
+ message,
28938
+ stage: "failed"
28939
+ })
28940
+ );
28941
+ } else if (session.phase.kind === "idle") {
28942
+ session.phase = { cancelRequested: false, kind: "idle" };
28943
+ }
28944
+ const bg2 = this.#takeBackgroundTasksUpdate(sessionId, session);
28945
+ if (bg2 !== null) {
28946
+ this.#emitMetaUpdate(bg2);
28947
+ }
28948
+ }
28949
+ };
28950
+ dispose = () => {
28951
+ if (this.#disposed) {
28952
+ return;
28953
+ }
28954
+ this.#disposed = true;
28955
+ for (const session of this.#sessions.values()) {
28956
+ this.#cancelWakeupTimers(session.phase);
28957
+ }
28958
+ this.#sessions.clear();
28959
+ this.#pendingRequests.clear();
28960
+ };
28961
+ };
28962
+
27948
28963
  // src/engine/acp/adapter/antigravity/agent-connection.ts
27949
28964
  var FULL_ACCESS_MODE_ID = "full-access";
27950
28965
  var FULL_ACCESS_MODE_NAME = "Full access";
@@ -28041,23 +29056,49 @@ function identifySessionUpdate(update, state) {
28041
29056
  return { nextState: { kind: "none" }, update };
28042
29057
  }
28043
29058
  }
28044
- function isRequestMessage2(message) {
29059
+ function isRequestMessage3(message) {
28045
29060
  return "method" in message && "id" in message;
28046
29061
  }
28047
- function isNotificationMessage2(message) {
29062
+ function isNotificationMessage3(message) {
28048
29063
  return "method" in message && !("id" in message);
28049
29064
  }
28050
- function isResponseMessage2(message) {
29065
+ function isResponseMessage3(message) {
28051
29066
  return "id" in message && !("method" in message);
28052
29067
  }
28053
- function requestKeyOf(id) {
29068
+ function requestKeyOf2(id) {
28054
29069
  return typeof id === "string" || typeof id === "number" ? id : void 0;
28055
29070
  }
29071
+ function hasMobiusWakeupMeta(update) {
29072
+ if (update.sessionUpdate !== "session_info_update") {
29073
+ return false;
29074
+ }
29075
+ const meta3 = update._meta;
29076
+ return meta3 !== void 0 && meta3 !== null && (BACKGROUND_TASKS_META in meta3 || AGENT_TURN_META in meta3);
29077
+ }
29078
+ function toJsonRpcNotification(notification) {
29079
+ return {
29080
+ jsonrpc: "2.0",
29081
+ method: methods.client.session.update,
29082
+ params: notification
29083
+ };
29084
+ }
29085
+ var activeConnectionsByClient = /* @__PURE__ */ new WeakMap();
29086
+ async function prepareAntigravitySessionCancel(clientConnection2, sessionId) {
29087
+ const owner = activeConnectionsByClient.get(clientConnection2);
29088
+ if (owner === void 0) {
29089
+ return "retain";
29090
+ }
29091
+ return await owner.prepareSessionCancel(sessionId);
29092
+ }
28056
29093
  var AntigravityAgentConnection = class {
28057
29094
  connection;
28058
29095
  termination;
28059
29096
  #child;
28060
29097
  #consumeStderr;
29098
+ #clientOnUpdate;
29099
+ #backgroundWakeup;
29100
+ #deliveries = new SerialTaskQueue();
29101
+ #deliveryAbort = new AbortController();
28061
29102
  #permissionModes = /* @__PURE__ */ new Map();
28062
29103
  #messageStreams = /* @__PURE__ */ new Map();
28063
29104
  #pendingRequests = /* @__PURE__ */ new Map();
@@ -28066,21 +29107,30 @@ var AntigravityAgentConnection = class {
28066
29107
  #sessionEstablished = false;
28067
29108
  #closePromise = null;
28068
29109
  constructor(options) {
29110
+ this.#clientOnUpdate = options.client.onUpdate;
29111
+ const launchEnvironment = {
29112
+ ...process.env,
29113
+ ...options.environment,
29114
+ BROWSER: "false"
29115
+ };
29116
+ this.#backgroundWakeup = new AntigravityBackgroundWakeup({
29117
+ emitMetaUpdate: (notification) => {
29118
+ this.#queueMetaUpdate(notification);
29119
+ },
29120
+ launchEnvironment
29121
+ });
28069
29122
  const launch = executableLaunch2(options.command, ["acp"]);
28070
29123
  const child = spawn2(launch.command, [...launch.arguments], {
28071
29124
  cwd: options.cwd,
28072
29125
  ...platformSpawnOptions,
28073
- env: {
28074
- ...process.env,
28075
- ...options.environment,
28076
- BROWSER: "false"
28077
- },
29126
+ env: launchEnvironment,
28078
29127
  shell: false,
28079
29128
  stdio: ["pipe", "pipe", "pipe"]
28080
29129
  });
28081
29130
  this.#child = child;
28082
29131
  const { stdin, stdout, stderr } = child;
28083
29132
  if (stdin === null || stdout === null || stderr === null) {
29133
+ this.#backgroundWakeup.dispose();
28084
29134
  child.kill("SIGKILL");
28085
29135
  throw new AcpExecutionError("Antigravity ACP process streams are unavailable");
28086
29136
  }
@@ -28095,15 +29145,31 @@ var AntigravityAgentConnection = class {
28095
29145
  };
28096
29146
  this.termination = termination.promise;
28097
29147
  child.once("error", (cause) => {
28098
- resolveTermination({
28099
- kind: "failed",
28100
- error: new AcpExecutionError("Antigravity ACP process failed to start", { cause })
29148
+ const terminationError = new AcpExecutionError("Antigravity ACP process failed to start", { cause });
29149
+ if (this.#closePromise === null) {
29150
+ this.#backgroundWakeup.onUnexpectedProcessExit(terminationError.message);
29151
+ this.#backgroundWakeup.dispose();
29152
+ }
29153
+ void this.#flushDeliveries().finally(() => {
29154
+ resolveTermination({
29155
+ kind: "failed",
29156
+ error: terminationError
29157
+ });
28101
29158
  });
28102
29159
  });
28103
29160
  child.once("exit", (code, signal) => {
28104
- resolveTermination({
28105
- kind: "failed",
28106
- error: new AcpExecutionError("The Antigravity ACP process stopped", { cause: { code, signal } })
29161
+ const terminationError = new AcpExecutionError("The Antigravity ACP process stopped", {
29162
+ cause: { code, signal }
29163
+ });
29164
+ if (this.#closePromise === null) {
29165
+ this.#backgroundWakeup.onUnexpectedProcessExit(terminationError.message);
29166
+ this.#backgroundWakeup.dispose();
29167
+ }
29168
+ void this.#flushDeliveries().finally(() => {
29169
+ resolveTermination({
29170
+ kind: "failed",
29171
+ error: terminationError
29172
+ });
28107
29173
  });
28108
29174
  });
28109
29175
  let stderrTail = "";
@@ -28149,13 +29215,10 @@ var AntigravityAgentConnection = class {
28149
29215
  };
28150
29216
  let pendingUpdates = 0;
28151
29217
  this.connection = createAcpClient(clientHandler).onNotification(methods.client.session.update, async ({ params }) => {
28152
- const currentState = this.#messageStreams.get(params.sessionId) ?? { kind: "none" };
28153
- const identified = identifySessionUpdate(params.update, currentState);
28154
- this.#messageStreams.set(params.sessionId, identified.nextState);
28155
29218
  pendingUpdates += 1;
28156
29219
  stdout.pause();
28157
29220
  try {
28158
- await options.client.onUpdate({ ...params, update: identified.update });
29221
+ await this.#deliverUpdateNotification(params);
28159
29222
  } finally {
28160
29223
  pendingUpdates -= 1;
28161
29224
  if (pendingUpdates === 0) {
@@ -28163,7 +29226,55 @@ var AntigravityAgentConnection = class {
28163
29226
  }
28164
29227
  }
28165
29228
  }).connect(wrappedStream);
29229
+ activeConnectionsByClient.set(this.connection, this);
28166
29230
  }
29231
+ #deliverUpdateNotification = async (params) => {
29232
+ if (this.#deliveryAbort.signal.aborted) {
29233
+ return;
29234
+ }
29235
+ try {
29236
+ await this.#deliveries.run(async () => {
29237
+ if (hasMobiusWakeupMeta(params.update)) {
29238
+ const meta3 = params.update._meta;
29239
+ if (meta3 !== void 0 && meta3 !== null && AGENT_TURN_META in meta3) {
29240
+ this.#messageStreams.set(params.sessionId, { kind: "none" });
29241
+ }
29242
+ await this.#clientOnUpdate({ ...params, update: params.update });
29243
+ return;
29244
+ }
29245
+ const currentState = this.#messageStreams.get(params.sessionId) ?? { kind: "none" };
29246
+ const identified = identifySessionUpdate(params.update, currentState);
29247
+ this.#messageStreams.set(params.sessionId, identified.nextState);
29248
+ await this.#clientOnUpdate({ ...params, update: identified.update });
29249
+ }, this.#deliveryAbort.signal);
29250
+ } catch (error62) {
29251
+ if (!this.#deliveryAbort.signal.aborted) {
29252
+ throw error62;
29253
+ }
29254
+ }
29255
+ };
29256
+ #queueMetaUpdate = (notification) => {
29257
+ if (this.#deliveryAbort.signal.aborted) {
29258
+ return;
29259
+ }
29260
+ void this.#deliveries.run(async () => {
29261
+ await this.#clientOnUpdate(notification);
29262
+ }, this.#deliveryAbort.signal).catch(() => void 0);
29263
+ };
29264
+ #flushDeliveries = async () => {
29265
+ if (this.#deliveryAbort.signal.aborted) {
29266
+ return;
29267
+ }
29268
+ try {
29269
+ await this.#deliveries.run(async () => void 0, this.#deliveryAbort.signal);
29270
+ } catch {
29271
+ }
29272
+ };
29273
+ prepareSessionCancel = async (sessionId) => {
29274
+ const disposition = this.#backgroundWakeup.cancelSession(sessionId);
29275
+ await this.#flushDeliveries();
29276
+ return disposition;
29277
+ };
28167
29278
  initialize = async (signal) => {
28168
29279
  signal.throwIfAborted();
28169
29280
  };
@@ -28171,11 +29282,14 @@ var AntigravityAgentConnection = class {
28171
29282
  closeProcess = () => {
28172
29283
  this.#closePromise ??= (async () => {
28173
29284
  try {
29285
+ this.#backgroundWakeup.dispose();
29286
+ this.#deliveryAbort.abort(new DOMException("Antigravity ACP connection closed", "AbortError"));
28174
29287
  const captured = await captureProcessTree(this.#child);
28175
29288
  this.connection.close();
28176
29289
  this.#child.stdin?.end();
28177
29290
  await stopProcessTree(this.#child, captured);
28178
29291
  } finally {
29292
+ this.#backgroundWakeup.dispose();
28179
29293
  this.#child.stderr?.removeListener("data", this.#consumeStderr);
28180
29294
  this.connection.close();
28181
29295
  }
@@ -28218,7 +29332,12 @@ var AntigravityAgentConnection = class {
28218
29332
  signal.throwIfAborted();
28219
29333
  const modeState = this.#permissionModes.get(request.sessionId) ?? { kind: "native" };
28220
29334
  if (modeState.kind !== "full-access") {
28221
- return await client2.onPermission(request, signal);
29335
+ this.#backgroundWakeup.beginInteraction(request.sessionId);
29336
+ try {
29337
+ return await client2.onPermission(request, signal);
29338
+ } finally {
29339
+ this.#backgroundWakeup.endInteraction(request.sessionId);
29340
+ }
28222
29341
  }
28223
29342
  const allowOption = request.options.find((option) => option.kind === "allow_once") ?? request.options.find((option) => option.kind === "allow_always");
28224
29343
  if (allowOption === void 0) {
@@ -28233,10 +29352,19 @@ var AntigravityAgentConnection = class {
28233
29352
  if (modeState.kind === "full-access") {
28234
29353
  return { action: "decline" };
28235
29354
  }
28236
- return await client2.onElicitation(request, signal);
29355
+ if (sessionId !== void 0) {
29356
+ this.#backgroundWakeup.beginInteraction(sessionId);
29357
+ }
29358
+ try {
29359
+ return await client2.onElicitation(request, signal);
29360
+ } finally {
29361
+ if (sessionId !== void 0) {
29362
+ this.#backgroundWakeup.endInteraction(sessionId);
29363
+ }
29364
+ }
28237
29365
  };
28238
29366
  #transformOutgoing = (message) => {
28239
- if (isNotificationMessage2(message) && message.method === CANCEL_REQUEST_METHOD2) {
29367
+ if (isNotificationMessage3(message) && message.method === CANCEL_REQUEST_METHOD2) {
28240
29368
  const params2 = isRecord5(message.params) ? message.params : void 0;
28241
29369
  const rawRequestId = params2 === void 0 ? void 0 : params2["requestId"];
28242
29370
  const targetKey = typeof rawRequestId === "string" || typeof rawRequestId === "number" ? rawRequestId : void 0;
@@ -28246,12 +29374,12 @@ var AntigravityAgentConnection = class {
28246
29374
  }
28247
29375
  return message;
28248
29376
  }
28249
- if (!isRequestMessage2(message)) {
29377
+ if (!isRequestMessage3(message)) {
28250
29378
  return message;
28251
29379
  }
28252
29380
  const params = isRecord5(message.params) ? message.params : void 0;
28253
29381
  const sessionId = params === void 0 ? void 0 : readStringProperty(params, "sessionId");
28254
- const key = requestKeyOf(message.id);
29382
+ const key = requestKeyOf2(message.id);
28255
29383
  switch (message.method) {
28256
29384
  case methods.agent.session.prompt: {
28257
29385
  if (sessionId !== void 0) {
@@ -28331,8 +29459,8 @@ var AntigravityAgentConnection = class {
28331
29459
  return true;
28332
29460
  };
28333
29461
  #transformIncoming = (message) => {
28334
- if (isResponseMessage2(message)) {
28335
- const key = requestKeyOf(message.id);
29462
+ if (isResponseMessage3(message)) {
29463
+ const key = requestKeyOf2(message.id);
28336
29464
  const tracked = key === void 0 ? void 0 : this.#pendingRequests.get(key);
28337
29465
  if (key !== void 0) {
28338
29466
  this.#pendingRequests.delete(key);
@@ -28367,7 +29495,7 @@ var AntigravityAgentConnection = class {
28367
29495
  const result = augmentModeInConfigPayload(message.result, modeState);
28368
29496
  return result === message.result ? message : { ...message, result };
28369
29497
  }
28370
- if (isNotificationMessage2(message) && message.method === methods.client.session.update) {
29498
+ if (isNotificationMessage3(message) && message.method === methods.client.session.update) {
28371
29499
  const params = message.params;
28372
29500
  if (!isRecord5(params)) {
28373
29501
  return message;
@@ -28409,17 +29537,43 @@ var AntigravityAgentConnection = class {
28409
29537
  const transformIncoming = this.#transformIncoming;
28410
29538
  const readable = rawStream.readable.pipeThrough(
28411
29539
  new TransformStream({
28412
- transform(chunk, controller) {
29540
+ transform: async (chunk, controller) => {
28413
29541
  const transformed = transformIncoming(chunk);
28414
- if (transformed !== void 0) {
29542
+ if (transformed === void 0) {
29543
+ return;
29544
+ }
29545
+ const outcome = await this.#backgroundWakeup.onIncomingMessage(transformed);
29546
+ if (isResponseMessage3(transformed)) {
29547
+ for (const metaUpdate of outcome.beforeUpdates) {
29548
+ this.#queueMetaUpdate(metaUpdate);
29549
+ }
29550
+ if (outcome.beforeUpdates.length > 0) {
29551
+ await this.#flushDeliveries();
29552
+ }
28415
29553
  controller.enqueue(transformed);
29554
+ for (const metaUpdate of outcome.afterUpdates) {
29555
+ this.#queueMetaUpdate(metaUpdate);
29556
+ }
29557
+ return;
29558
+ }
29559
+ for (const metaUpdate of outcome.beforeUpdates) {
29560
+ controller.enqueue(toJsonRpcNotification(metaUpdate));
29561
+ }
29562
+ controller.enqueue(transformed);
29563
+ for (const metaUpdate of outcome.afterUpdates) {
29564
+ controller.enqueue(toJsonRpcNotification(metaUpdate));
28416
29565
  }
28417
29566
  }
28418
29567
  })
28419
29568
  );
28420
29569
  const writable = new WritableStream({
28421
- write(chunk) {
28422
- return writer.write(transformOutgoing(chunk));
29570
+ write: async (chunk) => {
29571
+ const outgoing = transformOutgoing(chunk);
29572
+ await this.#backgroundWakeup.onOutgoingMessage(outgoing);
29573
+ if (isRequestMessage3(outgoing) && outgoing.method === methods.agent.session.prompt) {
29574
+ await this.#flushDeliveries();
29575
+ }
29576
+ return await writer.write(outgoing);
28423
29577
  },
28424
29578
  close() {
28425
29579
  return writer.close();
@@ -74013,19 +75167,6 @@ var CodexAppServerClient = class {
74013
75167
  // src/engine/acp/harness/codex/borrowed-agent.ts
74014
75168
  import { randomUUID as randomUUID9 } from "node:crypto";
74015
75169
 
74016
- // src/engine/util/timer.ts
74017
- var SystemTimer = class {
74018
- schedule = (callback, milliseconds) => {
74019
- const timeout = setTimeout(callback, milliseconds);
74020
- return {
74021
- cancel: () => {
74022
- clearTimeout(timeout);
74023
- }
74024
- };
74025
- };
74026
- };
74027
- var systemTimer = new SystemTimer();
74028
-
74029
75170
  // src/engine/acp/harness/codex/items.ts
74030
75171
  import { pathToFileURL } from "node:url";
74031
75172
  var TOOL_OUTPUT_CHARACTER_LIMIT = 32768;
@@ -76641,13 +77782,13 @@ var CodexAgentSpecification = class extends InProcessAcpAgentSpecification {
76641
77782
 
76642
77783
  // src/engine/agent/specification/vendors/pi-agent.ts
76643
77784
  import { createHash as createHash3 } from "node:crypto";
76644
- import { join as join22 } from "node:path";
77785
+ import { join as join23 } from "node:path";
76645
77786
 
76646
77787
  // src/engine/acp/harness/pi/upstream/dist/acp/agent.js
76647
77788
  import { spawnSync } from "node:child_process";
76648
77789
  import { randomUUID as randomUUID12 } from "node:crypto";
76649
77790
  import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as readFileSync9, realpathSync as realpathSync3, statSync as statSync3, unlinkSync as unlinkSync2 } from "node:fs";
76650
- import { basename as basename6, dirname as dirname8, isAbsolute as isAbsolute13, join as join21 } from "node:path";
77791
+ import { basename as basename6, dirname as dirname8, isAbsolute as isAbsolute13, join as join22 } from "node:path";
76651
77792
 
76652
77793
  // src/engine/acp/harness/pi/upstream/dist/pi-rpc/process.js
76653
77794
  import { spawn as spawn6 } from "node:child_process";
@@ -77103,20 +78244,20 @@ function maybeAuthRequiredError(err) {
77103
78244
  }
77104
78245
 
77105
78246
  // src/engine/acp/harness/pi/upstream/dist/acp/paths.js
77106
- import { join as join17 } from "node:path";
78247
+ import { join as join18 } from "node:path";
77107
78248
 
77108
78249
  // src/engine/acp/harness/pi/upstream/dist/acp/environment.js
77109
- import { homedir as homedir2 } from "node:os";
78250
+ import { homedir as homedir3 } from "node:os";
77110
78251
  function environmentHome(environment) {
77111
- return environment["HOME"] ?? environment["USERPROFILE"] ?? homedir2();
78252
+ return environment["HOME"] ?? environment["USERPROFILE"] ?? homedir3();
77112
78253
  }
77113
78254
 
77114
78255
  // src/engine/acp/harness/pi/upstream/dist/acp/paths.js
77115
78256
  function getPiAcpDir(environment = process.env) {
77116
- return join17(environmentHome(environment), ".pi", "pi-acp");
78257
+ return join18(environmentHome(environment), ".pi", "pi-acp");
77117
78258
  }
77118
78259
  function getPiAcpSessionMapPath(environment = process.env) {
77119
- return join17(getPiAcpDir(environment), "session-map.json");
78260
+ return join18(getPiAcpDir(environment), "session-map.json");
77120
78261
  }
77121
78262
 
77122
78263
  // src/engine/acp/harness/pi/upstream/dist/acp/pi-commands.js
@@ -77238,15 +78379,15 @@ async function readPiLatestEntryId(sessionFile) {
77238
78379
 
77239
78380
  // src/engine/acp/harness/pi/upstream/dist/acp/pi-sessions.js
77240
78381
  import { closeSync as closeSync2, existsSync as existsSync5, openSync as openSync2, readdirSync as readdirSync4, readFileSync as readFileSync4, readSync as readSync2, statSync as statSync2 } from "node:fs";
77241
- import { isAbsolute as isAbsolute11, join as join18, resolve as resolve11 } from "node:path";
78382
+ import { isAbsolute as isAbsolute11, join as join19, resolve as resolve11 } from "node:path";
77242
78383
  var DEFAULT_TAIL_BYTES = 256 * 1024;
77243
78384
  var DEFAULT_HEAD_BYTES = 64 * 1024;
77244
78385
  function getPiAgentDir(environment) {
77245
78386
  const configured = environment["PI_CODING_AGENT_DIR"];
77246
- return configured ? resolve11(configured) : join18(environmentHome(environment), ".pi", "agent");
78387
+ return configured ? resolve11(configured) : join19(environmentHome(environment), ".pi", "agent");
77247
78388
  }
77248
78389
  function readSessionDirFromSettings(agentDir) {
77249
- const settingsPath = join18(agentDir, "settings.json");
78390
+ const settingsPath = join19(agentDir, "settings.json");
77250
78391
  try {
77251
78392
  if (!existsSync5(settingsPath)) {
77252
78393
  return null;
@@ -77267,7 +78408,7 @@ function readSessionDirFromSettings(agentDir) {
77267
78408
  }
77268
78409
  function getPiSessionsDir(environment = process.env) {
77269
78410
  const agentDir = getPiAgentDir(environment);
77270
- return readSessionDirFromSettings(agentDir) ?? join18(agentDir, "sessions");
78411
+ return readSessionDirFromSettings(agentDir) ?? join19(agentDir, "sessions");
77271
78412
  }
77272
78413
  function getPiSessionDiscoveryDirs(environment) {
77273
78414
  const discoveryDirectories = [getPiSessionsDir(environment)];
@@ -77278,7 +78419,7 @@ function getPiSessionDiscoveryDirs(environment) {
77278
78419
  if (!entry.isDirectory()) {
77279
78420
  continue;
77280
78421
  }
77281
- const directory = join18(mobiusSessionsRoot, entry.name);
78422
+ const directory = join19(mobiusSessionsRoot, entry.name);
77282
78423
  if (!discoveryDirectories.includes(directory)) {
77283
78424
  discoveryDirectories.push(directory);
77284
78425
  }
@@ -77295,7 +78436,7 @@ function walkJsonlFiles(dir, out2) {
77295
78436
  }
77296
78437
  for (const e of entries) {
77297
78438
  const name2 = typeof e.name === "string" ? e.name : String(e.name);
77298
- const p = join18(dir, name2);
78439
+ const p = join19(dir, name2);
77299
78440
  if (e.isDirectory()) {
77300
78441
  walkJsonlFiles(p, out2);
77301
78442
  } else if (e.isFile() && name2.endsWith(".jsonl")) {
@@ -77564,7 +78705,7 @@ function findPiSession(sessionId, environment = process.env) {
77564
78705
 
77565
78706
  // src/engine/acp/harness/pi/upstream/dist/acp/pi-settings.js
77566
78707
  import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
77567
- import { join as join19, resolve as resolve12 } from "node:path";
78708
+ import { join as join20, resolve as resolve12 } from "node:path";
77568
78709
  function isObject2(x) {
77569
78710
  return Boolean(x) && typeof x === "object" && !Array.isArray(x);
77570
78711
  }
@@ -77593,7 +78734,7 @@ function readJsonFile2(path6) {
77593
78734
  }
77594
78735
  }
77595
78736
  function getMergedSettings(cwd, environment) {
77596
- const globalSettingsPath = join19(getAgentDir(environment), "settings.json");
78737
+ const globalSettingsPath = join20(getAgentDir(environment), "settings.json");
77597
78738
  const projectSettingsPath = resolve12(cwd, ".pi", "settings.json");
77598
78739
  const global2 = readJsonFile2(globalSettingsPath);
77599
78740
  const project = readJsonFile2(projectSettingsPath);
@@ -77601,7 +78742,7 @@ function getMergedSettings(cwd, environment) {
77601
78742
  }
77602
78743
  function getAgentDir(environment = process.env) {
77603
78744
  const configured = environment["PI_CODING_AGENT_DIR"];
77604
- return configured ? resolve12(configured) : join19(environmentHome(environment), ".pi", "agent");
78745
+ return configured ? resolve12(configured) : join20(environmentHome(environment), ".pi", "agent");
77605
78746
  }
77606
78747
  function getEnableSkillCommands(cwd, environment = process.env) {
77607
78748
  const merged = getMergedSettings(cwd, environment);
@@ -77855,7 +78996,7 @@ var SessionStore = class {
77855
78996
 
77856
78997
  // src/engine/acp/harness/pi/upstream/dist/acp/slash-commands.js
77857
78998
  import { existsSync as existsSync7, readdirSync as readdirSync5, readFileSync as readFileSync7 } from "node:fs";
77858
- import { join as join20, resolve as resolve13 } from "node:path";
78999
+ import { join as join21, resolve as resolve13 } from "node:path";
77859
79000
  function parseFrontmatter(content) {
77860
79001
  const frontmatter = {};
77861
79002
  if (!content.startsWith("---")) {
@@ -77883,7 +79024,7 @@ function loadCommandsFromDir(dir, source, subdir = "") {
77883
79024
  try {
77884
79025
  const entries = readdirSync5(dir, { withFileTypes: true });
77885
79026
  for (const entry of entries) {
77886
- const fullPath = join20(dir, entry.name);
79027
+ const fullPath = join21(dir, entry.name);
77887
79028
  if (entry.isDirectory()) {
77888
79029
  const newSubdir = subdir ? `${subdir}:${entry.name}` : entry.name;
77889
79030
  commands.push(...loadCommandsFromDir(fullPath, source, newSubdir));
@@ -77923,7 +79064,7 @@ function loadCommandsFromDir(dir, source, subdir = "") {
77923
79064
  }
77924
79065
  function loadSlashCommands(cwd, environment = process.env) {
77925
79066
  const commands = [];
77926
- const userDir = join20(environmentHome(environment), ".pi", "agent", "prompts");
79067
+ const userDir = join21(environmentHome(environment), ".pi", "agent", "prompts");
77927
79068
  const projectDir = resolve13(cwd, ".pi", "prompts");
77928
79069
  commands.push(...loadCommandsFromDir(userDir, "user"));
77929
79070
  commands.push(...loadCommandsFromDir(projectDir, "project"));
@@ -79592,7 +80733,7 @@ ${JSON.stringify(stats, null, 2)}`;
79592
80733
  if (piPath) {
79593
80734
  const resolved = realpathSync3(piPath);
79594
80735
  const pkgRoot = dirname8(dirname8(resolved));
79595
- const p = join21(pkgRoot, "CHANGELOG.md");
80736
+ const p = join22(pkgRoot, "CHANGELOG.md");
79596
80737
  if (existsSync8(p)) {
79597
80738
  return p;
79598
80739
  }
@@ -79603,7 +80744,7 @@ ${JSON.stringify(stats, null, 2)}`;
79603
80744
  const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
79604
80745
  const root = String(npmRoot.stdout ?? "").trim();
79605
80746
  if (root) {
79606
- const p = join21(root, "@earendil-works", "pi-coding-agent", "CHANGELOG.md");
80747
+ const p = join22(root, "@earendil-works", "pi-coding-agent", "CHANGELOG.md");
79607
80748
  if (existsSync8(p)) {
79608
80749
  return p;
79609
80750
  }
@@ -79697,7 +80838,7 @@ ${JSON.stringify(stats, null, 2)}`;
79697
80838
  return { stopReason: "end_turn" };
79698
80839
  }
79699
80840
  const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
79700
- const outputPath = join21(session.cwd, `pi-session-${safeSessionId}.html`);
80841
+ const outputPath = join22(session.cwd, `pi-session-${safeSessionId}.html`);
79701
80842
  let resultPath = "";
79702
80843
  try {
79703
80844
  const result2 = await session.proc.exportHtml(outputPath);
@@ -80434,7 +81575,7 @@ function buildStartupInfo(opts) {
80434
81575
  md.push("");
80435
81576
  };
80436
81577
  const contextItems = [];
80437
- const contextPath = join21(opts.cwd, "AGENTS.md");
81578
+ const contextPath = join22(opts.cwd, "AGENTS.md");
80438
81579
  if (existsSync8(contextPath)) {
80439
81580
  contextItems.push(contextPath);
80440
81581
  }
@@ -80443,7 +81584,7 @@ function buildStartupInfo(opts) {
80443
81584
  const pushSkillFromRoot = (root) => {
80444
81585
  try {
80445
81586
  for (const e of readdirSync6(root)) {
80446
- const p = join21(root, e);
81587
+ const p = join22(root, e);
80447
81588
  try {
80448
81589
  const st2 = statSync3(p);
80449
81590
  if (st2.isFile() && e.toLowerCase().endsWith(".md")) {
@@ -80468,7 +81609,7 @@ function buildStartupInfo(opts) {
80468
81609
  if (name2 === "node_modules" || name2 === ".git") {
80469
81610
  continue;
80470
81611
  }
80471
- const p = join21(dir, name2);
81612
+ const p = join22(dir, name2);
80472
81613
  let st2;
80473
81614
  try {
80474
81615
  st2 = statSync3(p);
@@ -80485,16 +81626,16 @@ function buildStartupInfo(opts) {
80485
81626
  } catch {
80486
81627
  }
80487
81628
  };
80488
- const globalSkillsDir = join21(getAgentDir(opts.environment), "skills");
81629
+ const globalSkillsDir = join22(getAgentDir(opts.environment), "skills");
80489
81630
  pushSkillFromRoot(globalSkillsDir);
80490
81631
  const home = opts.environment["HOME"] ?? opts.environment["USERPROFILE"] ?? "";
80491
- const legacyAgentsSkillsDir = join21(home, ".agents", "skills");
81632
+ const legacyAgentsSkillsDir = join22(home, ".agents", "skills");
80492
81633
  pushSkillFromRoot(legacyAgentsSkillsDir);
80493
- const projectSkillsDir = join21(opts.cwd, ".pi", "skills");
81634
+ const projectSkillsDir = join22(opts.cwd, ".pi", "skills");
80494
81635
  pushSkillFromRoot(projectSkillsDir);
80495
81636
  addSection("Skills", skillsItems);
80496
81637
  const promptsItems = [];
80497
- const promptsDir = join21(home, ".pi", "agent", "prompts");
81638
+ const promptsDir = join22(home, ".pi", "agent", "prompts");
80498
81639
  try {
80499
81640
  const prompts = readdirSync6(promptsDir).filter((f) => f.endsWith(".md"));
80500
81641
  for (const f of prompts) {
@@ -80504,17 +81645,17 @@ function buildStartupInfo(opts) {
80504
81645
  }
80505
81646
  addSection("Prompts", promptsItems);
80506
81647
  const extItems = [];
80507
- const extDir = join21(home, ".pi", "agent", "extensions");
81648
+ const extDir = join22(home, ".pi", "agent", "extensions");
80508
81649
  try {
80509
81650
  const exts = readdirSync6(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
80510
81651
  for (const f of exts) {
80511
- extItems.push(join21(extDir, f));
81652
+ extItems.push(join22(extDir, f));
80512
81653
  }
80513
81654
  } catch {
80514
81655
  }
80515
81656
  const settingsPaths = [
80516
- join21(getAgentDir(opts.environment), "settings.json"),
80517
- join21(opts.cwd, ".pi", "settings.json")
81657
+ join22(getAgentDir(opts.environment), "settings.json"),
81658
+ join22(opts.cwd, ".pi", "settings.json")
80518
81659
  ];
80519
81660
  for (const settingsPath of settingsPaths) {
80520
81661
  try {
@@ -80705,7 +81846,7 @@ var PiAgentSpecification = class extends InProcessAcpAgentSpecification {
80705
81846
  // keeps the adapter's opt-in capability flag enabled for every launch it owns.
80706
81847
  createLaunchEnvironment = async (_agent, context) => {
80707
81848
  const workspaceHash = createHash3("sha256").update(context.defaultWorkspace).digest("hex").slice(0, 24);
80708
- const sessionDirectory = join22(context.dataDirectory, "agents", "pi", "sessions", workspaceHash);
81849
+ const sessionDirectory = join23(context.dataDirectory, "agents", "pi", "sessions", workspaceHash);
80709
81850
  return Object.freeze({
80710
81851
  PI_ACP_ENABLE_EMBEDDED_CONTEXT: "true",
80711
81852
  MOBIUS_PI_SESSION_DIR: sessionDirectory
@@ -81536,7 +82677,7 @@ var SessionConfigProtocolError = class extends Error {
81536
82677
  function isRecord8(value) {
81537
82678
  return typeof value === "object" && value !== null && !Array.isArray(value);
81538
82679
  }
81539
- function readString3(value, fallback = "") {
82680
+ function readString4(value, fallback = "") {
81540
82681
  return typeof value === "string" ? value : fallback;
81541
82682
  }
81542
82683
  function truncate3(value, maximum) {
@@ -81551,10 +82692,10 @@ function normalizeConfigValue(option, groupId = "", groupName = "") {
81551
82692
  return void 0;
81552
82693
  }
81553
82694
  return {
81554
- description: truncate3(readString3(option["description"]), 500),
82695
+ description: truncate3(readString4(option["description"]), 500),
81555
82696
  groupId: truncate3(groupId, 128),
81556
82697
  groupName: truncate3(groupName, 255),
81557
- name: truncate3(readString3(option["name"], value), 255),
82698
+ name: truncate3(readString4(option["name"], value), 255),
81558
82699
  value: truncate3(value, 500)
81559
82700
  };
81560
82701
  }
@@ -81569,8 +82710,8 @@ function normalizeConfigValues(value) {
81569
82710
  }
81570
82711
  const groupedOptions = entry["options"];
81571
82712
  if (Array.isArray(groupedOptions)) {
81572
- const groupId = readString3(entry["group"]);
81573
- const groupName = readString3(entry["name"]);
82713
+ const groupId = readString4(entry["group"]);
82714
+ const groupName = readString4(entry["name"]);
81574
82715
  for (const groupedOption of groupedOptions) {
81575
82716
  if (isRecord8(groupedOption)) {
81576
82717
  const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
@@ -81600,9 +82741,9 @@ function normalizeConfigOptions(value, modes) {
81600
82741
  if (!isRecord8(option)) {
81601
82742
  continue;
81602
82743
  }
81603
- const id = truncate3(readString3(option["id"]), 128);
81604
- const name2 = truncate3(readString3(option["name"], id), 255);
81605
- const category = truncate3(readString3(option["category"]), 128);
82744
+ const id = truncate3(readString4(option["id"]), 128);
82745
+ const name2 = truncate3(readString4(option["name"], id), 255);
82746
+ const category = truncate3(readString4(option["category"]), 128);
81606
82747
  if (id.length === 0 || name2.length === 0 || category === "_mobius_permission") {
81607
82748
  continue;
81608
82749
  }
@@ -81611,7 +82752,7 @@ function normalizeConfigOptions(value, modes) {
81611
82752
  booleanValue: readBoolean2(option["currentValue"]),
81612
82753
  category,
81613
82754
  currentValue: "",
81614
- description: truncate3(readString3(option["description"]), 500),
82755
+ description: truncate3(readString4(option["description"]), 500),
81615
82756
  id,
81616
82757
  name: name2,
81617
82758
  type: "boolean",
@@ -81621,13 +82762,13 @@ function normalizeConfigOptions(value, modes) {
81621
82762
  }
81622
82763
  if (option["type"] === "select") {
81623
82764
  const values = normalizeConfigValues(option["options"]);
81624
- const currentValue = truncate3(readString3(option["currentValue"]), 500);
82765
+ const currentValue = truncate3(readString4(option["currentValue"]), 500);
81625
82766
  if (values.some((entry) => entry.value === currentValue)) {
81626
82767
  normalized.push({
81627
82768
  booleanValue: false,
81628
82769
  category,
81629
82770
  currentValue,
81630
- description: truncate3(readString3(option["description"]), 500),
82771
+ description: truncate3(readString4(option["description"]), 500),
81631
82772
  id,
81632
82773
  name: name2,
81633
82774
  type: "select",
@@ -81645,20 +82786,20 @@ function normalizeConfigOptions(value, modes) {
81645
82786
  if (!isRecord8(mode)) {
81646
82787
  continue;
81647
82788
  }
81648
- const id = truncate3(readString3(mode["id"]), 500);
82789
+ const id = truncate3(readString4(mode["id"]), 500);
81649
82790
  if (id.length === 0) {
81650
82791
  continue;
81651
82792
  }
81652
82793
  values.push({
81653
- description: truncate3(readString3(mode["description"]), 500),
82794
+ description: truncate3(readString4(mode["description"]), 500),
81654
82795
  groupId: "",
81655
82796
  groupName: "",
81656
- name: truncate3(readString3(mode["name"], id), 255),
82797
+ name: truncate3(readString4(mode["name"], id), 255),
81657
82798
  value: id
81658
82799
  });
81659
82800
  }
81660
82801
  }
81661
- const currentValue = truncate3(readString3(modes["currentModeId"]), 500);
82802
+ const currentValue = truncate3(readString4(modes["currentModeId"]), 500);
81662
82803
  if (values.length > 1 && currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode") && !duplicatesThinkingOption(normalized, currentValue, values)) {
81663
82804
  normalized.unshift({
81664
82805
  booleanValue: false,
@@ -82284,6 +83425,7 @@ var targetSchema = external_exports.object({
82284
83425
  });
82285
83426
  var AcpExecutionConnections = class {
82286
83427
  #sessions = /* @__PURE__ */ new Set();
83428
+ #closing = /* @__PURE__ */ new WeakSet();
82287
83429
  #externalizer;
82288
83430
  #normalizeEvent;
82289
83431
  constructor(externalizer, normalizeEvent = (event) => event) {
@@ -82409,10 +83551,12 @@ var AcpExecutionConnections = class {
82409
83551
  signal.throwIfAborted();
82410
83552
  return;
82411
83553
  }
83554
+ const alreadyClosing = this.#closing.has(session);
83555
+ this.#closing.add(session);
82412
83556
  const { connection } = session;
82413
83557
  try {
82414
83558
  signal.throwIfAborted();
82415
- if (connection.snapshot().capabilities.closeSession) {
83559
+ if (!alreadyClosing && connection.snapshot().capabilities.closeSession) {
82416
83560
  try {
82417
83561
  await connection.connection.agent.request(
82418
83562
  methods.agent.session.close,
@@ -83033,7 +84177,17 @@ var AntigravityAdapter = class {
83033
84177
  await connection.race(connection.events.drained(), "ACP agent exited while loading a session", signal);
83034
84178
  return normalizeOpenedSession(execution, nativeSessionId, response, signal);
83035
84179
  });
83036
- cancel = (...args) => this.#executionConnections.cancel(...args);
84180
+ cancel = async (params) => {
84181
+ const connection = this.#executionConnections.connection(params);
84182
+ if (connection !== void 0) {
84183
+ const disposition = await prepareAntigravitySessionCancel(connection.connection, params.nativeSessionId);
84184
+ if (disposition === "close") {
84185
+ await this.#executionConnections.closeSession(params);
84186
+ return "closed";
84187
+ }
84188
+ }
84189
+ return await this.#executionConnections.cancel(params);
84190
+ };
83037
84191
  closeSession = (...args) => this.#executionConnections.closeSession(...args);
83038
84192
  releaseSession = (params) => this.#executionConnections.releaseSession(params);
83039
84193
  readNativeHistoryRevision = (params) => this.#executionConnections.readNativeHistoryRevision(params);
@@ -83754,11 +84908,11 @@ function describeEnvironmentProxyRoute(target) {
83754
84908
  }
83755
84909
 
83756
84910
  // src/engine/runtime/observability/diagnostic-log.ts
83757
- import { join as join25 } from "node:path";
84911
+ import { join as join26 } from "node:path";
83758
84912
 
83759
84913
  // src/engine/storage/logs/bounded-log.ts
83760
84914
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
83761
- import { join as join23 } from "node:path";
84915
+ import { join as join24 } from "node:path";
83762
84916
  var BoundedLineLog = class {
83763
84917
  #path;
83764
84918
  #maximumBytes;
@@ -83767,7 +84921,7 @@ var BoundedLineLog = class {
83767
84921
  #onWriteFailure;
83768
84922
  constructor(directory, filename, maximumBytes, onWriteFailure = () => void 0) {
83769
84923
  this.#directory = directory;
83770
- this.#path = join23(directory, filename);
84924
+ this.#path = join24(directory, filename);
83771
84925
  this.#maximumBytes = maximumBytes;
83772
84926
  this.#onWriteFailure = onWriteFailure;
83773
84927
  }
@@ -83818,21 +84972,21 @@ var BoundedLineLog = class {
83818
84972
 
83819
84973
  // src/engine/storage/logs/log-files.ts
83820
84974
  import { readFileSync as readFileSync11 } from "node:fs";
83821
- import { join as join24 } from "node:path";
84975
+ import { join as join25 } from "node:path";
83822
84976
  var DAEMON_LOG_FILENAME = "daemon.log";
83823
84977
  var WORKER_LIFECYCLE_LOG_FILENAME = "worker-lifecycle.log";
83824
84978
  function unhandledRejectionLogFilename(role) {
83825
84979
  return `unhandled-rejections-${role}.log`;
83826
84980
  }
83827
84981
  function logDirectory(dataDirectory) {
83828
- return join24(dataDirectory, "logs");
84982
+ return join25(dataDirectory, "logs");
83829
84983
  }
83830
84984
  function processLogPaths(dataDirectory) {
83831
84985
  return [
83832
84986
  WORKER_LIFECYCLE_LOG_FILENAME,
83833
84987
  unhandledRejectionLogFilename("manager"),
83834
84988
  unhandledRejectionLogFilename("worker")
83835
- ].map((filename) => join24(logDirectory(dataDirectory), filename));
84989
+ ].map((filename) => join25(logDirectory(dataDirectory), filename));
83836
84990
  }
83837
84991
  function readLogText(path6) {
83838
84992
  try {
@@ -83907,7 +85061,7 @@ var RuntimeDiagnosticLog = class {
83907
85061
  this.#maximumBytes = maximumBytes;
83908
85062
  const processLogsDirectory = options.processLogsDirectory;
83909
85063
  this.#sources = [
83910
- { maximumBytes, path: join25(directory, DAEMON_LOG_FILENAME) },
85064
+ { maximumBytes, path: join26(directory, DAEMON_LOG_FILENAME) },
83911
85065
  // The process logs a Runtime does not own, but must read to explain its own deaths.
83912
85066
  ...processLogsDirectory === void 0 ? [] : processLogPaths(processLogsDirectory).map((path6) => ({ maximumBytes: null, path: path6 }))
83913
85067
  ];
@@ -84138,20 +85292,6 @@ async function publishAgentCatalog(config2, signal) {
84138
85292
  // src/engine/runtime/config.ts
84139
85293
  import { resolve as resolve15 } from "node:path";
84140
85294
 
84141
- // src/engine/util/serial-task-queue.ts
84142
- var SerialTaskQueue = class {
84143
- #tail = Promise.resolve();
84144
- run = async (task, signal) => {
84145
- signal.throwIfAborted();
84146
- const result = this.#tail.then(() => {
84147
- signal.throwIfAborted();
84148
- return task(signal);
84149
- });
84150
- this.#tail = result.catch(() => void 0);
84151
- return await result;
84152
- };
84153
- };
84154
-
84155
85295
  // src/engine/agent/catalog.ts
84156
85296
  var LocalAgentCatalogSnapshot = class {
84157
85297
  agents;
@@ -85056,7 +86196,7 @@ function sql(strings, ...params) {
85056
86196
  return new SQL([new StringChunk(str)]);
85057
86197
  }
85058
86198
  _sql.raw = raw;
85059
- function join32(chunks, separator) {
86199
+ function join33(chunks, separator) {
85060
86200
  const result = [];
85061
86201
  for (const [i, chunk] of chunks.entries()) {
85062
86202
  if (i > 0 && separator !== void 0) result.push(separator);
@@ -85064,7 +86204,7 @@ function sql(strings, ...params) {
85064
86204
  }
85065
86205
  return new SQL(result);
85066
86206
  }
85067
- _sql.join = join32;
86207
+ _sql.join = join33;
85068
86208
  function identifier2(value) {
85069
86209
  return new Name(value);
85070
86210
  }
@@ -87209,7 +88349,7 @@ var SQLiteSelectBase = class extends TypedQueryBuilder {
87209
88349
  const baseTableName = this.tableName;
87210
88350
  const tableName = getTableLikeName(table);
87211
88351
  for (const item of extractUsedTable(table)) this.usedTables.add(item);
87212
- if (typeof tableName === "string" && this.config.joins?.some((join32) => join32.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
88352
+ if (typeof tableName === "string" && this.config.joins?.some((join33) => join33.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
87213
88353
  if (!this.isPartialSelect) {
87214
88354
  if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
87215
88355
  if (typeof tableName === "string" && !is(table, SQL)) {
@@ -88048,7 +89188,7 @@ var SQLiteDialect = class {
88048
89188
  if (!joins2) return;
88049
89189
  const withEntries = Object.entries(joins2).filter(([_, v]) => v);
88050
89190
  if (!withEntries.length) return;
88051
- return sql.join(withEntries.map(([k2, join32]) => {
89191
+ return sql.join(withEntries.map(([k2, join33]) => {
88052
89192
  const relation = tableConfig.relations[k2];
88053
89193
  const isSingle2 = is(relation, One2);
88054
89194
  const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
@@ -88059,7 +89199,7 @@ var SQLiteDialect = class {
88059
89199
  table: targetTable,
88060
89200
  mode: isSingle2 ? "first" : "many",
88061
89201
  schema,
88062
- queryConfig: join32,
89202
+ queryConfig: join33,
88063
89203
  tableConfig: schema[relation.targetTableName],
88064
89204
  relationWhere: filter,
88065
89205
  isNested: true,
@@ -88073,7 +89213,7 @@ var SQLiteDialect = class {
88073
89213
  key: k2,
88074
89214
  selection: innerQuery.selection,
88075
89215
  isArray: !isSingle2,
88076
- isOptional: (relation.optional ?? false) || join32 !== true && !!join32.where
89216
+ isOptional: (relation.optional ?? false) || join33 !== true && !!join33.where
88077
89217
  });
88078
89218
  const jsonColumns = sql.join(innerQuery.selection.map((s) => {
88079
89219
  return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
@@ -88689,7 +89829,7 @@ var SQLiteUpdateBase = class {
88689
89829
  createJoin(joinType) {
88690
89830
  return ((table, on2) => {
88691
89831
  const tableName = getTableLikeName(table);
88692
- if (typeof tableName === "string" && this.config.joins.some((join32) => join32.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
89832
+ if (typeof tableName === "string" && this.config.joins.some((join33) => join33.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
88693
89833
  if (typeof on2 === "function") {
88694
89834
  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;
88695
89835
  on2 = on2(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
@@ -89643,7 +90783,7 @@ var SessionEventCacheTable = class {
89643
90783
  // src/engine/storage/sqlite/local-databases.ts
89644
90784
  import { createHash as createHash4 } from "node:crypto";
89645
90785
  import { existsSync as existsSync9 } from "node:fs";
89646
- import { join as join26 } from "node:path";
90786
+ import { join as join27 } from "node:path";
89647
90787
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
89648
90788
 
89649
90789
  // src/engine/generated/acp-session-store-migrations.ts
@@ -89896,9 +91036,9 @@ var LocalSqliteDatabase = class {
89896
91036
  function channelSessionDatabasePaths(stateDirectory, channelId) {
89897
91037
  const channelHash = createHash4("sha256").update(channelId).digest("hex");
89898
91038
  return {
89899
- cancellations: join26(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
89900
- events: join26(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
89901
- sessions: join26(stateDirectory, "sessions", `${channelHash}.sqlite`)
91039
+ cancellations: join27(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
91040
+ events: join27(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
91041
+ sessions: join27(stateDirectory, "sessions", `${channelHash}.sqlite`)
89902
91042
  };
89903
91043
  }
89904
91044
  function recordAppliedAdmissionOrder(path6) {
@@ -92477,8 +93617,26 @@ var AgentSession = class _AgentSession {
92477
93617
  message: "The Agent process ended before the work it started on its own finished"
92478
93618
  };
92479
93619
  this.#backgroundActivity = "none";
92480
- await this.#releaseHeld(this.#agentTurn?.held === true ? failure2 : void 0);
92481
- await this.#failAgentTurn(failure2.code, failure2.message);
93620
+ const agentTurn = this.#agentTurn;
93621
+ if (agentTurn?.cancelled === true) {
93622
+ if (agentTurn.held) {
93623
+ await this.#releaseHeld();
93624
+ } else {
93625
+ this.#agentTurn = null;
93626
+ await this.recordLifecycleEvent({
93627
+ payload: {
93628
+ commandId: agentTurn.commandId,
93629
+ kind: "prompt.completed",
93630
+ stopReason: "cancelled"
93631
+ },
93632
+ type: "lifecycle-metadata"
93633
+ });
93634
+ this.#getObserver().onAgentTurn?.(this.#mobiusSessionId, null);
93635
+ }
93636
+ } else {
93637
+ await this.#releaseHeld(agentTurn?.held === true ? failure2 : void 0);
93638
+ await this.#failAgentTurn(failure2.code, failure2.message);
93639
+ }
92482
93640
  await this.#recordBackgroundTasks([]);
92483
93641
  };
92484
93642
  #failAgentTurn = async (code, message) => {
@@ -92557,19 +93715,23 @@ var AgentSession = class _AgentSession {
92557
93715
  */
92558
93716
  cancelAgentTurn = async (commandId, signal) => {
92559
93717
  const held = this.#held?.commandId === commandId ? this.#held : null;
92560
- if (held === null && this.#agentTurn?.commandId !== commandId) {
92561
- return false;
93718
+ const agentTurn = this.#agentTurn?.commandId === commandId ? this.#agentTurn : null;
93719
+ if (held === null && agentTurn === null) {
93720
+ return "none";
92562
93721
  }
92563
93722
  if (held !== null) {
92564
93723
  held.cancelled = true;
92565
93724
  }
93725
+ if (agentTurn !== null) {
93726
+ this.#agentTurn = { ...agentTurn, cancelled: true };
93727
+ }
92566
93728
  await this.#interactions.cancelPendingInteractions();
92567
93729
  signal.throwIfAborted();
92568
- await this.#adapter.cancel({ ...this.#target(), signal });
92569
- if (held !== null && this.#agentTurn === null) {
93730
+ const outcome = await this.#adapter.cancel({ ...this.#target(), signal });
93731
+ if (outcome === "retained" && held !== null && this.#agentTurn === null) {
92570
93732
  await this.#releaseHeld();
92571
93733
  }
92572
- return true;
93734
+ return outcome;
92573
93735
  };
92574
93736
  #recordAgentTurn = async (report) => {
92575
93737
  switch (report.stage) {
@@ -92581,6 +93743,7 @@ var AgentSession = class _AgentSession {
92581
93743
  if (held !== null) {
92582
93744
  this.#agentTurn = {
92583
93745
  attemptId: held.attemptId,
93746
+ cancelled: false,
92584
93747
  commandId: held.commandId,
92585
93748
  continues: void 0,
92586
93749
  held: true
@@ -92593,6 +93756,7 @@ var AgentSession = class _AgentSession {
92593
93756
  })[0] ?? this.#lastClientCommandId;
92594
93757
  const agentTurn = {
92595
93758
  attemptId: randomUUID15(),
93759
+ cancelled: false,
92596
93760
  commandId: `agent-${randomUUID15()}`,
92597
93761
  continues,
92598
93762
  held: false
@@ -93366,7 +94530,22 @@ var SessionManager2 = class {
93366
94530
  /** Cancels the named command's Agent execution; a command that is not executing has nothing to stop. */
93367
94531
  cancelPrompt = async (sessionId, commandId, signal = AbortSignal.timeout(3e4)) => this.#operations.run({ signal }, async ({ signal: signal2 }) => {
93368
94532
  if (this.#agentTurns.get(sessionId) === commandId) {
93369
- await this.#executionProcesses.get(sessionId)?.cancelAgentTurn(commandId, signal2);
94533
+ const runtime = this.#executionProcesses.get(sessionId);
94534
+ if (runtime !== void 0) {
94535
+ const outcome = await runtime.cancelAgentTurn(commandId, signal2);
94536
+ switch (outcome) {
94537
+ case "none":
94538
+ case "retained":
94539
+ break;
94540
+ case "closed":
94541
+ await this.#stopSessionProcess(sessionId, runtime);
94542
+ break;
94543
+ default: {
94544
+ const unreachable2 = outcome;
94545
+ throw new AcpExecutionError("Unexpected cancellation outcome", { cause: unreachable2 });
94546
+ }
94547
+ }
94548
+ }
93370
94549
  return;
93371
94550
  }
93372
94551
  await this.#executions.cancel(sessionId, commandId, async () => {
@@ -94871,8 +96050,8 @@ var SessionTurns = class {
94871
96050
  };
94872
96051
 
94873
96052
  // src/engine/session/workspace/workspace-directory.ts
94874
- import { homedir as homedir3 } from "node:os";
94875
- import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute16, join as join27, normalize as normalize2, relative as relative3 } from "node:path";
96053
+ 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";
94876
96055
 
94877
96056
  // src/engine/session/workspace/local-authorization-error.ts
94878
96057
  var LocalAuthorizationError = class extends OperationError {
@@ -94903,7 +96082,7 @@ function encodePath(path6) {
94903
96082
  return `path-${encoded}`;
94904
96083
  }
94905
96084
  function expandCurrentUserHome(path6) {
94906
- return path6.replace(/^~(?=$|\/|\\)/, homedir3());
96085
+ return path6.replace(/^~(?=$|\/|\\)/, homedir4());
94907
96086
  }
94908
96087
  function decodePath(value, prefix) {
94909
96088
  const encoded = value.slice(prefix.length);
@@ -94934,7 +96113,7 @@ var WorkspaceDirectoryService = class {
94934
96113
  return this.#defaultWorkspace;
94935
96114
  }
94936
96115
  if (id === "home") {
94937
- return homedir3();
96116
+ return homedir4();
94938
96117
  }
94939
96118
  if (id.startsWith("path-")) {
94940
96119
  const path6 = expandCurrentUserHome(decodePath(id, "path-"));
@@ -94969,7 +96148,7 @@ var WorkspaceDirectoryService = class {
94969
96148
  }
94970
96149
  };
94971
96150
  label = (path6) => {
94972
- const suffix = relative3(homedir3(), path6);
96151
+ const suffix = relative3(homedir4(), path6);
94973
96152
  return suffix === "" ? "~" : !isAbsolute16(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path6;
94974
96153
  };
94975
96154
  identify = async (bindingId, requestedPath2, signal) => {
@@ -95018,7 +96197,7 @@ var WorkspaceDirectoryService = class {
95018
96197
  continue;
95019
96198
  }
95020
96199
  try {
95021
- const path6 = await this.resolvePath(join27(target, child.name), signal);
96200
+ const path6 = await this.resolvePath(join28(target, child.name), signal);
95022
96201
  entries.push({ directoryId: encodePath(path6), name: child.name });
95023
96202
  } catch (cause) {
95024
96203
  signal.throwIfAborted();
@@ -95203,13 +96382,13 @@ function buildSessionLayer(options) {
95203
96382
 
95204
96383
  // src/engine/session/content/external-content-store.ts
95205
96384
  import { createHash as createHash8 } from "node:crypto";
95206
- import { extname as extname2, join as join29 } from "node:path";
96385
+ import { extname as extname2, join as join30 } from "node:path";
95207
96386
  import { pathToFileURL as pathToFileURL3 } from "node:url";
95208
96387
 
95209
96388
  // src/engine/storage/files/scratch-directory.ts
95210
96389
  import { randomUUID as randomUUID18 } from "node:crypto";
95211
96390
  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";
95212
- import { dirname as dirname11, join as join28 } from "node:path";
96391
+ import { dirname as dirname11, join as join29 } from "node:path";
95213
96392
  async function atomicWrite(path6, bytes, signal) {
95214
96393
  const temporary = `${path6}.${randomUUID18()}.tmp`;
95215
96394
  try {
@@ -95223,7 +96402,7 @@ async function atomicWrite(path6, bytes, signal) {
95223
96402
  var ScratchDirectory = class {
95224
96403
  #root;
95225
96404
  constructor(parent) {
95226
- this.#root = join28(parent, randomUUID18());
96405
+ this.#root = join29(parent, randomUUID18());
95227
96406
  }
95228
96407
  /** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
95229
96408
  refreshLease = async (leaseMilliseconds) => {
@@ -95234,7 +96413,7 @@ var ScratchDirectory = class {
95234
96413
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
95235
96414
  continue;
95236
96415
  }
95237
- const path6 = join28(dirname11(this.#root), directory.name);
96416
+ const path6 = join29(dirname11(this.#root), directory.name);
95238
96417
  if (path6 === this.#root) {
95239
96418
  continue;
95240
96419
  }
@@ -95249,10 +96428,10 @@ var ScratchDirectory = class {
95249
96428
  };
95250
96429
  /** Writes `bytes` atomically to `<group>/<name>` with owner-only permissions and returns the path. */
95251
96430
  write = async (group, name2, bytes, signal) => {
95252
- const directory = join28(this.#root, group);
96431
+ const directory = join29(this.#root, group);
95253
96432
  await mkdir5(directory, { mode: 448, recursive: true });
95254
96433
  signal.throwIfAborted();
95255
- const path6 = join28(directory, name2);
96434
+ const path6 = join29(directory, name2);
95256
96435
  await atomicWrite(path6, bytes, signal);
95257
96436
  return path6;
95258
96437
  };
@@ -95303,7 +96482,7 @@ var LocalExternalContentStore = class {
95303
96482
  #expirationTimer;
95304
96483
  #cleanup = Promise.resolve();
95305
96484
  constructor(stateDirectory) {
95306
- this.#scratch = new ScratchDirectory(join29(stateDirectory, "tmp", "session-content"));
96485
+ this.#scratch = new ScratchDirectory(join30(stateDirectory, "tmp", "session-content"));
95307
96486
  this.#expirationTimer = setInterval(() => {
95308
96487
  void this.#expire().catch(() => void 0);
95309
96488
  }, 6e4);
@@ -95711,7 +96890,7 @@ var AgentProcessPool = class {
95711
96890
 
95712
96891
  // src/engine/session/settings/agent-settings-cache.ts
95713
96892
  import { createHash as createHash9, randomUUID as randomUUID19 } from "node:crypto";
95714
- import { join as join30 } from "node:path";
96893
+ import { join as join31 } from "node:path";
95715
96894
  var CACHE_FILE_LIMIT = 32 * 1024 * 1024;
95716
96895
  var CACHE_FORMAT = 1;
95717
96896
  var generationSchema = external_exports.union([external_exports.literal("initial"), external_exports.uuid()]);
@@ -95776,8 +96955,8 @@ var AgentSettingsCache = class {
95776
96955
  #generationPath;
95777
96956
  #generation = 0;
95778
96957
  constructor(stateDirectory) {
95779
- this.#directory = join30(stateDirectory, "agent-settings");
95780
- this.#generationPath = join30(this.#directory, "generation");
96958
+ this.#directory = join31(stateDirectory, "agent-settings");
96959
+ this.#generationPath = join31(this.#directory, "generation");
95781
96960
  }
95782
96961
  get generation() {
95783
96962
  return this.#generation;
@@ -95788,7 +96967,7 @@ var AgentSettingsCache = class {
95788
96967
  };
95789
96968
  open = async (agent2, signal) => {
95790
96969
  const inspections = /* @__PURE__ */ new Map();
95791
- const path6 = join30(this.#directory, `${hash2(agent2.id)}.json`);
96970
+ const path6 = join31(this.#directory, `${hash2(agent2.id)}.json`);
95792
96971
  const fingerprint = hash2([
95793
96972
  agent2.agentVersion,
95794
96973
  agent2.adapterVersion,
@@ -96813,7 +97992,7 @@ function createContentWriteCommands(context) {
96813
97992
  import { WebSocket as WebSocket5 } from "undici";
96814
97993
 
96815
97994
  // src/engine/session/content/session-files.ts
96816
- import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as join31, normalize as normalize3, resolve as resolve17 } from "node:path";
97995
+ import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as join32, normalize as normalize3, resolve as resolve17 } from "node:path";
96817
97996
  import { fileURLToPath as fileURLToPath2 } from "node:url";
96818
97997
  function requestedPath(value) {
96819
97998
  if (value.includes("\0")) {
@@ -96837,7 +98016,7 @@ async function resolveFile(value, workingDirectory, signal) {
96837
98016
  if (isAbsolute17(requested.path) && normalize3(requested.path) !== requested.path) {
96838
98017
  return null;
96839
98018
  }
96840
- const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [join31(workingDirectory, requested.path), requested.path] : [resolve17(workingDirectory, requested.path)];
98019
+ const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [join32(workingDirectory, requested.path), requested.path] : [resolve17(workingDirectory, requested.path)];
96841
98020
  for (const candidate of candidates) {
96842
98021
  if (!isAbsolute17(candidate) || normalize3(candidate) !== candidate) {
96843
98022
  continue;
@@ -99414,4 +100593,4 @@ export {
99414
100593
  * MIT Licensed
99415
100594
  *)
99416
100595
  */
99417
- //# sourceMappingURL=chunk-DVSY3FDV.js.map
100596
+ //# sourceMappingURL=chunk-PVKEDOVN.js.map