replicas-engine 0.1.1480 → 0.1.1482

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-42KI6PWX.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-7XEYU7LU.js";
69
69
  import {
70
70
  publishedPullRequestUrls
71
- } from "./chunk-YVSEANOR.js";
71
+ } from "./chunk-IXLDRWXE.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-RASOS4B7.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-EURRNWGA.js";
158
158
  import {
159
159
  getCodexModelProvider
160
- } from "./chunk-4UBMDXMC.js";
160
+ } from "./chunk-VZAEFFIH.js";
161
161
  import {
162
162
  SUBPROCESS_MAX_BUFFER,
163
163
  execAsync,
164
164
  execFileAsync
165
- } from "./chunk-5SY2R2PG.js";
165
+ } from "./chunk-BDAFCBZS.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-NXPL5WVX.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,14 +11109,19 @@ 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";
11117
+
11118
+ // ../shared/src/persisted-query-hashes.ts
11119
+ var PERSISTED_QUERY_HASHES = {
11120
+ workspaceChats: "3d2e5d60"
11121
+ };
11113
11122
 
11114
11123
  // ../shared/src/workspace-chat.ts
11115
- var WORKSPACE_CHATS_QUERY_SCHEMA_VERSION = 18;
11116
- var WORKSPACE_CHATS_QUERY_ROOT = `workspace-chats:v${WORKSPACE_CHATS_QUERY_SCHEMA_VERSION}`;
11124
+ var WORKSPACE_CHATS_QUERY_ROOT = `workspace-chats:${PERSISTED_QUERY_HASHES.workspaceChats}`;
11117
11125
  function isAcceptedUserMessage(event) {
11118
11126
  return getUserMessage(event) !== null && event.payload.source === ACCEPTED_USER_MESSAGE_SOURCE;
11119
11127
  }
@@ -11268,7 +11276,10 @@ function mergeWorkspaceChatHistoryEvents(primary, supplemental, removedMessageId
11268
11276
  }
11269
11277
  const previous = position === -1 ? null : list[position];
11270
11278
  if (!previous) {
11271
- addEvent(event);
11279
+ const ms = getEventTimestampMs(event);
11280
+ const latest = primary.at(-1);
11281
+ const waiting = isAcceptedUserMessage(event) && latest !== void 0 && ms >= getEventTimestampMs(primary[0]) && ms < getEventTimestampMs(latest) && !primary.some((other) => workspaceChatEventSignals(other).userMessageId !== null && getEventTimestampMs(other) > ms) && !supplemental.some((other) => getEventTimestampMs(other) > ms && findDuplicatePosition(index, other) === -1);
11282
+ addEvent(waiting ? { ...event, timestamp: latest.timestamp } : event);
11272
11283
  continue;
11273
11284
  }
11274
11285
  const messageId = getUserMessageId(event);
@@ -12115,6 +12126,10 @@ var MessageQueueService = class {
12115
12126
  this.queue.splice(clamped, 0, message);
12116
12127
  this.onQueueChanged();
12117
12128
  }
