replicas-engine 0.1.1480 → 0.1.1481

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.
package/dist/src/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  evaluateCommandProtection,
28
28
  extractToolCommand,
29
29
  reportCommandProtectionBlock
30
- } from "./chunk-NTGKYLT7.js";
30
+ } from "./chunk-USE4YC4W.js";
31
31
  import {
32
32
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
33
33
  AGENT_MESSAGE_DELTA_METHOD,
@@ -65,10 +65,10 @@ import {
65
65
  spawnMuseMsp,
66
66
  startMuseSession,
67
67
  uuidV7
68
- } from "./chunk-4CCYMHTQ.js";
68
+ } from "./chunk-XIDUCX5X.js";
69
69
  import {
70
70
  publishedPullRequestUrls
71
- } from "./chunk-YVSEANOR.js";
71
+ } from "./chunk-WPIMOLCN.js";
72
72
  import {
73
73
  ACCOUNT_RATE_LIMITS_READ_METHOD,
74
74
  AsyncLock,
@@ -143,7 +143,7 @@ import {
143
143
  timestampFromSeconds,
144
144
  upsertCredentialFileLines,
145
145
  writeSecureCredentialFile
146
- } from "./chunk-TFG7LKJO.js";
146
+ } from "./chunk-WHJ46GWP.js";
147
147
  import {
148
148
  ENGINE_ENV,
149
149
  UNQUOTED_PATHS_CONFIG,
@@ -154,15 +154,15 @@ import {
154
154
  resolveDiffBase,
155
155
  setAgentCredentialSnapshot,
156
156
  setLinearSessionId
157
- } from "./chunk-PQZH4XFP.js";
157
+ } from "./chunk-X6STGOX4.js";
158
158
  import {
159
159
  getCodexModelProvider
160
- } from "./chunk-4UBMDXMC.js";
160
+ } from "./chunk-LJROL6EN.js";
161
161
  import {
162
162
  SUBPROCESS_MAX_BUFFER,
163
163
  execAsync,
164
164
  execFileAsync
165
- } from "./chunk-5SY2R2PG.js";
165
+ } from "./chunk-ZFCKZEGG.js";
166
166
  import {
167
167
  isRecord as isRecord2
168
168
  } from "./chunk-UZSNFLDQ.js";