12129
+ restore(messages) {
12130
+ this.queue.unshift(...messages);
12131
+ this.onQueueChanged();
12132
+ }
12118
12133
  resumeIfIdle() {
12119
12134
  if (this.processing || this.starting || this.queue.length === 0) return;
12120
12135
  void this.processNextInQueue().catch((error) => {
@@ -12200,6 +12215,8 @@ var CodingAgentManager = class _CodingAgentManager {
12200
12215
  // Unset until this process sends a turn, so a restart can't mistake the first one for a change.
12201
12216
  sentTurn = false;
12202
12217
  lastCustomInstructions;
12218
+ previousTurnLost;
12219
+ restoredMessages = /* @__PURE__ */ new WeakSet();
12203
12220
  onLastSenderKeyChanged;
12204
12221
  constructor(options) {
12205
12222
  this.workingDirectory = options.workingDirectory ?? ENGINE_ENV.WORKSPACE_ROOT;
@@ -12227,6 +12244,7 @@ var CodingAgentManager = class _CodingAgentManager {
12227
12244
  this.onModelSwitched = options.onModelSwitched ?? (async () => {
12228
12245
  });
12229
12246
  this.lastSenderKey = options.lastSenderKey ?? null;
12247
+ this.previousTurnLost = options.previousTurnLost ?? false;
12230
12248
  this.onLastSenderKeyChanged = options.onLastSenderKeyChanged ?? (async () => {
12231
12249
  });
12232
12250
  this.authFallback = options.provider ? new AuthFallbackCoordinator(options.provider, (event) => {
@@ -12296,13 +12314,17 @@ var CodingAgentManager = class _CodingAgentManager {
12296
12314
  if (stopped && (request.engineTurn || !await this.keepStoppedRequest(delivered))) return;
12297
12315
  await this.saveLastSenderKey(senderKey);
12298
12316
  if (stopped) return;
12299
- const instructionsChanged = this.sentTurn && this.lastCustomInstructions !== request.customInstructions && !request.goalMode && !request.message.trimStart().startsWith("/");
12317
+ const takesNotes = !request.goalMode && !request.message.trimStart().startsWith("/");
12318
+ const instructionsChanged = takesNotes && this.sentTurn && this.lastCustomInstructions !== request.customInstructions;
12300
12319
  this.sentTurn = true;
12301
12320
  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);
12321
+ const turnLost = takesNotes && this.previousTurnLost;
12322
+ if (turnLost) this.previousTurnLost = false;
12323
+ const notes = [
12324
+ ...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." : ""}`] : [],
12325
+ ...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."] : []
12326
+ ].map((note) => wrapInTag(note, REPLICAS_INSTRUCTIONS_TAG));
12327
+ await processMessage(notes.length > 0 ? { ...delivered, message: [delivered.message, ...notes].join("\n\n") } : delivered, signal);
12306
12328
  } finally {
12307
12329
  this.closeTurn();
12308
12330
  }
@@ -12473,6 +12495,11 @@ ${request.message}` }, senderKey };
12473
12495
  reorderQueue(messageId, newPosition) {
12474
12496
  return this.messageQueue.reorderQueue(messageId, newPosition);
12475
12497
  }
12498
+ restoreQueue(messages) {
12499
+ for (const message of messages) this.restoredMessages.add(message);
12500
+ this.messageQueue.restore(messages);
12501
+ void this.initialized.then(() => this.messageQueue.resumeIfIdle());
12502
+ }
12476
12503
  async enqueueMessage(request, onAccepted) {
12477
12504
  await this.initialized;
12478
12505
  return this.messageQueue.enqueue(request, onAccepted);
@@ -13202,28 +13229,27 @@ var CodexHistoryFile = class {
13202
13229
  }
13203
13230
  async findLastEvent(needle, matches) {
13204
13231
  let found = null;
13232
+ for await (const event of this.eventsFrom(0, [needle])) {
13233
+ if (matches(event)) found = event;
13234
+ }
13235
+ return found;
13236
+ }
13237
+ async *eventsFrom(start, needles) {
13205
13238
  try {
13206
- for await (const line of createInterface({ input: createReadStream(this.filePath), crlfDelay: Infinity })) {
13207
- if (!line.includes(needle)) continue;
13239
+ for await (const line of createInterface({ input: createReadStream(this.filePath, { start }), crlfDelay: Infinity })) {
13240
+ if (!needles.some((needle) => line.includes(needle))) continue;
13208
13241
  const event = parseAgentEventJsonlLine(line);
13209
- if (event && matches(event)) found = event;
13242
+ if (event) yield event;
13210
13243
  }
13211
13244
  } catch (error) {
13212
13245
  if (!isMissingFile(error)) throw error;
13213
13246
  }
13214
- return found;
13215
13247
  }
13216
13248
  async findSubagentItems() {
13217
13249
  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;
13250
+ for await (const event of this.eventsFrom(0, ['"subagent"'])) {
13251
+ const payload = event.type === CODEX_ITEM_EVENT_TYPE ? codexItemFromEvent(event) : null;
13252
+ if (payload?.item.type === "subagent") found.set(payload.item.id, { turnId: payload.turnId, item: payload.item });
13227
13253
  }
13228
13254
  return found;
13229
13255
  }
@@ -59391,6 +59417,80 @@ var PiManager = class extends CodingAgentManager {
59391
59417
  }
59392
59418
  };
59393
59419
 
59420
+ // src/services/chat/chat-commands.ts
59421
+ import { mkdir as mkdir16, readFile as readFile12, rm as rm6 } from "fs/promises";
59422
+ import { join as join23 } from "path";
59423
+ import { z as z3 } from "zod";
59424
+ var CHAT_COMMANDS_DIR = join23(ENGINE_DIR, "chat-commands");
59425
+ var ACCEPTED_RETENTION_MS = 8 * 24 * 60 * 6e4;
59426
+ var MAX_REMOVED_MESSAGE_IDS = 6e3;
59427
+ var queuedMessageSchema = sendChatMessageRequestSchema.extend({ id: z3.string(), queuedAt: z3.string() });
59428
+ var chatCommandStateSchema = z3.object({
59429
+ queue: z3.array(queuedMessageSchema),
59430
+ running: z3.object({
59431
+ id: z3.string().optional(),
59432
+ errorNotificationTargets: z3.array(integrationErrorNotificationTargetSchema)
59433
+ }).optional(),
59434
+ lost: z3.object({
59435
+ errorNotificationTargets: z3.array(integrationErrorNotificationTargetSchema),
59436
+ reported: z3.literal(true).optional(),
59437
+ told: z3.literal(true).optional()
59438
+ }).optional(),
59439
+ accepted: z3.record(z3.string(), sendChatMessageResponseSchema.extend({ at: z3.string() })).transform((accepted) => new Map(Object.entries(accepted))),
59440
+ removed: z3.array(z3.string()),
59441
+ removing: z3.array(z3.string()),
59442
+ checkFrom: z3.number().optional()
59443
+ });
59444
+ var ChatCommands = class _ChatCommands {
59445
+ constructor(chatId, state = { queue: [], accepted: /* @__PURE__ */ new Map(), removed: [], removing: [] }) {
59446
+ this.chatId = chatId;
59447
+ this.state = state;
59448
+ }
59449
+ chatId;
59450
+ state;
59451
+ writing = Promise.resolve();
59452
+ static async load(chatId) {
59453
+ const content = await readFile12(join23(CHAT_COMMANDS_DIR, `${chatId}.json`), "utf-8").catch((error) => {
59454
+ if (error.code === "ENOENT") return null;
59455
+ throw error;
59456
+ });
59457
+ if (content === null) return null;
59458
+ try {
59459
+ const saved = JSON.parse(content);
59460
+ if (isRecord(saved) && Array.isArray(saved.queue)) {
59461
+ saved.queue = saved.queue.filter((entry) => {
59462
+ const { success, error } = queuedMessageSchema.safeParse(entry);
59463
+ if (!success) console.error("[ChatCommands] Dropped an unreadable queued message:", { chatId, error });
59464
+ return success;
59465
+ });
59466
+ }
59467
+ return new _ChatCommands(chatId, chatCommandStateSchema.parse(saved));
59468
+ } catch (error) {
59469
+ console.error("[ChatCommands] Unreadable command file, starting empty:", { chatId, error });
59470
+ return new _ChatCommands(chatId);
59471
+ }
59472
+ }
59473
+ save() {
59474
+ const cutoff = new Date(Date.now() - ACCEPTED_RETENTION_MS).toISOString();
59475
+ for (const [key, { at }] of this.state.accepted) {
59476
+ if (at < cutoff) this.state.accepted.delete(key);
59477
+ }
59478
+ this.state.removed.splice(0, this.state.removed.length - MAX_REMOVED_MESSAGE_IDS);
59479
+ const data = JSON.stringify({ ...this.state, accepted: Object.fromEntries(this.state.accepted) });
59480
+ this.writing = this.writing.catch(() => {
59481
+ }).then(async () => {
59482
+ await mkdir16(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
59483
+ await atomicWriteFile(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
59484
+ });
59485
+ return this.writing;
59486
+ }
59487
+ remove() {
59488
+ this.writing = this.writing.catch(() => {
59489
+ }).then(() => rm6(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), { force: true }));
59490
+ return this.writing;
59491
+ }
59492
+ };
59493
+
59394
59494
  // src/analytics/agent/activity/agent-chat-activity-tracker-service.ts
59395
59495
  import { randomUUID as randomUUID8 } from "crypto";
59396
59496
 
@@ -59405,14 +59505,14 @@ async function uploadAnalytics(endpoint, body) {
59405
59505
  // src/analytics/analytics-record-buffer.ts
59406
59506
  import {
59407
59507
  appendFile as appendFile4,
59408
- mkdir as mkdir16,
59409
- readFile as readFile12,
59508
+ mkdir as mkdir17,
59509
+ readFile as readFile13,
59410
59510
  readdir as readdir5,
59411
59511
  rename as rename2,
59412
59512
  unlink
59413
59513
  } from "fs/promises";
59414
59514
  import { existsSync as existsSync14, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "fs";
59415
- import { join as join23 } from "path";
59515
+ import { join as join24 } from "path";
59416
59516
  var MAX_FAILED_RECORDS = 500;
59417
59517
  var FLUSH_DEBOUNCE_MS = 15e3;
59418
59518
  var MAX_UPLOADED_SEGMENTS = 50;
@@ -59424,7 +59524,7 @@ var AnalyticsRecordBuffer = class {
59424
59524
  options.storageName,
59425
59525
  ...options.legacyStorageNames ?? []
59426
59526
  ];
59427
- this.liveFile = join23(ENGINE_DIR, `${options.storageName}.jsonl`);
59527
+ this.liveFile = join24(ENGINE_DIR, `${options.storageName}.jsonl`);
59428
59528
  this.segmentFilePatterns = this.storageNames.map(
59429
59529
  (storageName) => new RegExp(`^${storageName}\\.(\\d+)\\.jsonl$`)
59430
59530
  );
@@ -59447,7 +59547,7 @@ var AnalyticsRecordBuffer = class {
59447
59547
  if (this.recordIds.has(recordId)) return;
59448
59548
  this.recordIds.add(recordId);
59449
59549
  }
59450
- const pending = mkdir16(ENGINE_DIR, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
59550
+ const pending = mkdir17(ENGINE_DIR, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
59451
59551
  `, "utf-8")).catch((error) => {
59452
59552
  console.error(
59453
59553
  `[${this.options.storageName}] Append failed, will retry on flush:`,
@@ -59462,7 +59562,7 @@ var AnalyticsRecordBuffer = class {
59462
59562
  if (!existsSync14(ENGINE_DIR)) return [];
59463
59563
  return readdirSync2(ENGINE_DIR, { withFileTypes: true }).filter((entry) => entry.isFile() && this.storageNames.some(
59464
59564
  (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) => {
59565
+ )).map(({ name }) => name).sort().flatMap((name) => this.parseRecords(readFileSync5(join24(ENGINE_DIR, name), "utf-8"))).map((record3) => {
59466
59566
  const recordId = this.options.getRecordId?.(record3);
59467
59567
  if (recordId) this.recordIds.add(recordId);
59468
59568
  return record3;
@@ -59497,8 +59597,8 @@ var AnalyticsRecordBuffer = class {
59497
59597
  }
59498
59598
  for (const storageName of this.storageNames) {
59499
59599
  await rename2(
59500
- join23(ENGINE_DIR, `${storageName}.jsonl`),
59501
- join23(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
59600
+ join24(ENGINE_DIR, `${storageName}.jsonl`),
59601
+ join24(ENGINE_DIR, `${storageName}.${Date.now()}.jsonl`)
59502
59602
  ).catch(() => {
59503
59603
  });
59504
59604
  }
@@ -59508,7 +59608,7 @@ var AnalyticsRecordBuffer = class {
59508
59608
  for (const entry of entries) {
59509
59609
  if (!this.segmentFilePatterns.some((pattern) => pattern.test(entry))) continue;
59510
59610
  try {
59511
- await this.uploadSegment(join23(ENGINE_DIR, entry));
59611
+ await this.uploadSegment(join24(ENGINE_DIR, entry));
59512
59612
  flushed++;
59513
59613
  } catch (error) {
59514
59614
  failed++;
@@ -59537,14 +59637,14 @@ var AnalyticsRecordBuffer = class {
59537
59637
  (storageName) => entry.startsWith(`${storageName}.`)
59538
59638
  ) && entry.endsWith(UPLOADED_SUFFIX)).sort();
59539
59639
  for (const entry of uploaded.slice(0, -MAX_UPLOADED_SEGMENTS)) {
59540
- await unlink(join23(ENGINE_DIR, entry)).catch(() => {
59640
+ await unlink(join24(ENGINE_DIR, entry)).catch(() => {
59541
59641
  });
59542
59642
  }
59543
59643
  }
59544
59644
  return { flushed, failed };
59545
59645
  }
59546
59646
  async uploadSegment(filePath) {
59547
- const records = this.parseRecords(await readFile12(filePath, "utf-8"));
59647
+ const records = this.parseRecords(await readFile13(filePath, "utf-8"));
59548
59648
  if (records.length > 0) await this.options.upload(records);
59549
59649
  await rename2(filePath, `${filePath}${UPLOADED_SUFFIX}`).catch(() => {
59550
59650
  });
@@ -60349,9 +60449,9 @@ var KeepAliveService = class _KeepAliveService {
60349
60449
  var keepAliveService = new KeepAliveService();
60350
60450
 
60351
60451
  // src/services/canvas-service.ts
60352
- import { readdir as readdir6, readFile as readFile14, stat as stat3 } from "fs/promises";
60452
+ import { readdir as readdir6, readFile as readFile15, stat as stat3 } from "fs/promises";
60353
60453
  import { homedir as homedir8 } from "os";
60354
- import { join as join24 } from "path";
60454
+ import { join as join25 } from "path";
60355
60455
 
60356
60456
  // src/utils/contained-file.ts
60357
60457
  import { realpath, stat as stat2 } from "fs/promises";
@@ -60377,9 +60477,9 @@ function fileRevision(content) {
60377
60477
  }
60378
60478
 
60379
60479
  // src/utils/revisioned-text-file.ts
60380
- import { readFile as readFile13 } from "fs/promises";
60480
+ import { readFile as readFile14 } from "fs/promises";
60381
60481
  async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60382
- const current = await readFile13(filePath, "utf8");
60482
+ const current = await readFile14(filePath, "utf8");
60383
60483
  const revision = fileRevision(current);
60384
60484
  if (revision !== expectedRevision) {
60385
60485
  return {
@@ -60393,15 +60493,15 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60393
60493
 
60394
60494
  // src/services/canvas-service.ts
60395
60495
  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")
60496
+ join25(homedir8(), ".claude", "plans"),
60497
+ join25(process.env.XDG_DATA_HOME ?? join25(homedir8(), ".local", "share"), "opencode", "plans"),
60498
+ join25(homedir8(), ".replicas", "canvas")
60399
60499
  ];
60400
60500
  async function canvasDirectories() {
60401
60501
  const repositories = await gitService.listRepositories().catch(() => []);
60402
60502
  return [
60403
60503
  ...GLOBAL_CANVAS_DIRECTORIES,
60404
- ...repositories.map((repository) => join24(repository.path, ".opencode", "plans"))
60504
+ ...repositories.map((repository) => join25(repository.path, ".opencode", "plans"))
60405
60505
  ];
60406
60506
  }
60407
60507
  var CanvasService = class {
@@ -60426,7 +60526,7 @@ var CanvasService = class {
60426
60526
  for (const entry of entries) {
60427
60527
  if (entry.name.startsWith(".")) continue;
60428
60528
  const filename = current.relativePath ? `${current.relativePath}/${entry.name}` : entry.name;
60429
- const filePath = join24(current.directory, entry.name);
60529
+ const filePath = join25(current.directory, entry.name);
60430
60530
  if (entry.isDirectory()) {
60431
60531
  pending.push({ directory: filePath, relativePath: filename });
60432
60532
  continue;
@@ -60450,7 +60550,7 @@ var CanvasService = class {
60450
60550
  const safe = sanitizeCanvasFilename(filename);
60451
60551
  if (!safe) return null;
60452
60552
  for (const directory of await this.directories()) {
60453
- const path7 = join24(directory, safe);
60553
+ const path7 = join25(directory, safe);
60454
60554
  const stats = await stat3(path7).catch(() => null);
60455
60555
  if (stats?.isFile()) {
60456
60556
  return {
@@ -60469,7 +60569,7 @@ var CanvasService = class {
60469
60569
  if (!item) return null;
60470
60570
  const { path: path7, ...file } = item;
60471
60571
  if (file.sizeBytes > maxBytes) return { ...file, tooLarge: true };
60472
- const bytes = await readFile14(path7).catch(() => null);
60572
+ const bytes = await readFile15(path7).catch(() => null);
60473
60573
  return bytes ? { ...file, bytes } : null;
60474
60574
  }
60475
60575
  async getItem(filename) {
@@ -60626,14 +60726,14 @@ async function reconcileCanvasItems(filenames) {
60626
60726
  // src/services/upload-chat-transcripts.ts
60627
60727
  import { createReadStream as createReadStream3 } from "fs";
60628
60728
  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";
60729
+ import { readFile as readFile16, readdir as readdir7, stat as stat4 } from "fs/promises";
60730
+ import { basename as basename3, join as join27 } from "path";
60631
60731
 
60632
60732
  // src/services/chat/chat-senders.ts
60633
- import { join as join25 } from "path";
60634
- var CHAT_SENDERS_DIR = join25(ENGINE_DIR, "chat-senders");
60733
+ import { join as join26 } from "path";
60734
+ var CHAT_SENDERS_DIR = join26(ENGINE_DIR, "chat-senders");
60635
60735
  function chatMessageSendersFilePath(chatId) {
60636
- return join25(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
60736
+ return join26(CHAT_SENDERS_DIR, `${chatId}.jsonl`);
60637
60737
  }
60638
60738
  function parseChatMessageSendersJsonl(content) {
60639
60739
  return content.split("\n").flatMap((line) => {
@@ -60720,7 +60820,7 @@ async function flushAllChatTranscripts(chatsById = /* @__PURE__ */ new Map(), ca
60720
60820
  const chat = chatsById.get(chatId);
60721
60821
  if (!shouldFlushChatTranscript(dir, chat, chatsById, Boolean(capture))) continue;
60722
60822
  tasks.push(
60723
- uploadChatTranscript(chatId, join26(dir, entry), chat, capture).then(async (artifact) => {
60823
+ uploadChatTranscript(chatId, join27(dir, entry), chat, capture).then(async (artifact) => {
60724
60824
  flushed++;
60725
60825
  if (artifact && capture) revisions.push(artifact);
60726
60826
  await onUploaded?.(chatId, artifact).catch((err) => {
@@ -60770,7 +60870,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60770
60870
  } : {};
60771
60871
  try {
60772
60872
  metadata.senders = parseChatMessageSendersJsonl(
60773
- await readFile15(chatMessageSendersFilePath(chatId), "utf-8")
60873
+ await readFile16(chatMessageSendersFilePath(chatId), "utf-8")
60774
60874
  );
60775
60875
  } catch (error) {
60776
60876
  if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) throw error;
@@ -60858,7 +60958,7 @@ async function flushRepoState() {
60858
60958
  // src/services/upload-engine-logs.ts
60859
60959
  import { createReadStream as createReadStream4 } from "fs";
60860
60960
  import { readdir as readdir8, stat as stat5 } from "fs/promises";
60861
- import { join as join27 } from "path";
60961
+ import { join as join28 } from "path";
60862
60962
  var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
60863
60963
  var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
60864
60964
  var ENGINE_LOG_FLUSH_TIMEOUT_MS = 2e4;
@@ -60887,7 +60987,7 @@ async function flushAllEngineLogs() {
60887
60987
  const candidates = (await Promise.all(filenames.slice(0, MAX_ENGINE_LOG_FLUSH_SESSIONS).map(async (filename) => {
60888
60988
  try {
60889
60989
  const sessionId = filename.slice(0, -".log".length);
60890
- const filePath = join27(LOG_DIR, filename);
60990
+ const filePath = join28(LOG_DIR, filename);
60891
60991
  const fileStat = await runBeforeDeadline(() => stat5(filePath), deadline);
60892
60992
  if (!fileStat.isFile()) {
60893
60993
  skipped++;
@@ -60984,9 +61084,9 @@ async function uploadEngineLog(input, timeoutMs) {
60984
61084
 
60985
61085
  // src/services/chat/fork-handoff.ts
60986
61086
  import { createHash as createHash9 } from "crypto";
60987
- import { mkdir as mkdir17, open as open3, readFile as readFile16, writeFile as writeFile8 } from "fs/promises";
61087
+ import { mkdir as mkdir18, open as open3, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
60988
61088
  import { homedir as homedir9 } from "os";
60989
- import { join as join28 } from "path";
61089
+ import { join as join29 } from "path";
60990
61090
  var EXCERPT_MAX_CHARS = 24e3;
60991
61091
  var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
60992
61092
  var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
@@ -61054,7 +61154,7 @@ ${text}` : null;
61054
61154
  }
61055
61155
  async function buildForkHandoff(input) {
61056
61156
  const sources = await Promise.all(input.segments.map(async (segment, index) => {
61057
- const rawHistoryPath = join28(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61157
+ const rawHistoryPath = join29(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61058
61158
  const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
61059
61159
  const last = index === input.segments.length - 1;
61060
61160
  const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
@@ -61068,9 +61168,9 @@ async function buildForkHandoff(input) {
61068
61168
  const start = blocks.findLastIndex((block) => block.startsWith("## User") && ++turns === input.turnLimit);
61069
61169
  blocks = blocks.slice(Math.max(0, start));
61070
61170
  }
61071
- const forkDir = join28(FORKS_DIR, input.targetChatId);
61072
- await mkdir17(forkDir, { recursive: true });
61073
- const transcriptPath = join28(forkDir, input.transcriptName ?? "source-transcript.md");
61171
+ const forkDir = join29(FORKS_DIR, input.targetChatId);
61172
+ await mkdir18(forkDir, { recursive: true });
61173
+ const transcriptPath = join29(forkDir, input.transcriptName ?? "source-transcript.md");
61074
61174
  const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
61075
61175
  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
61176
 
@@ -61089,7 +61189,7 @@ async function buildForkHandoff(input) {
61089
61189
  };
61090
61190
  }
61091
61191
  async function readPullRequestDecisions(notesPath) {
61092
- const notes = await readFile16(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
61192
+ const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
61093
61193
  const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
61094
61194
  if (!decisions) return null;
61095
61195
  const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
@@ -61158,15 +61258,13 @@ var FINAL_MESSAGE_MAX = 6e3;
61158
61258
  var PROGRESS_INTERVAL_MS = 2e4;
61159
61259
  var PROGRESS_STEP_MAX = 120;
61160
61260
  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()
61261
+ var toolInputRequestSchema = z4.object({
61262
+ requestId: z4.string().optional(),
61263
+ toolName: z4.string().optional(),
61264
+ questions: z4.array(z4.custom(isToolInputQuestion)).optional(),
61265
+ plan: z4.string().optional()
61166
61266
  });
61167
- var toolInputResolvedSchema = z3.object({ requestId: z3.string() });
61168
- var MAX_ACCEPTED_SEND_RESPONSES = 50;
61169
- var MAX_REMOVED_MESSAGE_IDS = 6e3;
61267
+ var toolInputResolvedSchema = z4.object({ requestId: z4.string() });
61170
61268
  var SUBAGENT_POLL_INTERVAL_MS = 2e3;
61171
61269
  var CHAT_IDLE_RELEASE_MS = 15 * 6e4;
61172
61270
  var CHILD_CHAT_IDLE_RELEASE_MS = 2 * 6e4;
@@ -61224,12 +61322,15 @@ function normalizePersistedChat(chat) {
61224
61322
  transcriptAuth: normalizeTranscriptAuth(chat.transcriptAuth),
61225
61323
  ...typeof chat.lastSenderKey === "string" ? { lastSenderKey: chat.lastSenderKey } : {},
61226
61324
  ...typeof chat.turnStartedAt === "string" ? { turnStartedAt: chat.turnStartedAt } : {},
61325
+ ...chat.turnErrorNotificationTargets ? { turnErrorNotificationTargets: z4.array(integrationErrorNotificationTargetSchema).safeParse(chat.turnErrorNotificationTargets).data } : {},
61227
61326
  ...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
- })) : {}
61327
+ ...Array.isArray(chat.removedMessageIds) ? { removedMessageIds: chat.removedMessageIds.filter((id) => typeof id === "string") } : {},
61328
+ ...isRecord2(chat.acceptedSendResponses) ? {
61329
+ acceptedSendResponses: Object.fromEntries(Object.entries(chat.acceptedSendResponses).flatMap(([key, value]) => {
61330
+ const response = sendChatMessageResponseSchema.safeParse(value);
61331
+ return response.success ? [[key, response.data]] : [];
61332
+ }))
61333
+ } : {}
61233
61334
  };
61234
61335
  }
61235
61336
  function parsePersistedChatsContent(content) {
@@ -61258,33 +61359,134 @@ var ChatService = class {
61258
61359
  awaitedSubagents = /* @__PURE__ */ new Map();
61259
61360
  heldSubagentReports = /* @__PURE__ */ new Map();
61260
61361
  forkSourceSeenBlocks = /* @__PURE__ */ new Map();
61362
+ restartedChats = /* @__PURE__ */ new Map();
61261
61363
  persistPromise = null;
61262
61364
  persistQueued = false;
61263
61365
  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 });
61366
+ await mkdir19(ENGINE_DIR, { recursive: true });
61367
+ await mkdir19(CLAUDE_HISTORY_DIR, { recursive: true });
61368
+ await mkdir19(CODEX_HISTORY_DIR, { recursive: true });
61369
+ await mkdir19(CURSOR_HISTORY_DIR, { recursive: true });
61370
+ await mkdir19(OPENCODE_HISTORY_DIR, { recursive: true });
61371
+ await mkdir19(CHAT_SENDERS_DIR, { recursive: true });
61270
61372
  const persisted = await this.loadChats();
61271
- const lostTurn = persisted.some((chat) => chat.turnStartedAt);
61373
+ let fromOlderEngine = false;
61272
61374
  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;
61375
+ const stored = await ChatCommands.load(chat.id);
61376
+ const commands = stored ?? new ChatCommands(chat.id);
61377
+ const { state } = commands;
61378
+ let changed = !stored;
61379
+ if (chat.acceptedSendResponses || chat.removedMessageIds || chat.turnStartedAt) {
61380
+ fromOlderEngine = true;
61381
+ for (const [key, response] of Object.entries(chat.acceptedSendResponses ?? {})) state.accepted.set(key, { ...response, at: chat.updatedAt });
61382
+ state.queue = [];
61383
+ state.removed.push(...chat.removedMessageIds ?? []);
61384
+ delete state.lost;
61385
+ delete state.running;
61386
+ if (chat.turnStartedAt) state.running = { errorNotificationTargets: chat.turnErrorNotificationTargets ?? [] };
61387
+ changed = true;
61388
+ }
61389
+ delete chat.acceptedSendResponses;
61390
+ delete chat.removedMessageIds;
61391
+ delete chat.turnStartedAt;
61392
+ delete chat.turnErrorNotificationTargets;
61393
+ if (chat.deletedAt && (state.running || state.lost || state.queue.length > 0)) {
61394
+ delete state.running;
61395
+ delete state.lost;
61396
+ state.queue = [];
61397
+ changed = true;
61398
+ }
61399
+ const runtime = this.createRuntimeChat(chat, commands);
61400
+ const history = new CodexHistoryFile(this.historyPath(chat));
61401
+ try {
61402
+ const accepted = /* @__PURE__ */ new Set();
61403
+ const removed = /* @__PURE__ */ new Set();
61404
+ let lostRecorded = false;
61405
+ if (state.running?.id || state.queue.length > 0 || state.removing.length > 0) {
61406
+ for await (const event of history.eventsFrom(state.checkFrom ?? 0, [CHAT_TURN_LOST_EVENT_TYPE, ACCEPTED_USER_MESSAGE_SOURCE, QUEUED_MESSAGE_REMOVED_EVENT_TYPE])) {
61407
+ if (event.type === CHAT_TURN_LOST_EVENT_TYPE && state.running?.id && event.payload.messageId === state.running.id) lostRecorded = true;
61408
+ const messageId = event.payload.source === ACCEPTED_USER_MESSAGE_SOURCE ? getUserMessageId(event) : null;
61409
+ if (messageId) accepted.add(messageId);
61410
+ for (const removedId of getRemovedMessageIds(event)) removed.add(removedId);
61411
+ }
61412
+ }
61413
+ if (state.running) {
61414
+ if (!lostRecorded) {
61415
+ await runtime.provider.persistHistoryEvent({
61416
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61417
+ type: CHAT_TURN_LOST_EVENT_TYPE,
61418
+ payload: state.running.id ? { messageId: state.running.id } : {}
61419
+ });
61420
+ }
61421
+ const owed = state.lost && !state.lost.reported ? state.lost.errorNotificationTargets : [];
61422
+ state.lost = {
61423
+ errorNotificationTargets: [
61424
+ ...owed,
61425
+ ...state.running.errorNotificationTargets.filter((target) => !owed.some((other) => JSON.stringify(other) === JSON.stringify(target)))
61426
+ ]
61427
+ };
61428
+ delete state.running;
61429
+ changed = true;
61430
+ }
61431
+ if (state.lost && !state.lost.reported) {
61432
+ runtime.activeErrorNotificationTargets = state.lost.errorNotificationTargets;
61433
+ this.restartedChats.set(chat.id, true);
61434
+ }
61435
+ for (const message of state.queue) {
61436
+ if (accepted.has(message.id)) continue;
61437
+ const { event, sender } = createTurnMetadata(message, message.id, message.queuedAt);
61438
+ await runtime.provider.persistHistoryEvent(event);
61439
+ if (sender) await this.appendSender(chat.id, sender);
61440
+ }
61441
+ const unrecorded = state.removing.filter((messageId) => !removed.has(messageId));
61442
+ if (unrecorded.length > 0) {
61443
+ await runtime.provider.persistHistoryEvent({
61444
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61445
+ type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
61446
+ payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: unrecorded }
61447
+ });
61448
+ }
61449
+ if (state.removing.length > 0) {
61450
+ state.removing = [];
61451
+ changed = true;
61452
+ }
61453
+ } catch (error) {
61454
+ console.error("[ChatService] Failed to recover a chat after an engine restart:", { chatId: chat.id, error });
61280
61455
  }
61456
+ if (state.queue.length > 0 && !this.restartedChats.has(chat.id)) this.restartedChats.set(chat.id, false);
61457
+ if (changed) await commands.save();
61281
61458
  if (chat.uploadedHistory) {
61282
61459
  const size = await stat6(this.historyPath(chat)).then(({ size: size2 }) => size2, () => null);
61283
61460
  if (size === chat.uploadedHistory.size) runtime.historyVersion = chat.uploadedHistory.version;
61284
61461
  }
61285
61462
  this.chats.set(chat.id, runtime);
61286
61463
  }
61287
- if (lostTurn) await this.persistAllChats();
61464
+ if (fromOlderEngine) await this.persistAllChats();
61465
+ }
61466
+ /** The monolith is only reachable once the engine is active, so what a restart interrupted is picked up here rather than at load. */
61467
+ resumeAfterRestart() {
61468
+ for (const [chatId, turnLost] of this.restartedChats) {
61469
+ this.restartedChats.delete(chatId);
61470
+ const chat = this.getRuntimeChat(chatId);
61471
+ if (!chat) continue;
61472
+ const { queue } = chat.commands.state;
61473
+ for (const message of queue) {
61474
+ chat.pendingMessageIds.push(message.id);
61475
+ if (message.errorNotificationTargets?.length) chat.errorNotificationTargets.set(message.id, message.errorNotificationTargets);
61476
+ this.agentChatActivityTrackerService.noteMessageAccepted(message.id, message);
61477
+ chat.lastSendRequest = message;
61478
+ }
61479
+ if (queue.length > 0) chat.provider.restoreQueue(queue);
61480
+ if (turnLost) {
61481
+ this.handleTurnFinished(chatId, true).catch((error) => console.error("[ChatService] Failed to report a turn lost to an engine restart:", { chatId, error }));
61482
+ }
61483
+ }
61484
+ }
61485
+ settleLostTurn(chat, done) {
61486
+ const { state } = chat.commands;
61487
+ if (!state.lost) return;
61488
+ state.lost[done] = true;
61489
+ if (state.lost.reported && state.lost.told) delete state.lost;
61288
61490
  }
61289
61491
  listChats(includeChildren = false) {
61290
61492
  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 +61510,7 @@ var ChatService = class {
61308
61510
  const [discovered, learnedSkills] = await Promise.all([
61309
61511
  chat.provider.listSlashCommands?.() ?? [],
61310
61512
  // 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())
61513
+ 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
61514
  ]);
61313
61515
  const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
61314
61516
  ...command,
@@ -61534,9 +61736,10 @@ var ChatService = class {
61534
61736
  if (idempotencyKey) {
61535
61737
  const accepting2 = chat.acceptingSendResponses.get(idempotencyKey);
61536
61738
  if (accepting2) return accepting2;
61537
- const accepted = chat.acceptedSendResponses.get(idempotencyKey);
61739
+ const accepted = chat.commands.state.accepted.get(idempotencyKey);
61538
61740
  if (accepted) {
61539
- return accepted;
61741
+ const { at: _at, ...response } = accepted;
61742
+ return response;
61540
61743
  }
61541
61744
  }
61542
61745
  if (chat.switching) await chat.switching.catch(() => {
@@ -61642,15 +61845,24 @@ ${decisions}` };
61642
61845
  result.messageId,
61643
61846
  submittedAt
61644
61847
  );
61645
- try {
61646
- await chat.provider.persistHistoryEvent(acceptedEvent);
61647
- } catch (error) {
61648
- throw new ChatMessagePersistenceError(error);
61649
- }
61650
- const previousAcceptedSendResponses = new Map(chat.acceptedSendResponses);
61848
+ const { state } = chat.commands;
61849
+ const existingTargets = chat.errorNotificationTargets.get(result.messageId) ?? [];
61850
+ const notificationTargets = [
61851
+ ...existingTargets,
61852
+ ...[
61853
+ ...request.errorNotificationTargets ?? [],
61854
+ ...request.errorNotificationTarget ? [request.errorNotificationTarget] : []
61855
+ ].filter((target) => !existingTargets.some((existing) => JSON.stringify(existing) === JSON.stringify(target)))
61856
+ ];
61857
+ const previousQueued = state.queue.find(({ id }) => id === result.messageId);
61858
+ const queued = {
61859
+ ...acceptedMessage,
61860
+ id: result.messageId,
61861
+ queuedAt: previousQueued?.queuedAt ?? submittedAt,
61862
+ ...notificationTargets.length > 0 ? { errorNotificationTargets: notificationTargets } : {}
61863
+ };
61651
61864
  const previousPendingMessageIds = [...chat.pendingMessageIds];
61652
61865
  const previousAcceptedEvent = chat.acceptedUserEvents.get(result.messageId);
61653
- const previousPersistedResponses = chat.persisted.acceptedSendResponses;
61654
61866
  const previousLastMessageText = chat.persisted.lastMessageText;
61655
61867
  const previousModel = chat.persisted.model;
61656
61868
  const previousThinkingLevel = chat.persisted.thinkingLevel;
@@ -61658,15 +61870,12 @@ ${decisions}` };
61658
61870
  const previousFork = chat.persisted.fork;
61659
61871
  const previousPendingForkHandoff = chat.persisted.pendingForkHandoff;
61660
61872
  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)) {
61873
+ const previousAccepted = idempotencyKey ? state.accepted.get(idempotencyKey) : void 0;
61874
+ if (idempotencyKey) state.accepted.set(idempotencyKey, { ...result, at: (/* @__PURE__ */ new Date()).toISOString() });
61875
+ if (!state.removed.includes(result.messageId)) {
61876
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
61877
+ if (previousQueued) state.queue[state.queue.indexOf(previousQueued)] = queued;
61878
+ else state.queue.push(queued);
61670
61879
  if (!chat.pendingMessageIds.includes(result.messageId)) {
61671
61880
  chat.pendingMessageIds.push(result.messageId);
61672
61881
  }
@@ -61681,37 +61890,31 @@ ${decisions}` };
61681
61890
  chat.persisted.fork = { ...chat.persisted.fork, state: "ready", completedAt: chat.persisted.updatedAt };
61682
61891
  }
61683
61892
  try {
61893
+ await chat.commands.save();
61684
61894
  await this.persistAllChats();
61895
+ await chat.provider.persistHistoryEvent(acceptedEvent);
61685
61896
  } catch (error) {
61686
- chat.acceptedSendResponses.clear();
61687
- for (const [key, response] of previousAcceptedSendResponses) {
61688
- chat.acceptedSendResponses.set(key, response);
61689
- }
61897
+ const index = state.queue.indexOf(queued);
61898
+ if (index !== -1) state.queue.splice(index, 1, ...previousQueued ? [previousQueued] : []);
61899
+ if (idempotencyKey && previousAccepted) state.accepted.set(idempotencyKey, previousAccepted);
61900
+ else if (idempotencyKey) state.accepted.delete(idempotencyKey);
61690
61901
  chat.pendingMessageIds = previousPendingMessageIds;
61691
61902
  if (previousAcceptedEvent) chat.acceptedUserEvents.set(result.messageId, previousAcceptedEvent);
61692
61903
  else chat.acceptedUserEvents.delete(result.messageId);
61693
- chat.persisted.acceptedSendResponses = previousPersistedResponses;
61694
61904
  chat.persisted.lastMessageText = previousLastMessageText;
61695
61905
  chat.persisted.model = previousModel;
61696
61906
  chat.persisted.thinkingLevel = previousThinkingLevel;
61697
61907
  chat.persisted.updatedAt = previousUpdatedAt;
61698
61908
  chat.persisted.fork = previousFork;
61699
61909
  chat.persisted.pendingForkHandoff = previousPendingForkHandoff;
61910
+ await chat.commands.save().catch((saveError) => {
61911
+ console.error("[ChatService] Failed to take a rejected message back out of the command file:", { chatId, error: saveError });
61912
+ });
61700
61913
  throw new ChatMessagePersistenceError(error);
61701
61914
  }
61702
61915
  chat.lastSendRequest = request;
61703
61916
  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
- }
61917
+ if (notificationTargets.length > 0) chat.errorNotificationTargets.set(result.messageId, notificationTargets);
61715
61918
  if (recordedSender) {
61716
61919
  await this.appendSender(chatId, recordedSender);
61717
61920
  }
@@ -61742,7 +61945,7 @@ ${decisions}` };
61742
61945
  }
61743
61946
  }
61744
61947
  async readSenders(chatId) {
61745
- return readFile17(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
61948
+ return readFile18(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
61746
61949
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
61747
61950
  console.error("[ChatService] Failed to read sender records:", error);
61748
61951
  return [];
@@ -61750,13 +61953,7 @@ ${decisions}` };
61750
61953
  }
61751
61954
  async interrupt(chatId, stoppedAt) {
61752
61955
  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;
61956
+ const result = await this.stopTurn(chat, stoppedAt);
61760
61957
  this.touch(chat);
61761
61958
  await this.publish({
61762
61959
  type: "chat.interrupted",
@@ -61768,6 +61965,24 @@ ${decisions}` };
61768
61965
  });
61769
61966
  return result;
61770
61967
  }
61968
+ async stopTurn(chat, stoppedAt) {
61969
+ const stopped = new Set(chat.provider.isProcessing() ? chat.commands.state.queue.map(({ id }) => id) : []);
61970
+ const result = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds), stoppedAt);
61971
+ const kept = new Set(chat.provider.getQueue().map(({ id }) => id));
61972
+ const { state } = chat.commands;
61973
+ const queue = state.queue.filter(({ id }) => kept.has(id) || !stopped.has(id));
61974
+ if (queue.length !== state.queue.length) {
61975
+ state.queue = queue;
61976
+ await chat.commands.save();
61977
+ }
61978
+ this.endTrackedTurn(chat);
61979
+ chat.hasActiveTurn = false;
61980
+ chat.activeMessageId = null;
61981
+ chat.pendingMessageIds = [];
61982
+ chat.acceptedUserEvents.clear();
61983
+ chat.turnAnswer = null;
61984
+ return result;
61985
+ }
61771
61986
  async clearGoal(chatId) {
61772
61987
  const chat = this.requireChat(chatId);
61773
61988
  if (!chat.provider.clearGoal) {
@@ -61776,13 +61991,7 @@ ${decisions}` };
61776
61991
  this.cancelIdleRelease(chat);
61777
61992
  await chat.release;
61778
61993
  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;
61994
+ const interruptResult = await this.stopTurn(chat);
61786
61995
  const goal = await chat.provider.clearGoal(chat.persisted.model).finally(() => {
61787
61996
  chat.live = !!chat.provider.dispose;
61788
61997
  this.scheduleIdleRelease(chat);
@@ -61870,17 +62079,34 @@ ${decisions}` };
61870
62079
  type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
61871
62080
  payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: [...removed] }
61872
62081
  };
61873
- await chat.provider.persistHistoryEvent(event);
61874
- chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
62082
+ const { state } = chat.commands;
62083
+ const queued = state.queue.filter(({ id }) => removed.has(id));
62084
+ const newlyRemoved = messageIds.filter((id) => !state.removed.includes(id));
62085
+ const previousCheckFrom = state.checkFrom;
62086
+ state.queue = state.queue.filter(({ id }) => !removed.has(id));
62087
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
62088
+ state.removed.push(...newlyRemoved);
62089
+ state.removing.push(...messageIds);
62090
+ try {
62091
+ await chat.commands.save();
62092
+ await chat.provider.persistHistoryEvent(event);
62093
+ } catch (error) {
62094
+ state.queue.push(...queued);
62095
+ state.checkFrom = previousCheckFrom;
62096
+ state.removed = state.removed.filter((id) => !newlyRemoved.includes(id));
62097
+ state.removing = state.removing.filter((id) => !removed.has(id));
62098
+ await chat.commands.save().catch((saveError) => {
62099
+ console.error("[ChatService] Failed to put messages back in the command file:", { chatId: chat.persisted.id, error: saveError });
62100
+ });
62101
+ throw error;
62102
+ }
62103
+ state.removing = state.removing.filter((id) => !removed.has(id));
61875
62104
  chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
61876
62105
  this.forkSourceSeenBlocks.delete(chat.persisted.id);
61877
62106
  for (const messageId of removed) {
61878
62107
  chat.acceptedUserEvents.delete(messageId);
61879
62108
  chat.errorNotificationTargets.delete(messageId);
61880
62109
  }
61881
- await this.persistAllChats().catch((error) => {
61882
- console.error("[ChatService] Failed to persist queued-message removals:", error);
61883
- });
61884
62110
  await this.publish({
61885
62111
  type: "chat.turn.delta",
61886
62112
  payload: { chatId: chat.persisted.id, event }
@@ -61916,10 +62142,15 @@ ${decisions}` };
61916
62142
  removedMessageIds: success ? queuedIds : []
61917
62143
  };
61918
62144
  }
61919
- updateQueuedMessage(chatId, messageId, message) {
62145
+ async updateQueuedMessage(chatId, messageId, message) {
61920
62146
  const chat = this.requireChat(chatId);
61921
62147
  const success = chat.provider.updateQueuedMessage(messageId, message);
61922
62148
  if (success) {
62149
+ const queued = chat.commands.state.queue.find(({ id }) => id === messageId);
62150
+ if (queued) {
62151
+ queued.message = message;
62152
+ await chat.commands.save();
62153
+ }
61923
62154
  const acceptedEvent = chat.acceptedUserEvents.get(messageId);
61924
62155
  if (acceptedEvent) {
61925
62156
  chat.acceptedUserEvents.set(messageId, {
@@ -61937,14 +62168,23 @@ ${decisions}` };
61937
62168
  queue: chat.provider.getQueue()
61938
62169
  };
61939
62170
  }
61940
- reorderQueue(chatId, messageId, position) {
62171
+ async reorderQueue(chatId, messageId, position) {
61941
62172
  const chat = this.requireChat(chatId);
61942
62173
  const success = chat.provider.reorderQueue(messageId, position);
62174
+ if (success) await this.saveQueueOrder(chat);
61943
62175
  return {
61944
62176
  success,
61945
62177
  queue: chat.provider.getQueue()
61946
62178
  };
61947
62179
  }
62180
+ async saveQueueOrder(chat) {
62181
+ const order = new Map(chat.provider.getQueue().map(({ id }, index) => [id, index]));
62182
+ const { state } = chat.commands;
62183
+ const queue = [...state.queue].sort((a, b) => (order.get(a.id) ?? -1) - (order.get(b.id) ?? -1));
62184
+ if (queue.every((message, index) => message === state.queue[index])) return;
62185
+ state.queue = queue;
62186
+ await chat.commands.save();
62187
+ }
61948
62188
  async steerFromQueue(chatId, messageId) {
61949
62189
  const chat = this.requireChat(chatId);
61950
62190
  const result = await chat.provider.steerFromQueue(messageId);
@@ -61980,6 +62220,7 @@ ${decisions}` };
61980
62220
  if (target.provider.isProcessing()) {
61981
62221
  await target.provider.interrupt((messageIds) => this.forgetPendingMessages(target, messageIds)).catch(() => {
61982
62222
  });
62223
+ this.endTrackedTurn(target);
61983
62224
  target.hasActiveTurn = false;
61984
62225
  target.activeMessageId = null;
61985
62226
  target.pendingMessageIds = [];
@@ -61988,11 +62229,18 @@ ${decisions}` };
61988
62229
  const started = hasChatStarted(this.toSummary(target));
61989
62230
  if (started) {
61990
62231
  target.persisted.deletedAt = deletedAt;
62232
+ target.commands.state.queue = [];
62233
+ delete target.commands.state.running;
62234
+ delete target.commands.state.lost;
62235
+ await target.commands.save();
61991
62236
  } else {
61992
62237
  this.chats.delete(id);
61993
62238
  }
61994
62239
  await this.releaseAgentProcess(target);
61995
- if (!started) await this.deleteHistoryFile(target.persisted);
62240
+ if (!started) {
62241
+ await this.deleteHistoryFile(target.persisted);
62242
+ await target.commands.remove();
62243
+ }
61996
62244
  await this.publish({ type: "chat.deleted", payload: { chatId: id, chat: this.toSummary(target) } });
61997
62245
  }
61998
62246
  await this.persistAllChats();
@@ -62046,9 +62294,9 @@ ${decisions}` };
62046
62294
  historyPath,
62047
62295
  `${historyPath}.pages.jsonl`,
62048
62296
  `${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 });
62297
+ ].map((path7) => rm7(path7, { force: true })));
62298
+ await rm7(chatMessageSendersFilePath(persisted.id), { force: true });
62299
+ await rm7(join30(FORKS_DIR, persisted.id), { recursive: true, force: true });
62052
62300
  }
62053
62301
  switchHarness(source, request) {
62054
62302
  const switching = (async () => {
@@ -62077,7 +62325,7 @@ ${decisions}` };
62077
62325
  source.switching = null;
62078
62326
  for (const queued of carried) {
62079
62327
  const key = queued.idempotencyKey ?? queued.messageId;
62080
- if (key) source.acceptedSendResponses.delete(key);
62328
+ if (key) source.commands.state.accepted.delete(key);
62081
62329
  await this.sendMessage(source.persisted.id, queued).catch((restoreError) => {
62082
62330
  console.error("[ChatService] Failed to requeue a message after a failed harness switch:", { chatId: source.persisted.id, error: restoreError });
62083
62331
  });
@@ -62310,7 +62558,7 @@ ${note}`;
62310
62558
  const historyEvents = excludeQueuedAcceptedEvents(
62311
62559
  mergeWorkspaceChatHistoryEvents([], history.events),
62312
62560
  chat.provider.getQueue(),
62313
- chat.persisted.removedMessageIds
62561
+ chat.commands.state.removed
62314
62562
  );
62315
62563
  for (const [messageId, acceptedEvent] of chat.acceptedUserEvents) {
62316
62564
  if (historyEvents.some((event) => isSameAcceptedUserEvent(event, acceptedEvent))) {
@@ -62324,14 +62572,14 @@ ${note}`;
62324
62572
  const events = excludeQueuedAcceptedEvents(
62325
62573
  [...historyEvents, ...acceptedEvents].sort((a, b) => getEventTimestampMs(a) - getEventTimestampMs(b)),
62326
62574
  [],
62327
- chat.persisted.removedMessageIds
62575
+ chat.commands.state.removed
62328
62576
  );
62329
62577
  if (history.appendsAfter !== void 0 || page2.limit !== void 0 && "beforeCursor" in history) {
62330
62578
  const response = {
62331
62579
  ...history,
62332
62580
  historyVersion,
62333
62581
  events,
62334
- removedMessageIds: chat.persisted.removedMessageIds,
62582
+ removedMessageIds: chat.commands.state.removed,
62335
62583
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62336
62584
  senders: getChatHistoryPageSenders(senders, page2)
62337
62585
  };
@@ -62350,7 +62598,7 @@ ${note}`;
62350
62598
  ...history,
62351
62599
  historyVersion,
62352
62600
  events,
62353
- removedMessageIds: chat.persisted.removedMessageIds,
62601
+ removedMessageIds: chat.commands.state.removed,
62354
62602
  totalEvents: (history.totalEvents ?? history.eventsStartIndex + history.events.length) - (history.events.length - historyEvents.length) + acceptedEvents.length,
62355
62603
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62356
62604
  senders
@@ -62360,7 +62608,7 @@ ${note}`;
62360
62608
  thread_id: history.thread_id,
62361
62609
  historyVersion,
62362
62610
  events,
62363
- removedMessageIds: chat.persisted.removedMessageIds,
62611
+ removedMessageIds: chat.commands.state.removed,
62364
62612
  goal: history.goal ?? chat.provider.getGoal?.() ?? null,
62365
62613
  senders
62366
62614
  }, page2);
@@ -62377,13 +62625,17 @@ ${note}`;
62377
62625
  toTranscriptSource(chat) {
62378
62626
  return {
62379
62627
  ...this.toSummary(chat),
62380
- removedMessageIds: chat.persisted.removedMessageIds,
62628
+ removedMessageIds: chat.commands.state.removed,
62381
62629
  transcriptAuth: chat.persisted.transcriptAuth,
62382
62630
  currentHistoryVersion: () => this.toSummary(chat).historyVersion
62383
62631
  };
62384
62632
  }
62385
62633
  historyPath(persisted) {
62386
- return join29(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62634
+ return join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62635
+ }
62636
+ /** 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. */
62637
+ historySizeOnDisk(persisted) {
62638
+ return statSync4(this.historyPath(persisted), { throwIfNoEntry: false })?.size ?? 0;
62387
62639
  }
62388
62640
  async recordUploadedHistory(chatId, artifact) {
62389
62641
  const chat = this.getRuntimeChat(chatId);
@@ -62439,7 +62691,7 @@ ${note}`;
62439
62691
  mcpActivity: chatActivity.mcpActivity
62440
62692
  };
62441
62693
  }
62442
- createRuntimeChat(persisted) {
62694
+ createRuntimeChat(persisted, commands = new ChatCommands(persisted.id)) {
62443
62695
  const saveSession = async (sessionId) => {
62444
62696
  persisted.providerSessionId = sessionId;
62445
62697
  delete persisted.pendingProviderFork;
@@ -62481,7 +62733,15 @@ ${note}`;
62481
62733
  if (processing) return;
62482
62734
  this.handleProcessingStopped(persisted.id);
62483
62735
  };
62484
- const onQueueChanged = () => queueMicrotask(() => this.publishQueueIfChanged(persisted.id));
62736
+ const onQueueChanged = () => queueMicrotask(() => {
62737
+ this.publishQueueIfChanged(persisted.id);
62738
+ const chat = this.getRuntimeChat(persisted.id);
62739
+ if (chat) {
62740
+ this.saveQueueOrder(chat).catch((error) => {
62741
+ console.error("[ChatService] Failed to save the queue order:", { chatId: persisted.id, error });
62742
+ });
62743
+ }
62744
+ });
62485
62745
  const fallbackContext = () => {
62486
62746
  const chat = this.chats.get(persisted.id);
62487
62747
  return {
@@ -62511,7 +62771,7 @@ ${note}`;
62511
62771
  chat = this.chats.get(next)?.persisted;
62512
62772
  }
62513
62773
  const baseProvider = persisted.provider;
62514
- const historyFilePath = join29(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62774
+ const historyFilePath = join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62515
62775
  const managerOptions = {
62516
62776
  provider: baseProvider,
62517
62777
  workingDirectory: this.workingDirectory,
@@ -62533,6 +62793,7 @@ ${note}`;
62533
62793
  onChatCredential,
62534
62794
  lastSenderKey: persisted.lastSenderKey,
62535
62795
  onLastSenderKeyChanged,
62796
+ previousTurnLost: Boolean(commands.state.running || commands.state.lost && !commands.state.lost.told),
62536
62797
  parentChatId: persisted.parentChatId
62537
62798
  };
62538
62799
  let provider;
@@ -62568,7 +62829,7 @@ ${note}`;
62568
62829
  pendingMessageIds: [],
62569
62830
  steeringOnArrival: /* @__PURE__ */ new Set(),
62570
62831
  acceptedUserEvents: /* @__PURE__ */ new Map(),
62571
- acceptedSendResponses: new Map(Object.entries(persisted.acceptedSendResponses ?? {})),
62832
+ commands,
62572
62833
  acceptingSendResponses: /* @__PURE__ */ new Map(),
62573
62834
  acceptingMessages: 0,
62574
62835
  activeMessageId: null,
@@ -62633,7 +62894,13 @@ ${note}`;
62633
62894
  activateTurn(chat, messageId) {
62634
62895
  chat.hasActiveTurn = true;
62635
62896
  chat.activeMessageId = messageId;
62636
- chat.persisted.turnStartedAt = (/* @__PURE__ */ new Date()).toISOString();
62897
+ chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
62898
+ chat.errorNotificationTargets.delete(messageId);
62899
+ const { state } = chat.commands;
62900
+ state.queue = state.queue.filter(({ id }) => id !== messageId);
62901
+ state.running = { id: messageId, errorNotificationTargets: chat.activeErrorNotificationTargets };
62902
+ this.settleLostTurn(chat, "told");
62903
+ const saved = chat.commands.save();
62637
62904
  this.touch(chat);
62638
62905
  chat.live = !!chat.provider.dispose;
62639
62906
  this.enforceLiveProcessCap();
@@ -62646,8 +62913,7 @@ ${note}`;
62646
62913
  chat.persisted.provider
62647
62914
  );
62648
62915
  this.agentTokenUsageTracker.startTurn(context);
62649
- chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
62650
- chat.errorNotificationTargets.delete(messageId);
62916
+ return saved;
62651
62917
  }
62652
62918
  async handleTurnStarted(chatId, message) {
62653
62919
  const chat = this.getRuntimeChat(chatId);
@@ -62659,11 +62925,14 @@ ${note}`;
62659
62925
  (/* @__PURE__ */ new Date()).toISOString()
62660
62926
  );
62661
62927
  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();
62928
+ const saved = this.activateTurn(chat, message.id);
62929
+ chat.persisted.transcriptAuth = currentTranscriptAuth(chat.persisted.provider);
62930
+ try {
62931
+ await saved;
62932
+ } catch (error) {
62933
+ chat.lastTurnErrors = ["This message was not run because the workspace could not save the chat."];
62934
+ await this.handleTurnFinished(chatId);
62935
+ throw error;
62667
62936
  }
62668
62937
  await this.publish({
62669
62938
  type: "chat.turn.started",
@@ -62686,7 +62955,9 @@ ${note}`;
62686
62955
  if (!messageId) {
62687
62956
  return;
62688
62957
  }
62689
- this.activateTurn(chat, messageId);
62958
+ this.activateTurn(chat, messageId).catch((error) => {
62959
+ console.error("[ChatService] Failed to save the running turn:", { chatId, error });
62960
+ });
62690
62961
  this.publish({
62691
62962
  type: "chat.turn.started",
62692
62963
  payload: {
@@ -62723,6 +62994,14 @@ ${note}`;
62723
62994
  if (event.type === AGENT_QUOTA_EXHAUSTED_EVENT_TYPE) {
62724
62995
  chat.quotaExhaustion = agentQuotaExhaustedPayloadSchema.safeParse(event.payload).data ?? null;
62725
62996
  }
62997
+ const { state } = chat.commands;
62998
+ const readMessageId = event.payload[USER_MESSAGE_ID_PAYLOAD_KEY];
62999
+ if (state.queue.some(({ id }) => id === readMessageId)) {
63000
+ state.queue = state.queue.filter(({ id }) => id !== readMessageId);
63001
+ chat.commands.save().catch((error) => {
63002
+ console.error("[ChatService] Failed to save a steered message as read:", { chatId, error });
63003
+ });
63004
+ }
62726
63005
  let eventToPublish = event;
62727
63006
  if (event.type === "event_msg" && event.payload.type === "user_message") {
62728
63007
  if (chat.activeMessageId && !event.payload[USER_MESSAGE_ID_PAYLOAD_KEY]) {
@@ -62840,19 +63119,25 @@ ${note}`;
62840
63119
  endTrackedTurn(chat) {
62841
63120
  this.agentTokenUsageTracker.endTurn(chat.persisted.id);
62842
63121
  this.agentChatActivityTrackerService.noteTurnEnded(chat.persisted.id);
62843
- delete chat.persisted.turnStartedAt;
63122
+ if (chat.commands.state.running) {
63123
+ delete chat.commands.state.running;
63124
+ chat.commands.save().catch((error) => {
63125
+ console.error("[ChatService] Failed to save the end of a turn:", { chatId: chat.persisted.id, error });
63126
+ });
63127
+ }
62844
63128
  this.progressCoalescer.cancel(chat.persisted.id);
62845
63129
  chat.progressStep = null;
62846
63130
  chat.progressSentStep = null;
62847
63131
  chat.plainStep = null;
62848
63132
  this.touch(chat);
62849
63133
  }
62850
- async handleTurnFinished(chatId) {
63134
+ async handleTurnFinished(chatId, lostToRestart = false) {
62851
63135
  const chat = this.getRuntimeChat(chatId);
62852
63136
  if (!chat) {
62853
63137
  return;
62854
63138
  }
62855
- const userTurn = chat.hasActiveTurn;
63139
+ if (lostToRestart) chat.lastTurnErrors = [`${CHAT_TURN_LOST_MESSAGE}${chat.provider.getQueue().length > 0 ? " Queued messages are running now." : ""}`];
63140
+ const userTurn = chat.hasActiveTurn || lostToRestart;
62856
63141
  if (!userTurn) {
62857
63142
  const queuedMessageIds = new Set(chat.provider.getQueue().map((message) => message.id));
62858
63143
  const completedMessageId = chat.pendingMessageIds.find((messageId) => !queuedMessageIds.has(messageId));
@@ -62880,7 +63165,7 @@ ${note}`;
62880
63165
  chat.turnAnswer = null;
62881
63166
  if (answer) chat.turnRequest = null;
62882
63167
  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(() => {
63168
+ 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
63169
  if (chat.turnCompletion === completion) chat.turnCompletion = null;
62885
63170
  this.notifyWorkspaceAgentIdle();
62886
63171
  this.scheduleIdleRelease(chat);
@@ -62926,7 +63211,7 @@ ${note}`;
62926
63211
  }
62927
63212
  async loadChats() {
62928
63213
  try {
62929
- const content = await readFile17(CHATS_FILE, "utf-8");
63214
+ const content = await readFile18(CHATS_FILE, "utf-8");
62930
63215
  return parsePersistedChatsContent(content);
62931
63216
  } catch (error) {
62932
63217
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
@@ -62941,7 +63226,7 @@ ${note}`;
62941
63226
  console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
62942
63227
  }
62943
63228
  try {
62944
- const backupContent = await readFile17(CHATS_BACKUP_FILE, "utf-8");
63229
+ const backupContent = await readFile18(CHATS_BACKUP_FILE, "utf-8");
62945
63230
  return parsePersistedChatsContent(backupContent);
62946
63231
  } catch (backupError) {
62947
63232
  if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
@@ -63015,7 +63300,7 @@ ${note}`;
63015
63300
  } catch {
63016
63301
  }
63017
63302
  }
63018
- async publishAgentTurnCompleteWebhook(chat, completedAt, processing, quotaExhaustion, responseComplete, previousCompletion) {
63303
+ async publishAgentTurnCompleteWebhook(chat, completedAt, processing, quotaExhaustion, responseComplete, previousCompletion, turnLost) {
63019
63304
  const linearSessionId = ENGINE_ENV.REPLICAS_LINEAR_SESSION_ID;
63020
63305
  const errors = chat.persisted.parentChatId === null ? chat.lastTurnErrors : null;
63021
63306
  chat.lastTurnErrors = null;
@@ -63044,11 +63329,16 @@ ${note}`;
63044
63329
  repoStatuses,
63045
63330
  ...unlinkedPullRequestUrls.length > 0 ? { unlinkedPullRequestUrls } : {},
63046
63331
  ...errors?.length ? { errors } : {},
63332
+ ...turnLost ? { turnLost } : {},
63047
63333
  ...(errors?.length || quotaExhaustion) && errorNotificationTargets.length > 0 ? { errorNotificationTargets } : {},
63048
63334
  ...quotaExhaustion ? { quotaExhaustion } : {},
63049
63335
  ...isPullRequestFeedbackChat(chat.persisted) ? { pullRequestFeedback: true } : {}
63050
63336
  };
63051
- await monolithService.sendEvent({ type: "agent_turn_complete", payload });
63337
+ const sent = await monolithService.sendEvent({ type: "agent_turn_complete", payload });
63338
+ if (turnLost && sent) {
63339
+ this.settleLostTurn(chat, "reported");
63340
+ await chat.commands.save();
63341
+ }
63052
63342
  } catch (error) {
63053
63343
  console.error("[ChatService] Failed to send agent_turn_complete event:", error);
63054
63344
  }
@@ -63067,15 +63357,15 @@ ${note}`;
63067
63357
 
63068
63358
  // src/services/repo-file-service.ts
63069
63359
  import { execFile as execFile7 } from "child_process";
63070
- import { readFile as readFile18 } from "fs/promises";
63360
+ import { readFile as readFile19 } from "fs/promises";
63071
63361
  import { homedir as homedir10 } from "os";
63072
- import { extname as extname3, join as join31 } from "path";
63362
+ import { extname as extname3, join as join32 } from "path";
63073
63363
 
63074
63364
  // src/services/language-server-service.ts
63075
63365
  import { spawn as spawn4 } from "child_process";
63076
63366
  import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
63077
63367
  import { createRequire as createRequire5 } from "module";
63078
- import { delimiter as delimiter2, dirname as dirname16, join as join30, relative as relative2 } from "path";
63368
+ import { delimiter as delimiter2, dirname as dirname16, join as join31, relative as relative2 } from "path";
63079
63369
  import { setTimeout as setTimeout3 } from "timers/promises";
63080
63370
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
63081
63371
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
@@ -63194,7 +63484,7 @@ var LanguageServerService = class {
63194
63484
  if (config.package && config.bin) command = process.execPath;
63195
63485
  else if (config.command) {
63196
63486
  const commandName = config.command;
63197
- command = process.env.PATH?.split(delimiter2).map((directory) => join30(directory, commandName)).find(existsSync15);
63487
+ command = process.env.PATH?.split(delimiter2).map((directory) => join31(directory, commandName)).find(existsSync15);
63198
63488
  }
63199
63489
  const args = config.package && config.bin ? [packageBin(config.package, config.bin), ...config.args] : config.args;
63200
63490
  if (!command) return null;
@@ -63375,7 +63665,7 @@ var RepoFileService = class {
63375
63665
  sizeBytes,
63376
63666
  binary: true,
63377
63667
  tooLarge: false,
63378
- base64: (await readFile18(fullPath)).toString("base64"),
63668
+ base64: (await readFile19(fullPath)).toString("base64"),
63379
63669
  mimeType
63380
63670
  };
63381
63671
  }
@@ -63400,7 +63690,7 @@ var RepoFileService = class {
63400
63690
  tooLarge: true
63401
63691
  };
63402
63692
  }
63403
- const content = await readFile18(fullPath, "utf-8");
63693
+ const content = await readFile19(fullPath, "utf-8");
63404
63694
  return {
63405
63695
  repoName,
63406
63696
  path: filePath,
@@ -63431,7 +63721,7 @@ var RepoFileService = class {
63431
63721
  async inspectSymbol(repoName, filePath, line, character, action) {
63432
63722
  const resolved = await this.resolveFile(repoName, filePath);
63433
63723
  if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
63434
- const content = await readFile18(resolved.fullPath, "utf8");
63724
+ const content = await readFile19(resolved.fullPath, "utf8");
63435
63725
  const sourceLine = content.split("\n")[line - 1];
63436
63726
  if (sourceLine === void 0) return null;
63437
63727
  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 +63771,7 @@ var RepoFileService = class {
63481
63771
  return await resolveContainedFile(repo.path, filePath);
63482
63772
  }
63483
63773
  async resolveSkillFile(filePath) {
63484
- const skillRoots = SANDBOX_SKILL_DIRS.map((dir) => join31(this.homeDir, dir));
63774
+ const skillRoots = SANDBOX_SKILL_DIRS.map((dir) => join32(this.homeDir, dir));
63485
63775
  if (!skillRoots.some((root) => filePath.startsWith(`${root}/`))) return null;
63486
63776
  const repos = await this.gitService.listRepositories();
63487
63777
  for (const root of [...skillRoots, ...repos.map((repo) => repo.path)]) {
@@ -63553,30 +63843,30 @@ var RepoFileService = class {
63553
63843
 
63554
63844
  // src/v1-routes.ts
63555
63845
  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";
63846
+ import { z as z6 } from "zod";
63847
+ import { readdir as readdir10, stat as stat7, readFile as readFile22 } from "fs/promises";
63558
63848
  import { openAsBlob } from "fs";
63559
- import { join as join34, resolve as resolve5 } from "path";
63849
+ import { join as join35, resolve as resolve5 } from "path";
63560
63850
 
63561
63851
  // src/services/warm-hooks-service.ts
63562
63852
  import { spawn as spawn5 } from "child_process";
63563
- import { readFile as readFile20 } from "fs/promises";
63853
+ import { readFile as readFile21 } from "fs/promises";
63564
63854
  import { existsSync as existsSync16 } from "fs";
63565
- import { join as join33 } from "path";
63855
+ import { join as join34 } from "path";
63566
63856
 
63567
63857
  // 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";
63858
+ import { mkdir as mkdir20, readFile as readFile20, writeFile as writeFile9, readdir as readdir9, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
63569
63859
  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");
63860
+ import { join as join33 } from "path";
63861
+ var LOGS_DIR2 = join33(homedir11(), ".replicas", "warm-hook-logs");
63862
+ var CURRENT_RUN_LOG = join33(LOGS_DIR2, "current-run.log");
63573
63863
  function withPreview2(stored) {
63574
63864
  const preview = buildHookOutputPreview(stored.output);
63575
63865
  return { ...stored, ...preview };
63576
63866
  }
63577
63867
  var WarmHookLogsService = class {
63578
63868
  async ensureDir() {
63579
- await mkdir19(LOGS_DIR2, { recursive: true });
63869
+ await mkdir20(LOGS_DIR2, { recursive: true });
63580
63870
  }
63581
63871
  async saveEnvironmentHookLog(entry) {
63582
63872
  await this.ensureDir();
@@ -63585,7 +63875,7 @@ var WarmHookLogsService = class {
63585
63875
  hookName: "environment",
63586
63876
  ...entry
63587
63877
  };
63588
- await writeFile9(join32(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
63878
+ await writeFile9(join33(LOGS_DIR2, ENVIRONMENT_HOOK_LOG_FILENAME), `${JSON.stringify(log, null, 2)}
63589
63879
  `, "utf-8");
63590
63880
  }
63591
63881
  async saveRepoHookLog(repoName, entry) {
@@ -63595,7 +63885,7 @@ var WarmHookLogsService = class {
63595
63885
  hookName: repoName,
63596
63886
  ...entry
63597
63887
  };
63598
- await writeFile9(join32(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
63888
+ await writeFile9(join33(LOGS_DIR2, repoHookLogFilename(repoName)), `${JSON.stringify(log, null, 2)}
63599
63889
  `, "utf-8");
63600
63890
  }
63601
63891
  async getAllLogs() {
@@ -63614,7 +63904,7 @@ var WarmHookLogsService = class {
63614
63904
  continue;
63615
63905
  }
63616
63906
  try {
63617
- const raw = await readFile19(join32(LOGS_DIR2, file), "utf-8");
63907
+ const raw = await readFile20(join33(LOGS_DIR2, file), "utf-8");
63618
63908
  const stored = JSON.parse(raw);
63619
63909
  if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
63620
63910
  logs.push(withPreview2(stored));
@@ -63641,7 +63931,7 @@ var WarmHookLogsService = class {
63641
63931
  }
63642
63932
  async getCurrentRunLog() {
63643
63933
  try {
63644
- return await readFile19(CURRENT_RUN_LOG, "utf-8");
63934
+ return await readFile20(CURRENT_RUN_LOG, "utf-8");
63645
63935
  } catch (err) {
63646
63936
  if (err.code === "ENOENT") return null;
63647
63937
  throw err;
@@ -63650,7 +63940,7 @@ var WarmHookLogsService = class {
63650
63940
  async getFullOutput(hookType, hookName) {
63651
63941
  const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
63652
63942
  try {
63653
- const raw = await readFile19(join32(LOGS_DIR2, filename), "utf-8");
63943
+ const raw = await readFile20(join33(LOGS_DIR2, filename), "utf-8");
63654
63944
  const stored = JSON.parse(raw);
63655
63945
  if (stored.hookType !== hookType || stored.hookName !== hookName) {
63656
63946
  return null;
@@ -63669,12 +63959,12 @@ var warmHookLogsService = new WarmHookLogsService();
63669
63959
  // src/services/warm-hooks-service.ts
63670
63960
  async function readRepoWarmHook(repoPath) {
63671
63961
  for (const filename of REPLICAS_CONFIG_FILENAMES) {
63672
- const configPath = join33(repoPath, filename);
63962
+ const configPath = join34(repoPath, filename);
63673
63963
  if (!existsSync16(configPath)) {
63674
63964
  continue;
63675
63965
  }
63676
63966
  try {
63677
- const raw = await readFile20(configPath, "utf-8");
63967
+ const raw = await readFile21(configPath, "utf-8");
63678
63968
  const config = parseReplicasConfigString(raw, filename);
63679
63969
  if (!config.warmHook) {
63680
63970
  return null;
@@ -63901,17 +64191,17 @@ ${combinedScript}` : combinedScript;
63901
64191
  import { randomUUID as randomUUID10 } from "crypto";
63902
64192
  import { existsSync as existsSync17 } from "fs";
63903
64193
  import { spawn as spawn6 } from "node-pty";
63904
- import { z as z4 } from "zod";
64194
+ import { z as z5 } from "zod";
63905
64195
  var MAX_REPLAY_CHARS2 = 1024 * 1024;
63906
64196
  var MAX_TERMINAL_SESSIONS = 8;
63907
64197
  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)
64198
+ var terminalSizeSchema = z5.object({
64199
+ cols: z5.number().int().min(2).max(500),
64200
+ rows: z5.number().int().min(1).max(200)
63911
64201
  });
63912
- var terminalCommandSchema = z4.discriminatedUnion("type", [
63913
- z4.object({ type: z4.literal("input"), data: z4.string() }),
63914
- terminalSizeSchema.extend({ type: z4.literal("resize") })
64202
+ var terminalCommandSchema = z5.discriminatedUnion("type", [
64203
+ z5.object({ type: z5.literal("input"), data: z5.string() }),
64204
+ terminalSizeSchema.extend({ type: z5.literal("resize") })
63915
64205
  ]);
63916
64206
  var TerminalService = class {
63917
64207
  sessions = /* @__PURE__ */ new Map();
@@ -64032,24 +64322,24 @@ var TerminalService = class {
64032
64322
  var terminalService = new TerminalService();
64033
64323
 
64034
64324
  // src/v1-routes.ts
64035
- var createPreviewSchema = z5.object({
64036
- port: z5.number().int().min(1).max(65535),
64037
- publicUrl: z5.string().min(1)
64325
+ var createPreviewSchema = z6.object({
64326
+ port: z6.number().int().min(1).max(65535),
64327
+ publicUrl: z6.string().min(1)
64038
64328
  });
64039
- var writeTerminalSessionSchema = z5.object({
64040
- data: z5.string().max(64 * 1024),
64041
- generation: z5.number().int().nonnegative(),
64042
- sequence: z5.number().int().nonnegative()
64329
+ var writeTerminalSessionSchema = z6.object({
64330
+ data: z6.string().max(64 * 1024),
64331
+ generation: z6.number().int().nonnegative(),
64332
+ sequence: z6.number().int().nonnegative()
64043
64333
  });
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()
64334
+ var updateGoalSchema = z6.object({
64335
+ objective: z6.string().trim().min(1).max(MAX_CODEX_GOAL_OBJECTIVE_CHARS).optional(),
64336
+ status: z6.enum(["active", "paused"]).optional()
64047
64337
  }).refine((body) => body.objective !== void 0 || body.status !== void 0, {
64048
64338
  message: "Goal objective or status required"
64049
64339
  });
64050
- var updateTextFileSchema = (maxLength) => z5.object({
64051
- content: z5.string().max(maxLength),
64052
- expectedRevision: z5.string().regex(/^[a-f0-9]{64}$/)
64340
+ var updateTextFileSchema = (maxLength) => z6.object({
64341
+ content: z6.string().max(maxLength),
64342
+ expectedRevision: z6.string().regex(/^[a-f0-9]{64}$/)
64053
64343
  });
64054
64344
  function jsonError(message, details) {
64055
64345
  return { error: message, details };
@@ -64099,11 +64389,11 @@ function createV1Routes(deps) {
64099
64389
  const app2 = new Hono();
64100
64390
  app2.post("/pull-requests/check", async (c) => {
64101
64391
  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()
64392
+ const result = z6.object({
64393
+ toolName: z6.string(),
64394
+ toolInput: z6.unknown(),
64395
+ output: z6.unknown(),
64396
+ success: z6.boolean()
64107
64397
  }).safeParse(await c.req.json().catch(() => null));
64108
64398
  if (!result.success) return c.json({ error: "Invalid PR tool result" }, 400);
64109
64399
  await pullRequestCheckService.onToolResult(result.data);
@@ -64323,7 +64613,7 @@ function createV1Routes(deps) {
64323
64613
  const chat = await deps.chatService.updateDisplayName(c.req.param("chatId"), body.displayName);
64324
64614
  return c.json({ chat });
64325
64615
  } catch (error) {
64326
- if (error instanceof z5.ZodError) {
64616
+ if (error instanceof z6.ZodError) {
64327
64617
  return c.json(jsonError(error.issues[0]?.message || "Invalid tab name"), 400);
64328
64618
  }
64329
64619
  if (error instanceof ChatNotFoundError) {
@@ -64444,7 +64734,7 @@ function createV1Routes(deps) {
64444
64734
  const result = await deps.chatService.updateGoal(c.req.param("chatId"), body);
64445
64735
  return c.json(result);
64446
64736
  } catch (error) {
64447
- if (error instanceof z5.ZodError) {
64737
+ if (error instanceof z6.ZodError) {
64448
64738
  return c.json(jsonError(error.issues[0]?.message || "Invalid goal update"), 400);
64449
64739
  }
64450
64740
  if (error instanceof ChatNotFoundError) {
@@ -64527,7 +64817,7 @@ function createV1Routes(deps) {
64527
64817
  if (!body.messageId || typeof body.position !== "number" || !Number.isFinite(body.position)) {
64528
64818
  return c.json(jsonError("Invalid request", "messageId and position are required"), 400);
64529
64819
  }
64530
- const result = deps.chatService.reorderQueue(c.req.param("chatId"), body.messageId, body.position);
64820
+ const result = await deps.chatService.reorderQueue(c.req.param("chatId"), body.messageId, body.position);
64531
64821
  return c.json(result);
64532
64822
  } catch (error) {
64533
64823
  if (error instanceof ChatNotFoundError) {
@@ -64543,7 +64833,7 @@ function createV1Routes(deps) {
64543
64833
  if (!message) {
64544
64834
  return c.json(jsonError("Invalid request", "message is required"), 400);
64545
64835
  }
64546
- const result = deps.chatService.updateQueuedMessage(c.req.param("chatId"), c.req.param("messageId"), message);
64836
+ const result = await deps.chatService.updateQueuedMessage(c.req.param("chatId"), c.req.param("messageId"), message);
64547
64837
  return c.json(result);
64548
64838
  } catch (error) {
64549
64839
  if (error instanceof ChatNotFoundError) {
@@ -64990,7 +65280,7 @@ data: ${JSON.stringify("Terminal session not found")}
64990
65280
  return c.json({ success: true, repos: [] });
64991
65281
  });
64992
65282
  app2.put("/linear-session", async (c) => {
64993
- const body = z5.object({ linearSessionId: z5.string().min(1) }).safeParse(await c.req.json().catch(() => null));
65283
+ const body = z6.object({ linearSessionId: z6.string().min(1) }).safeParse(await c.req.json().catch(() => null));
64994
65284
  if (!body.success) return c.json(jsonError("linearSessionId is required"), 400);
64995
65285
  setLinearSessionId(body.data.linearSessionId);
64996
65286
  return c.json({ success: true });
@@ -65044,7 +65334,7 @@ data: ${JSON.stringify("Terminal session not found")}
65044
65334
  const logFiles = files.filter((f) => f.endsWith(".log"));
65045
65335
  const sessions = await Promise.all(
65046
65336
  logFiles.map(async (filename) => {
65047
- const filePath = join34(LOG_DIR, filename);
65337
+ const filePath = join35(LOG_DIR, filename);
65048
65338
  const fileStat = await stat7(filePath);
65049
65339
  const sessionId = filename.replace(/\.log$/, "");
65050
65340
  return {
@@ -65079,7 +65369,7 @@ data: ${JSON.stringify("Terminal session not found")}
65079
65369
  }
65080
65370
  let content;
65081
65371
  try {
65082
- content = await readFile21(filePath, "utf-8");
65372
+ content = await readFile22(filePath, "utf-8");
65083
65373
  } catch {
65084
65374
  return c.json(jsonError("Log session not found"), 404);
65085
65375
  }
@@ -65100,17 +65390,17 @@ data: ${JSON.stringify("Terminal session not found")}
65100
65390
  }
65101
65391
 
65102
65392
  // src/services/terminal-socket.ts
65103
- import { z as z6 } from "zod";
65393
+ import { z as z7 } from "zod";
65104
65394
  var ndcModule;
65105
65395
  var loadNdc = () => ndcModule ??= import("node-datachannel").then((module) => module.default, () => null);
65106
65396
  var CHANNEL_CHUNK_CHARS = 16384;
65107
65397
  var MAX_QUEUED_CANDIDATES = 32;
65108
65398
  var MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
65109
- var socketMessageSchema = z6.union([
65399
+ var socketMessageSchema = z7.union([
65110
65400
  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") })
65401
+ z7.object({ type: z7.literal("rtc-offer"), sdp: z7.string().max(64 * 1024) }),
65402
+ z7.object({ type: z7.literal("rtc-candidate"), candidate: z7.string().max(1024), mid: z7.string().max(64) }),
65403
+ z7.object({ type: z7.literal("rtc-switch") })
65114
65404
  ]);
65115
65405
  function parse(schema, raw) {
65116
65406
  try {
@@ -65198,13 +65488,13 @@ function attachTerminalSocket(id, socket) {
65198
65488
  }
65199
65489
 
65200
65490
  // src/services/resource-monitor.ts
65201
- import { readFile as readFile22 } from "fs/promises";
65491
+ import { readFile as readFile23 } from "fs/promises";
65202
65492
  var SAMPLE_INTERVAL_MS = 5e3;
65203
65493
  var READ_TIMEOUT_MS = 2e3;
65204
65494
  var pendingReads = new InFlightMap();
65205
65495
  var boundedReads = /* @__PURE__ */ new WeakMap();
65206
65496
  function readWithin(path7) {
65207
- const read = pendingReads.run(path7, () => readFile22(path7, "utf8"));
65497
+ const read = pendingReads.run(path7, () => readFile23(path7, "utf8"));
65208
65498
  const bounded = boundedReads.get(read) ?? withTimeout(read, READ_TIMEOUT_MS, `Timed out reading ${path7}`);
65209
65499
  boundedReads.set(read, bounded);
65210
65500
  return bounded;
@@ -65436,7 +65726,7 @@ var HeartbeatService = class _HeartbeatService {
65436
65726
  var heartbeatService = new HeartbeatService();
65437
65727
 
65438
65728
  // src/services/workspace-sdk-service.ts
65439
- import { cp, mkdir as mkdir20 } from "fs/promises";
65729
+ import { cp, mkdir as mkdir21 } from "fs/promises";
65440
65730
  import { dirname as dirname17, resolve as resolve6 } from "path";
65441
65731
  import { fileURLToPath as fileURLToPath6 } from "url";
65442
65732
  async function installWorkspaceSdk() {
@@ -65446,16 +65736,16 @@ async function installWorkspaceSdk() {
65446
65736
  "/tmp/node_modules/@replicas/sdk"
65447
65737
  ];
65448
65738
  await Promise.all(targets.map(async (target) => {
65449
- await mkdir20(target, { recursive: true });
65739
+ await mkdir21(target, { recursive: true });
65450
65740
  await cp(source, target, { recursive: true, force: true });
65451
65741
  }));
65452
65742
  }
65453
65743
 
65454
65744
  // src/services/git-push-tracker.ts
65455
- import { mkdir as mkdir21, rm as rm7 } from "fs/promises";
65745
+ import { mkdir as mkdir22, rm as rm8 } from "fs/promises";
65456
65746
  import { createServer as createServer3 } from "net";
65457
- import { join as join35 } from "path";
65458
- var SOCKET_PATH = join35(ENGINE_DIR, "git-trace2.sock");
65747
+ import { join as join36 } from "path";
65748
+ var SOCKET_PATH = join36(ENGINE_DIR, "git-trace2.sock");
65459
65749
  var MAX_LINE_LENGTH = 1024 * 1024;
65460
65750
  var listening = null;
65461
65751
  function startGitPushTracker() {
@@ -65465,8 +65755,8 @@ function startGitPushTracker() {
65465
65755
  });
65466
65756
  }
65467
65757
  async function listen() {
65468
- await mkdir21(ENGINE_DIR, { recursive: true });
65469
- await rm7(SOCKET_PATH, { force: true });
65758
+ await mkdir22(ENGINE_DIR, { recursive: true });
65759
+ await rm8(SOCKET_PATH, { force: true });
65470
65760
  const server3 = createServer3((socket) => {
65471
65761
  let buffered = "";
65472
65762
  let ignored = false;
@@ -65862,6 +66152,7 @@ async function activate(requested) {
65862
66152
  })
65863
66153
  ]);
65864
66154
  lifecycle.set("active");
66155
+ chatService.resumeAfterRestart();
65865
66156
  backgroundServices = Promise.allSettled([
65866
66157
  registerDesktopPreview(signal),
65867
66158
  devicesConnected,