@@ -184,6 +184,7 @@ import {
184
184
  CHAT_GOAL_EVENT_TYPE,
185
185
  CHAT_INTERRUPTED_EVENT_TYPE,
186
186
  CHAT_TURN_LOST_EVENT_TYPE,
187
+ CHAT_TURN_LOST_MESSAGE,
187
188
  CLAUDE_AUTH_ENV_KEYS,
188
189
  CLAUDE_AUTH_ENV_KEYS_BY_METHOD,
189
190
  CLAUDE_HAIKU_4_5_BEDROCK_MODEL,
@@ -346,6 +347,7 @@ import {
346
347
  hasChatStarted,
347
348
  hasGeneratedChatTitle,
348
349
  imageContentToUserMessageImages,
350
+ integrationErrorNotificationTargetSchema,
349
351
  interruptChatRequestSchema,
350
352
  isAgentChatMcpActivityRecord,
351
353
  isAgentChatSkillActivityRecord,
@@ -418,6 +420,7 @@ import {
418
420
  sanitizeCanvasFilename,
419
421
  searchRepoFileIndex,
420
422
  sendChatMessageRequestSchema,
423
+ sendChatMessageResponseSchema,
421
424
  serializeCanvasContentResponse,
422
425
  serializeMuseAuthFile,
423
426
  shellQuotePosix,
@@ -439,7 +442,7 @@ import {
439
442
  workspaceTokenRequestSchema,
440
443
  workspaceTokenResponseSchema,
441
444
  wrapInTag
442
- } from "./chunk-6PVWK5AC.js";
445
+ } from "./chunk-3WCKGWA3.js";
443
446
  import {
444
447
  cloneMcpConfig,
445
448
  ensureCompatibilityImports,
@@ -640,7 +643,7 @@ var require_lib = __commonJS({
640
643
  "../node_modules/.bun/which@5.0.0/node_modules/which/lib/index.js"(exports, module) {
641
644
  "use strict";
642
645
  var { isexe, sync: isexeSync } = require_index_min();
643
- var { join: join36, delimiter: delimiter3, sep: sep2, posix } = __require("path");
646
+ var { join: join37, delimiter: delimiter3, sep: sep2, posix } = __require("path");
644
647
  var isWindows = process.platform === "win32";
645
648
  var rSlash = new RegExp(`[${posix.sep}${sep2 === posix.sep ? "" : sep2}]`.replace(/(\\)/g, "\\$1"));
646
649
  var rRel = new RegExp(`^\\.${rSlash.source}`);
@@ -669,7 +672,7 @@ var require_lib = __commonJS({
669
672
  var getPathPart = (raw, cmd) => {
670
673
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw;
671
674
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
672
- return prefix + join36(pathPart, cmd);
675
+ return prefix + join37(pathPart, cmd);
673
676
  };
674
677
  var which = async (cmd, opt = {}) => {
675
678
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
@@ -11106,10 +11109,11 @@ function devicesInstruction() {
11106
11109
  }
11107
11110
 
11108
11111
  // src/services/chat/chat-service.ts
11109
- import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir18, readFile as readFile17, rename as rename3, rm as rm6, stat as stat6 } from "fs/promises";
11110
- import { join as join29 } from "path";
11112
+ import { statSync as statSync4 } from "fs";
11113
+ import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir19, readFile as readFile18, rename as rename3, rm as rm7, stat as stat6 } from "fs/promises";
11114
+ import { join as join30 } from "path";
11111
11115
  import { randomUUID as randomUUID9 } from "crypto";
11112
- import { z as z3 } from "zod";
11116
+ import { z as z4 } from "zod";
11113
11117
 
11114
11118
  // ../shared/src/workspace-chat.ts
11115
11119
  var WORKSPACE_CHATS_QUERY_SCHEMA_VERSION = 18;
@@ -12115,6 +12119,10 @@ var MessageQueueService = class {
12115
12119
  this.queue.splice(clamped, 0, message);
12116
12120
  this.onQueueChanged();
12117
12121
  }
12122
+ restore(messages) {
12123
+ this.queue.unshift(...messages);
12124
+ this.onQueueChanged();
12125
+ }
12118
12126
  resumeIfIdle() {
12119
12127
  if (this.processing || this.starting || this.queue.length === 0) return;
12120
12128
  void this.processNextInQueue().catch((error) => {
@@ -12200,6 +12208,8 @@ var CodingAgentManager = class _CodingAgentManager {
12200
12208
  // Unset until this process sends a turn, so a restart can't mistake the first one for a change.
12201
12209
  sentTurn = false;
12202
12210
  lastCustomInstructions;
12211
+ previousTurnLost;
12212
+ restoredMessages = /* @__PURE__ */ new WeakSet();
12203
12213
  onLastSenderKeyChanged;
12204
12214
  constructor(options) {
12205
12215
  this.workingDirectory = options.workingDirectory ?? ENGINE_ENV.WORKSPACE_ROOT;
@@ -12227,6 +12237,7 @@ var CodingAgentManager = class _CodingAgentManager {
12227
12237
  this.onModelSwitched = options.onModelSwitched ?? (async () => {
12228
12238
  });
12229
12239
  this.lastSenderKey = options.lastSenderKey ?? null;
12240
+ this.previousTurnLost = options.previousTurnLost ?? false;
12230
12241
  this.onLastSenderKeyChanged = options.onLastSenderKeyChanged ?? (async () => {
12231
12242
  });
12232
12243
  this.authFallback = options.provider ? new AuthFallbackCoordinator(options.provider, (event) => {
@@ -12296,13 +12307,17 @@ var CodingAgentManager = class _CodingAgentManager {
12296
12307
  if (stopped && (request.engineTurn || !await this.keepStoppedRequest(delivered))) return;
12297
12308
  await this.saveLastSenderKey(senderKey);
12298
12309
  if (stopped) return;
12299
- const instructionsChanged = this.sentTurn && this.lastCustomInstructions !== request.customInstructions && !request.goalMode && !request.message.trimStart().startsWith("/");
12310
+ const takesNotes = !request.goalMode && !request.message.trimStart().startsWith("/");
12311
+ const instructionsChanged = takesNotes && this.sentTurn && this.lastCustomInstructions !== request.customInstructions;
12300
12312
  this.sentTurn = true;
12301
12313
  this.lastCustomInstructions = request.customInstructions;
12302
- const note = wrapInTag("Your instructions changed since your previous turn. Earlier turns followed the old version: follow the current instructions from here on, and leave earlier replies as they are.", REPLICAS_INSTRUCTIONS_TAG);
12303
- await processMessage(instructionsChanged ? { ...delivered, message: `${delivered.message}
12304
-
12305
- ${note}` } : delivered, signal);
12314
+ const turnLost = takesNotes && this.previousTurnLost;
12315
+ if (turnLost) this.previousTurnLost = false;
12316
+ const notes = [
12317
+ ...turnLost ? [`A workspace restart cut your previous turn off, and it was not retried. The working tree may hold partial work from it.${this.restoredMessages.has(request) ? " This message was sent before the restart." : ""}`] : [],
12318
+ ...instructionsChanged ? ["Your instructions changed since your previous turn. Earlier turns followed the old version: follow the current instructions from here on, and leave earlier replies as they are."] : []
12319
+ ].map((note) => wrapInTag(note, REPLICAS_INSTRUCTIONS_TAG));
12320
+ await processMessage(notes.length > 0 ? { ...delivered, message: [delivered.message, ...notes].join("\n\n") } : delivered, signal);
12306
12321
  } finally {
12307
12322
  this.closeTurn();
12308
12323
  }
@@ -12473,6 +12488,11 @@ ${request.message}` }, senderKey };
12473
12488
  reorderQueue(messageId, newPosition) {
12474
12489
  return this.messageQueue.reorderQueue(messageId, newPosition);
12475
12490
  }
12491
+ restoreQueue(messages) {
12492
+ for (const message of messages) this.restoredMessages.add(message);
12493
+ this.messageQueue.restore(messages);
12494
+ void this.initialized.then(() => this.messageQueue.resumeIfIdle());
12495
+ }
12476
12496
  async enqueueMessage(request, onAccepted) {
12477
12497
  await this.initialized;
12478
12498
  return this.messageQueue.enqueue(request, onAccepted);
@@ -13202,28 +13222,27 @@ var CodexHistoryFile = class {
13202
13222
  }
13203
13223
  async findLastEvent(needle, matches) {
13204
13224
  let found = null;
13225
+ for await (const event of this.eventsFrom(0, [needle])) {
13226
+ if (matches(event)) found = event;
13227
+ }
13228
+ return found;
13229
+ }
13230
+ async *eventsFrom(start, needles) {
13205
13231
  try {
13206
- for await (const line of createInterface({ input: createReadStream(this.filePath), crlfDelay: Infinity })) {
13207
- if (!line.includes(needle)) continue;
13232
+ for await (const line of createInterface({ input: createReadStream(this.filePath, { start }), crlfDelay: Infinity })) {
13233
+ if (!needles.some((needle) => line.includes(needle))) continue;
13208
13234
  const event = parseAgentEventJsonlLine(line);
13209
- if (event && matches(event)) found = event;
13235
+ if (event) yield event;
13210
13236
  }
13211
13237
  } catch (error) {
13212
13238
  if (!isMissingFile(error)) throw error;
13213
13239
  }
13214
- return found;
13215
13240
  }
13216
13241
  async findSubagentItems() {
13217
13242
  const found = /* @__PURE__ */ new Map();
13218
- try {
13219
- for await (const line of createInterface({ input: createReadStream(this.filePath), crlfDelay: Infinity })) {
13220
- if (!line.includes('"subagent"')) continue;
13221
- const event = parseAgentEventJsonlLine(line);
13222
- const payload = event?.type === CODEX_ITEM_EVENT_TYPE ? codexItemFromEvent(event) : null;
13223
- if (payload?.item.type === "subagent") found.set(payload.item.id, { turnId: payload.turnId, item: payload.item });
13224
- }
13225
- } catch (error) {
13226
- if (!isMissingFile(error)) throw error;
13243
+ for await (const event of this.eventsFrom(0, ['"subagent"'])) {
13244
+ const payload = event.type === CODEX_ITEM_EVENT_TYPE ? codexItemFromEvent(event) : null;
13245
+ if (payload?.item.type === "subagent") found.set(payload.item.id, { turnId: payload.turnId, item: payload.item });
13227
13246
  }
13228
13247
  return found;
13229
13248
  }
@@ -59391,6 +59410,80 @@ var PiManager = class extends CodingAgentManager {
59391
59410
  }
59392
59411
  };
59393
59412
 
59413
+ // src/services/chat/chat-commands.ts
59414
+ import { mkdir as mkdir16, readFile as readFile12, rm as rm6 } from "fs/promises";
59415
+ import { join as join23 } from "path";
59416
+ import { z as z3 } from "zod";
59417
+ var CHAT_COMMANDS_DIR = join23(ENGINE_DIR, "chat-commands");
59418
+ var ACCEPTED_RETENTION_MS = 8 * 24 * 60 * 6e4;
59419
+ var MAX_REMOVED_MESSAGE_IDS = 6e3;
59420
+ var queuedMessageSchema = sendChatMessageRequestSchema.extend({ id: z3.string(), queuedAt: z3.string() });
59421
+ var chatCommandStateSchema = z3.object({
59422
+ queue: z3.array(queuedMessageSchema),
59423
+ running: z3.object({
59424
+ id: z3.string().optional(),
59425
+ errorNotificationTargets: z3.array(integrationErrorNotificationTargetSchema)
59426
+ }).optional(),
59427
+ lost: z3.object({
59428
+ errorNotificationTargets: z3.array(integrationErrorNotificationTargetSchema),
59429
+ reported: z3.literal(true).optional(),
59430
+ told: z3.literal(true).optional()
59431
+ }).optional(),
59432
+ accepted: z3.record(z3.string(), sendChatMessageResponseSchema.extend({ at: z3.string() })).transform((accepted) => new Map(Object.entries(accepted))),
59433
+ removed: z3.array(z3.string()),
59434
+ removing: z3.array(z3.string()),
59435
+ checkFrom: z3.number().optional()
59436
+ });
59437
+ var ChatCommands = class _ChatCommands {
59438
+ constructor(chatId, state = { queue: [], accepted: /* @__PURE__ */ new Map(), removed: [], removing: [] }) {
59439
+ this.chatId = chatId;
59440
+ this.state = state;
59441
+ }
59442
+ chatId;
59443
+ state;
59444
+ writing = Promise.resolve();
59445
+ static async load(chatId) {
59446
+ const content = await readFile12(join23(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
59447
+ if (error.code === "ENOENT") return null;
59448
+ throw error;
59449
+ });
59450
+ if (content === null) return null;
59451
+ try {
59452
+ const saved = JSON.parse(content);
59453
+ if (isRecord(saved) && Array.isArray(saved.queue)) {
59454
+ saved.queue = saved.queue.filter((entry) => {
59455
+ const { success, error } = queuedMessageSchema.safeParse(entry);
59456
+ if (!success) console.error("[ChatCommands] Dropped an unreadable queued message:", { chatId, error });
59457
+ return success;
59458
+ });
59459
+ }
59460
+ return new _ChatCommands(chatId, chatCommandStateSchema.parse(saved));
59461
+ } catch (error) {
59462
+ console.error("[ChatCommands] Unreadable command file, starting empty:", { chatId, error });
59463
+ return new _ChatCommands(chatId);
59464
+ }
59465
+ }
59466
+ save() {
59467
+ const cutoff = new Date(Date.now() - ACCEPTED_RETENTION_MS).toISOString();
59468
+ for (const [key, { at }] of this.state.accepted) {
59469
+ if (at < cutoff) this.state.accepted.delete(key);
59470
+ }
59471
+ this.state.removed.splice(0, this.state.removed.length - MAX_REMOVED_MESSAGE_IDS);
59472
+ const data = JSON.stringify({ ...this.state, accepted: Object.fromEntries(this.state.accepted) });
59473
+ this.writing = this.writing.catch(() => {
59474
+ }).then(async () => {
59475
+ await mkdir16(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
59476
+ await atomicWriteFile(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
59477
+ });
59478
+ return this.writing;
59479
+ }
59480
+ remove() {
59481
+ this.writing = this.writing.catch(() => {
59482
+ }).then(() => rm6(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
59483
+ return this.writing;
59484
+ }
59485
+ };
59486
+
59394
59487
  // src/analytics/agent/activity/agent-chat-activity-tracker-service.ts
59395
59488
  import { randomUUID as randomUUID8 } from "crypto";
59396
59489
 
@@ -59405,14 +59498,14 @@ async function uploadAnalytics(endpoint, body) {
59405
59498
  // src/analytics/analytics-record-buffer.ts
59406
59499
  import {
59407
59500
  appendFile as appendFile4,
59408
- mkdir as mkdir16,
59409
- readFile as readFile12,
59501
+ mkdir as mkdir17,
59502
+ readFile as readFile13,
59410
59503
  readdir as readdir5,
59411
59504
  rename as rename2,
59412
59505
  unlink
59413
59506
  } from "fs/promises";
59414
59507
  import { existsSync as existsSync14, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "fs";
59415
- import { join as join23 } from "path";
59508
+ import { join as join24 } from "path";
59416
59509
  var MAX_FAILED_RECORDS = 500;
59417
59510
  var FLUSH_DEBOUNCE_MS = 15e3;
59418
59511
  var MAX_UPLOADED_SEGMENTS = 50;
@@ -59424,7 +59517,7 @@ var AnalyticsRecordBuffer = class {
59424
59517
  options.storageName,
59425
59518
  ...options.legacyStorageNames ?? []
59426
59519
  ];
59427
- this.liveFile = join23(ENGINE_DIR, `${options.storageName}.jsonl`);
59520
+ this.liveFile = join24(ENGINE_DIR, `${options.storageName}.jsonl`);
59428
59521
  this.segmentFilePatterns = this.storageNames.map(
59429
59522
  (storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
59430
59523
  );
@@ -59447,7 +59540,7 @@ var AnalyticsRecordBuffer = class {
59447
59540
  if (this.recordIds.has(recordId)) return;
59448
59541
  this.recordIds.add(recordId);
59449
59542
  }
59450
- const pending = mkdir16(ENGINE_DIR, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
59543
+ const pending = mkdir17(ENGINE_DIR, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
59451
59544
  `, "utf-8")).catch((error) => {
59452
59545
  console.error(
59453
59546
  `[${this.options.storageName}] Append failed, will retry on flush:`,
@@ -59462,7 +59555,7 @@ var AnalyticsRecordBuffer = class {
59462
59555
  if (!existsSync14(ENGINE_DIR)) return [];
59463
59556
  return readdirSync2(ENGINE_DIR, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
59464
59557
  (storageName) => entry.name === `${storageName}.jsonl` || entry.name.startsWith(`${storageName}.`) && (entry.name.endsWith(".jsonl") || entry.name.endsWith(`.jsonl${UPLOADED_SUFFIX}`))
59465
- )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join23(ENGINE_DIR, name), "utf-8"))).map((record3) => {
59558
+ )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join24(ENGINE_DIR, name), "utf-8"))).map((record3) => {
59466
59559
  const recordId = this.options.getRecordId?.(record3);
59467
59560
  if (recordId) this.recordIds.add(recordId);
59468
59561
  return record3;
@@ -59497,8 +59590,8 @@ var AnalyticsRecordBuffer = class {
59497
59590
  }
59498
59591
  for (const storageName of this.storageNames) {
59499
59592
  await rename2(
59500
- join23(ENGINE_DIR, `${storageName}.jsonl`),
59501
- join23(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
59593
+ join24(ENGINE_DIR, `${storageName}.jsonl`),
59594
+ join24(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
59502
59595
  ).catch(() => {
59503
59596
  });
59504
59597
  }
@@ -59508,7 +59601,7 @@ var AnalyticsRecordBuffer = class {
59508
59601
  for (const entry of entries) {
59509
59602
  if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
59510
59603
  try {
59511
- await this.uploadSegment(join23(ENGINE_DIR, entry));
59604
+ await this.uploadSegment(join24(ENGINE_DIR, entry));
59512
59605
  flushed++;
59513
59606
  } catch (error) {
59514
59607
  failed++;
@@ -59537,14 +59630,14 @@ var AnalyticsRecordBuffer = class {
59537
59630
  (storageName) => entry.startsWith(`${storageName}.`)
59538
59631
  ) && entry.endsWith(UPLOADED_SUFFIX)).sort();
59539
59632
  for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
59540
- await unlink(join23(ENGINE_DIR, entry)).catch(() => {
59633
+ await unlink(join24(ENGINE_DIR, entry)).catch(() => {
59541
59634
  });
59542
59635
  }
59543
59636
  }
59544
59637
  return { flushed, failed };
59545
59638
  }
59546
59639
  async uploadSegment(filePath) {
59547
- const records = this.parseRecords(await readFile12(filePath, "utf-8"));
59640
+ const records = this.parseRecords(await readFile13(filePath, "utf-8"));
59548
59641
  if (records.length > 0) await this.options.upload(records);
59549
59642
  await rename2(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
59550
59643
  });
@@ -60349,9 +60442,9 @@ var KeepAliveService = class _KeepAliveService {
60349
60442
  var keepAliveService = new KeepAliveService();
60350
60443
 
60351
60444
  // src/services/canvas-service.ts
60352
- import { readdir as readdir6, readFile as readFile14, stat as stat3 } from "fs/promises";
60445
+ import { readdir as readdir6, readFile as readFile15, stat as stat3 } from "fs/promises";
60353
60446
  import { homedir as homedir8 } from "os";
60354
- import { join as join24 } from "path";
60447
+ import { join as join25 } from "path";
60355
60448
 
60356
60449
  // src/utils/contained-file.ts
60357
60450
  import { realpath, stat as stat2 } from "fs/promises";
@@ -60377,9 +60470,9 @@ function fileRevision(content) {
60377
60470
  }
60378
60471
 
60379
60472
  // src/utils/revisioned-text-file.ts
60380
- import { readFile as readFile13 } from "fs/promises";
60473
+ import { readFile as readFile14 } from "fs/promises";
60381
60474
  async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60382
- const current = await readFile13(filePath, "utf8");
60475
+ const current = await readFile14(filePath, "utf8");
60383
60476
  const revision = fileRevision(current);
60384
60477
  if (revision !== expectedRevision) {
60385
60478
  return {
@@ -60393,15 +60486,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60393
60486
 
60394
60487
  // src/services/canvas-service.ts
60395
60488
  var GLOBAL_CANVAS_DIRECTORIES = [
60396
- join24(homedir8(), ".claude", "plans"),
60397
- join24(process.env.XDG_DATA_HOME ?? join24(homedir8(), ".local", "share"), "opencode", "plans"),
60398
- join24(homedir8(), ".replicas", "canvas")
60489
+ join25(homedir8(), ".claude", "plans"),
60490
+ join25(process.env.XDG_DATA_HOME ?? join25(homedir8(), ".local", "share"), "opencode", "plans"),
60491
+ join25(homedir8(), ".replicas", "canvas")
60399
60492
  ];
60400
60493
  async function canvasDirectories() {
60401
60494
  const repositories = await gitService.listRepositories().catch(() => []);
60402
60495
  return [
60403
60496
  ...GLOBAL_CANVAS_DIRECTORIES,
60404
- ...repositories.map((repository) => join24(repository.path, ".opencode", "plans"))
60497
+ ...repositories.map((repository) => join25(repository.path, ".opencode", "plans"))
60405
60498
  ];
60406
60499
  }
60407
60500
  var CanvasService = class {
@@ -60426,7 +60519,7 @@ var CanvasService = class {
60426
60519
  for (const entry of entries) {
60427
60520
  if (entry.name.startsWith(".")) continue;
60428
60521
  const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
60429
- const filePath = join24(current.directory, entry.name);
60522
+ const filePath = join25(current.directory, entry.name);
60430
60523
  if (entry.isDirectory()) {
60431
60524
  pending.push({ directory: filePath, relativePath: filename });
60432
60525
  continue;
@@ -60450,7 +60543,7 @@ var CanvasService = class {
60450
60543
  const safe = sanitizeCanvasFilename(filename);
60451
60544
  if (!safe) return null;
60452
60545
  for (const directory of await this.directories()) {
60453
- const path7 = join24(directory, safe);
60546
+ const path7 = join25(directory, safe);
60454
60547
  const stats = await stat3(path7).catch(() => null);
60455
60548
  if (stats?.isFile()) {
60456
60549
  return {
@@ -60469,7 +60562,7 @@ var CanvasService = class {
60469
60562
  if (!item) return null;
60470
60563
  const { path: path7, ...file } = item;
60471
60564
  if (file.sizeBytes > maxBytes) return { ...file, tooLarge: true };
60472
- const bytes = await readFile14(path7).catch(() => null);
60565
+ const bytes = await readFile15(path7).catch(() => null);
60473
60566
  return bytes ? { ...file, bytes } : null;
60474
60567
  }
60475
60568
  async getItem(filename) {
@@ -60626,14 +60719,14 @@ async function reconcileCanvasItems(filenames) {
60626
60719
  // src/services/upload-chat-transcripts.ts
60627
60720
  import { createReadStream as createReadStream3 } from "fs";
60628
60721
  import { createHash as createHash8 } from "crypto";
60629
- import { readFile as readFile15, readdir as readdir7, stat as stat4 } from "fs/promises";
60630
- import { basename as basename3, join as join26 } from "path";
60722
+ import { readFile as readFile16, readdir as readdir7, stat as stat4 } from "fs/promises";
60723
+ import { basename as basename3, join as join27 } from "path";
60631
60724
 
60632
60725
  // src/services/chat/chat-senders.ts
60633
- import { join as join25 } from "path";
60634
- var CHAT_SENDERS_DIR = join25(ENGINE_DIR, "chat-senders");
60726
+ import { join as join26 } from "path";
60727
+ var CHAT_SENDERS_DIR = join26(ENGINE_DIR, "chat-senders");
60635
60728
  function chatMessageSendersFilePath(chatId) {
60636
- return join25(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
60729
+ return join26(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
60637
60730
  }
60638
60731
  function parseChatMessageSendersJsonl(content) {
60639
60732
  return content.split("\n").flatMap((line) => {
@@ -60720,7 +60813,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
60720
60813
  const chat = chatsById.get(chatId);
60721
60814
  if (!shouldFlushChatTranscript(dir, chat, chatsById, Boolean(capture))) continue;
60722
60815
  tasks.push(
60723
- uploadChatTranscript(chatId, join26(dir, entry), chat, capture).then(async (artifact) => {
60816
+ uploadChatTranscript(chatId, join27(dir, entry), chat, capture).then(async (artifact) => {
60724
60817
  flushed++;
60725
60818
  if (artifact && capture) revisions.push(artifact);
60726
60819
  await onUploaded?.(chatId, artifact).catch((err) => {
@@ -60770,7 +60863,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60770
60863
  } : {};
60771
60864
  try {
60772
60865
  metadata.senders = parseChatMessageSendersJsonl(
60773
- await readFile15(chatMessageSendersFilePath(chatId), "utf-8")
60866
+ await readFile16(chatMessageSendersFilePath(chatId), "utf-8")
60774
60867
  );
60775
60868
  } catch (error) {
60776
60869
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
@@ -60858,7 +60951,7 @@ async function flushRepoState() {
60858
60951
  // src/services/upload-engine-logs.ts
60859
60952
  import { createReadStream as createReadStream4 } from "fs";
60860
60953
  import { readdir as readdir8, stat as stat5 } from "fs/promises";
60861
- import { join as join27 } from "path";
60954
+ import { join as join28 } from "path";
60862
60955
  var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
60863
60956
  var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
60864
60957
  var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
@@ -60887,7 +60980,7 @@ async function flushAllEngineLogs() {
60887
60980
  const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
60888
60981
  try {
60889
60982
  const sessionId = filename.slice(0, -".log".length);
60890
- const filePath = join27(LOG_DIR, filename);
60983
+ const filePath = join28(LOG_DIR, filename);
60891
60984
  const fileStat = await runBeforeDeadline(() => stat5(filePath), deadline);
60892
60985
  if (!fileStat.isFile()) {
60893
60986
  skipped++;
@@ -60984,9 +61077,9 @@ async function uploadEngineLog(input, timeoutMs) {
60984
61077
 
60985
61078
  // src/services/chat/fork-handoff.ts
60986
61079
  import { createHash as createHash9 } from "crypto";
60987
- import { mkdir as mkdir17, open as open3, readFile as readFile16, writeFile as writeFile8 } from "fs/promises";
61080
+ import { mkdir as mkdir18, open as open3, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
60988
61081
  import { homedir as homedir9 } from "os";
60989
- import { join as join28 } from "path";
61082
+ import { join as join29 } from "path";
60990
61083
  var EXCERPT_MAX_CHARS = 24e3;
60991
61084
  var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
60992
61085
  var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
@@ -61054,7 +61147,7 @@ ${text}` : null;
61054
61147
  }
61055
61148
  async function buildForkHandoff(input) {
61056
61149
  const sources = await Promise.all(input.segments.map(async (segment, index) => {
61057
- const rawHistoryPath = join28(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61150
+ const rawHistoryPath = join29(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61058
61151
  const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
61059
61152
  const last = index === input.segments.length - 1;
61060
61153
  const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
@@ -61068,9 +61161,9 @@ async function buildForkHandoff(input) {
61068
61161
  const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
61069
61162
  blocks = blocks.slice(Math.max(0, start));
61070
61163
  }
61071
- const forkDir = join28(FORKS_DIR, input.targetChatId);
61072
- await mkdir17(forkDir, { recursive: true });
61073
- const transcriptPath = join28(forkDir, input.transcriptName ?? "source-transcript.md");
61164
+ const forkDir = join29(FORKS_DIR, input.targetChatId);
61165
+ await mkdir18(forkDir, { recursive: true });
61166
+ const transcriptPath = join29(forkDir, input.transcriptName ?? "source-transcript.md");
61074
61167
  const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
61075
61168
  const header = sourceTruncated ? `_This file was generated from only the most recent ${MAX_SANITIZED_SOURCE_BYTES / 1024 / 1024} MB of ${sources.length > 1 ? "each part of " : ""}the source chat.${fullHistory ? ` The complete raw event ${sources.length > 1 ? `logs are, oldest first: ${rawHistoryPaths.join(", ")}` : `log is at ${rawHistoryPaths[0]}`}; grep ${sources.length > 1 ? "them" : "it"} for anything earlier.` : ""}_
61076
61169
 
@@ -61089,7 +61182,7 @@ async function buildForkHandoff(input) {
61089
61182
  };
61090
61183
  }
61091
61184
  async function readPullRequestDecisions(notesPath) {
61092
- const notes = await readFile16(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
61185
+ const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
61093
61186
  const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
61094
61187
  if (!decisions) return null;
61095
61188
  const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
@@ -61158,15 +61251,13 @@ var FINAL_MESSAGE_MAX = 6e3;
61158
61251
  var PROGRESS_INTERVAL_MS = 2e4;
61159
61252
  var PROGRESS_STEP_MAX = 120;
61160
61253
  var TURN_REQUEST_MAX = 8e3;
61161
- var toolInputRequestSchema = z3.object({
61162
- requestId: z3.string().optional(),
61163
- toolName: z3.string().optional(),
61164
- questions: z3.array(z3.custom(isToolInputQuestion)).optional(),
61165
- plan: z3.string().optional()
61254
+ var toolInputRequestSchema = z4.object({
61255
+ requestId: z4.string().optional(),
61256
+ toolName: z4.string().optional(),
61257
+ questions: z4.array(z4.custom(isToolInputQuestion)).optional(),
61258
+ plan: z4.string().optional()
61166
61259
  });
61167
- var toolInputResolvedSchema = z3.object({ requestId: z3.string() });
61168
- var MAX_ACCEPTED_SEND_RESPONSES = 50;
61169
- var MAX_REMOVED_MESSAGE_IDS = 6e3;
61260
+ var toolInputResolvedSchema = z4.object({ requestId: z4.string() });
61170
61261
  var SUBAGENT_POLL_INTERVAL_MS = 2e3;
61171
61262
  var CHAT_IDLE_RELEASE_MS = 15 * 6e4;
61172
61263
  var CHILD_CHAT_IDLE_RELEASE_MS = 2 * 6e4;
@@ -61224,12 +61315,15 @@ function normalizePersistedChat(chat) {
61224
61315
  transcriptAuth: normalizeTranscriptAuth(chat.transcriptAuth),
61225
61316
  ...typeof chat.lastSenderKey === "string" ? { lastSenderKey: chat.lastSenderKey } : {},
61226
61317
  ...typeof chat.turnStartedAt === "string" ? { turnStartedAt: chat.turnStartedAt } : {},
61318
+ ...chat.turnErrorNotificationTargets ? { turnErrorNotificationTargets: z4.array(integrationErrorNotificationTargetSchema).safeParse(chat.turnErrorNotificationTargets).data } : {},
61227
61319
  ...isRecord2(chat.uploadedHistory) && typeof chat.uploadedHistory.version === "string" && typeof chat.uploadedHistory.size === "number" ? { uploadedHistory: { version: chat.uploadedHistory.version, size: chat.uploadedHistory.size } } : {},
61228
- removedMessageIds: Array.isArray(chat.removedMessageIds) ? chat.removedMessageIds.filter((id) => typeof id === "string").slice(-MAX_REMOVED_MESSAGE_IDS) : [],
61229
- acceptedSendResponses: isRecord2(chat.acceptedSendResponses) ? Object.fromEntries(Object.entries(chat.acceptedSendResponses).filter((entry) => {
61230
- const response = entry[1];
61231
- return isRecord2(response) && typeof response.messageId === "string" && typeof response.queued === "boolean" && typeof response.position === "number";
61232
- })) : {}
61320
+ ...Array.isArray(chat.removedMessageIds) ? { removedMessageIds: chat.removedMessageIds.filter((id) => typeof id === "string") } : {},
61321
+ ...isRecord2(chat.acceptedSendResponses) ? {
61322
+ acceptedSendResponses: Object.fromEntries(Object.entries(chat.acceptedSendResponses).flatMap(([key, value]) => {
61323
+ const response = sendChatMessageResponseSchema.safeParse(value);
61324
+ return response.success ? [[key, response.data]] : [];
61325
+ }))
61326
+ } : {}
61233
61327
  };
61234
61328
  }
61235
61329
  function parsePersistedChatsContent(content) {
@@ -61258,33 +61352,134 @@ var ChatService = class {
61258
61352
  awaitedSubagents = /* @__PURE__ */ new Map();
61259
61353
  heldSubagentReports = /* @__PURE__ */ new Map();
61260
61354
  forkSourceSeenBlocks = /* @__PURE__ */ new Map();
61355
+ restartedChats = /* @__PURE__ */ new Map();
61261
61356
  persistPromise = null;
61262
61357
  persistQueued = false;
61263
61358
  async initialize() {
61264
- await mkdir18(ENGINE_DIR, { recursive: true });
61265
- await mkdir18(CLAUDE_HISTORY_DIR, { recursive: true });
61266
- await mkdir18(CODEX_HISTORY_DIR, { recursive: true });
61267
- await mkdir18(CURSOR_HISTORY_DIR, { recursive: true });
61268
- await mkdir18(OPENCODE_HISTORY_DIR, { recursive: true });
61269
- await mkdir18(CHAT_SENDERS_DIR, { recursive: true });
61359
+ await mkdir19(ENGINE_DIR, { recursive: true });
61360
+ await mkdir19(CLAUDE_HISTORY_DIR, { recursive: true });
61361
+ await mkdir19(CODEX_HISTORY_DIR, { recursive: true });
61362
+ await mkdir19(CURSOR_HISTORY_DIR, { recursive: true });
61363
+ await mkdir19(OPENCODE_HISTORY_DIR, { recursive: true });
61364
+ await mkdir19(CHAT_SENDERS_DIR, { recursive: true });
61270
61365
  const persisted = await this.loadChats();
61271
- const lostTurn = persisted.some((chat) => chat.turnStartedAt);
61366
+ let fromOlderEngine = false;
61272
61367
  for (const chat of persisted) {
61273
- const runtime = this.createRuntimeChat(chat);
61274
- if (chat.turnStartedAt && !chat.deletedAt) {
61275
- await runtime.provider.persistHistoryEvent({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), type: CHAT_TURN_LOST_EVENT_TYPE, payload: {} }).then(() => {
61276
- delete chat.turnStartedAt;
61277
- }).catch((error) => console.error("[ChatService] Failed to record a turn lost to an engine restart:", { chatId: chat.id, error }));
61278
- } else {
61279
- delete chat.turnStartedAt;
61368
+ const stored = await ChatCommands.load(chat.id);
61369
+ const commands = stored ?? new ChatCommands(chat.id);
61370
+ const { state } = commands;
61371
+ let changed = !stored;
61372
+ if (chat.acceptedSendResponses || chat.removedMessageIds || chat.turnStartedAt) {
61373
+ fromOlderEngine = true;
61374
+ for (const [key, response] of Object.entries(chat.acceptedSendResponses ?? {})) state.accepted.set(key, { ...response, at: chat.updatedAt });
61375
+ state.queue = [];
61376
+ state.removed.push(...chat.removedMessageIds ?? []);
61377
+ delete state.lost;
61378
+ delete state.running;
61379
+ if (chat.turnStartedAt) state.running = { errorNotificationTargets: chat.turnErrorNotificationTargets ?? [] };
61380
+ changed = true;
61381
+ }
61382
+ delete chat.acceptedSendResponses;
61383
+ delete chat.removedMessageIds;
61384
+ delete chat.turnStartedAt;
61385
+ delete chat.turnErrorNotificationTargets;
61386
+ if (chat.deletedAt && (state.running || state.lost || state.queue.length > 0)) {
61387
+ delete state.running;
61388
+ delete state.lost;
61389
+ state.queue = [];
61390
+ changed = true;
61391
+ }
61392
+ const runtime = this.createRuntimeChat(chat, commands);
61393
+ const history = new CodexHistoryFile(this.historyPath(chat));
61394
+ try {
61395
+ const accepted = /* @__PURE__ */ new Set();
61396
+ const removed = /* @__PURE__ */ new Set();
61397
+ let lostRecorded = false;
61398
+ if (state.running?.id || state.queue.length > 0 || state.removing.length > 0) {
61399
+ for await (const event of history.eventsFrom(state.checkFrom ?? 0, [CHAT_TURN_LOST_EVENT_TYPE, ACCEPTED_USER_MESSAGE_SOURCE, QUEUED_MESSAGE_REMOVED_EVENT_TYPE])) {
61400
+ if (event.type === CHAT_TURN_LOST_EVENT_TYPE && state.running?.id && event.payload.messageId === state.running.id) lostRecorded = true;
61401
+ const messageId = event.payload.source === ACCEPTED_USER_MESSAGE_SOURCE ? getUserMessageId(event) : null;
61402
+ if (messageId) accepted.add(messageId);
61403
+ for (const removedId of getRemovedMessageIds(event)) removed.add(removedId);
61404
+ }
61405
+ }
61406
+ if (state.running) {
61407
+ if (!lostRecorded) {
61408
+ await runtime.provider.persistHistoryEvent({
61409
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61410
+ type: CHAT_TURN_LOST_EVENT_TYPE,
61411
+ payload: state.running.id ? { messageId: state.running.id } : {}
61412
+ });
61413
+ }
61414
+ const owed = state.lost && !state.lost.reported ? state.lost.errorNotificationTargets : [];
61415
+ state.lost = {
61416
+ errorNotificationTargets: [
61417
+ ...owed,
61418
+ ...state.running.errorNotificationTargets.filter((target) => !owed.some((other) => JSON.stringify(other) === JSON.stringify(target)))
61419
+ ]
61420
+ };
61421
+ delete state.running;
61422
+ changed = true;
61423
+ }
61424
+ if (state.lost && !state.lost.reported) {
61425
+ runtime.activeErrorNotificationTargets = state.lost.errorNotificationTargets;
61426
+ this.restartedChats.set(chat.id, true);
61427
+ }
61428
+ for (const message of state.queue) {
61429
+ if (accepted.has(message.id)) continue;
61430
+ const { event, sender } = createTurnMetadata(message, message.id, message.queuedAt);
61431
+ await runtime.provider.persistHistoryEvent(event);
61432
+ if (sender) await this.appendSender(chat.id, sender);
61433
+ }
61434
+ const unrecorded = state.removing.filter((messageId) => !removed.has(messageId));
61435
+ if (unrecorded.length > 0) {
61436
+ await runtime.provider.persistHistoryEvent({
61437
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61438
+ type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
61439
+ payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: unrecorded }
61440
+ });
61441
+ }
61442
+ if (state.removing.length > 0) {
61443
+ state.removing = [];
61444
+ changed = true;
61445
+ }
61446
+ } catch (error) {
61447
+ console.error("[ChatService] Failed to recover a chat after an engine restart:", { chatId: chat.id, error });
61280
61448
  }
61449
+ if (state.queue.length > 0 && !this.restartedChats.has(chat.id)) this.restartedChats.set(chat.id, false);
61450
+ if (changed) await commands.save();
61281
61451
  if (chat.uploadedHistory) {
61282
61452
  const size = await stat6(this.historyPath(chat)).then(({ size: size2 }) => size2, () => null);
61283
61453
  if (size === chat.uploadedHistory.size) runtime.historyVersion = chat.uploadedHistory.version;
61284
61454
  }
61285
61455
  this.chats.set(chat.id, runtime);
61286
61456
  }
61287
- if (lostTurn) await this.persistAllChats();
61457
+ if (fromOlderEngine) await this.persistAllChats();
61458
+ }
61459
+ /** The monolith is only reachable once the engine is active, so what a restart interrupted is picked up here rather than at load. */
61460
+ resumeAfterRestart() {
61461
+ for (const [chatId, turnLost] of this.restartedChats) {
61462
+ this.restartedChats.delete(chatId);
61463
+ const chat = this.getRuntimeChat(chatId);
61464
+ if (!chat) continue;
61465
+ const { queue } = chat.commands.state;
61466
+ for (const message of queue) {
61467
+ chat.pendingMessageIds.push(message.id);
61468
+ if (message.errorNotificationTargets?.length) chat.errorNotificationTargets.set(message.id, message.errorNotificationTargets);
61469
+ this.agentChatActivityTrackerService.noteMessageAccepted(message.id, message);
61470
+ chat.lastSendRequest = message;
61471
+ }
61472
+ if (queue.length > 0) chat.provider.restoreQueue(queue);
61473
+ if (turnLost) {
61474
+ this.handleTurnFinished(chatId, true).catch((error) => console.error("[ChatService] Failed to report a turn lost to an engine restart:", { chatId, error }));
61475
+ }
61476
+ }
61477
+ }
61478
+ settleLostTurn(chat, done) {
61479
+ const { state } = chat.commands;
61480
+ if (!state.lost) return;
61481
+ state.lost[done] = true;
61482
+ if (state.lost.reported && state.lost.told) delete state.lost;
61288
61483
  }
61289
61484
  listChats(includeChildren = false) {
61290
61485
  return Array.from(this.chats.values()).filter((chat) => !chat.persisted.deletedAt && (includeChildren || chat.persisted.parentChatId === null)).map((chat) => this.toSummary(chat)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
@@ -61308,7 +61503,7 @@ var ChatService = class {
61308
61503
  const [discovered, learnedSkills] = await Promise.all([
61309
61504
  chat.provider.listSlashCommands?.() ?? [],
61310
61505
  // Learned skills work in the background, so they stay out of the slash menu.
61311
- readFile17(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
61506
+ readFile18(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
61312
61507
  ]);
61313
61508
  const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
61314
61509
  ...command,
@@ -61534,9 +61729,10 @@ var ChatService = class {
61534
61729
  if (idempotencyKey) {
61535
61730
  const accepting2 = chat.acceptingSendResponses.get(idempotencyKey);
61536
61731
  if (accepting2) return accepting2;
61537
- const accepted = chat.acceptedSendResponses.get(idempotencyKey);
61732
+ const accepted = chat.commands.state.accepted.get(idempotencyKey);
61538
61733
  if (accepted) {
61539
- return accepted;
61734
+ const { at: _at, ...response } = accepted;
61735
+ return response;
61540
61736
  }
61541
61737
  }
61542
61738
  if (chat.switching) await chat.switching.catch(() => {
@@ -61642,15 +61838,24 @@ ${decisions}` };
61642
61838
  result.messageId,
61643
61839
  submittedAt
61644
61840
  );
61645
- try {
61646
- await chat.provider.persistHistoryEvent(acceptedEvent);
61647
- } catch (error) {
61648
- throw new ChatMessagePersistenceError(error);
61649
- }
61650
- const previousAcceptedSendResponses = new Map(chat.acceptedSendResponses);
61841
+ const { state } = chat.commands;
61842
+ const existingTargets = chat.errorNotificationTargets.get(result.messageId) ?? [];
61843
+ const notificationTargets = [
61844
+ ...existingTargets,
61845
+ ...[
61846
+ ...request.errorNotificationTargets ?? [],
61847
+ ...request.errorNotificationTarget ? [request.errorNotificationTarget] : []
61848
+ ].filter((target) => !existingTargets.some((existing) => JSON.stringify(existing) === JSON.stringify(target)))
61849
+ ];
61850
+ const previousQueued = state.queue.find(({ id }) => id === result.messageId);
61851
+ const queued = {
61852
+ ...acceptedMessage,
61853
+ id: result.messageId,
61854
+ queuedAt: previousQueued?.queuedAt ?? submittedAt,
61855
+ ...notificationTargets.length > 0 ? { errorNotificationTargets: notificationTargets } : {}
61856
+ };
61651
61857
  const previousPendingMessageIds = [...chat.pendingMessageIds];
61652
61858
  const previousAcceptedEvent = chat.acceptedUserEvents.get(result.messageId);
61653
- const previousPersistedResponses = chat.persisted.acceptedSendResponses;
61654
61859
  const previousLastMessageText = chat.persisted.lastMessageText;
61655
61860
  const previousModel = chat.persisted.model;
61656
61861
  const previousThinkingLevel = chat.persisted.thinkingLevel;
@@ -61658,15 +61863,12 @@ ${decisions}` };
61658
61863
  const previousFork = chat.persisted.fork;
61659
61864
  const previousPendingForkHandoff = chat.persisted.pendingForkHandoff;
61660
61865
  const idempotencyKey = request.idempotencyKey ?? request.messageId;
61661
- if (idempotencyKey) {
61662
- chat.acceptedSendResponses.set(idempotencyKey, result);
61663
- for (const key of chat.acceptedSendResponses.keys()) {
61664
- if (chat.acceptedSendResponses.size <= MAX_ACCEPTED_SEND_RESPONSES) break;
61665
- chat.acceptedSendResponses.delete(key);
61666
- }
61667
- chat.persisted.acceptedSendResponses = Object.fromEntries(chat.acceptedSendResponses);
61668
- }
61669
- if (!chat.persisted.removedMessageIds?.includes(result.messageId)) {
61866
+ const previousAccepted = idempotencyKey ? state.accepted.get(idempotencyKey) : void 0;
61867
+ if (idempotencyKey) state.accepted.set(idempotencyKey, { ...result, at: (/* @__PURE__ */ new Date()).toISOString() });
61868
+ if (!state.removed.includes(result.messageId)) {
61869
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
61870
+ if (previousQueued) state.queue[state.queue.indexOf(previousQueued)] = queued;
61871
+ else state.queue.push(queued);
61670
61872
  if (!chat.pendingMessageIds.includes(result.messageId)) {
61671
61873
  chat.pendingMessageIds.push(result.messageId);
61672
61874
  }
@@ -61681,37 +61883,31 @@ ${decisions}` };
61681
61883
  chat.persisted.fork = { ...chat.persisted.fork, state: "ready", completedAt: chat.persisted.updatedAt };
61682
61884
  }
61683
61885
  try {
61886
+ await chat.commands.save();
61684
61887
  await this.persistAllChats();
61888
+ await chat.provider.persistHistoryEvent(acceptedEvent);
61685
61889
  } catch (error) {
61686
- chat.acceptedSendResponses.clear();
61687
- for (const [key, response] of previousAcceptedSendResponses) {
61688
- chat.acceptedSendResponses.set(key, response);
61689
- }
61890
+ const index = state.queue.indexOf(queued);
61891
+ if (index !== -1) state.queue.splice(index, 1, ...previousQueued ? [previousQueued] : []);
61892
+ if (idempotencyKey && previousAccepted) state.accepted.set(idempotencyKey, previousAccepted);
61893
+ else if (idempotencyKey) state.accepted.delete(idempotencyKey);
61690
61894
  chat.pendingMessageIds = previousPendingMessageIds;
61691
61895
  if (previousAcceptedEvent) chat.acceptedUserEvents.set(result.messageId, previousAcceptedEvent);
61692
61896
  else chat.acceptedUserEvents.delete(result.messageId);
61693
- chat.persisted.acceptedSendResponses = previousPersistedResponses;
61694
61897
  chat.persisted.lastMessageText = previousLastMessageText;
61695
61898
  chat.persisted.model = previousModel;
61696
61899
  chat.persisted.thinkingLevel = previousThinkingLevel;
61697
61900
  chat.persisted.updatedAt = previousUpdatedAt;
61698
61901
  chat.persisted.fork = previousFork;
61699
61902
  chat.persisted.pendingForkHandoff = previousPendingForkHandoff;
61903
+ await chat.commands.save().catch((saveError) => {
61904
+ console.error("[ChatService] Failed to take a rejected message back out of the command file:", { chatId, error: saveError });
61905
+ });
61700
61906
  throw new ChatMessagePersistenceError(error);
61701
61907
  }
61702
61908
  chat.lastSendRequest = request;
61703
61909
  this.agentChatActivityTrackerService.noteMessageAccepted(result.messageId, request);
61704
- const notificationTargets = [
61705
- ...request.errorNotificationTargets ?? [],
61706
- ...request.errorNotificationTarget ? [request.errorNotificationTarget] : []
61707
- ];
61708
- if (notificationTargets.length > 0) {
61709
- const existingTargets = chat.errorNotificationTargets.get(result.messageId) ?? [];
61710
- chat.errorNotificationTargets.set(result.messageId, [
61711
- ...existingTargets,
61712
- ...notificationTargets.filter((target) => !existingTargets.some((existing) => JSON.stringify(existing) === JSON.stringify(target)))
61713
- ]);
61714
- }
61910
+ if (notificationTargets.length > 0) chat.errorNotificationTargets.set(result.messageId, notificationTargets);
61715
61911
  if (recordedSender) {
61716
61912
  await this.appendSender(chatId, recordedSender);
61717
61913
  }
@@ -61742,7 +61938,7 @@ ${decisions}` };
61742
61938
  }
61743
61939
  }
61744
61940
  async readSenders(chatId) {
61745
- return readFile17(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
61941
+ return readFile18(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
61746
61942
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
61747
61943
  console.error("[ChatService] Failed to read sender records:", error);
61748
61944
  return [];
@@ -61750,13 +61946,7 @@ ${decisions}` };
61750
61946
  }
61751
61947
  async interrupt(chatId, stoppedAt) {
61752
61948
  const chat = this.requireChat(chatId);
61753
- const result = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds), stoppedAt);
61754
- this.endTrackedTurn(chat);
61755
- chat.hasActiveTurn = false;
61756
- chat.activeMessageId = null;
61757
- chat.pendingMessageIds = [];
61758
- chat.acceptedUserEvents.clear();
61759
- chat.turnAnswer = null;
61949
+ const result = await this.stopTurn(chat, stoppedAt);
61760
61950
  this.touch(chat);
61761
61951
  await this.publish({
61762
61952
  type: "chat.interrupted",
@@ -61768,6 +61958,24 @@ ${decisions}` };
61768
61958
  });
61769
61959
  return result;
61770
61960
  }
61961
+ async stopTurn(chat, stoppedAt) {
61962
+ const stopped = new Set(chat.provider.isProcessing() ? chat.commands.state.queue.map(({ id }) => id) : []);
61963
+ const result = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds), stoppedAt);
61964
+ const kept = new Set(chat.provider.getQueue().map(({ id }) => id));
61965
+ const { state } = chat.commands;
61966
+ const queue = state.queue.filter(({ id }) => kept.has(id) || !stopped.has(id));
61967
+ if (queue.length !== state.queue.length) {
61968
+ state.queue = queue;
61969
+ await chat.commands.save();
61970
+ }
61971
+ this.endTrackedTurn(chat);
61972
+ chat.hasActiveTurn = false;
61973
+ chat.activeMessageId = null;
61974
+ chat.pendingMessageIds = [];
61975
+ chat.acceptedUserEvents.clear();
61976
+ chat.turnAnswer = null;
61977
+ return result;
61978
+ }
61771
61979
  async clearGoal(chatId) {
61772
61980
  const chat = this.requireChat(chatId);
61773
61981
  if (!chat.provider.clearGoal) {
@@ -61776,13 +61984,7 @@ ${decisions}` };
61776
61984
  this.cancelIdleRelease(chat);
61777
61985
  await chat.release;
61778
61986
  this.requireChat(chatId);
61779
- const interruptResult = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds));
61780
- this.endTrackedTurn(chat);
61781
- chat.hasActiveTurn = false;
61782
- chat.activeMessageId = null;
61783
- chat.pendingMessageIds = [];
61784
- chat.acceptedUserEvents.clear();
61785
- chat.turnAnswer = null;
61987
+ const interruptResult = await this.stopTurn(chat);
61786
61988
  const goal = await chat.provider.clearGoal(chat.persisted.model).finally(() => {
61787
61989
  chat.live = !!chat.provider.dispose;
61788
61990
  this.scheduleIdleRelease(chat);
@@ -61870,17 +62072,34 @@ ${decisions}` };
61870
62072
  type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
61871
62073
  payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: [...removed] }
61872
62074
  };
61873
- await chat.provider.persistHistoryEvent(event);
61874
- chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
62075
+ const { state } = chat.commands;
62076
+ const queued = state.queue.filter(({ id }) => removed.has(id));
62077
+ const newlyRemoved = messageIds.filter((id) => !state.removed.includes(id));
62078
+ const previousCheckFrom = state.checkFrom;
62079
+ state.queue = state.queue.filter(({ id }) => !removed.has(id));
62080
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
62081
+ state.removed.push(...newlyRemoved);
62082
+ state.removing.push(...messageIds);
62083
+ try {
62084
+ await chat.commands.save();
62085
+ await chat.provider.persistHistoryEvent(event);
62086
+ } catch (error) {
62087
+ state.queue.push(...queued);
62088
+ state.checkFrom = previousCheckFrom;
62089
+ state.removed = state.removed.filter((id) => !newlyRemoved.includes(id));
62090
+ state.removing = state.removing.filter((id) => !removed.has(id));
62091
+ await chat.commands.save().catch((saveError) => {
62092
+ console.error("[ChatService] Failed to put messages back in the command file:", { chatId: chat.persisted.id, error: saveError });
62093
+ });
62094
+ throw error;
62095
+ }
62096
+ state.removing = state.removing.filter((id) => !removed.has(id));
61875
62097
  chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
61876
62098
  this.forkSourceSeenBlocks.delete(chat.persisted.id);
61877
62099
  for (const messageId of removed) {
61878
62100
  chat.acceptedUserEvents.delete(messageId);
61879
62101
  chat.errorNotificationTargets.delete(messageId);
61880
62102
  }
61881
- await this.persistAllChats().catch((error) => {
61882
- console.error("[ChatService] Failed to persist queued-message removals:", error);
61883
- });
61884
62103
  await this.publish({
61885
62104
  type: "chat.turn.delta",
61886
62105
  payload: { chatId: chat.persisted.id, event }
@@ -61916,10 +62135,15 @@ ${decisions}` };
61916
62135
  removedMessageIds: success ? queuedIds : []
61917
62136
  };
61918
62137
  }
61919
- updateQueuedMessage(chatId, messageId, message) {
62138
+ async updateQueuedMessage(chatId, messageId, message) {
61920
62139
  const chat = this.requireChat(chatId);
61921
62140
  const success = chat.provider.updateQueuedMessage(messageId, message);
61922
62141
  if (success) {
62142
+ const queued = chat.commands.state.queue.find(({ id }) => id === messageId);
62143
+ if (queued) {
62144
+ queued.message = message;
62145
+ await chat.commands.save();
62146
+ }
61923
62147
  const acceptedEvent = chat.acceptedUserEvents.get(messageId);
61924
62148
  if (acceptedEvent) {
61925
62149
  chat.acceptedUserEvents.set(messageId, {
@@ -61937,14 +62161,23 @@ ${decisions}` };
61937
62161
  queue: chat.provider.getQueue()
61938
62162
  };
61939
62163
  }
61940
- reorderQueue(chatId, messageId, position) {
62164
+ async reorderQueue(chatId, messageId, position) {
61941
62165
  const chat = this.requireChat(chatId);
61942
62166
  const success = chat.provider.reorderQueue(messageId, position);
62167
+ if (success) await this.saveQueueOrder(chat);
61943
62168
  return {
61944
62169
  success,
61945
62170
  queue: chat.provider.getQueue()
61946
62171
  };
61947
62172
  }
62173
+ async saveQueueOrder(chat) {
62174
+ const order = new Map(chat.provider.getQueue().map(({ id }, index) => [id, index]));
62175
+ const { state } = chat.commands;
62176
+ const queue = [...state.queue].sort((a, b) => (order.get(a.id) ?? -1) - (order.get(b.id) ?? -1));
62177
+ if (queue.every((message, index) => message === state.queue[index])) return;
62178
+ state.queue = queue;
62179
+ await chat.commands.save();
62180
+ }
61948
62181
  async steerFromQueue(chatId, messageId) {
61949
62182
  const chat = this.requireChat(chatId);
61950
62183
  const result = await chat.provider.steerFromQueue(messageId);
@@ -61980,6 +62213,7 @@ ${decisions}` };
61980
62213
  if (target.provider.isProcessing()) {
61981
62214
  await target.provider.interrupt((messageIds) => this.forgetPendingMessages(target, messageIds)).catch(() => {
61982
62215
  });
62216
+ this.endTrackedTurn(target);
61983
62217
  target.hasActiveTurn = false;
61984
62218
  target.activeMessageId = null;
61985
62219
  target.pendingMessageIds = [];
@@ -61988,11 +62222,18 @@ ${decisions}` };
61988
62222
  const started = hasChatStarted(this.toSummary(target));
61989
62223
  if (started) {
61990
62224
  target.persisted.deletedAt = deletedAt;
62225
+ target.commands.state.queue = [];
62226
+ delete target.commands.state.running;
62227
+ delete target.commands.state.lost;
62228
+ await target.commands.save();
61991
62229
  } else {
61992
62230
  this.chats.delete(id);
61993
62231
  }
61994
62232
  await this.releaseAgentProcess(target);
61995
- if (!started) await this.deleteHistoryFile(target.persisted);
62233
+ if (!started) {
62234
+ await this.deleteHistoryFile(target.persisted);
62235
+ await target.commands.remove();
62236
+ }
61996
62237
  await this.publish({ type: "chat.deleted", payload: { chatId: id, chat: this.toSummary(target) } });
61997
62238
  }
61998
62239
  await this.persistAllChats();
@@ -62046,9 +62287,9 @@ ${decisions}` };
62046
62287
  historyPath,
62047
62288
  `${historyPath}.pages.jsonl`,
62048
62289
  `${historyPath}.pages.index.json`
62049
- ].map((path7) => rm6(path7, { force: true })));
62050
- await rm6(chatMessageSendersFilePath(persisted.id), { force: true });
62051
- await rm6(join29(FORKS_DIR, persisted.id), { recursive: true, force: true });
62290
+ ].map((path7) => rm7(path7, { force: true })));
62291
+ await rm7(chatMessageSendersFilePath(persisted.id), { force: true });
62292
+ await rm7(join30(FORKS_DIR, persisted.id), { recursive: true, force: true });
62052
62293
  }
62053
62294
  switchHarness(source, request) {
62054
62295
  const switching = (async () => {
@@ -62077,7 +62318,7 @@ ${decisions}` };
62077
62318
  source.switching = null;
62078
62319
  for (const queued of carried) {
62079
62320
  const key = queued.idempotencyKey ?? queued.messageId;
62080
- if (key) source.acceptedSendResponses.delete(key);
62321
+ if (key) source.commands.state.accepted.delete(key);
62081
62322
  await this.sendMessage(source.persisted.id, queued).catch((restoreError) => {
62082
62323
  console.error("[ChatService] Failed to requeue a message after a failed harness switch:", { chatId: source.persisted.id, error: restoreError });
62083
62324
  });
@@ -62310,7 +62551,7 @@ ${note}`;
62310
62551
  const historyEvents = excludeQueuedAcceptedEvents(
62311
62552
  mergeWorkspaceChatHistoryEvents([], history.events),
62312
62553
  chat.provider.getQueue(),
62313
- chat.persisted.removedMessageIds
62554
+ chat.commands.state.removed
62314
62555
  );
62315
62556
  for (const [messageId, acceptedEvent] of chat.acceptedUserEvents) {
62316
62557
  if (historyEvents.some((event) => isSameAcceptedUserEvent(event, acceptedEvent))) {
@@ -62324,14 +62565,14 @@ ${note}`;
62324
62565
  const events = excludeQueuedAcceptedEvents(
62325
62566
  [...historyEvents, ...acceptedEvents].sort((a, b) => getEventTimestampMs(a) - getEventTimestampMs(b)),
62326
62567
  [],
62327
- chat.persisted.removedMessageIds
62568
+ chat.commands.state.removed
62328
62569
  );
62329
62570
  if (history.appendsAfter !== void 0 || page2.limit !== void 0 && "beforeCursor" in history) {
62330
62571
  const response = {
62331
62572
  ...history,
62332
62573
  historyVersion,
62333
62574
  events,
62334
- removedMessageIds: chat.persisted.removedMessageIds,
62575
+ removedMessageIds: chat.commands.state.removed,
62335
62576
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62336
62577
  senders: getChatHistoryPageSenders(senders, page2)
62337
62578
  };
@@ -62350,7 +62591,7 @@ ${note}`;
62350
62591
  ...history,
62351
62592
  historyVersion,
62352
62593
  events,
62353
- removedMessageIds: chat.persisted.removedMessageIds,
62594
+ removedMessageIds: chat.commands.state.removed,
62354
62595
  totalEvents: (history.totalEvents ?? history.eventsStartIndex + history.events.length) - (history.events.length - historyEvents.length) + acceptedEvents.length,
62355
62596
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62356
62597
  senders
@@ -62360,7 +62601,7 @@ ${note}`;
62360
62601
  thread_id: history.thread_id,
62361
62602
  historyVersion,
62362
62603
  events,
62363
- removedMessageIds: chat.persisted.removedMessageIds,
62604
+ removedMessageIds: chat.commands.state.removed,
62364
62605
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62365
62606
  senders
62366
62607
  }, page2);
@@ -62377,13 +62618,17 @@ ${note}`;
62377
62618
  toTranscriptSource(chat) {
62378
62619
  return {
62379
62620
  ...this.toSummary(chat),
62380
- removedMessageIds: chat.persisted.removedMessageIds,
62621
+ removedMessageIds: chat.commands.state.removed,
62381
62622
  transcriptAuth: chat.persisted.transcriptAuth,
62382
62623
  currentHistoryVersion: () => this.toSummary(chat).historyVersion
62383
62624
  };
62384
62625
  }
62385
62626
  historyPath(persisted) {
62386
- return join29(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62627
+ return join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62628
+ }
62629
+ /** Read from the disk, not from the provider's own count, which several providers lose after their first turn. Any record written later starts at or after it. */
62630
+ historySizeOnDisk(persisted) {
62631
+ return statSync4(this.historyPath(persisted), { throwIfNoEntry: false })?.size ?? 0;
62387
62632
  }
62388
62633
  async recordUploadedHistory(chatId, artifact) {
62389
62634
  const chat = this.getRuntimeChat(chatId);
@@ -62439,7 +62684,7 @@ ${note}`;
62439
62684
  mcpActivity: chatActivity.mcpActivity
62440
62685
  };
62441
62686
  }
62442
- createRuntimeChat(persisted) {
62687
+ createRuntimeChat(persisted, commands = new ChatCommands(persisted.id)) {
62443
62688
  const saveSession = async (sessionId) => {
62444
62689
  persisted.providerSessionId = sessionId;
62445
62690
  delete persisted.pendingProviderFork;
@@ -62481,7 +62726,15 @@ ${note}`;
62481
62726
  if (processing) return;
62482
62727
  this.handleProcessingStopped(persisted.id);
62483
62728
  };
62484
- const onQueueChanged = () => queueMicrotask(() => this.publishQueueIfChanged(persisted.id));
62729
+ const onQueueChanged = () => queueMicrotask(() => {
62730
+ this.publishQueueIfChanged(persisted.id);
62731
+ const chat = this.getRuntimeChat(persisted.id);
62732
+ if (chat) {
62733
+ this.saveQueueOrder(chat).catch((error) => {
62734
+ console.error("[ChatService] Failed to save the queue order:", { chatId: persisted.id, error });
62735
+ });
62736
+ }
62737
+ });
62485
62738
  const fallbackContext = () => {
62486
62739
  const chat = this.chats.get(persisted.id);
62487
62740
  return {
@@ -62511,7 +62764,7 @@ ${note}`;
62511
62764
  chat = this.chats.get(next)?.persisted;
62512
62765
  }
62513
62766
  const baseProvider = persisted.provider;
62514
- const historyFilePath = join29(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62767
+ const historyFilePath = join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62515
62768
  const managerOptions = {
62516
62769
  provider: baseProvider,
62517
62770
  workingDirectory: this.workingDirectory,
@@ -62533,6 +62786,7 @@ ${note}`;
62533
62786
  onChatCredential,
62534
62787
  lastSenderKey: persisted.lastSenderKey,
62535
62788
  onLastSenderKeyChanged,
62789
+ previousTurnLost: Boolean(commands.state.running || commands.state.lost && !commands.state.lost.told),
62536
62790
  parentChatId: persisted.parentChatId
62537
62791
  };
62538
62792
  let provider;
@@ -62568,7 +62822,7 @@ ${note}`;
62568
62822
  pendingMessageIds: [],
62569
62823
  steeringOnArrival: /* @__PURE__ */ new Set(),
62570
62824
  acceptedUserEvents: /* @__PURE__ */ new Map(),
62571
- acceptedSendResponses: new Map(Object.entries(persisted.acceptedSendResponses ?? {})),
62825
+ commands,
62572
62826
  acceptingSendResponses: /* @__PURE__ */ new Map(),
62573
62827
  acceptingMessages: 0,
62574
62828
  activeMessageId: null,
@@ -62633,7 +62887,13 @@ ${note}`;
62633
62887
  activateTurn(chat, messageId) {
62634
62888
  chat.hasActiveTurn = true;
62635
62889
  chat.activeMessageId = messageId;
62636
- chat.persisted.turnStartedAt = (/* @__PURE__ */ new Date()).toISOString();
62890
+ chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
62891
+ chat.errorNotificationTargets.delete(messageId);
62892
+ const { state } = chat.commands;
62893
+ state.queue = state.queue.filter(({ id }) => id !== messageId);
62894
+ state.running = { id: messageId, errorNotificationTargets: chat.activeErrorNotificationTargets };
62895
+ this.settleLostTurn(chat, "told");
62896
+ const saved = chat.commands.save();
62637
62897
  this.touch(chat);
62638
62898
  chat.live = !!chat.provider.dispose;
62639
62899
  this.enforceLiveProcessCap();
@@ -62646,8 +62906,7 @@ ${note}`;
62646
62906
  chat.persisted.provider
62647
62907
  );
62648
62908
  this.agentTokenUsageTracker.startTurn(context);
62649
- chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
62650
- chat.errorNotificationTargets.delete(messageId);
62909
+ return saved;
62651
62910
  }
62652
62911
  async handleTurnStarted(chatId, message) {
62653
62912
  const chat = this.getRuntimeChat(chatId);
@@ -62659,11 +62918,14 @@ ${note}`;
62659
62918
  (/* @__PURE__ */ new Date()).toISOString()
62660
62919
  );
62661
62920
  chat.acceptedUserEvents.set(message.id, acceptedEvent);
62662
- this.activateTurn(chat, message.id);
62663
- const transcriptAuth = currentTranscriptAuth(chat.persisted.provider);
62664
- if (JSON.stringify(chat.persisted.transcriptAuth) !== JSON.stringify(transcriptAuth)) {
62665
- chat.persisted.transcriptAuth = transcriptAuth;
62666
- await this.persistAllChats();
62921
+ const saved = this.activateTurn(chat, message.id);
62922
+ chat.persisted.transcriptAuth = currentTranscriptAuth(chat.persisted.provider);
62923
+ try {
62924
+ await saved;
62925
+ } catch (error) {
62926
+ chat.lastTurnErrors = ["This message was not run because the workspace could not save the chat."];
62927
+ await this.handleTurnFinished(chatId);
62928
+ throw error;
62667
62929
  }
62668
62930
  await this.publish({
62669
62931
  type: "chat.turn.started",
@@ -62686,7 +62948,9 @@ ${note}`;
62686
62948
  if (!messageId) {
62687
62949
  return;
62688
62950
  }
62689
- this.activateTurn(chat, messageId);
62951
+ this.activateTurn(chat, messageId).catch((error) => {
62952
+ console.error("[ChatService] Failed to save the running turn:", { chatId, error });
62953
+ });
62690
62954
  this.publish({
62691
62955
  type: "chat.turn.started",
62692
62956
  payload: {
@@ -62723,6 +62987,14 @@ ${note}`;
62723
62987
  if (event.type === AGENT_QUOTA_EXHAUSTED_EVENT_TYPE) {
62724
62988
  chat.quotaExhaustion = agentQuotaExhaustedPayloadSchema.safeParse(event.payload).data ?? null;
62725
62989
  }
62990
+ const { state } = chat.commands;
62991
+ const readMessageId = event.payload[USER_MESSAGE_ID_PAYLOAD_KEY];
62992
+ if (state.queue.some(({ id }) => id === readMessageId)) {
62993
+ state.queue = state.queue.filter(({ id }) => id !== readMessageId);
62994
+ chat.commands.save().catch((error) => {
62995
+ console.error("[ChatService] Failed to save a steered message as read:", { chatId, error });
62996
+ });
62997
+ }
62726
62998
  let eventToPublish = event;
62727
62999
  if (event.type === "event_msg" && event.payload.type === "user_message") {
62728
63000
  if (chat.activeMessageId && !event.payload[USER_MESSAGE_ID_PAYLOAD_KEY]) {
@@ -62840,19 +63112,25 @@ ${note}`;
62840
63112
  endTrackedTurn(chat) {
62841
63113
  this.agentTokenUsageTracker.endTurn(chat.persisted.id);
62842
63114
  this.agentChatActivityTrackerService.noteTurnEnded(chat.persisted.id);
62843
- delete chat.persisted.turnStartedAt;
63115
+ if (chat.commands.state.running) {
63116
+ delete chat.commands.state.running;
63117
+ chat.commands.save().catch((error) => {
63118
+ console.error("[ChatService] Failed to save the end of a turn:", { chatId: chat.persisted.id, error });
63119
+ });
63120
+ }
62844
63121
  this.progressCoalescer.cancel(chat.persisted.id);
62845
63122
  chat.progressStep = null;
62846
63123
  chat.progressSentStep = null;
62847
63124
  chat.plainStep = null;
62848
63125
  this.touch(chat);
62849
63126
  }
62850
- async handleTurnFinished(chatId) {
63127
+ async handleTurnFinished(chatId, lostToRestart = false) {
62851
63128
  const chat = this.getRuntimeChat(chatId);
62852
63129
  if (!chat) {
62853
63130
  return;
62854
63131
  }
62855
- const userTurn = chat.hasActiveTurn;
63132
+ if (lostToRestart) chat.lastTurnErrors = [`${CHAT_TURN_LOST_MESSAGE}${chat.provider.getQueue().length > 0 ? " Queued messages are running now." : ""}`];
63133
+ const userTurn = chat.hasActiveTurn || lostToRestart;
62856
63134
  if (!userTurn) {
62857
63135
  const queuedMessageIds = new Set(chat.provider.getQueue().map((message) => message.id));
62858
63136
  const completedMessageId = chat.pendingMessageIds.find((messageId) => !queuedMessageIds.has(messageId));
@@ -62880,7 +63158,7 @@ ${note}`;
62880
63158
  chat.turnAnswer = null;
62881
63159
  if (answer) chat.turnRequest = null;
62882
63160
  const responseComplete = this.publishTurnCompleted(chat, completedAt, stillProcessing, answer, request, userTurn);
62883
- const completion = this.publishAgentTurnCompleteWebhook(chat, completedAt, stillProcessing, forked ? null : exhaustion, responseComplete, chat.turnCompletion).catch((error) => console.error("[ChatService] Failed to report turn completion:", { chatId, error })).finally(() => {
63161
+ const completion = this.publishAgentTurnCompleteWebhook(chat, completedAt, stillProcessing, forked ? null : exhaustion, responseComplete, chat.turnCompletion, lostToRestart).catch((error) => console.error("[ChatService] Failed to report turn completion:", { chatId, error })).finally(() => {
62884
63162
  if (chat.turnCompletion === completion) chat.turnCompletion = null;
62885
63163
  this.notifyWorkspaceAgentIdle();
62886
63164
  this.scheduleIdleRelease(chat);
@@ -62926,7 +63204,7 @@ ${note}`;
62926
63204
  }
62927
63205
  async loadChats() {
62928
63206
  try {
62929
- const content = await readFile17(CHATS_FILE, "utf-8");
63207
+ const content = await readFile18(CHATS_FILE, "utf-8");
62930
63208
  return parsePersistedChatsContent(content);
62931
63209
  } catch (error) {
62932
63210
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
@@ -62941,7 +63219,7 @@ ${note}`;
62941
63219
  console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
62942
63220
  }
62943
63221
  try {
62944
- const backupContent = await readFile17(CHATS_BACKUP_FILE, "utf-8");
63222
+ const backupContent = await readFile18(CHATS_BACKUP_FILE, "utf-8");
62945
63223
  return parsePersistedChatsContent(backupContent);
62946
63224
  } catch (backupError) {
62947
63225
  if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
@@ -63015,7 +63293,7 @@ ${note}`;
63015
63293
  } catch {
63016
63294
  }
63017
63295
  }
63018
- async publishAgentTurnCompleteWebhook(chat, completedAt, processing, quotaExhaustion, responseComplete, previousCompletion) {
63296
+ async publishAgentTurnCompleteWebhook(chat, completedAt, processing, quotaExhaustion, responseComplete, previousCompletion, turnLost) {
63019
63297
  const linearSessionId = ENGINE_ENV.REPLICAS_LINEAR_SESSION_ID;
63020
63298
  const errors = chat.persisted.parentChatId === null ? chat.lastTurnErrors : null;
63021
63299
  chat.lastTurnErrors = null;
@@ -63044,11 +63322,16 @@ ${note}`;
63044
63322
  repoStatuses,
63045
63323
  ...unlinkedPullRequestUrls.length > 0 ? { unlinkedPullRequestUrls } : {},
63046
63324
  ...errors?.length ? { errors } : {},
63325
+ ...turnLost ? { turnLost } : {},
63047
63326
  ...(errors?.length || quotaExhaustion) && errorNotificationTargets.length > 0 ? { errorNotificationTargets } : {},
63048
63327
  ...quotaExhaustion ? { quotaExhaustion } : {},
63049
63328
  ...isPullRequestFeedbackChat(chat.persisted) ? { pullRequestFeedback: true } : {}
63050
63329
  };
63051
- await monolithService.sendEvent({ type: "agent_turn_complete", payload });
63330
+ const sent = await monolithService.sendEvent({ type: "agent_turn_complete", payload });
63331
+ if (turnLost && sent) {
63332
+ this.settleLostTurn(chat, "reported");
63333
+ await chat.commands.save();
63334
+ }
63052
63335
  } catch (error) {
63053
63336
  console.error("[ChatService] Failed to send agent_turn_complete event:", error);
63054
63337
  }
@@ -63067,15 +63350,15 @@ ${note}`;
63067
63350
 
63068
63351
  // src/services/repo-file-service.ts
63069
63352
  import { execFile as execFile7 } from "child_process";
63070
- import { readFile as readFile18 } from "fs/promises";
63353
+ import { readFile as readFile19 } from "fs/promises";
63071
63354
  import { homedir as homedir10 } from "os";
63072
- import { extname as extname3, join as join31 } from "path";
63355
+ import { extname as extname3, join as join32 } from "path";
63073
63356
 
63074
63357
  // src/services/language-server-service.ts
63075
63358
  import { spawn as spawn4 } from "child_process";
63076
63359
  import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
63077
63360
  import { createRequire as createRequire5 } from "module";
63078
- import { delimiter as delimiter2, dirname as dirname16, join as join30, relative as relative2 } from "path";
63361
+ import { delimiter as delimiter2, dirname as dirname16, join as join31, relative as relative2 } from "path";
63079
63362
  import { setTimeout as setTimeout3 } from "timers/promises";
63080
63363
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
63081
63364
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
@@ -63194,7 +63477,7 @@ var LanguageServerService = class {
63194
63477
  if (config.package && config.bin) command = process.execPath;
63195
63478
  else if (config.command) {
63196
63479
  const commandName = config.command;
63197
- command = process.env.PATH?.split(delimiter2).map((directory) => join30(directory, commandName)).find(existsSync15);
63480
+ command = process.env.PATH?.split(delimiter2).map((directory) => join31(directory, commandName)).find(existsSync15);
63198
63481
  }
63199
63482
  const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
63200
63483
  if (!command) return null;
@@ -63375,7 +63658,7 @@ var RepoFileService = class {
63375
63658
  sizeBytes,
63376
63659
  binary: true,
63377
63660
  tooLarge: false,
63378
- base64: (await readFile18(fullPath)).toString("base64"),
63661
+ base64: (await readFile19(fullPath)).toString("base64"),
63379
63662
  mimeType
63380
63663
  };
63381
63664
  }
@@ -63400,7 +63683,7 @@ var RepoFileService = class {
63400
63683
  tooLarge: true
63401
63684
  };
63402
63685
  }
63403
- const content = await readFile18(fullPath, "utf-8");
63686
+ const content = await readFile19(fullPath, "utf-8");
63404
63687
  return {
63405
63688
  repoName,
63406
63689
  path: filePath,
@@ -63431,7 +63714,7 @@ var RepoFileService = class {
63431
63714
  async inspectSymbol(repoName, filePath, line, character, action) {
63432
63715
  const resolved = await this.resolveFile(repoName, filePath);
63433
63716
  if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
63434
- const content = await readFile18(resolved.fullPath, "utf8");
63717
+ const content = await readFile19(resolved.fullPath, "utf8");
63435
63718
  const sourceLine = content.split("\n")[line - 1];
63436
63719
  if (sourceLine === void 0) return null;
63437
63720
  const symbolMatch = Array.from(sourceLine.matchAll(/[\p{L}_$][\p{L}\p{N}_$]*/gu)).find((match) => character >= match.index && character <= match.index + match[0].length);
@@ -63481,7 +63764,7 @@ var RepoFileService = class {
63481
63764
  return await resolveContainedFile(repo.path, filePath);
63482
63765
  }
63483
63766
  async resolveSkillFile(filePath) {
63484
- const skillRoots = SANDBOX_SKILL_DIRS.map((dir) => join31(this.homeDir, dir));
63767
+ const skillRoots = SANDBOX_SKILL_DIRS.map((dir) => join32(this.homeDir, dir));
63485
63768
  if (!skillRoots.some((root) => filePath.startsWith(`${root}/`))) return null;
63486
63769
  const repos = await this.gitService.listRepositories();
63487
63770
  for (const root of [...skillRoots, ...repos.map((repo) => repo.path)]) {
@@ -63553,30 +63836,30 @@ var RepoFileService = class {
63553
63836
 
63554
63837
  // src/v1-routes.ts
63555
63838
  import { Hono } from "hono";
63556
- import { z as z5 } from "zod";
63557
- import { readdir as readdir10, stat as stat7, readFile as readFile21 } from "fs/promises";
63839
+ import { z as z6 } from "zod";
63840
+ import { readdir as readdir10, stat as stat7, readFile as readFile22 } from "fs/promises";
63558
63841
  import { openAsBlob } from "fs";
63559
- import { join as join34, resolve as resolve5 } from "path";
63842
+ import { join as join35, resolve as resolve5 } from "path";
63560
63843
 
63561
63844
  // src/services/warm-hooks-service.ts
63562
63845
  import { spawn as spawn5 } from "child_process";
63563
- import { readFile as readFile20 } from "fs/promises";
63846
+ import { readFile as readFile21 } from "fs/promises";
63564
63847
  import { existsSync as existsSync16 } from "fs";
63565
- import { join as join33 } from "path";
63848
+ import { join as join34 } from "path";
63566
63849
 
63567
63850
  // src/services/warm-hook-logs-service.ts
63568
- import { mkdir as mkdir19, readFile as readFile19, writeFile as writeFile9, readdir as readdir9, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
63851
+ import { mkdir as mkdir20, readFile as readFile20, writeFile as writeFile9, readdir as readdir9, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
63569
63852
  import { homedir as homedir11 } from "os";
63570
- import { join as join32 } from "path";
63571
- var LOGS_DIR2 = join32(homedir11(), ".replicas", "warm-hook-logs");
63572
- var CURRENT_RUN_LOG = join32(LOGS_DIR2, "current-run.log");
63853
+ import { join as join33 } from "path";
63854
+ var LOGS_DIR2 = join33(homedir11(), ".replicas", "warm-hook-logs");
63855
+ var CURRENT_RUN_LOG = join33(LOGS_DIR2, "current-run.log");
63573
63856
  function withPreview2(stored) {
63574
63857
  const preview = buildHookOutputPreview(stored.output);
63575
63858
  return { ...stored, ...preview };
63576
63859
  }
63577
63860
  var WarmHookLogsService = class {
63578
63861
  async ensureDir() {
63579
- await mkdir19(LOGS_DIR2, { recursive: true });
63862
+ await mkdir20(LOGS_DIR2, { recursive: true });
63580
63863
  }
63581
63864
  async saveEnvironmentHookLog(entry) {
63582
63865
  await this.ensureDir();
@@ -63585,7 +63868,7 @@ var WarmHookLogsService = class {
63585
63868
  hookName: "environment",
63586
63869
  ...entry
63587
63870
  };
63588
- await writeFile9(join32(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
63871
+ await writeFile9(join33(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
63589
63872
  `, "utf-8");
63590
63873
  }
63591
63874
  async saveRepoHookLog(repoName, entry) {
@@ -63595,7 +63878,7 @@ var WarmHookLogsService = class {
63595
63878
  hookName: repoName,
63596
63879
  ...entry
63597
63880
  };
63598
- await writeFile9(join32(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
63881
+ await writeFile9(join33(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
63599
63882
  `, "utf-8");
63600
63883
  }
63601
63884
  async getAllLogs() {
@@ -63614,7 +63897,7 @@ var WarmHookLogsService = class {
63614
63897
  continue;
63615
63898
  }
63616
63899
  try {
63617
- const raw = await readFile19(join32(LOGS_DIR2, file), "utf-8");
63900
+ const raw = await readFile20(join33(LOGS_DIR2, file), "utf-8");
63618
63901
  const stored = JSON.parse(raw);
63619
63902
  if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
63620
63903
  logs.push(withPreview2(stored));
@@ -63641,7 +63924,7 @@ var WarmHookLogsService = class {
63641
63924
  }
63642
63925
  async getCurrentRunLog() {
63643
63926
  try {
63644
- return await readFile19(CURRENT_RUN_LOG, "utf-8");
63927
+ return await readFile20(CURRENT_RUN_LOG, "utf-8");
63645
63928
  } catch (err) {
63646
63929
  if (err.code === "ENOENT") return null;
63647
63930
  throw err;
@@ -63650,7 +63933,7 @@ var WarmHookLogsService = class {
63650
63933
  async getFullOutput(hookType, hookName) {
63651
63934
  const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
63652
63935
  try {
63653
- const raw = await readFile19(join32(LOGS_DIR2, filename), "utf-8");
63936
+ const raw = await readFile20(join33(LOGS_DIR2, filename), "utf-8");
63654
63937
  const stored = JSON.parse(raw);
63655
63938
  if (stored.hookType !== hookType || stored.hookName !== hookName) {
63656
63939
  return null;
@@ -63669,12 +63952,12 @@ var warmHookLogsService = new WarmHookLogsService();
63669
63952
  // src/services/warm-hooks-service.ts
63670
63953
  async function readRepoWarmHook(repoPath) {
63671
63954
  for (const filename of REPLICAS_CONFIG_FILENAMES) {
63672
- const configPath = join33(repoPath, filename);
63955
+ const configPath = join34(repoPath, filename);
63673
63956
  if (!existsSync16(configPath)) {
63674
63957
  continue;
63675
63958
  }
63676
63959
  try {
63677
- const raw = await readFile20(configPath, "utf-8");
63960
+ const raw = await readFile21(configPath, "utf-8");
63678
63961
  const config = parseReplicasConfigString(raw, filename);
63679
63962
  if (!config.warmHook) {
63680
63963
  return null;
@@ -63901,17 +64184,17 @@ ${combinedScript}` : combinedScript;
63901
64184
  import { randomUUID as randomUUID10 } from "crypto";
63902
64185
  import { existsSync as existsSync17 } from "fs";
63903
64186
  import { spawn as spawn6 } from "node-pty";
63904
- import { z as z4 } from "zod";
64187
+ import { z as z5 } from "zod";
63905
64188
  var MAX_REPLAY_CHARS2 = 1024 * 1024;
63906
64189
  var MAX_TERMINAL_SESSIONS = 8;
63907
64190
  var MAX_PENDING_INPUT = 64;
63908
- var terminalSizeSchema = z4.object({
63909
- cols: z4.number().int().min(2).max(500),
63910
- rows: z4.number().int().min(1).max(200)
64191
+ var terminalSizeSchema = z5.object({
64192
+ cols: z5.number().int().min(2).max(500),
64193
+ rows: z5.number().int().min(1).max(200)
63911
64194
  });
63912
- var terminalCommandSchema = z4.discriminatedUnion("type", [
63913
- z4.object({ type: z4.literal("input"), data: z4.string() }),
63914
- terminalSizeSchema.extend({ type: z4.literal("resize") })
64195
+ var terminalCommandSchema = z5.discriminatedUnion("type", [
64196
+ z5.object({ type: z5.literal("input"), data: z5.string() }),
64197
+ terminalSizeSchema.extend({ type: z5.literal("resize") })
63915
64198
  ]);
63916
64199
  var TerminalService = class {
63917
64200
  sessions = /* @__PURE__ */ new Map();
@@ -64032,24 +64315,24 @@ var TerminalService = class {
64032
64315
  var terminalService = new TerminalService();
64033
64316
 
64034
64317
  // src/v1-routes.ts
64035
- var createPreviewSchema = z5.object({
64036
- port: z5.number().int().min(1).max(65535),
64037
- publicUrl: z5.string().min(1)
64318
+ var createPreviewSchema = z6.object({
64319
+ port: z6.number().int().min(1).max(65535),
64320
+ publicUrl: z6.string().min(1)
64038
64321
  });
64039
- var writeTerminalSessionSchema = z5.object({
64040
- data: z5.string().max(64 * 1024),
64041
- generation: z5.number().int().nonnegative(),
64042
- sequence: z5.number().int().nonnegative()
64322
+ var writeTerminalSessionSchema = z6.object({
64323
+ data: z6.string().max(64 * 1024),
64324
+ generation: z6.number().int().nonnegative(),
64325
+ sequence: z6.number().int().nonnegative()
64043
64326
  });
64044
- var updateGoalSchema = z5.object({
64045
- objective: z5.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
64046
- status: z5.enum(["active", "paused"]).optional()
64327
+ var updateGoalSchema = z6.object({
64328
+ objective: z6.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
64329
+ status: z6.enum(["active", "paused"]).optional()
64047
64330
  }).refine((body) => body.objective !== void 0 || body.status !== void 0, {
64048
64331
  message: "Goal objective or status required"
64049
64332
  });
64050
- var updateTextFileSchema = (maxLength) => z5.object({
64051
- content: z5.string().max(maxLength),
64052
- expectedRevision: z5.string().regex(/^[a-f0-9]{64}$/)
64333
+ var updateTextFileSchema = (maxLength) => z6.object({
64334
+ content: z6.string().max(maxLength),
64335
+ expectedRevision: z6.string().regex(/^[a-f0-9]{64}$/)
64053
64336
  });
64054
64337
  function jsonError(message, details) {
64055
64338
  return { error: message, details };
@@ -64099,11 +64382,11 @@ function createV1Routes(deps) {
64099
64382
  const app2 = new Hono();
64100
64383
  app2.post("/pull-requests/check", async (c) => {
64101
64384
  if (c.req.header("content-type")?.includes("application/json")) {
64102
- const result = z5.object({
64103
- toolName: z5.string(),
64104
- toolInput: z5.unknown(),
64105
- output: z5.unknown(),
64106
- success: z5.boolean()
64385
+ const result = z6.object({
64386
+ toolName: z6.string(),
64387
+ toolInput: z6.unknown(),
64388
+ output: z6.unknown(),
64389
+ success: z6.boolean()
64107
64390
  }).safeParse(await c.req.json().catch(() => null));
64108
64391
  if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
64109
64392
  await pullRequestCheckService.onToolResult(result.data);
@@ -64323,7 +64606,7 @@ function createV1Routes(deps) {
64323
64606
  const chat = await deps.chatService.updateDisplayName(c.req.param("chatId"), body.displayName);
64324
64607
  return c.json({ chat });
64325
64608
  } catch (error) {
64326
- if (error instanceof z5.ZodError) {
64609
+ if (error instanceof z6.ZodError) {
64327
64610
  return c.json(jsonError(error.issues[0]?.message || "Invalid tab name"), 400);
64328
64611
  }
64329
64612
  if (error instanceof ChatNotFoundError) {
@@ -64444,7 +64727,7 @@ function createV1Routes(deps) {
64444
64727
  const result = await deps.chatService.updateGoal(c.req.param("chatId"), body);
64445
64728
  return c.json(result);
64446
64729
  } catch (error) {
64447
- if (error instanceof z5.ZodError) {
64730
+ if (error instanceof z6.ZodError) {
64448
64731
  return c.json(jsonError(error.issues[0]?.message || "Invalid goal update"), 400);
64449
64732
  }
64450
64733
  if (error instanceof ChatNotFoundError) {
@@ -64527,7 +64810,7 @@ function createV1Routes(deps) {
64527
64810
  if (!body.messageId || typeof body.position !== "number" || !Number.isFinite(body.position)) {
64528
64811
  return c.json(jsonError("Invalid request", "messageId and position are required"), 400);
64529
64812
  }
64530
- const result = deps.chatService.reorderQueue(c.req.param("chatId"), body.messageId, body.position);
64813
+ const result = await deps.chatService.reorderQueue(c.req.param("chatId"), body.messageId, body.position);
64531
64814
  return c.json(result);
64532
64815
  } catch (error) {
64533
64816
  if (error instanceof ChatNotFoundError) {
@@ -64543,7 +64826,7 @@ function createV1Routes(deps) {
64543
64826
  if (!message) {
64544
64827
  return c.json(jsonError("Invalid request", "message is required"), 400);
64545
64828
  }
64546
- const result = deps.chatService.updateQueuedMessage(c.req.param("chatId"), c.req.param("messageId"), message);
64829
+ const result = await deps.chatService.updateQueuedMessage(c.req.param("chatId"), c.req.param("messageId"), message);
64547
64830
  return c.json(result);
64548
64831
  } catch (error) {
64549
64832
  if (error instanceof ChatNotFoundError) {
@@ -64990,7 +65273,7 @@ data: ${JSON.stringify("Terminal session not found")}
64990
65273
  return c.json({ success: true, repos: [] });
64991
65274
  });
64992
65275
  app2.put("/linear-session", async (c) => {
64993
- const body = z5.object({ linearSessionId: z5.string().min(1) }).safeParse(await c.req.json().catch(() => null));
65276
+ const body = z6.object({ linearSessionId: z6.string().min(1) }).safeParse(await c.req.json().catch(() => null));
64994
65277
  if (!body.success) return c.json(jsonError("linearSessionId is required"), 400);
64995
65278
  setLinearSessionId(body.data.linearSessionId);
64996
65279
  return c.json({ success: true });
@@ -65044,7 +65327,7 @@ data: ${JSON.stringify("Terminal session not found")}
65044
65327
  const logFiles = files.filter((f) => f.endsWith(".log"));
65045
65328
  const sessions = await Promise.all(
65046
65329
  logFiles.map(async (filename) => {
65047
- const filePath = join34(LOG_DIR, filename);
65330
+ const filePath = join35(LOG_DIR, filename);
65048
65331
  const fileStat = await stat7(filePath);
65049
65332
  const sessionId = filename.replace(/\.log$/, "");
65050
65333
  return {
@@ -65079,7 +65362,7 @@ data: ${JSON.stringify("Terminal session not found")}
65079
65362
  }
65080
65363
  let content;
65081
65364
  try {
65082
- content = await readFile21(filePath, "utf-8");
65365
+ content = await readFile22(filePath, "utf-8");
65083
65366
  } catch {
65084
65367
  return c.json(jsonError("Log session not found"), 404);
65085
65368
  }
@@ -65100,17 +65383,17 @@ data: ${JSON.stringify("Terminal session not found")}
65100
65383
  }
65101
65384
 
65102
65385
  // src/services/terminal-socket.ts
65103
- import { z as z6 } from "zod";
65386
+ import { z as z7 } from "zod";
65104
65387
  var ndcModule;
65105
65388
  var loadNdc = () => ndcModule ??= import("node-datachannel").then((module) => module.default, () => null);
65106
65389
  var CHANNEL_CHUNK_CHARS = 16384;
65107
65390
  var MAX_QUEUED_CANDIDATES = 32;
65108
65391
  var MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
65109
- var socketMessageSchema = z6.union([
65392
+ var socketMessageSchema = z7.union([
65110
65393
  terminalCommandSchema,
65111
- z6.object({ type: z6.literal("rtc-offer"), sdp: z6.string().max(64 * 1024) }),
65112
- z6.object({ type: z6.literal("rtc-candidate"), candidate: z6.string().max(1024), mid: z6.string().max(64) }),
65113
- z6.object({ type: z6.literal("rtc-switch") })
65394
+ z7.object({ type: z7.literal("rtc-offer"), sdp: z7.string().max(64 * 1024) }),
65395
+ z7.object({ type: z7.literal("rtc-candidate"), candidate: z7.string().max(1024), mid: z7.string().max(64) }),
65396
+ z7.object({ type: z7.literal("rtc-switch") })
65114
65397
  ]);
65115
65398
  function parse(schema, raw) {
65116
65399
  try {
@@ -65198,13 +65481,13 @@ function attachTerminalSocket(id, socket) {
65198
65481
  }
65199
65482
 
65200
65483
  // src/services/resource-monitor.ts
65201
- import { readFile as readFile22 } from "fs/promises";
65484
+ import { readFile as readFile23 } from "fs/promises";
65202
65485
  var SAMPLE_INTERVAL_MS = 5e3;
65203
65486
  var READ_TIMEOUT_MS = 2e3;
65204
65487
  var pendingReads = new InFlightMap();
65205
65488
  var boundedReads = /* @__PURE__ */ new WeakMap();
65206
65489
  function readWithin(path7) {
65207
- const read = pendingReads.run(path7, () => readFile22(path7, "utf8"));
65490
+ const read = pendingReads.run(path7, () => readFile23(path7, "utf8"));
65208
65491
  const bounded = boundedReads.get(read) ?? withTimeout(read, READ_TIMEOUT_MS, `Timed out reading ${path7}`);
65209
65492
  boundedReads.set(read, bounded);
65210
65493
  return bounded;
@@ -65436,7 +65719,7 @@ var HeartbeatService = class _HeartbeatService {
65436
65719
  var heartbeatService = new HeartbeatService();
65437
65720
 
65438
65721
  // src/services/workspace-sdk-service.ts
65439
- import { cp, mkdir as mkdir20 } from "fs/promises";
65722
+ import { cp, mkdir as mkdir21 } from "fs/promises";
65440
65723
  import { dirname as dirname17, resolve as resolve6 } from "path";
65441
65724
  import { fileURLToPath as fileURLToPath6 } from "url";
65442
65725
  async function installWorkspaceSdk() {
@@ -65446,16 +65729,16 @@ async function installWorkspaceSdk() {
65446
65729
  "/tmp/node_modules/@replicas/sdk"
65447
65730
  ];
65448
65731
  await Promise.all(targets.map(async (target) => {
65449
- await mkdir20(target, { recursive: true });
65732
+ await mkdir21(target, { recursive: true });
65450
65733
  await cp(source, target, { recursive: true, force: true });
65451
65734
  }));
65452
65735
  }
65453
65736
 
65454
65737
  // src/services/git-push-tracker.ts
65455
- import { mkdir as mkdir21, rm as rm7 } from "fs/promises";
65738
+ import { mkdir as mkdir22, rm as rm8 } from "fs/promises";
65456
65739
  import { createServer as createServer3 } from "net";
65457
- import { join as join35 } from "path";
65458
- var SOCKET_PATH = join35(ENGINE_DIR, "git-trace2.sock");
65740
+ import { join as join36 } from "path";
65741
+ var SOCKET_PATH = join36(ENGINE_DIR, "git-trace2.sock");
65459
65742
  var MAX_LINE_LENGTH = 1024 * 1024;
65460
65743
  var listening = null;
65461
65744
  function startGitPushTracker() {
@@ -65465,8 +65748,8 @@ function startGitPushTracker() {
65465
65748
  });
65466
65749
  }
65467
65750
  async function listen() {
65468
- await mkdir21(ENGINE_DIR, { recursive: true });
65469
- await rm7(SOCKET_PATH, { force: true });
65751
+ await mkdir22(ENGINE_DIR, { recursive: true });
65752
+ await rm8(SOCKET_PATH, { force: true });
65470
65753
  const server3 = createServer3((socket) => {
65471
65754
  let buffered = "";
65472
65755
  let ignored = false;
@@ -65862,6 +66145,7 @@ async function activate(requested) {
65862
66145
  })
65863
66146
  ]);
65864
66147
  lifecycle.set("active");
66148
+ chatService.resumeAfterRestart();
65865
66149
  backgroundServices = Promise.allSettled([
65866
66150
  registerDesktopPreview(signal),
65867
66151
  devicesConnected,