replicas-engine 0.1.1487 → 0.1.1488

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-FRGVWKYR.js";
30
+ } from "./chunk-RSNKZNGV.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-OFVUB7GI.js";
68
+ } from "./chunk-YPSSLI23.js";
69
69
  import {
70
70
  publishedPullRequestUrls
71
- } from "./chunk-IJJQPXPJ.js";
71
+ } from "./chunk-3XBF7PYD.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-PLJMIBJJ.js";
146
+ } from "./chunk-INZWL7E7.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-XYXD4AM2.js";
157
+ } from "./chunk-SPZZGZHC.js";
158
158
  import {
159
159
  getCodexModelProvider
160
- } from "./chunk-GAT4P26F.js";
160
+ } from "./chunk-TUX3C5XD.js";
161
161
  import {
162
162
  SUBPROCESS_MAX_BUFFER,
163
163
  execAsync,
164
164
  execFileAsync
165
- } from "./chunk-W3VANMAT.js";
165
+ } from "./chunk-DPGPRAVR.js";
166
166
  import {
167
167
  isRecord as isRecord2
168
168
  } from "./chunk-UZSNFLDQ.js";
@@ -443,7 +443,7 @@ import {
443
443
  workspaceTokenRequestSchema,
444
444
  workspaceTokenResponseSchema,
445
445
  wrapInTag
446
- } from "./chunk-WEC7UDO5.js";
446
+ } from "./chunk-2ZQ4OOSC.js";
447
447
  import {
448
448
  cloneMcpConfig,
449
449
  ensureCompatibilityImports,
@@ -1378,11 +1378,11 @@ var require_codegen2 = __commonJS({
1378
1378
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
1379
1379
  return `${varKind} ${this.name}${rhs};` + _n;
1380
1380
  }
1381
- optimizeNames(names, constants) {
1381
+ optimizeNames(names, constants2) {
1382
1382
  if (!names[this.name.str])
1383
1383
  return;
1384
1384
  if (this.rhs)
1385
- this.rhs = optimizeExpr(this.rhs, names, constants);
1385
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
1386
1386
  return this;
1387
1387
  }
1388
1388
  get names() {
@@ -1399,10 +1399,10 @@ var require_codegen2 = __commonJS({
1399
1399
  render({ _n }) {
1400
1400
  return `${this.lhs} = ${this.rhs};` + _n;
1401
1401
  }
1402
- optimizeNames(names, constants) {
1402
+ optimizeNames(names, constants2) {
1403
1403
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
1404
1404
  return;
1405
- this.rhs = optimizeExpr(this.rhs, names, constants);
1405
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
1406
1406
  return this;
1407
1407
  }
1408
1408
  get names() {
@@ -1463,8 +1463,8 @@ var require_codegen2 = __commonJS({
1463
1463
  optimizeNodes() {
1464
1464
  return `${this.code}` ? this : void 0;
1465
1465
  }
1466
- optimizeNames(names, constants) {
1467
- this.code = optimizeExpr(this.code, names, constants);
1466
+ optimizeNames(names, constants2) {
1467
+ this.code = optimizeExpr(this.code, names, constants2);
1468
1468
  return this;
1469
1469
  }
1470
1470
  get names() {
@@ -1493,12 +1493,12 @@ var require_codegen2 = __commonJS({
1493
1493
  }
1494
1494
  return nodes.length > 0 ? this : void 0;
1495
1495
  }
1496
- optimizeNames(names, constants) {
1496
+ optimizeNames(names, constants2) {
1497
1497
  const { nodes } = this;
1498
1498
  let i = nodes.length;
1499
1499
  while (i--) {
1500
1500
  const n = nodes[i];
1501
- if (n.optimizeNames(names, constants))
1501
+ if (n.optimizeNames(names, constants2))
1502
1502
  continue;
1503
1503
  subtractNames(names, n.names);
1504
1504
  nodes.splice(i, 1);
@@ -1551,12 +1551,12 @@ var require_codegen2 = __commonJS({
1551
1551
  return void 0;
1552
1552
  return this;
1553
1553
  }
1554
- optimizeNames(names, constants) {
1554
+ optimizeNames(names, constants2) {
1555
1555
  var _a;
1556
- this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
1557
- if (!(super.optimizeNames(names, constants) || this.else))
1556
+ this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants2);
1557
+ if (!(super.optimizeNames(names, constants2) || this.else))
1558
1558
  return;
1559
- this.condition = optimizeExpr(this.condition, names, constants);
1559
+ this.condition = optimizeExpr(this.condition, names, constants2);
1560
1560
  return this;
1561
1561
  }
1562
1562
  get names() {
@@ -1579,10 +1579,10 @@ var require_codegen2 = __commonJS({
1579
1579
  render(opts) {
1580
1580
  return `for(${this.iteration})` + super.render(opts);
1581
1581
  }
1582
- optimizeNames(names, constants) {
1583
- if (!super.optimizeNames(names, constants))
1582
+ optimizeNames(names, constants2) {
1583
+ if (!super.optimizeNames(names, constants2))
1584
1584
  return;
1585
- this.iteration = optimizeExpr(this.iteration, names, constants);
1585
+ this.iteration = optimizeExpr(this.iteration, names, constants2);
1586
1586
  return this;
1587
1587
  }
1588
1588
  get names() {
@@ -1618,10 +1618,10 @@ var require_codegen2 = __commonJS({
1618
1618
  render(opts) {
1619
1619
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
1620
1620
  }
1621
- optimizeNames(names, constants) {
1622
- if (!super.optimizeNames(names, constants))
1621
+ optimizeNames(names, constants2) {
1622
+ if (!super.optimizeNames(names, constants2))
1623
1623
  return;
1624
- this.iterable = optimizeExpr(this.iterable, names, constants);
1624
+ this.iterable = optimizeExpr(this.iterable, names, constants2);
1625
1625
  return this;
1626
1626
  }
1627
1627
  get names() {
@@ -1663,11 +1663,11 @@ var require_codegen2 = __commonJS({
1663
1663
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
1664
1664
  return this;
1665
1665
  }
1666
- optimizeNames(names, constants) {
1666
+ optimizeNames(names, constants2) {
1667
1667
  var _a, _b;
1668
- super.optimizeNames(names, constants);
1669
- (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
1670
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
1668
+ super.optimizeNames(names, constants2);
1669
+ (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants2);
1670
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
1671
1671
  return this;
1672
1672
  }
1673
1673
  get names() {
@@ -1968,7 +1968,7 @@ var require_codegen2 = __commonJS({
1968
1968
  function addExprNames(names, from) {
1969
1969
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
1970
1970
  }
1971
- function optimizeExpr(expr, names, constants) {
1971
+ function optimizeExpr(expr, names, constants2) {
1972
1972
  if (expr instanceof code_1.Name)
1973
1973
  return replaceName(expr);
1974
1974
  if (!canOptimize(expr))
@@ -1983,14 +1983,14 @@ var require_codegen2 = __commonJS({
1983
1983
  return items;
1984
1984
  }, []));
1985
1985
  function replaceName(n) {
1986
- const c = constants[n.str];
1986
+ const c = constants2[n.str];
1987
1987
  if (c === void 0 || names[n.str] !== 1)
1988
1988
  return n;
1989
1989
  delete names[n.str];
1990
1990
  return c;
1991
1991
  }
1992
1992
  function canOptimize(e) {
1993
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
1993
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
1994
1994
  }
1995
1995
  }
1996
1996
  function subtractNames(names, from) {
@@ -11127,8 +11127,7 @@ function localControlInstruction() {
11127
11127
  }
11128
11128
 
11129
11129
  // src/services/chat/chat-service.ts
11130
- import { statSync as statSync4 } from "fs";
11131
- 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";
11130
+ import { appendFile as appendFile4, copyFile as copyFile2, mkdir as mkdir15, readFile as readFile18, rename as rename3, rm as rm7 } from "fs/promises";
11132
11131
  import { join as join30 } from "path";
11133
11132
  import { randomUUID as randomUUID9 } from "crypto";
11134
11133
  import { z as z4 } from "zod";
@@ -11368,9 +11367,8 @@ import {
11368
11367
  query
11369
11368
  } from "@anthropic-ai/claude-agent-sdk";
11370
11369
  import { randomUUID as randomUUID3 } from "crypto";
11371
- import { dirname as dirname3, join as join11 } from "path";
11372
- import { mkdir as mkdir8, readdir as readdir4, readFile as readFile7 } from "fs/promises";
11373
- import { homedir as homedir7 } from "os";
11370
+ import { join as join11 } from "path";
11371
+ import { readdir as readdir4, readFile as readFile7 } from "fs/promises";
11374
11372
 
11375
11373
  // src/utils/linear-converter.ts
11376
11374
  function linearThoughtToResponse(thought) {
@@ -12231,6 +12229,8 @@ var CodingAgentManager = class _CodingAgentManager {
12231
12229
  initialized;
12232
12230
  initialSessionId;
12233
12231
  onSaveSessionId;
12232
+ historyFile;
12233
+ record;
12234
12234
  onEvent;
12235
12235
  onUsageUpdate;
12236
12236
  topLevel;
@@ -12269,6 +12269,8 @@ var CodingAgentManager = class _CodingAgentManager {
12269
12269
  if (!sessionId) await this.saveLastSenderKey(null);
12270
12270
  await options.onSaveSessionId(sessionId);
12271
12271
  };
12272
+ this.historyFile = options.history;
12273
+ this.record = options.record;
12272
12274
  this.onEvent = options.onEvent;
12273
12275
  this.onUsageUpdate = options.onUsageUpdate ?? (() => {
12274
12276
  });
@@ -12291,10 +12293,7 @@ var CodingAgentManager = class _CodingAgentManager {
12291
12293
  this.previousTurnLost = options.previousTurnLost ?? false;
12292
12294
  this.onLastSenderKeyChanged = options.onLastSenderKeyChanged ?? (async () => {
12293
12295
  });
12294
- this.authFallback = options.provider ? new AuthFallbackCoordinator(options.provider, (event) => {
12295
- this.onEvent(event);
12296
- this.getHistorySink()?.append(event);
12297
- }, options.fallbackContext ?? (() => ({ excludeProviders: [], forkable: false }))) : null;
12296
+ this.authFallback = options.provider ? new AuthFallbackCoordinator(options.provider, this.record, options.fallbackContext ?? (() => ({ excludeProviders: [], forkable: false }))) : null;
12298
12297
  }
12299
12298
  async fallBackCredential(reason, detail, attempted, resetsAt, afterLimit = false) {
12300
12299
  if (!this.authFallback) return { outcome: "unavailable" };
@@ -12316,7 +12315,7 @@ var CodingAgentManager = class _CodingAgentManager {
12316
12315
  emitQuotaExhausted(payload) {
12317
12316
  this.emitSyntheticEvent(AGENT_QUOTA_EXHAUSTED_EVENT_TYPE, { ...payload });
12318
12317
  }
12319
- recordHistoryEvent(type, payload, historyFile) {
12318
+ recordHistoryEvent(type, payload) {
12320
12319
  const eventPayload2 = {};
12321
12320
  if (payload && typeof payload === "object") {
12322
12321
  Object.assign(eventPayload2, payload);
@@ -12328,15 +12327,10 @@ var CodingAgentManager = class _CodingAgentManager {
12328
12327
  type,
12329
12328
  payload: eventPayload2
12330
12329
  };
12331
- this.onEvent(event);
12332
- historyFile.append(event);
12333
- }
12334
- recordUserMessageHistoryEvent(request, historyFile, extraPayload = {}) {
12335
- this.recordHistoryEvent(
12336
- "event_msg",
12337
- this.createUserMessageHistoryPayload(request, extraPayload),
12338
- historyFile
12339
- );
12330
+ this.record(event);
12331
+ }
12332
+ recordUserMessageHistoryEvent(request, extraPayload = {}) {
12333
+ this.recordHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, extraPayload));
12340
12334
  }
12341
12335
  createUserMessageHistoryPayload(request, extraPayload = {}) {
12342
12336
  return {
@@ -12388,6 +12382,8 @@ var CodingAgentManager = class _CodingAgentManager {
12388
12382
  );
12389
12383
  this.initialized = this.initialize();
12390
12384
  }
12385
+ async initialize() {
12386
+ }
12391
12387
  async keepStoppedRequest(_request) {
12392
12388
  return false;
12393
12389
  }
@@ -12430,14 +12426,6 @@ ${request.message}` }, senderKey };
12430
12426
  subagentMcpParentChatId() {
12431
12427
  return this.subagentMcpEnabledForTurn ? this.subagentMcpChatId : void 0;
12432
12428
  }
12433
- getHistoryEnd() {
12434
- return this.getHistorySink()?.historyEnd;
12435
- }
12436
- async persistHistoryEvent(event) {
12437
- const history = this.getHistorySink();
12438
- if (!history?.appendDurably) throw new Error("Chat history is unavailable");
12439
- await history.appendDurably(event);
12440
- }
12441
12429
  async interrupt(persistRemoval, requestedStoppedAt) {
12442
12430
  const now = Date.now();
12443
12431
  const requested = requestedStoppedAt ? Date.parse(requestedStoppedAt) : NaN;
@@ -12488,8 +12476,7 @@ ${request.message}` }, senderKey };
12488
12476
  type: CHAT_INTERRUPTED_EVENT_TYPE,
12489
12477
  payload: steered ? { steered: true } : {}
12490
12478
  };
12491
- this.onEvent(event);
12492
- this.getHistorySink()?.append(event);
12479
+ this.record(event);
12493
12480
  }
12494
12481
  isProcessing() {
12495
12482
  return this.messageQueue.isProcessing();
@@ -12660,14 +12647,12 @@ ${note}` };
12660
12647
  }
12661
12648
  });
12662
12649
  }
12663
- emitContextUsage(payload) {
12664
- const event = {
12650
+ recordContextUsage(payload) {
12651
+ this.record({
12665
12652
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12666
12653
  type: CONTEXT_USAGE_EVENT_TYPE,
12667
12654
  payload: { ...payload }
12668
- };
12669
- this.onEvent(event);
12670
- return event;
12655
+ });
12671
12656
  }
12672
12657
  buildCombinedInstructions(customInstructions, includeMemory = false) {
12673
12658
  const startHooksInstruction = this.getStartHooksInstruction();
@@ -13184,208 +13169,6 @@ function isNotFoundError(error) {
13184
13169
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
13185
13170
  }
13186
13171
 
13187
- // src/managers/codex-asp/codex-history-file.ts
13188
- import { createReadStream, statSync } from "fs";
13189
- import { appendFile as appendFile2, open, rename } from "fs/promises";
13190
- import { createInterface } from "readline";
13191
- var MIGRATION_FLUSH_CHARS = 1 << 20;
13192
- function isMissingFile(error) {
13193
- return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
13194
- }
13195
- var CodexHistoryFile = class {
13196
- constructor(filePath) {
13197
- this.filePath = filePath;
13198
- try {
13199
- this.reservedSize = statSync(filePath).size;
13200
- } catch (error) {
13201
- if (!isMissingFile(error)) throw error;
13202
- this.reservedSize = 0;
13203
- }
13204
- }
13205
- filePath;
13206
- writeLock = new AsyncLock();
13207
- // Bytes the file holds once every queued append lands; unknown after a failed write or a rewrite.
13208
- reservedSize;
13209
- get historyEnd() {
13210
- return this.reservedSize;
13211
- }
13212
- /** Best-effort ordered append; failures must not disrupt the turn. */
13213
- append(event) {
13214
- void this.appendDurably(event).catch((error) => {
13215
- console.error("[CodexHistoryFile] Failed to append event:", error);
13216
- });
13217
- }
13218
- appendDurably(event) {
13219
- const reserved = `${JSON.stringify(event)}
13220
- `;
13221
- if (this.reservedSize !== void 0) this.reservedSize += Buffer.byteLength(reserved);
13222
- return this.writeLock.run(() => {
13223
- const line = `${JSON.stringify(event)}
13224
- `;
13225
- if (line !== reserved) this.reservedSize = void 0;
13226
- return appendFile2(this.filePath, line);
13227
- }).catch((error) => {
13228
- this.reservedSize = void 0;
13229
- throw error;
13230
- });
13231
- }
13232
- async flush() {
13233
- await this.writeLock.drain();
13234
- }
13235
- /**
13236
- * Rewrites a file that still holds legacy Codex transcript records as plain
13237
- * item events, once. The file is read line by line: a long-lived chat can
13238
- * exceed the largest string V8 will hold. The rewritten file starts with a
13239
- * format marker so later starts only read that first line.
13240
- */
13241
- async ensureItemEventFormat() {
13242
- const firstLine = await this.readFirstLine();
13243
- if (firstLine === null) {
13244
- await this.appendDurably(codexHistoryFormatEvent());
13245
- return;
13246
- }
13247
- if (parseAgentEventJsonlLine(firstLine)?.type === CODEX_HISTORY_FORMAT_EVENT_TYPE) return;
13248
- this.reservedSize = void 0;
13249
- await this.writeLock.run(async () => {
13250
- const events = await this.loadAll();
13251
- const rewritten = `${this.filePath}.migrating`;
13252
- const handle = await open(rewritten, "w");
13253
- try {
13254
- let pending = "";
13255
- for (const event of [codexHistoryFormatEvent(), ...events]) {
13256
- pending += `${JSON.stringify(event)}
13257
- `;
13258
- if (pending.length >= MIGRATION_FLUSH_CHARS) {
13259
- await handle.write(pending);
13260
- pending = "";
13261
- }
13262
- }
13263
- if (pending) await handle.write(pending);
13264
- } finally {
13265
- await handle.close();
13266
- }
13267
- await rename(rewritten, this.filePath);
13268
- });
13269
- }
13270
- /**
13271
- * Newest event of `type`, scanning the whole file so a value older than the
13272
- * most recent page is still found. Streams line by line and retains only the
13273
- * match, so history size does not bound memory.
13274
- */
13275
- async findLastEventOfType(type) {
13276
- return this.findLastEvent(type, (event) => event.type === type);
13277
- }
13278
- async findLastEvent(needle, matches) {
13279
- let found = null;
13280
- for await (const event of this.eventsFrom(0, [needle])) {
13281
- if (matches(event)) found = event;
13282
- }
13283
- return found;
13284
- }
13285
- async *eventsFrom(start, needles) {
13286
- try {
13287
- for await (const line of createInterface({ input: createReadStream(this.filePath, { start }), crlfDelay: Infinity })) {
13288
- if (!needles.some((needle) => line.includes(needle))) continue;
13289
- const event = parseAgentEventJsonlLine(line);
13290
- if (event) yield event;
13291
- }
13292
- } catch (error) {
13293
- if (!isMissingFile(error)) throw error;
13294
- }
13295
- }
13296
- async findSubagentItems() {
13297
- const found = /* @__PURE__ */ new Map();
13298
- for await (const event of this.eventsFrom(0, ['"subagent"'])) {
13299
- const payload = event.type === CODEX_ITEM_EVENT_TYPE ? codexItemFromEvent(event) : null;
13300
- if (payload?.item.type === "subagent") found.set(payload.item.id, { turnId: payload.turnId, item: payload.item });
13301
- }
13302
- return found;
13303
- }
13304
- async loadAll() {
13305
- const folder = new CodexHistoryEventFolder();
13306
- try {
13307
- for await (const line of createInterface({ input: createReadStream(this.filePath), crlfDelay: Infinity })) {
13308
- const event = parseAgentEventJsonlLine(line);
13309
- if (event) folder.push(event);
13310
- }
13311
- } catch (error) {
13312
- if (!isMissingFile(error)) throw error;
13313
- }
13314
- return folder.finish();
13315
- }
13316
- async loadEventsPage(page2) {
13317
- if (page2.subagents) {
13318
- const events = await this.read((size, readRange) => readChatSubagentHistory({ size, compact: page2.compact, readRange }));
13319
- return { events: events ?? [], beforeCursor: null };
13320
- }
13321
- if (page2.limit === void 0) return { events: await this.loadAll() };
13322
- const cursor = parseChatHistoryCursor(page2.beforeCursor);
13323
- if (page2.beforeCursor !== void 0 && cursor?.mode !== "range") throw new RangeError("Invalid chat history cursor");
13324
- if (cursor?.events === null) return { events: [], beforeCursor: null };
13325
- const { limit } = page2;
13326
- return await this.read(async (size, readRange) => {
13327
- if (page2.afterCursor !== void 0 && cursor === void 0) {
13328
- const appended = await readChatHistoryAppended({ size, after: page2.afterCursor, compact: page2.compact, readRange });
13329
- if (appended) return { events: appended.items, afterCursor: appended.after, appendsAfter: page2.afterCursor };
13330
- }
13331
- const result = await readChatHistoryPage({
13332
- size,
13333
- limit,
13334
- userTurns: page2.userTurns,
13335
- compact: page2.compact,
13336
- before: cursor?.events,
13337
- readRange
13338
- });
13339
- return {
13340
- events: result.items,
13341
- beforeCursor: createChatHistoryCursor({ events: result.before, turns: null }),
13342
- ...cursor === void 0 ? { afterCursor: String(size) } : {},
13343
- ...page2.userTurns ? { userTurns: page2.userTurns } : {}
13344
- };
13345
- }) ?? { events: [], beforeCursor: null };
13346
- }
13347
- async readRecord(record3) {
13348
- return await this.read((size, readRange) => readChatHistoryRecord({ size, record: record3, readRange })) ?? void 0;
13349
- }
13350
- async read(use) {
13351
- let file;
13352
- try {
13353
- file = await open(this.filePath, "r");
13354
- } catch (error) {
13355
- if (isMissingFile(error)) return null;
13356
- throw error;
13357
- }
13358
- try {
13359
- return await use((await file.stat()).size, async (startByte, endByte) => {
13360
- const bytes = Buffer.allocUnsafe(endByte - startByte);
13361
- const { bytesRead } = await file.read(bytes, 0, bytes.length, startByte);
13362
- return bytes.subarray(0, bytesRead);
13363
- });
13364
- } finally {
13365
- await file.close();
13366
- }
13367
- }
13368
- async readFirstLine() {
13369
- let file;
13370
- try {
13371
- file = await open(this.filePath, "r");
13372
- } catch (error) {
13373
- if (isMissingFile(error)) return null;
13374
- throw error;
13375
- }
13376
- try {
13377
- const bytes = Buffer.allocUnsafe(4096);
13378
- const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
13379
- if (bytesRead === 0) return null;
13380
- const text = bytes.subarray(0, bytesRead).toString("utf-8");
13381
- const newline = text.indexOf("\n");
13382
- return newline === -1 ? text : text.slice(0, newline);
13383
- } finally {
13384
- await file.close();
13385
- }
13386
- }
13387
- };
13388
-
13389
13172
  // src/managers/claude-activity.ts
13390
13173
  function createClaudeSessionActivity() {
13391
13174
  return { state: "idle", observedAuthoritativeState: false };
@@ -13691,8 +13474,6 @@ function normalizeClaudeSlashCommands(commands) {
13691
13474
  return mergeSlashCommands(...commands.map(toSlashCommands));
13692
13475
  }
13693
13476
  var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13694
- historyFilePath;
13695
- historyFile;
13696
13477
  sessionId = null;
13697
13478
  activeQuery = null;
13698
13479
  activePromptStream = null;
@@ -13753,13 +13534,8 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13753
13534
  });
13754
13535
  this.onChatCredential = options.onChatCredential ?? (() => {
13755
13536
  });
13756
- this.historyFilePath = options.historyFilePath ?? join11(homedir7(), ".replicas", "claude", "history.jsonl");
13757
- this.historyFile = new CodexHistoryFile(this.historyFilePath);
13758
13537
  this.initializeManager(this.processMessageInternal.bind(this));
13759
13538
  }
13760
- getHistorySink() {
13761
- return this.historyFile;
13762
- }
13763
13539
  async interruptActiveTurn(stoppedAt) {
13764
13540
  this.pendingInterrupt = true;
13765
13541
  this.stoppedAtMs = stoppedAt ? Date.parse(stoppedAt) : Date.now();
@@ -13841,7 +13617,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13841
13617
  ...name ? { name } : {},
13842
13618
  ...from ? { from } : {},
13843
13619
  body
13844
- }, this.historyFile);
13620
+ });
13845
13621
  }
13846
13622
  return;
13847
13623
  }
@@ -13895,7 +13671,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13895
13671
  recordGoalChange(goal) {
13896
13672
  if (!goal && !this.currentGoal) return;
13897
13673
  this.currentGoal = goal;
13898
- this.recordHistoryEvent(CHAT_GOAL_EVENT_TYPE, { goal }, this.historyFile);
13674
+ this.recordHistoryEvent(CHAT_GOAL_EVENT_TYPE, { goal });
13899
13675
  }
13900
13676
  // Keeps the workspace alive without showing the chat as working: an idle agent isn't waiting on these.
13901
13677
  hasActiveBackgroundTasks() {
@@ -13997,8 +13773,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13997
13773
  type,
13998
13774
  payload: { ...payload, parent_tool_use_id: null }
13999
13775
  };
14000
- this.historyFile.append(event);
14001
- this.onEvent(event);
13776
+ this.record(event);
14002
13777
  }
14003
13778
  buildCanUseTool() {
14004
13779
  return async (toolName, input, options) => {
@@ -14098,8 +13873,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14098
13873
  session_id: typeof entry.sessionId === "string" ? entry.sessionId : this.sessionId ?? ""
14099
13874
  }
14100
13875
  };
14101
- this.historyFile.append(event);
14102
- this.onEvent(event);
13876
+ this.record(event);
14103
13877
  }
14104
13878
  }
14105
13879
  }
@@ -14289,8 +14063,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14289
14063
  parent_tool_use_id: null
14290
14064
  }
14291
14065
  };
14292
- this.historyFile.append(event);
14293
- this.onEvent(event);
14066
+ this.record(event);
14294
14067
  }
14295
14068
  async emitAuthRetryExhaustedEvent(error, login, revoked) {
14296
14069
  const detail = error instanceof Error ? error.message : String(error);
@@ -14740,7 +14513,7 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
14740
14513
  this.sessionLinearForwarder.sendEvent(convertClaudeEvent(msg, linearSessionId));
14741
14514
  }
14742
14515
  if (msg.type === "result") {
14743
- await this.recordContextUsage(response);
14516
+ await this.recordQueryContextUsage(response);
14744
14517
  if (this.activeQuery !== response) break;
14745
14518
  this.sessionLinearForwarder?.flushThoughtAsResponse();
14746
14519
  const pendingUuids = this.pendingTurn?.userMessageUuids;
@@ -14978,11 +14751,10 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
14978
14751
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
14979
14752
  };
14980
14753
  }
14981
- async recordContextUsage(response) {
14754
+ async recordQueryContextUsage(response) {
14982
14755
  try {
14983
14756
  const usage = await response.getContextUsage({ detail: "summary" });
14984
- const event = this.emitContextUsage(this.buildContextUsagePayload(usage));
14985
- this.historyFile.append(event);
14757
+ this.recordContextUsage(this.buildContextUsagePayload(usage));
14986
14758
  } catch (error) {
14987
14759
  console.warn("[ClaudeManager] Failed to record context usage:", error instanceof Error ? error.message : error);
14988
14760
  }
@@ -15163,7 +14935,6 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
15163
14935
  }
15164
14936
  }
15165
14937
  async initialize() {
15166
- await mkdir8(dirname3(this.historyFilePath), { recursive: true });
15167
14938
  const goalEvent = await this.historyFile.findLastEventOfType(CHAT_GOAL_EVENT_TYPE);
15168
14939
  if (goalEvent) this.currentGoal = coerceChatGoalPayload(goalEvent.payload);
15169
14940
  if (this.initialSessionId) {
@@ -15236,14 +15007,13 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
15236
15007
  ...replacesMessageId ? { [REPLACED_MESSAGE_ID_PAYLOAD_KEY]: replacesMessageId } : {}
15237
15008
  }
15238
15009
  };
15239
- this.historyFile.append(jsonEvent);
15240
- this.onEvent(jsonEvent);
15010
+ this.record(jsonEvent);
15241
15011
  }
15242
15012
  };
15243
15013
 
15244
15014
  // src/managers/codex-asp/codex-asp-manager.ts
15245
15015
  import { existsSync as existsSync6 } from "fs";
15246
- import { mkdir as mkdir9, writeFile as writeFile5 } from "fs/promises";
15016
+ import { mkdir as mkdir8, writeFile as writeFile5 } from "fs/promises";
15247
15017
  import { join as join12 } from "path";
15248
15018
  import { setTimeout as sleep } from "timers/promises";
15249
15019
 
@@ -15350,7 +15120,7 @@ var CODEX_SLASH_COMMANDS_CACHE_MS = 3e4;
15350
15120
  var POLICY_REASON_INJECTION_TIMEOUT_MS = 5e3;
15351
15121
  var SUBAGENT_MCP_THREADS_DIR = join12(ENGINE_ENV.HOME_DIR, ".replicas", "codex", "subagent-mcp-threads");
15352
15122
  async function markSubagentMcpThread(threadId) {
15353
- await mkdir9(SUBAGENT_MCP_THREADS_DIR, { recursive: true });
15123
+ await mkdir8(SUBAGENT_MCP_THREADS_DIR, { recursive: true });
15354
15124
  await writeFile5(join12(SUBAGENT_MCP_THREADS_DIR, threadId), "");
15355
15125
  }
15356
15126
  function formatBlockedCommandReason(reason) {
@@ -15391,7 +15161,6 @@ var CodexAspManager = class extends CodingAgentManager {
15391
15161
  attachedModel = null;
15392
15162
  attachedDeveloperInstructions = null;
15393
15163
  attachedAutoCompactTokens = null;
15394
- historyFile;
15395
15164
  liveTurn = null;
15396
15165
  codexSubagents = /* @__PURE__ */ new Map();
15397
15166
  quotaStatus = new CodexQuotaStatusTracker();
@@ -15418,7 +15187,6 @@ var CodexAspManager = class extends CodingAgentManager {
15418
15187
  onCodexTurnCompleted;
15419
15188
  constructor(options) {
15420
15189
  super({ ...options, provider: AGENT.CODEX });
15421
- this.historyFile = options.historyFilePath ? new CodexHistoryFile(options.historyFilePath) : null;
15422
15190
  this.pendingFork = options.pendingFork ?? null;
15423
15191
  this.onCodexTurnStarted = options.onCodexTurnStarted;
15424
15192
  this.onCodexTokenUsage = options.onCodexTokenUsage;
@@ -15427,27 +15195,17 @@ var CodexAspManager = class extends CodingAgentManager {
15427
15195
  this.initializeManager(this.processMessageInternal.bind(this));
15428
15196
  }
15429
15197
  async initialize() {
15430
- await this.historyFile?.ensureItemEventFormat();
15198
+ await this.historyFile.ensureItemEventFormat();
15431
15199
  this.currentThreadId = this.initialSessionId;
15432
- const goalEvent = await this.historyFile?.findLastEventOfType(CHAT_GOAL_EVENT_TYPE);
15200
+ const goalEvent = await this.historyFile.findLastEventOfType(CHAT_GOAL_EVENT_TYPE);
15433
15201
  if (goalEvent) {
15434
15202
  this.currentGoal = coerceChatGoalPayload(goalEvent.payload);
15435
15203
  this.goalHistoryKnown = true;
15436
15204
  }
15437
- for (const { turnId, item } of (await this.historyFile?.findSubagentItems())?.values() ?? []) {
15205
+ for (const { turnId, item } of (await this.historyFile.findSubagentItems()).values()) {
15438
15206
  if (item.status === "in_progress") this.updateCodexSubagent({ turnId, item, active: /* @__PURE__ */ new Set(), failed: false });
15439
15207
  }
15440
15208
  }
15441
- getHistorySink() {
15442
- return {
15443
- append: (event) => this.trackHistoryEvent(event),
15444
- appendDurably: (event) => {
15445
- if (!this.historyFile) throw new Error("Chat history is unavailable");
15446
- return this.historyFile.appendDurably(event);
15447
- },
15448
- historyEnd: this.historyFile?.historyEnd
15449
- };
15450
- }
15451
15209
  async subagentMcpForTurn(enabled) {
15452
15210
  return this.currentThreadId ? existsSync6(join12(SUBAGENT_MCP_THREADS_DIR, this.currentThreadId)) : enabled;
15453
15211
  }
@@ -15560,7 +15318,7 @@ var CodexAspManager = class extends CodingAgentManager {
15560
15318
  THREAD_READ_METHOD,
15561
15319
  { threadId: sessionId, includeTurns: true }
15562
15320
  );
15563
- const edited = beforeMessageId ? parseAgentEvents(await this.historyFile?.loadAll() ?? [], "codex").findLast(({ id }) => id === beforeMessageId) : void 0;
15321
+ const edited = beforeMessageId ? parseAgentEvents(await this.historyFile.loadAll(), "codex").findLast(({ id }) => id === beforeMessageId) : void 0;
15564
15322
  const editedTurnId = edited && codexPromptTurnId(edited);
15565
15323
  const turns = beforeMessageId ? thread.turns.slice(0, Math.max(0, thread.turns.findIndex((turn) => turn.id === editedTurnId))) : thread.turns;
15566
15324
  const throughTurn = turns.findLast((turn) => turn.status !== "inProgress")?.id;
@@ -15573,7 +15331,7 @@ var CodexAspManager = class extends CodingAgentManager {
15573
15331
  }
15574
15332
  async getHistory(page2 = {}) {
15575
15333
  await this.initialized;
15576
- await this.historyFile?.flush();
15334
+ await this.historyFile.flush();
15577
15335
  const latestPage = isLatestChatHistoryPage(page2);
15578
15336
  if (latestPage && !this.goalHistoryKnown && this.currentThreadId) {
15579
15337
  try {
@@ -15582,7 +15340,7 @@ var CodexAspManager = class extends CodingAgentManager {
15582
15340
  console.warn("[CodexAspManager] Failed to connect while refreshing thread goal:", error);
15583
15341
  }
15584
15342
  }
15585
- const history = await this.historyFile?.loadEventsPage(page2) ?? { events: [] };
15343
+ const history = await this.historyFile.loadEventsPage(page2);
15586
15344
  const liveTurn = latestPage ? this.liveTurn : null;
15587
15345
  const liveEvents = liveTurn ? [...liveTurn.items.values()].map((item) => codexItemEvent(liveTurn.id, item, true)) : [];
15588
15346
  return {
@@ -15654,10 +15412,7 @@ var CodexAspManager = class extends CodingAgentManager {
15654
15412
  }
15655
15413
  recordUserMessageEvent(request, extraPayload = {}) {
15656
15414
  const images = imageContentToUserMessageImages(request.images);
15657
- this.onEvent(this.recordCodexHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, {
15658
- ...images ? { images } : {},
15659
- ...extraPayload
15660
- })));
15415
+ this.recordUserMessageHistoryEvent(request, { ...images ? { images } : {}, ...extraPayload });
15661
15416
  }
15662
15417
  async processMessageInternal(request, signal) {
15663
15418
  let userMessageRecorded = false;
@@ -15712,11 +15467,11 @@ var CodexAspManager = class extends CodingAgentManager {
15712
15467
  } catch (error) {
15713
15468
  let failure = error;
15714
15469
  for (let attempt = 1; failure instanceof CodexModelAtCapacityError && attempt <= MODEL_AT_CAPACITY_RETRIES; attempt++) {
15715
- this.onEvent(this.recordCodexHistoryEvent(CODEX_TURN_RETRY_EVENT_TYPE, {
15470
+ this.recordHistoryEvent(CODEX_TURN_RETRY_EVENT_TYPE, {
15716
15471
  attempt,
15717
15472
  maxAttempts: MODEL_AT_CAPACITY_RETRIES,
15718
15473
  [CODEX_ASP_ITEM_ID_PAYLOAD_KEY]: failure.turnId
15719
- }));
15474
+ });
15720
15475
  await sleep(MODEL_AT_CAPACITY_RETRY_BASE_MS * 2 ** (attempt - 1) * (0.5 + Math.random() / 2), void 0, { signal }).catch(() => {
15721
15476
  });
15722
15477
  if (signal.aborted) return;
@@ -15756,9 +15511,9 @@ var CodexAspManager = class extends CodingAgentManager {
15756
15511
  detail: terminalError.message,
15757
15512
  ...fallback.outcome === "fork" ? { forkTo: fallback.target } : {}
15758
15513
  });
15759
- this.onEvent(this.recordCodexHistoryEvent("codex-asp-error", {
15514
+ this.recordHistoryEvent("codex-asp-error", {
15760
15515
  message: describeQuotaExhaustion("codex", reason, attemptedCredential, fallback)
15761
- }));
15516
+ });
15762
15517
  if (reason === "out_of_credits") return;
15763
15518
  throw terminalError;
15764
15519
  }
@@ -15794,12 +15549,11 @@ var CodexAspManager = class extends CodingAgentManager {
15794
15549
  }
15795
15550
  const message = terminalError instanceof Error ? terminalError.message : String(terminalError);
15796
15551
  const failedTurnId = this.lastTurnFailure?.message === message ? this.lastTurnFailure.turnId : null;
15797
- const event = this.recordCodexHistoryEvent("codex-asp-error", {
15552
+ this.recordHistoryEvent("codex-asp-error", {
15798
15553
  message,
15799
15554
  ...failedTurnId ? { [CODEX_ASP_ITEM_ID_PAYLOAD_KEY]: failedTurnId } : {}
15800
15555
  });
15801
- this.onEvent(event);
15802
- if (loginFailure) this.onEvent(this.recordCodexHistoryEvent("codex-asp-error", { message: loginFailure }));
15556
+ if (loginFailure) this.recordHistoryEvent("codex-asp-error", { message: loginFailure });
15803
15557
  throw terminalError;
15804
15558
  } finally {
15805
15559
  this.itemUpdateCoalescer.flushPending();
@@ -15807,7 +15561,7 @@ var CodexAspManager = class extends CodingAgentManager {
15807
15561
  this.activeTurnId = null;
15808
15562
  this.compacting = false;
15809
15563
  await removeTempImageFiles(this.steeredTempImagePaths.splice(0));
15810
- await this.historyFile?.flush();
15564
+ await this.historyFile.flush();
15811
15565
  await this.onTurnComplete();
15812
15566
  }
15813
15567
  }
@@ -15929,7 +15683,7 @@ var CodexAspManager = class extends CodingAgentManager {
15929
15683
  const events = codexTranscriptToEvents(threadToAspTranscript(previous));
15930
15684
  const text = canonicalizeChatTranscriptBlocks(events.map((event) => JSON.stringify(event)).join("\n"), "codex", void 0).join("\n\n");
15931
15685
  const directory = join12(ENGINE_ENV.HOME_DIR, ".replicas", "codex", "provider-context");
15932
- await mkdir9(directory, { recursive: true });
15686
+ await mkdir8(directory, { recursive: true });
15933
15687
  const transcriptPath = join12(directory, `${previous.id}.md`);
15934
15688
  await writeFile5(transcriptPath, text, "utf8");
15935
15689
  const response = await host.client.request(
@@ -16464,16 +16218,14 @@ ${text.slice(-24e3)}`
16464
16218
  for (const threadId of subagent.active) this.codexSubagents.set(threadId, subagent);
16465
16219
  }
16466
16220
  const event = codexItemEvent(turnId, persisted);
16467
- this.historyFile?.append(event);
16468
- this.onEvent(event);
16221
+ this.record(event);
16469
16222
  }
16470
16223
  updateCodexSubagent(subagent) {
16471
16224
  const status = normalizeCodexAspTranscriptStatus(subagent.active.size > 0 ? "inProgress" : "completed", subagent.failed);
16472
16225
  if (subagent.item.status === status) return;
16473
16226
  subagent.item = { ...subagent.item, status };
16474
16227
  const event = codexItemEvent(subagent.turnId, subagent.item);
16475
- this.historyFile?.append(event);
16476
- this.onEvent(event);
16228
+ this.record(event);
16477
16229
  }
16478
16230
  closeCodexSubagents() {
16479
16231
  for (const subagent of new Set(this.codexSubagents.values())) {
@@ -16505,8 +16257,7 @@ ${text.slice(-24e3)}`
16505
16257
  const failure = turn.error ? formatTurnFailure(turn) : void 0;
16506
16258
  this.lastTurnFailure = failure === void 0 ? null : { turnId: turn.id, message: failure };
16507
16259
  const event = codexTurnEvent(turn.id, turn.status, completedAt, failure);
16508
- this.historyFile?.append(event);
16509
- this.onEvent(event);
16260
+ this.record(event);
16510
16261
  this.liveTurn = null;
16511
16262
  }
16512
16263
  appendAgentMessageDelta(turnId, itemId, delta) {
@@ -16550,26 +16301,10 @@ ${text.slice(-24e3)}`
16550
16301
  const nextGoal = goal ? aspGoalToChatGoal(goal) : null;
16551
16302
  if (force || JSON.stringify(this.currentGoal) !== JSON.stringify(nextGoal)) {
16552
16303
  this.currentGoal = nextGoal;
16553
- const event = this.recordCodexHistoryEvent(
16554
- CHAT_GOAL_EVENT_TYPE,
16555
- { goal: nextGoal }
16556
- );
16557
- this.onEvent(event);
16304
+ this.recordHistoryEvent(CHAT_GOAL_EVENT_TYPE, { goal: nextGoal });
16558
16305
  }
16559
16306
  this.onGoalChanged?.();
16560
16307
  }
16561
- recordCodexHistoryEvent(type, payload) {
16562
- const event = {
16563
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
16564
- type,
16565
- payload
16566
- };
16567
- this.trackHistoryEvent(event);
16568
- return event;
16569
- }
16570
- trackHistoryEvent(event) {
16571
- this.historyFile?.append(event);
16572
- }
16573
16308
  handleRateLimits(rateLimits) {
16574
16309
  const snapshot = extractRateLimitsSnapshot(rateLimits);
16575
16310
  if (snapshot) {
@@ -16605,8 +16340,7 @@ ${text.slice(-24e3)}`
16605
16340
  }
16606
16341
  emitQuotaEvent(event) {
16607
16342
  if (!event) return;
16608
- this.trackHistoryEvent(event);
16609
- this.onEvent(event);
16343
+ this.record(event);
16610
16344
  }
16611
16345
  emitCodexTokenUsage(tokenUsage, model, updatedAt) {
16612
16346
  const payload = buildCodexTokenUsageContextUsagePayload({
@@ -16620,19 +16354,364 @@ ${text.slice(-24e3)}`
16620
16354
  },
16621
16355
  updatedAt
16622
16356
  });
16623
- const event = this.emitContextUsage(payload);
16624
- this.trackHistoryEvent(event);
16357
+ this.recordContextUsage(payload);
16358
+ }
16359
+ };
16360
+
16361
+ // src/managers/codex-asp/codex-history-file.ts
16362
+ import { closeSync, constants, fstatSync, mkdirSync as mkdirSync2, openSync, readSync } from "fs";
16363
+ import { open, rename } from "fs/promises";
16364
+ import { dirname as dirname3 } from "path";
16365
+ import { StringDecoder } from "string_decoder";
16366
+ var MIGRATION_FLUSH_CHARS = 1 << 20;
16367
+ var WRITE_RETRY_DELAYS_MS = [100, 400, 1500, 3e3, 5e3];
16368
+ var NEWLINE = Buffer.from("\n");
16369
+ var READ_CHUNK_BYTES = 1 << 18;
16370
+ function isMissingFile(error) {
16371
+ return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
16372
+ }
16373
+ async function openWholeLog(path7) {
16374
+ let file;
16375
+ try {
16376
+ file = await open(path7, "r");
16377
+ } catch (error) {
16378
+ if (isMissingFile(error)) return null;
16379
+ throw error;
16380
+ }
16381
+ try {
16382
+ return { file, size: (await file.stat()).size };
16383
+ } catch (error) {
16384
+ await file.close();
16385
+ throw error;
16386
+ }
16387
+ }
16388
+ var CodexHistoryFile = class {
16389
+ constructor(filePath) {
16390
+ this.filePath = filePath;
16391
+ try {
16392
+ const file = openSync(filePath, "r");
16393
+ try {
16394
+ this.flushedEnd = fstatSync(file).size;
16395
+ const last = Buffer.alloc(1);
16396
+ this.tornTail = this.flushedEnd > 0 && readSync(file, last, 0, 1, this.flushedEnd - 1) === 1 && last[0] !== NEWLINE[0];
16397
+ } finally {
16398
+ closeSync(file);
16399
+ }
16400
+ } catch (error) {
16401
+ if (!isMissingFile(error)) throw error;
16402
+ mkdirSync2(dirname3(filePath), { recursive: true });
16403
+ }
16404
+ this.nextOffset = this.firstFreeOffset();
16405
+ }
16406
+ filePath;
16407
+ queued = [];
16408
+ writing = null;
16409
+ taken = Promise.resolve();
16410
+ // Every byte before this is on disk. Reads and the position clients are told stop here, so nothing outside the engine ever sees an offset a crash could take back.
16411
+ flushedEnd = 0;
16412
+ nextOffset = 0;
16413
+ // The file ends in a record with no newline (a write cut short): the next batch starts with one, so readers lose that fragment alone.
16414
+ tornTail = false;
16415
+ // Part of a dropped batch may have reached the disk. Until the file is cut back to the flushed end, a crash would bring those records back.
16416
+ cutPending = false;
16417
+ // Set while a rewritten file takes the old one's place, so a read never pairs one file with the other's flushed end.
16418
+ swapping = null;
16419
+ // Counts those swaps: an open that began before one and returned after it holds the old file.
16420
+ swaps = 0;
16421
+ get historyEnd() {
16422
+ return this.flushedEnd;
16423
+ }
16424
+ /** Where the next record will start. Not yet on disk, so it stays inside the engine. */
16425
+ get end() {
16426
+ return this.nextOffset;
16427
+ }
16428
+ record(event) {
16429
+ const bytes = Buffer.from(`${JSON.stringify(event)}
16430
+ `);
16431
+ const at = this.nextOffset;
16432
+ this.nextOffset += bytes.length;
16433
+ const written = new Promise((resolve7, reject) => {
16434
+ this.queued.push({ bytes, resolve: resolve7, reject });
16435
+ });
16436
+ this.taken = written.catch(() => {
16437
+ });
16438
+ this.writing ??= this.writeQueued();
16439
+ return { at, written };
16440
+ }
16441
+ /** Settles once every record taken so far is on disk or dropped. */
16442
+ flush() {
16443
+ return this.taken;
16444
+ }
16445
+ firstFreeOffset() {
16446
+ return this.flushedEnd + (this.tornTail ? NEWLINE.length : 0);
16447
+ }
16448
+ async writeQueued() {
16449
+ try {
16450
+ while (this.queued.length > 0) {
16451
+ const batch = this.queued.splice(0);
16452
+ const bytes = Buffer.concat([...this.tornTail ? [NEWLINE] : [], ...batch.map((record3) => record3.bytes)]);
16453
+ try {
16454
+ await this.writeAtFlushedEnd(bytes);
16455
+ } catch (error) {
16456
+ const dropped = [...batch, ...this.queued.splice(0)];
16457
+ console.error(`[CodexHistoryFile] Dropped ${dropped.length} records that could not be written:`, error);
16458
+ this.nextOffset = this.firstFreeOffset();
16459
+ this.cutPending = true;
16460
+ await this.cutToFlushedEnd().catch(() => {
16461
+ });
16462
+ for (const record3 of dropped) record3.reject(error);
16463
+ continue;
16464
+ }
16465
+ this.tornTail = false;
16466
+ this.flushedEnd += bytes.length;
16467
+ for (const record3 of batch) record3.resolve();
16468
+ }
16469
+ } finally {
16470
+ this.writing = null;
16471
+ }
16472
+ }
16473
+ async writeAtFlushedEnd(bytes) {
16474
+ for (let attempt = 0; ; attempt += 1) {
16475
+ try {
16476
+ if (this.cutPending) await this.cutToFlushedEnd();
16477
+ const file = await open(this.filePath, constants.O_WRONLY | constants.O_CREAT);
16478
+ try {
16479
+ for (let written = 0; written < bytes.length; ) {
16480
+ written += (await file.write(bytes, written, bytes.length - written, this.flushedEnd + written)).bytesWritten;
16481
+ }
16482
+ await file.datasync();
16483
+ } finally {
16484
+ await file.close();
16485
+ }
16486
+ return;
16487
+ } catch (error) {
16488
+ const delay2 = WRITE_RETRY_DELAYS_MS[attempt];
16489
+ if (delay2 === void 0) throw error;
16490
+ await new Promise((resolve7) => setTimeout(resolve7, delay2));
16491
+ }
16492
+ }
16493
+ }
16494
+ async cutToFlushedEnd() {
16495
+ const file = await open(this.filePath, constants.O_WRONLY | constants.O_CREAT);
16496
+ try {
16497
+ await file.truncate(this.flushedEnd);
16498
+ await file.datasync();
16499
+ } finally {
16500
+ await file.close();
16501
+ }
16502
+ this.cutPending = false;
16503
+ }
16504
+ /**
16505
+ * Rewrites a file that still holds legacy Codex transcript records as plain
16506
+ * item events, once. The file is read line by line: a long-lived chat can
16507
+ * exceed the largest string V8 will hold. The rewritten file starts with a
16508
+ * format marker so later starts only read that first line.
16509
+ */
16510
+ async ensureItemEventFormat() {
16511
+ await this.flush();
16512
+ const firstLine = await this.readFirstLine();
16513
+ if (firstLine === null) {
16514
+ await this.record(codexHistoryFormatEvent()).written;
16515
+ return;
16516
+ }
16517
+ if (parseAgentEventJsonlLine(firstLine)?.type === CODEX_HISTORY_FORMAT_EVENT_TYPE) return;
16518
+ while (this.writing) await this.writing;
16519
+ const rewrite = this.rewriteAsItemEvents();
16520
+ this.writing = rewrite.then(() => this.writeQueued(), () => this.writeQueued());
16521
+ this.taken = this.writing;
16522
+ await rewrite;
16523
+ }
16524
+ async rewriteAsItemEvents() {
16525
+ const events = await this.loadAll();
16526
+ const rewritten = `${this.filePath}.migrating`;
16527
+ const handle = await open(rewritten, "w");
16528
+ let size = 0;
16529
+ try {
16530
+ let pending = "";
16531
+ for (const event of [codexHistoryFormatEvent(), ...events]) {
16532
+ pending += `${JSON.stringify(event)}
16533
+ `;
16534
+ if (pending.length >= MIGRATION_FLUSH_CHARS) {
16535
+ size += (await handle.write(pending)).bytesWritten;
16536
+ pending = "";
16537
+ }
16538
+ }
16539
+ if (pending) size += (await handle.write(pending)).bytesWritten;
16540
+ await handle.datasync();
16541
+ } finally {
16542
+ await handle.close();
16543
+ }
16544
+ const swap = rename(rewritten, this.filePath);
16545
+ this.swapping = swap.then(() => {
16546
+ }, () => {
16547
+ });
16548
+ this.swaps += 1;
16549
+ try {
16550
+ await swap;
16551
+ this.flushedEnd = size;
16552
+ this.tornTail = false;
16553
+ this.nextOffset = size + this.queued.reduce((total, record3) => total + record3.bytes.length, 0);
16554
+ } finally {
16555
+ this.swapping = null;
16556
+ }
16557
+ }
16558
+ /**
16559
+ * Newest event of `type`, scanning the whole file so a value older than the
16560
+ * most recent page is still found. Streams line by line and retains only the
16561
+ * match, so history size does not bound memory.
16562
+ */
16563
+ async findLastEventOfType(type) {
16564
+ return this.findLastEvent(type, (event) => event.type === type);
16565
+ }
16566
+ async findLastEvent(needle, matches) {
16567
+ let found = null;
16568
+ for await (const event of this.eventsFrom(0, [needle])) {
16569
+ if (matches(event)) found = event;
16570
+ }
16571
+ return found;
16572
+ }
16573
+ async *eventsFrom(start, needles) {
16574
+ const opened = await this.openAtFlushedEnd();
16575
+ if (!opened) return;
16576
+ try {
16577
+ for await (const line of this.lines(opened, start)) {
16578
+ if (!needles.some((needle) => line.includes(needle))) continue;
16579
+ const event = parseAgentEventJsonlLine(line);
16580
+ if (event) yield event;
16581
+ }
16582
+ } finally {
16583
+ await opened.file.close();
16584
+ }
16585
+ }
16586
+ async findSubagentItems() {
16587
+ const found = /* @__PURE__ */ new Map();
16588
+ for await (const event of this.eventsFrom(0, ['"subagent"'])) {
16589
+ const payload = event.type === CODEX_ITEM_EVENT_TYPE ? codexItemFromEvent(event) : null;
16590
+ if (payload?.item.type === "subagent") found.set(payload.item.id, { turnId: payload.turnId, item: payload.item });
16591
+ }
16592
+ return found;
16593
+ }
16594
+ async loadAll() {
16595
+ const folder = new CodexHistoryEventFolder();
16596
+ const opened = await this.openAtFlushedEnd();
16597
+ if (!opened) return folder.finish();
16598
+ try {
16599
+ for await (const line of this.lines(opened, 0)) {
16600
+ const event = parseAgentEventJsonlLine(line);
16601
+ if (event) folder.push(event);
16602
+ }
16603
+ } finally {
16604
+ await opened.file.close();
16605
+ }
16606
+ return folder.finish();
16607
+ }
16608
+ async loadEventsPage(page2) {
16609
+ if (page2.subagents) {
16610
+ const events = await this.read((size, readRange) => readChatSubagentHistory({ size, compact: page2.compact, readRange }));
16611
+ return { events: events ?? [], beforeCursor: null };
16612
+ }
16613
+ if (page2.limit === void 0) return { events: await this.loadAll() };
16614
+ const cursor = parseChatHistoryCursor(page2.beforeCursor);
16615
+ if (page2.beforeCursor !== void 0 && cursor?.mode !== "range") throw new RangeError("Invalid chat history cursor");
16616
+ if (cursor?.events === null) return { events: [], beforeCursor: null };
16617
+ const { limit } = page2;
16618
+ return await this.read(async (size, readRange) => {
16619
+ if (page2.afterCursor !== void 0 && cursor === void 0) {
16620
+ const appended = await readChatHistoryAppended({ size, after: page2.afterCursor, compact: page2.compact, readRange });
16621
+ if (appended) return { events: appended.items, afterCursor: appended.after, appendsAfter: page2.afterCursor };
16622
+ }
16623
+ const result = await readChatHistoryPage({
16624
+ size,
16625
+ limit,
16626
+ userTurns: page2.userTurns,
16627
+ compact: page2.compact,
16628
+ before: cursor?.events,
16629
+ readRange
16630
+ });
16631
+ return {
16632
+ events: result.items,
16633
+ beforeCursor: createChatHistoryCursor({ events: result.before, turns: null }),
16634
+ ...cursor === void 0 ? { afterCursor: String(size) } : {},
16635
+ ...page2.userTurns ? { userTurns: page2.userTurns } : {}
16636
+ };
16637
+ }) ?? { events: [], beforeCursor: null };
16638
+ }
16639
+ async readRecord(record3) {
16640
+ return await this.read((size, readRange) => readChatHistoryRecord({ size, record: record3, readRange })) ?? void 0;
16641
+ }
16642
+ async read(use) {
16643
+ const opened = await this.openAtFlushedEnd();
16644
+ if (!opened) return null;
16645
+ const { file, size } = opened;
16646
+ try {
16647
+ return await use(size, async (startByte, endByte) => {
16648
+ const bytes = Buffer.allocUnsafe(endByte - startByte);
16649
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, startByte);
16650
+ return bytes.subarray(0, bytesRead);
16651
+ });
16652
+ } finally {
16653
+ await file.close();
16654
+ }
16655
+ }
16656
+ async openAtFlushedEnd() {
16657
+ for (; ; ) {
16658
+ await this.swapping;
16659
+ const { swaps } = this;
16660
+ let file;
16661
+ try {
16662
+ file = await open(this.filePath, "r");
16663
+ } catch (error) {
16664
+ if (isMissingFile(error)) return null;
16665
+ throw error;
16666
+ }
16667
+ if (!this.swapping && this.swaps === swaps) return { file, size: this.flushedEnd };
16668
+ await file.close();
16669
+ }
16670
+ }
16671
+ async *lines({ file, size }, start) {
16672
+ const decoder = new StringDecoder("utf8");
16673
+ const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
16674
+ let rest = "";
16675
+ for (let at = start; at < size; ) {
16676
+ const { bytesRead } = await file.read(chunk, 0, Math.min(chunk.length, size - at), at);
16677
+ if (bytesRead === 0) break;
16678
+ at += bytesRead;
16679
+ const lines = (rest + decoder.write(chunk.subarray(0, bytesRead))).split("\n");
16680
+ rest = lines.pop() ?? "";
16681
+ yield* lines;
16682
+ }
16683
+ rest += decoder.end();
16684
+ if (rest) yield rest;
16685
+ }
16686
+ async readFirstLine() {
16687
+ let file;
16688
+ try {
16689
+ file = await open(this.filePath, "r");
16690
+ } catch (error) {
16691
+ if (isMissingFile(error)) return null;
16692
+ throw error;
16693
+ }
16694
+ try {
16695
+ const bytes = Buffer.allocUnsafe(4096);
16696
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
16697
+ if (bytesRead === 0) return null;
16698
+ const text = bytes.subarray(0, bytesRead).toString("utf-8");
16699
+ const newline = text.indexOf("\n");
16700
+ return newline === -1 ? text : text.slice(0, newline);
16701
+ } finally {
16702
+ await file.close();
16703
+ }
16625
16704
  }
16626
16705
  };
16627
16706
 
16628
16707
  // src/managers/cursor-manager.ts
16629
- import { mkdir as mkdir11, readFile as readFile9, readdir as readdir5 } from "fs/promises";
16630
- import { basename as basename2, dirname as dirname5, extname, join as join14 } from "path";
16708
+ import { readFile as readFile9, readdir as readdir5 } from "fs/promises";
16709
+ import { basename as basename2, extname, join as join14 } from "path";
16631
16710
  import { Agent as CursorAgent2, AuthenticationError, CursorSdkError } from "@cursor/sdk";
16632
16711
 
16633
16712
  // src/services/native-command-protection-hooks.ts
16634
16713
  import { existsSync as existsSync7 } from "fs";
16635
- import { mkdir as mkdir10, readFile as readFile8 } from "fs/promises";
16714
+ import { mkdir as mkdir9, readFile as readFile8 } from "fs/promises";
16636
16715
  import { basename, dirname as dirname4, join as join13 } from "path";
16637
16716
  import { fileURLToPath } from "url";
16638
16717
  var moduleDirectory = dirname4(fileURLToPath(import.meta.url));
@@ -16684,7 +16763,7 @@ async function ensureCursorCommandProtectionHook() {
16684
16763
  ...existingPost.filter((entry) => !isRecord2(entry) || typeof entry.command !== "string" || !entry.command.includes("post-tool-pr-hook")),
16685
16764
  { command: shellCommand(postToolHookPath) }
16686
16765
  ];
16687
- await mkdir10(dirname4(path7), { recursive: true });
16766
+ await mkdir9(dirname4(path7), { recursive: true });
16688
16767
  await atomicWriteFile(path7, `${JSON.stringify({ ...config, version: 1, hooks }, null, 2)}
16689
16768
  `);
16690
16769
  }
@@ -16786,23 +16865,15 @@ var CursorManager = class extends CodingAgentManager {
16786
16865
  reconnectNoticeVisible = false;
16787
16866
  instructionsDelivered = false;
16788
16867
  resumeSessionId = null;
16789
- historyFilePath;
16790
- historyFile;
16791
16868
  slashCommandsCache = null;
16792
16869
  slashCommandsRequest = null;
16793
16870
  constructor(options) {
16794
16871
  super(options);
16795
- this.historyFilePath = options.historyFilePath ?? join14(ENGINE_ENV.HOME_DIR, ".replicas", "cursor", "history.jsonl");
16796
- this.historyFile = new CodexHistoryFile(this.historyFilePath);
16797
16872
  this.initializeManager(this.processMessageInternal.bind(this));
16798
16873
  }
16799
16874
  async initialize() {
16800
- await mkdir11(dirname5(this.historyFilePath), { recursive: true });
16801
16875
  await ensureCursorCommandProtectionHook();
16802
16876
  }
16803
- getHistorySink() {
16804
- return this.historyFile;
16805
- }
16806
16877
  async interruptActiveTurn() {
16807
16878
  await this.cancelRun(this.activeRun);
16808
16879
  this.abortActiveTurn?.();
@@ -16821,7 +16892,7 @@ var CursorManager = class extends CodingAgentManager {
16821
16892
  const pending = run.steer(request.message).then((outcome) => {
16822
16893
  if (outcome !== "complete_delivered") return;
16823
16894
  const steer = this.markSteerRead(request.id);
16824
- if (steer) this.recordUserMessageHistoryEvent(steer, this.historyFile);
16895
+ if (steer) this.recordUserMessageHistoryEvent(steer);
16825
16896
  }).catch((error) => {
16826
16897
  console.error("[CursorManager] Failed to steer Cursor run:", error);
16827
16898
  }).finally(() => this.pendingSteers.delete(pending));
@@ -16954,7 +17025,7 @@ var CursorManager = class extends CodingAgentManager {
16954
17025
  }
16955
17026
  }, CURSOR_RECONNECT_NOTICE_DELAY_MS);
16956
17027
  agent = await this.ensureAgent(request);
16957
- this.recordUserMessageHistoryEvent(request, this.historyFile);
17028
+ this.recordUserMessageHistoryEvent(request);
16958
17029
  run = await sendCursorRun(agent, message, {
16959
17030
  model: { id: model },
16960
17031
  mode: request.planMode ? "plan" : "agent",
@@ -16985,7 +17056,7 @@ var CursorManager = class extends CodingAgentManager {
16985
17056
  if (next.done) break;
16986
17057
  markCursorActivity();
16987
17058
  const event = next.value;
16988
- this.recordHistoryEvent(`cursor-${event.type}`, event, this.historyFile);
17059
+ this.recordHistoryEvent(`cursor-${event.type}`, event);
16989
17060
  const linearSessionId = this.linearSessionId;
16990
17061
  if (linearSessionId) {
16991
17062
  linearForwarder.sendEvent(convertCursorEvent(event, linearSessionId));
@@ -17061,13 +17132,13 @@ var CursorManager = class extends CodingAgentManager {
17061
17132
  ...failure.code ? { code: failure.code } : {},
17062
17133
  ...failure.runId ? { runId: failure.runId } : {},
17063
17134
  ...failure.requestId ? { requestId: failure.requestId } : {}
17064
- }, this.historyFile);
17135
+ });
17065
17136
  } catch (error) {
17066
17137
  await this.cancelRun(run);
17067
17138
  this.recordHistoryEvent("cursor-error", {
17068
17139
  type: "error",
17069
17140
  message: error instanceof Error ? error.message : String(error)
17070
- }, this.historyFile);
17141
+ });
17071
17142
  } finally {
17072
17143
  clearReconnectNoticeTimer();
17073
17144
  this.setReconnectNoticeVisible(false);
@@ -17161,21 +17232,17 @@ ${instructions}
17161
17232
  categories,
17162
17233
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
17163
17234
  };
17164
- this.historyFile.append(this.emitContextUsage(payload));
17235
+ this.recordContextUsage(payload);
17165
17236
  }
17166
17237
  };
17167
17238
 
17168
17239
  // src/managers/muse-manager.ts
17169
- import { mkdir as mkdir12 } from "fs/promises";
17170
- import { dirname as dirname6 } from "path";
17171
17240
  var MuseQuotaError = class extends Error {
17172
17241
  };
17173
17242
  function isPendingQuestion(value) {
17174
17243
  return isRecord(value) && typeof value.id === "string";
17175
17244
  }
17176
17245
  var MuseManager = class extends CodingAgentManager {
17177
- historyFile;
17178
- historyFilePath;
17179
17246
  process = null;
17180
17247
  client = null;
17181
17248
  sessionId = null;
@@ -17190,17 +17257,9 @@ var MuseManager = class extends CodingAgentManager {
17190
17257
  slashCommands = null;
17191
17258
  constructor(options) {
17192
17259
  super({ ...options, provider: "muse" });
17193
- this.historyFilePath = options.historyFilePath;
17194
- this.historyFile = new CodexHistoryFile(options.historyFilePath);
17195
17260
  this.sessionId = options.initialSessionId;
17196
17261
  this.initializeManager(this.processMessageInternal.bind(this));
17197
17262
  }
17198
- async initialize() {
17199
- await mkdir12(dirname6(this.historyFilePath), { recursive: true });
17200
- }
17201
- getHistorySink() {
17202
- return this.historyFile;
17203
- }
17204
17263
  async start(model) {
17205
17264
  if (this.process) return;
17206
17265
  const { child, client } = spawnMuseMsp(this.workingDirectory, this.originChatId ? { REPLICAS_CHAT_ID: this.originChatId } : void 0);
@@ -17272,7 +17331,7 @@ var MuseManager = class extends CodingAgentManager {
17272
17331
  selectionId: choice ? JSON.stringify({ approval: { options: [choice.choiceId] } }) : selectionId,
17273
17332
  selectionSummary: choice?.label,
17274
17333
  parent_tool_use_id: null
17275
- }, this.historyFile);
17334
+ });
17276
17335
  }
17277
17336
  handleApproval(params) {
17278
17337
  if (!this.sessionId || params.sessionId !== this.sessionId || typeof params.approvalId !== "string" || this.resolvedApprovals.has(params.approvalId)) return;
@@ -17318,10 +17377,10 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17318
17377
  options: choices.map((choice) => ({ id: choice.choiceId, label: choice.label, ...choice.rulePreview ? { preview: choice.rulePreview } : {} }))
17319
17378
  }],
17320
17379
  parent_tool_use_id: null
17321
- }, this.historyFile);
17380
+ });
17322
17381
  this.recordHistoryEvent("muse-item-started", {
17323
17382
  item: { itemId: pending.itemId, kind: "toolCall", tool: pending.toolName, args: pending.rawArgs, status: "inProgress" }
17324
- }, this.historyFile);
17383
+ });
17325
17384
  }
17326
17385
  handleProcessExit(child, error) {
17327
17386
  if (this.process !== child) return;
@@ -17332,7 +17391,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17332
17391
  for (const approvalId of this.pendingApprovals.keys()) this.resolveApproval(approvalId, "aborted");
17333
17392
  this.resolvedApprovals.clear();
17334
17393
  if (this.turnComplete && !hadPendingRequest) {
17335
- this.recordHistoryEvent("muse-error", { message: error.message }, this.historyFile);
17394
+ this.recordHistoryEvent("muse-error", { message: error.message });
17336
17395
  }
17337
17396
  this.turnComplete?.resolve();
17338
17397
  this.turnComplete = null;
@@ -17360,7 +17419,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17360
17419
  handleNotification(frame) {
17361
17420
  if (!isRecord(frame) || typeof frame.method !== "string" || !isRecord(frame.params)) return;
17362
17421
  if (typeof frame.params.sessionId === "string" && this.sessionId && frame.params.sessionId !== this.sessionId) return;
17363
- this.recordHistoryEvent(`muse-${frame.method.replaceAll("/", "-")}`, frame.params, this.historyFile);
17422
+ this.recordHistoryEvent(`muse-${frame.method.replaceAll("/", "-")}`, frame.params);
17364
17423
  if (frame.method === "approval/requested" || frame.method === "approval/updated") {
17365
17424
  this.handleApproval(frame.params);
17366
17425
  } else if (frame.method === "approval/resolved" && typeof frame.params.approvalId === "string") {
@@ -17382,7 +17441,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17382
17441
  } else if (frame.method === "session/contextUsage") {
17383
17442
  const used = typeof frame.params.usedTokens === "number" ? frame.params.usedTokens : 0;
17384
17443
  const size = typeof frame.params.windowTokens === "number" ? frame.params.windowTokens : 0;
17385
- this.historyFile.append(this.emitContextUsage({
17444
+ this.recordContextUsage({
17386
17445
  provider: "muse",
17387
17446
  source: "provider_usage",
17388
17447
  model: DEFAULT_MUSE_MODEL,
@@ -17391,7 +17450,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17391
17450
  percentage: size > 0 ? used / size * 100 : 0,
17392
17451
  categories: [],
17393
17452
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
17394
- }));
17453
+ });
17395
17454
  } else if (frame.method === "userInput/requested" && typeof frame.params.userInputId === "string") {
17396
17455
  const questions = Array.isArray(frame.params.questions) ? frame.params.questions.filter(isPendingQuestion) : [];
17397
17456
  this.pendingInput = {
@@ -17415,7 +17474,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17415
17474
  }] : [])
17416
17475
  })),
17417
17476
  parent_tool_use_id: null
17418
- }, this.historyFile);
17477
+ });
17419
17478
  }
17420
17479
  }
17421
17480
  async processMessageInternal(request, signal) {
@@ -17427,7 +17486,6 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17427
17486
  if (!userMessageRecorded) {
17428
17487
  this.recordUserMessageHistoryEvent(
17429
17488
  request,
17430
- this.historyFile,
17431
17489
  /^\/compact$/i.test(request.message.trim()) ? { command: "compact" } : {}
17432
17490
  );
17433
17491
  userMessageRecorded = true;
@@ -17493,7 +17551,7 @@ ${pending}
17493
17551
  if (retryError instanceof MuseQuotaError) return;
17494
17552
  this.recordHistoryEvent("muse-error", {
17495
17553
  message: retryError instanceof Error ? retryError.message : String(retryError)
17496
- }, this.historyFile);
17554
+ });
17497
17555
  throw retryError;
17498
17556
  }
17499
17557
  } else if (fallback.outcome === "fork") {
@@ -17501,7 +17559,7 @@ ${pending}
17501
17559
  }
17502
17560
  return;
17503
17561
  }
17504
- this.recordHistoryEvent("muse-error", { message: error instanceof Error ? error.message : String(error) }, this.historyFile);
17562
+ this.recordHistoryEvent("muse-error", { message: error instanceof Error ? error.message : String(error) });
17505
17563
  throw error;
17506
17564
  } finally {
17507
17565
  this.turnComplete?.resolve();
@@ -17588,7 +17646,7 @@ ${pending}
17588
17646
  toolName: "request_user_input",
17589
17647
  selectionId: selectionId === "declined" ? "aborted" : selectionId,
17590
17648
  parent_tool_use_id: null
17591
- }, this.historyFile);
17649
+ });
17592
17650
  return true;
17593
17651
  }
17594
17652
  isAwaitingInput() {
@@ -17633,8 +17691,8 @@ ${pending}
17633
17691
 
17634
17692
  // src/managers/opencode-manager.ts
17635
17693
  import { existsSync as existsSync8 } from "fs";
17636
- import { copyFile, mkdir as mkdir13, readFile as readFile10, rm as rm4 } from "fs/promises";
17637
- import { delimiter, dirname as dirname7, join as join15 } from "path";
17694
+ import { copyFile, mkdir as mkdir10, readFile as readFile10, rm as rm4 } from "fs/promises";
17695
+ import { delimiter, dirname as dirname5, join as join15 } from "path";
17638
17696
  import { randomBytes as randomBytes2 } from "crypto";
17639
17697
  import { fileURLToPath as fileURLToPath2 } from "url";
17640
17698
  import { Agent } from "undici";
@@ -17661,7 +17719,7 @@ async function getAllowedOpenRouterModels() {
17661
17719
  }
17662
17720
 
17663
17721
  // src/managers/opencode-manager.ts
17664
- var OPENCODE_SHIM_DIR = dirname7(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
17722
+ var OPENCODE_SHIM_DIR = dirname5(fileURLToPath2(new URL("../../scripts/opencode", import.meta.url)));
17665
17723
  var OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE = join15(OPENCODE_SHIM_DIR, "opencode-command-protection-plugin.ts");
17666
17724
  var OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.ts");
17667
17725
  var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "plugins", "replicas-command-protection.mjs");
@@ -17798,8 +17856,6 @@ var OpencodeManager = class extends CodingAgentManager {
17798
17856
  server = null;
17799
17857
  dispatcher = null;
17800
17858
  sessionId = null;
17801
- historyFilePath;
17802
- historyFile;
17803
17859
  activeAbortController = null;
17804
17860
  configuredModels = /* @__PURE__ */ new Set();
17805
17861
  clientUpdate = Promise.resolve();
@@ -17824,16 +17880,8 @@ var OpencodeManager = class extends CodingAgentManager {
17824
17880
  constructor(options) {
17825
17881
  super({ ...options, provider: "opencode" });
17826
17882
  this.sessionId = options.initialSessionId;
17827
- this.historyFilePath = options.historyFilePath ?? join15(ENGINE_ENV.HOME_DIR, ".replicas", "opencode", "history.jsonl");
17828
- this.historyFile = new CodexHistoryFile(this.historyFilePath);
17829
17883
  this.initializeManager(this.processMessageInternal.bind(this));
17830
17884
  }
17831
- async initialize() {
17832
- await mkdir13(dirname7(this.historyFilePath), { recursive: true });
17833
- }
17834
- getHistorySink() {
17835
- return this.historyFile;
17836
- }
17837
17885
  async interruptActiveTurn() {
17838
17886
  try {
17839
17887
  await this.abortActiveTurn();
@@ -17930,7 +17978,7 @@ var OpencodeManager = class extends CodingAgentManager {
17930
17978
  if (!existsSync8(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE)) {
17931
17979
  throw new Error("Opencode command protection plugin is missing from the engine package.");
17932
17980
  }
17933
- await mkdir13(dirname7(OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH), { recursive: true });
17981
+ await mkdir10(dirname5(OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH), { recursive: true });
17934
17982
  await copyFile(OPENCODE_COMMAND_PROTECTION_PLUGIN_SOURCE, OPENCODE_COMMAND_PROTECTION_PLUGIN_PATH);
17935
17983
  await rm4(OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH, { force: true });
17936
17984
  process.env.REPLICAS_COMMAND_PROTECTION_HOOK_PATH = getCommandProtectionHookPath();
@@ -17990,7 +18038,7 @@ var OpencodeManager = class extends CodingAgentManager {
17990
18038
  this.resolveEventSubscriptionReady?.();
17991
18039
  this.resolveEventSubscriptionReady = null;
17992
18040
  console.error("[OpencodeManager] Event subscription failed:", error);
17993
- this.recordHistoryEvent("opencode-error", opencodeErrorPayload(error), this.historyFile);
18041
+ this.recordHistoryEvent("opencode-error", opencodeErrorPayload(error));
17994
18042
  });
17995
18043
  await Promise.race([
17996
18044
  this.eventSubscriptionReady,
@@ -18078,7 +18126,7 @@ var OpencodeManager = class extends CodingAgentManager {
18078
18126
  const variant = await this.getThinkingVariant(client, providerID, modelID, request.thinkingLevel);
18079
18127
  const sessionId = await this.ensureSession(client, providerID, modelID, agent, variant);
18080
18128
  const system = this.buildCombinedInstructions(request.customInstructions);
18081
- if (!retry) this.recordUserMessageHistoryEvent(request, this.historyFile);
18129
+ if (!retry) this.recordUserMessageHistoryEvent(request);
18082
18130
  const result = await client.session.prompt({
18083
18131
  sessionID: sessionId,
18084
18132
  directory: this.workingDirectory,
@@ -18093,10 +18141,10 @@ var OpencodeManager = class extends CodingAgentManager {
18093
18141
  },
18094
18142
  parts: [{ type: "text", text: retry ? OPENCODE_SWITCHED_CREDENTIAL_PROMPT : request.message }]
18095
18143
  }, { signal: controller.signal, throwOnError: true });
18096
- this.recordHistoryEvent("opencode-message.updated", { info: result.data.info }, this.historyFile);
18144
+ this.recordHistoryEvent("opencode-message.updated", { info: result.data.info });
18097
18145
  for (const part of result.data.parts) this.recordOpencodePart(part);
18098
18146
  linearForwarder.flushThoughtAsResponse();
18099
- this.recordHistoryEvent("opencode-session.idle", { sessionID: sessionId }, this.historyFile);
18147
+ this.recordHistoryEvent("opencode-session.idle", { sessionID: sessionId });
18100
18148
  } catch (error) {
18101
18149
  const credentialSwitch = this.credentialSwitch;
18102
18150
  if (credentialSwitch) {
@@ -18106,10 +18154,10 @@ var OpencodeManager = class extends CodingAgentManager {
18106
18154
  if (!signal.aborted) return true;
18107
18155
  }
18108
18156
  if (controller.signal.aborted) {
18109
- this.recordHistoryEvent("opencode-session.idle", { sessionID: this.sessionId }, this.historyFile);
18157
+ this.recordHistoryEvent("opencode-session.idle", { sessionID: this.sessionId });
18110
18158
  } else {
18111
18159
  console.error("[OpencodeManager] Turn failed:", error);
18112
- this.recordHistoryEvent("opencode-error", opencodeErrorPayload(error), this.historyFile);
18160
+ this.recordHistoryEvent("opencode-error", opencodeErrorPayload(error));
18113
18161
  }
18114
18162
  } finally {
18115
18163
  for (const requestId of this.pendingQuestions.keys()) this.resolveQuestion(requestId, "aborted");
@@ -18164,7 +18212,7 @@ var OpencodeManager = class extends CodingAgentManager {
18164
18212
  });
18165
18213
  }
18166
18214
  if (this.recordOpencodeNextPart(event.type, payload)) return;
18167
- this.recordHistoryEvent(`opencode-${event.type}`, payload, this.historyFile);
18215
+ this.recordHistoryEvent(`opencode-${event.type}`, payload);
18168
18216
  }
18169
18217
  recordQuestion(request) {
18170
18218
  this.pendingQuestions.set(request.id, request);
@@ -18180,7 +18228,7 @@ var OpencodeManager = class extends CodingAgentManager {
18180
18228
  options: question.options.map((option) => ({ id: option.label, label: option.label, description: option.description }))
18181
18229
  })),
18182
18230
  parent_tool_use_id: null
18183
- }, this.historyFile);
18231
+ });
18184
18232
  }
18185
18233
  resolveQuestion(requestId, selectionId) {
18186
18234
  const request = this.pendingQuestions.get(requestId);
@@ -18192,7 +18240,7 @@ var OpencodeManager = class extends CodingAgentManager {
18192
18240
  toolName: "question",
18193
18241
  selectionId,
18194
18242
  parent_tool_use_id: null
18195
- }, this.historyFile);
18243
+ });
18196
18244
  }
18197
18245
  async respondToToolInput(requestId, selectionId) {
18198
18246
  const request = this.pendingQuestions.get(requestId);
@@ -18223,7 +18271,7 @@ var OpencodeManager = class extends CodingAgentManager {
18223
18271
  await this.credentialSwitch;
18224
18272
  return;
18225
18273
  }
18226
- this.recordHistoryEvent("opencode-error", { message, code: "account_rate_limit" }, this.historyFile);
18274
+ this.recordHistoryEvent("opencode-error", { message, code: "account_rate_limit" });
18227
18275
  this.emitQuotaExhausted({
18228
18276
  provider: "opencode",
18229
18277
  reason: "rate_limit",
@@ -18325,14 +18373,14 @@ var OpencodeManager = class extends CodingAgentManager {
18325
18373
  }
18326
18374
  recordOpencodePart(part) {
18327
18375
  if (part.type === "step-finish") this.onUsageUpdate(part, (/* @__PURE__ */ new Date()).toISOString());
18328
- this.recordHistoryEvent(`opencode-part-${part.type}`, { part }, this.historyFile);
18376
+ this.recordHistoryEvent(`opencode-part-${part.type}`, { part });
18329
18377
  this.forwardOpencodePartToLinear(part);
18330
18378
  }
18331
18379
  };
18332
18380
 
18333
18381
  // src/managers/pi-manager.ts
18334
- import { mkdir as mkdir15, readFile as readFile11 } from "fs/promises";
18335
- import { dirname as dirname15, join as join22 } from "path";
18382
+ import { readFile as readFile11 } from "fs/promises";
18383
+ import { join as join22 } from "path";
18336
18384
  import {
18337
18385
  createAgentSession,
18338
18386
  ModelRegistry,
@@ -29468,9 +29516,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29468
29516
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
29469
29517
  return `${varKind} ${this.name}${rhs};` + _n;
29470
29518
  }
29471
- optimizeNames(names, constants) {
29519
+ optimizeNames(names, constants2) {
29472
29520
  if (!names[this.name.str]) return;
29473
- if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants);
29521
+ if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants2);
29474
29522
  return this;
29475
29523
  }
29476
29524
  get names() {
@@ -29487,9 +29535,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29487
29535
  render({ _n }) {
29488
29536
  return `${this.lhs} = ${this.rhs};` + _n;
29489
29537
  }
29490
- optimizeNames(names, constants) {
29538
+ optimizeNames(names, constants2) {
29491
29539
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
29492
- this.rhs = optimizeExpr(this.rhs, names, constants);
29540
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
29493
29541
  return this;
29494
29542
  }
29495
29543
  get names() {
@@ -29548,8 +29596,8 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29548
29596
  optimizeNodes() {
29549
29597
  return `${this.code}` ? this : void 0;
29550
29598
  }
29551
- optimizeNames(names, constants) {
29552
- this.code = optimizeExpr(this.code, names, constants);
29599
+ optimizeNames(names, constants2) {
29600
+ this.code = optimizeExpr(this.code, names, constants2);
29553
29601
  return this;
29554
29602
  }
29555
29603
  get names() {
@@ -29575,12 +29623,12 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29575
29623
  }
29576
29624
  return nodes.length > 0 ? this : void 0;
29577
29625
  }
29578
- optimizeNames(names, constants) {
29626
+ optimizeNames(names, constants2) {
29579
29627
  const { nodes } = this;
29580
29628
  let i = nodes.length;
29581
29629
  while (i--) {
29582
29630
  const n = nodes[i];
29583
- if (n.optimizeNames(names, constants)) continue;
29631
+ if (n.optimizeNames(names, constants2)) continue;
29584
29632
  subtractNames(names, n.names);
29585
29633
  nodes.splice(i, 1);
29586
29634
  }
@@ -29627,11 +29675,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29627
29675
  if (cond === false || !this.nodes.length) return void 0;
29628
29676
  return this;
29629
29677
  }
29630
- optimizeNames(names, constants) {
29678
+ optimizeNames(names, constants2) {
29631
29679
  var _a;
29632
- this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
29633
- if (!(super.optimizeNames(names, constants) || this.else)) return;
29634
- this.condition = optimizeExpr(this.condition, names, constants);
29680
+ this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants2);
29681
+ if (!(super.optimizeNames(names, constants2) || this.else)) return;
29682
+ this.condition = optimizeExpr(this.condition, names, constants2);
29635
29683
  return this;
29636
29684
  }
29637
29685
  get names() {
@@ -29653,9 +29701,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29653
29701
  render(opts) {
29654
29702
  return `for(${this.iteration})` + super.render(opts);
29655
29703
  }
29656
- optimizeNames(names, constants) {
29657
- if (!super.optimizeNames(names, constants)) return;
29658
- this.iteration = optimizeExpr(this.iteration, names, constants);
29704
+ optimizeNames(names, constants2) {
29705
+ if (!super.optimizeNames(names, constants2)) return;
29706
+ this.iteration = optimizeExpr(this.iteration, names, constants2);
29659
29707
  return this;
29660
29708
  }
29661
29709
  get names() {
@@ -29690,9 +29738,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29690
29738
  render(opts) {
29691
29739
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
29692
29740
  }
29693
- optimizeNames(names, constants) {
29694
- if (!super.optimizeNames(names, constants)) return;
29695
- this.iterable = optimizeExpr(this.iterable, names, constants);
29741
+ optimizeNames(names, constants2) {
29742
+ if (!super.optimizeNames(names, constants2)) return;
29743
+ this.iterable = optimizeExpr(this.iterable, names, constants2);
29696
29744
  return this;
29697
29745
  }
29698
29746
  get names() {
@@ -29731,11 +29779,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29731
29779
  (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
29732
29780
  return this;
29733
29781
  }
29734
- optimizeNames(names, constants) {
29782
+ optimizeNames(names, constants2) {
29735
29783
  var _a, _b;
29736
- super.optimizeNames(names, constants);
29737
- (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants);
29738
- (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants);
29784
+ super.optimizeNames(names, constants2);
29785
+ (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants2);
29786
+ (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants2);
29739
29787
  return this;
29740
29788
  }
29741
29789
  get names() {
@@ -29984,7 +30032,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29984
30032
  function addExprNames(names, from) {
29985
30033
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
29986
30034
  }
29987
- function optimizeExpr(expr, names, constants) {
30035
+ function optimizeExpr(expr, names, constants2) {
29988
30036
  if (expr instanceof code_1.Name) return replaceName(expr);
29989
30037
  if (!canOptimize(expr)) return expr;
29990
30038
  return new code_1._Code(expr._items.reduce((items, c) => {
@@ -29994,13 +30042,13 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
29994
30042
  return items;
29995
30043
  }, []));
29996
30044
  function replaceName(n) {
29997
- const c = constants[n.str];
30045
+ const c = constants2[n.str];
29998
30046
  if (c === void 0 || names[n.str] !== 1) return n;
29999
30047
  delete names[n.str];
30000
30048
  return c;
30001
30049
  }
30002
30050
  function canOptimize(e) {
30003
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
30051
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
30004
30052
  }
30005
30053
  }
30006
30054
  function subtractNames(names, from) {
@@ -36438,11 +36486,11 @@ var EventSource = class extends EventTarget {
36438
36486
  return;
36439
36487
  }
36440
36488
  const decoder = new TextDecoder(), reader = body.getReader();
36441
- let open4 = true;
36489
+ let open3 = true;
36442
36490
  do {
36443
36491
  const { done, value } = await reader.read();
36444
- value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open4 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
36445
- } while (open4);
36492
+ value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open3 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
36493
+ } while (open3);
36446
36494
  }), __privateAdd(this, _onFetchError, (err) => {
36447
36495
  __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
36448
36496
  }), __privateAdd(this, _onEvent, (event) => {
@@ -40717,7 +40765,7 @@ var StreamableHTTPClientTransport = class {
40717
40765
  };
40718
40766
 
40719
40767
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/server-manager.ts
40720
- import { mkdirSync as mkdirSync3, statSync as statSync3 } from "fs";
40768
+ import { mkdirSync as mkdirSync4, statSync as statSync2 } from "fs";
40721
40769
  import { isDeepStrictEqual } from "util";
40722
40770
 
40723
40771
  // ../node_modules/.bun/@modelcontextprotocol+client@2.3.0/node_modules/@modelcontextprotocol/client/dist/stdio.mjs
@@ -41156,8 +41204,8 @@ async function probeMcpEndpoint(url3) {
41156
41204
  }
41157
41205
 
41158
41206
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/npx-resolver.ts
41159
- import { existsSync as existsSync9, readFileSync as readFileSync2, realpathSync, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync3, renameSync, mkdirSync as mkdirSync2, openSync, readSync, closeSync, unlinkSync } from "fs";
41160
- import { join as join16, dirname as dirname8, extname as extname2, resolve as resolve2, sep } from "path";
41207
+ import { existsSync as existsSync9, readFileSync as readFileSync2, realpathSync, readdirSync as readdirSync2, statSync, writeFileSync as writeFileSync3, renameSync, mkdirSync as mkdirSync3, openSync as openSync2, readSync as readSync2, closeSync as closeSync2, unlinkSync } from "fs";
41208
+ import { join as join16, dirname as dirname6, extname as extname2, resolve as resolve2, sep } from "path";
41161
41209
 
41162
41210
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/abort.ts
41163
41211
  function throwIfAborted(signal) {
@@ -41486,14 +41534,14 @@ function detectJsBinary(binPath) {
41486
41534
  const ext = extname2(binPath).toLowerCase();
41487
41535
  if (ext === ".js" || ext === ".mjs" || ext === ".cjs") return true;
41488
41536
  try {
41489
- const fd = openSync(binPath, "r");
41537
+ const fd = openSync2(binPath, "r");
41490
41538
  try {
41491
41539
  const buf = Buffer.alloc(256);
41492
- readSync(fd, buf, 0, 256, 0);
41540
+ readSync2(fd, buf, 0, 256, 0);
41493
41541
  const firstLine = buf.toString("utf-8").split("\n")[0] ?? "";
41494
41542
  return firstLine.startsWith("#!") && firstLine.includes("node");
41495
41543
  } finally {
41496
- closeSync(fd);
41544
+ closeSync2(fd);
41497
41545
  }
41498
41546
  } catch {
41499
41547
  return false;
@@ -41585,8 +41633,8 @@ function loadCache() {
41585
41633
  function saveCacheEntry(key, entry) {
41586
41634
  try {
41587
41635
  const cachePath = getNpxCachePath();
41588
- const dir = dirname8(cachePath);
41589
- mkdirSync2(dir, { recursive: true });
41636
+ const dir = dirname6(cachePath);
41637
+ mkdirSync3(dir, { recursive: true });
41590
41638
  const existing = toNpxCache(readNpxCachePayload(cachePath));
41591
41639
  const entries = createCacheEntries();
41592
41640
  if (existing) Object.assign(entries, existing.entries);
@@ -41607,7 +41655,7 @@ function safeRealpath(path7) {
41607
41655
  }
41608
41656
  function safeStatMtime(path7) {
41609
41657
  try {
41610
- return statSync2(path7).mtimeMs;
41658
+ return statSync(path7).mtimeMs;
41611
41659
  } catch {
41612
41660
  return 0;
41613
41661
  }
@@ -41672,7 +41720,7 @@ import { spawnSync } from "child_process";
41672
41720
  import { createHash as createHash3 } from "crypto";
41673
41721
  import { createRequire } from "module";
41674
41722
  import { readFileSync as readFileSync3, existsSync as existsSync10, rmSync as rmSync2 } from "fs";
41675
- import { dirname as dirname9, join as join17 } from "path";
41723
+ import { dirname as dirname7, join as join17 } from "path";
41676
41724
  import { fileURLToPath as fileURLToPath3 } from "url";
41677
41725
  var require2 = createRequire(import.meta.url);
41678
41726
  var AUTH_SECRET_SERVICE = "pi-mcp-adapter.oauth";
@@ -41828,7 +41876,7 @@ function loadKeyringNativeBindingFallback(keyringRequire, platform3, arch2) {
41828
41876
  for (const target of targets) {
41829
41877
  try {
41830
41878
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
41831
- return keyringRequire(join17(dirname9(packageJsonPath), target.bindingFile));
41879
+ return keyringRequire(join17(dirname7(packageJsonPath), target.bindingFile));
41832
41880
  } catch (error) {
41833
41881
  lastError = error;
41834
41882
  }
@@ -44545,7 +44593,7 @@ async function shutdownOAuth(runtime = legacyRuntime) {
44545
44593
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/mcp-bearer-store.ts
44546
44594
  import { createHash as createHash4 } from "crypto";
44547
44595
  import { createRequire as createRequire2 } from "module";
44548
- import { dirname as dirname10, join as join18 } from "path";
44596
+ import { dirname as dirname8, join as join18 } from "path";
44549
44597
  var require3 = createRequire2(import.meta.url);
44550
44598
  var BEARER_SECRET_SERVICE = "pi-mcp-adapter.bearer";
44551
44599
  var TEST_AUTH_STORE_ENV2 = "PI_MCP_ADAPTER_TEST_AUTH_STORE";
@@ -44647,7 +44695,7 @@ function loadKeyringNativeBindingFallback2(keyringRequire, platform3, arch2) {
44647
44695
  for (const target of targets) {
44648
44696
  try {
44649
44697
  const packageJsonPath = keyringRequire.resolve(`${target.packageName}/package.json`);
44650
- return keyringRequire(join18(dirname10(packageJsonPath), target.bindingFile));
44698
+ return keyringRequire(join18(dirname8(packageJsonPath), target.bindingFile));
44651
44699
  } catch (error) {
44652
44700
  lastError = error;
44653
44701
  }
@@ -45259,9 +45307,9 @@ function humanizeName(name) {
45259
45307
  }
45260
45308
 
45261
45309
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/mcp-trace.ts
45262
- import { appendFile as appendFile3, mkdir as mkdir14, writeFile as writeFile6 } from "fs/promises";
45310
+ import { appendFile as appendFile2, mkdir as mkdir11, writeFile as writeFile6 } from "fs/promises";
45263
45311
  import { Buffer as Buffer3 } from "buffer";
45264
- import { dirname as dirname11, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
45312
+ import { dirname as dirname9, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
45265
45313
  var MCP_TRACE_SCHEMA_VERSION = 1;
45266
45314
  var DEFAULT_MCP_TRACE_MAX_BYTES = 256 * 1024;
45267
45315
  var DEFAULT_MCP_TRACE_MAX_EVENTS = 1e4;
@@ -45325,16 +45373,16 @@ var McpTraceWriter = class {
45325
45373
  this.maxBytes = boundedPositiveInteger(options.maxBytes, DEFAULT_MCP_TRACE_MAX_BYTES);
45326
45374
  this.maxEvents = boundedPositiveInteger(options.maxEvents, DEFAULT_MCP_TRACE_MAX_EVENTS);
45327
45375
  this.append = options.appendFile ?? (async (path7, data, appendOptions) => {
45328
- await appendFile3(path7, data, appendOptions);
45376
+ await appendFile2(path7, data, appendOptions);
45329
45377
  });
45330
45378
  this.resetFile = options.writeFile ?? (async (path7, data, writeOptions) => {
45331
45379
  await writeFile6(path7, data, writeOptions);
45332
45380
  });
45333
45381
  this.makeDirectory = options.mkdir ?? (async (path7) => {
45334
- await mkdir14(path7, { recursive: true });
45382
+ await mkdir11(path7, { recursive: true });
45335
45383
  return void 0;
45336
45384
  });
45337
- this.fileReady = this.makeDirectory(dirname11(this.options.filePath), { recursive: true }).then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" })).catch(() => {
45385
+ this.fileReady = this.makeDirectory(dirname9(this.options.filePath), { recursive: true }).then(() => this.resetFile(this.options.filePath, "", { encoding: "utf8" })).catch(() => {
45338
45386
  this.initializationFailed = true;
45339
45387
  this.disabled = true;
45340
45388
  });
@@ -46259,7 +46307,7 @@ var McpServerManager = class {
46259
46307
  let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
46260
46308
  const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
46261
46309
  if (cwd !== void 0) {
46262
- const cwdStats = statSync3(cwd, { throwIfNoEntry: false });
46310
+ const cwdStats = statSync2(cwd, { throwIfNoEntry: false });
46263
46311
  if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
46264
46312
  if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
46265
46313
  }
@@ -46272,7 +46320,7 @@ var McpServerManager = class {
46272
46320
  }
46273
46321
  }
46274
46322
  throwIfAborted(signal);
46275
- if (definition.pluginDataDir) mkdirSync3(definition.pluginDataDir, { recursive: true });
46323
+ if (definition.pluginDataDir) mkdirSync4(definition.pluginDataDir, { recursive: true });
46276
46324
  const stdioTransport = new StdioClientTransport({
46277
46325
  command,
46278
46326
  args,
@@ -48459,8 +48507,8 @@ function getEffectiveIdleTimeoutMinutes(state, serverName) {
48459
48507
  }
48460
48508
 
48461
48509
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/onboarding-state.ts
48462
- import { existsSync as existsSync12, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4, renameSync as renameSync2 } from "fs";
48463
- import { dirname as dirname12 } from "path";
48510
+ import { existsSync as existsSync12, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync4, renameSync as renameSync2 } from "fs";
48511
+ import { dirname as dirname10 } from "path";
48464
48512
  var DEFAULT_STATE = {
48465
48513
  version: 1,
48466
48514
  sharedConfigHintShown: false,
@@ -48487,7 +48535,7 @@ function loadOnboardingState() {
48487
48535
  }
48488
48536
  function saveOnboardingState(state) {
48489
48537
  const path7 = getOnboardingStatePath();
48490
- mkdirSync4(dirname12(path7), { recursive: true });
48538
+ mkdirSync5(dirname10(path7), { recursive: true });
48491
48539
  const tmpPath = `${path7}.${process.pid}.tmp`;
48492
48540
  writeFileSync4(tmpPath, `${JSON.stringify(state, null, 2)}
48493
48541
  `, "utf-8");
@@ -49318,7 +49366,7 @@ function stringifyStructuredContent(value) {
49318
49366
  import { randomBytes as randomBytes3 } from "crypto";
49319
49367
  import { mkdtemp, rm as rm5, writeFile as writeFile7 } from "fs/promises";
49320
49368
  import { tmpdir as tmpdir2 } from "os";
49321
- import { dirname as dirname13, join as join20 } from "path";
49369
+ import { dirname as dirname11, join as join20 } from "path";
49322
49370
  var DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
49323
49371
  var DEFAULT_MCP_OUTPUT_MAX_LINES = 2e3;
49324
49372
  var DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
@@ -49636,7 +49684,7 @@ async function saveArtifact(kind, text) {
49636
49684
  }
49637
49685
  async function discardArtifact(path7) {
49638
49686
  try {
49639
- await rm5(dirname13(path7), { recursive: true, force: true });
49687
+ await rm5(dirname11(path7), { recursive: true, force: true });
49640
49688
  } catch {
49641
49689
  }
49642
49690
  }
@@ -51274,7 +51322,7 @@ function sendText(res, status, text) {
51274
51322
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+f2da34192be1730e/node_modules/pi-mcp-adapter/glimpse-ui.ts
51275
51323
  import { existsSync as existsSync13 } from "fs";
51276
51324
  import { execFileSync as execFileSync2 } from "child_process";
51277
- import { join as join21, dirname as dirname14 } from "path";
51325
+ import { join as join21, dirname as dirname12 } from "path";
51278
51326
  import { platform as platform2 } from "os";
51279
51327
  import { createRequire as createRequire3 } from "module";
51280
51328
  var glimpseAvailable = null;
@@ -51296,7 +51344,7 @@ function getGlimpseBinaryPath() {
51296
51344
  try {
51297
51345
  const require6 = createRequire3(import.meta.url);
51298
51346
  const glimpseuiPath = require6.resolve("glimpseui");
51299
- const binaryPath = join21(dirname14(glimpseuiPath), "glimpse");
51347
+ const binaryPath = join21(dirname12(glimpseuiPath), "glimpse");
51300
51348
  if (existsSync13(binaryPath)) return binaryPath;
51301
51349
  } catch {
51302
51350
  }
@@ -51309,7 +51357,7 @@ function getGlimpseBinaryPath() {
51309
51357
  return null;
51310
51358
  }
51311
51359
  async function openGlimpseWindow(html, options) {
51312
- const modulePath = resolvedBinaryPath ? join21(dirname14(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
51360
+ const modulePath = resolvedBinaryPath ? join21(dirname12(resolvedBinaryPath), "glimpse.mjs") : "glimpseui";
51313
51361
  const glimpse = await import(modulePath);
51314
51362
  let active = true;
51315
51363
  const win = glimpse.open(html, {
@@ -59176,7 +59224,7 @@ function explicitSkillName(session, message) {
59176
59224
  function piThinkingLevel(thinkingLevel) {
59177
59225
  return thinkingLevel === "max" || thinkingLevel === "ultra" || thinkingLevel === "ultracode" ? "xhigh" : thinkingLevel;
59178
59226
  }
59179
- function registerCommandProtection(cwd, historyFile, recordHistoryEvent) {
59227
+ function registerCommandProtection(cwd, recordHistoryEvent) {
59180
59228
  return (pi) => {
59181
59229
  pi.on("tool_call", async (event) => {
59182
59230
  const command = extractToolCommand(event.input);
@@ -59197,7 +59245,6 @@ function registerCommandProtection(cwd, historyFile, recordHistoryEvent) {
59197
59245
  result,
59198
59246
  command,
59199
59247
  context: { toolName: event.toolName, toolUseId: event.toolCallId },
59200
- historyFile,
59201
59248
  recordHistoryEvent
59202
59249
  });
59203
59250
  return { block: true, reason: result.reason ?? "Command blocked by Replicas protection." };
@@ -59218,23 +59265,13 @@ var PiManager = class extends CodingAgentManager {
59218
59265
  activeSessionFile = null;
59219
59266
  sessionSubagentMcpParentChatId;
59220
59267
  sessionInstructions;
59221
- historyFilePath;
59222
- historyFile;
59223
59268
  providerId = "openrouter";
59224
59269
  providerApiKey = null;
59225
59270
  modelRuntime = null;
59226
59271
  constructor(options) {
59227
59272
  super(options);
59228
- this.historyFilePath = options.historyFilePath ?? join22(PI_HISTORY_DIR, `${Date.now()}.jsonl`);
59229
- this.historyFile = new CodexHistoryFile(this.historyFilePath);
59230
59273
  this.initializeManager(this.processMessageInternal.bind(this));
59231
59274
  }
59232
- async initialize() {
59233
- await mkdir15(dirname15(this.historyFilePath), { recursive: true });
59234
- }
59235
- getHistorySink() {
59236
- return this.historyFile;
59237
- }
59238
59275
  async interruptActiveTurn() {
59239
59276
  await this.session?.abort();
59240
59277
  }
@@ -59390,11 +59427,7 @@ var PiManager = class extends CodingAgentManager {
59390
59427
  approveTools: false
59391
59428
  };
59392
59429
  }
59393
- const extensionFactories = [registerCommandProtection(
59394
- this.workingDirectory,
59395
- this.historyFile,
59396
- this.recordHistoryEvent.bind(this)
59397
- )];
59430
+ const extensionFactories = [registerCommandProtection(this.workingDirectory, this.recordHistoryEvent.bind(this))];
59398
59431
  if (Object.keys(mcpServers).length > 0) {
59399
59432
  extensionFactories.push(createMcpAdapter({
59400
59433
  config: {
@@ -59435,13 +59468,12 @@ var PiManager = class extends CodingAgentManager {
59435
59468
  handleEvent(event) {
59436
59469
  if (event.type === "message_end") this.onUsageUpdate(event, (/* @__PURE__ */ new Date()).toISOString());
59437
59470
  const payload = eventPayload(event);
59438
- this.recordHistoryEvent(`pi-${event.type}`, payload, this.historyFile);
59471
+ this.recordHistoryEvent(`pi-${event.type}`, payload);
59439
59472
  }
59440
59473
  recordUserMessage(session, request) {
59441
59474
  const skillName = explicitSkillName(session, request.message);
59442
59475
  this.recordUserMessageHistoryEvent(
59443
59476
  request,
59444
- this.historyFile,
59445
59477
  skillName ? { skillName } : {}
59446
59478
  );
59447
59479
  }
@@ -59457,7 +59489,7 @@ var PiManager = class extends CodingAgentManager {
59457
59489
  if (signal.aborted) return;
59458
59490
  await session.prompt(request.message, images ? { images } : void 0);
59459
59491
  } catch (error) {
59460
- this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) }, this.historyFile);
59492
+ this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) });
59461
59493
  throw error;
59462
59494
  } finally {
59463
59495
  await this.onTurnComplete();
@@ -59466,7 +59498,7 @@ var PiManager = class extends CodingAgentManager {
59466
59498
  };
59467
59499
 
59468
59500
  // src/services/chat/chat-commands.ts
59469
- import { mkdir as mkdir16, readFile as readFile12, rm as rm6 } from "fs/promises";
59501
+ import { mkdir as mkdir12, readFile as readFile12, rm as rm6 } from "fs/promises";
59470
59502
  import { join as join23 } from "path";
59471
59503
  import { z as z3 } from "zod";
59472
59504
  var CHAT_COMMANDS_DIR = join23(ENGINE_DIR, "chat-commands");
@@ -59527,7 +59559,7 @@ var ChatCommands = class _ChatCommands {
59527
59559
  const data = JSON.stringify({ ...this.state, accepted: Object.fromEntries(this.state.accepted) });
59528
59560
  this.writing = this.writing.catch(() => {
59529
59561
  }).then(async () => {
59530
- await mkdir16(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
59562
+ await mkdir12(CHAT_COMMANDS_DIR, { recursive: true, mode: 448 });
59531
59563
  await atomicWriteFile(join23(CHAT_COMMANDS_DIR, `${this.chatId}.json`), data, { mode: 384, flush: true });
59532
59564
  });
59533
59565
  return this.writing;
@@ -59552,8 +59584,8 @@ async function uploadAnalytics(endpoint, body) {
59552
59584
 
59553
59585
  // src/analytics/analytics-record-buffer.ts
59554
59586
  import {
59555
- appendFile as appendFile4,
59556
- mkdir as mkdir17,
59587
+ appendFile as appendFile3,
59588
+ mkdir as mkdir13,
59557
59589
  readFile as readFile13,
59558
59590
  readdir as readdir6,
59559
59591
  rename as rename2,
@@ -59595,7 +59627,7 @@ var AnalyticsRecordBuffer = class {
59595
59627
  if (this.recordIds.has(recordId)) return;
59596
59628
  this.recordIds.add(recordId);
59597
59629
  }
59598
- const pending = mkdir17(ENGINE_DIR, { recursive: true }).then(() => appendFile4(this.liveFile, `${JSON.stringify(record3)}
59630
+ const pending = mkdir13(ENGINE_DIR, { recursive: true }).then(() => appendFile3(this.liveFile, `${JSON.stringify(record3)}
59599
59631
  `, "utf-8")).catch((error) => {
59600
59632
  console.error(
59601
59633
  `[${this.options.storageName}] Append failed, will retry on flush:`,
@@ -60498,7 +60530,7 @@ var keepAliveService = new KeepAliveService();
60498
60530
 
60499
60531
  // src/services/canvas-service.ts
60500
60532
  import { readdir as readdir7, readFile as readFile15, stat as stat3 } from "fs/promises";
60501
- import { homedir as homedir8 } from "os";
60533
+ import { homedir as homedir7 } from "os";
60502
60534
  import { join as join25 } from "path";
60503
60535
 
60504
60536
  // src/utils/contained-file.ts
@@ -60541,9 +60573,9 @@ async function writeRevisionedTextFile(filePath, content, expectedRevision) {
60541
60573
 
60542
60574
  // src/services/canvas-service.ts
60543
60575
  var GLOBAL_CANVAS_DIRECTORIES = [
60544
- join25(homedir8(), ".claude", "plans"),
60545
- join25(process.env.XDG_DATA_HOME ?? join25(homedir8(), ".local", "share"), "opencode", "plans"),
60546
- join25(homedir8(), ".replicas", "canvas")
60576
+ join25(homedir7(), ".claude", "plans"),
60577
+ join25(process.env.XDG_DATA_HOME ?? join25(homedir7(), ".local", "share"), "opencode", "plans"),
60578
+ join25(homedir7(), ".replicas", "canvas")
60547
60579
  ];
60548
60580
  async function canvasDirectories() {
60549
60581
  const repositories = await gitService.listRepositories().catch(() => []);
@@ -60772,9 +60804,9 @@ async function reconcileCanvasItems(filenames) {
60772
60804
  }
60773
60805
 
60774
60806
  // src/services/upload-chat-transcripts.ts
60775
- import { createReadStream as createReadStream3 } from "fs";
60776
60807
  import { createHash as createHash8 } from "crypto";
60777
- import { readFile as readFile16, readdir as readdir8, stat as stat4 } from "fs/promises";
60808
+ import { readFile as readFile16, readdir as readdir8 } from "fs/promises";
60809
+ import { Readable } from "stream";
60778
60810
  import { basename as basename3, join as join27 } from "path";
60779
60811
 
60780
60812
  // src/services/chat/chat-senders.ts
@@ -60796,10 +60828,9 @@ function parseChatMessageSendersJsonl(content) {
60796
60828
  }
60797
60829
 
60798
60830
  // src/utils/presigned-upload.ts
60799
- import { createReadStream as createReadStream2 } from "fs";
60800
60831
  import { request as httpRequest } from "http";
60801
60832
  import { request as httpsRequest } from "https";
60802
- async function putPresignedFile(urlValue, filePath, size, contentType) {
60833
+ async function putPresignedFile(urlValue, body, size, contentType) {
60803
60834
  await new Promise((resolve7, reject) => {
60804
60835
  const url3 = new URL(urlValue);
60805
60836
  const request = (url3.protocol === "https:" ? httpsRequest : httpRequest)(url3, {
@@ -60810,25 +60841,25 @@ async function putPresignedFile(urlValue, filePath, size, contentType) {
60810
60841
  }
60811
60842
  }, (response) => {
60812
60843
  response.setEncoding("utf8");
60813
- let body = "";
60844
+ let body2 = "";
60814
60845
  response.on("data", (chunk) => {
60815
- body += chunk;
60846
+ body2 += chunk;
60816
60847
  });
60817
60848
  response.on("end", () => {
60818
60849
  const status = response.statusCode ?? 0;
60819
60850
  if (status >= 200 && status < 300) resolve7();
60820
- else reject(new Error(`upload failed: ${status} ${body}`));
60851
+ else reject(new Error(`upload failed: ${status} ${body2}`));
60821
60852
  });
60822
60853
  response.on("error", reject);
60823
60854
  });
60824
60855
  request.on("error", reject);
60825
- const file = size > 0 ? createReadStream2(filePath, { start: 0, end: size - 1 }) : createReadStream2(filePath);
60826
- file.on("error", (error) => request.destroy(error));
60827
- file.pipe(request);
60856
+ body.on("error", (error) => request.destroy(error));
60857
+ body.pipe(request);
60828
60858
  });
60829
60859
  }
60830
60860
 
60831
60861
  // src/services/upload-chat-transcripts.ts
60862
+ var UPLOAD_CHUNK_BYTES = 1 << 18;
60832
60863
  var HISTORY_DIRS = [...new Set(Object.values(HISTORY_DIR_BY_PROVIDER))];
60833
60864
  var ALWAYS_UPLOAD_HISTORY_DIRS = /* @__PURE__ */ new Set([
60834
60865
  HISTORY_DIR_BY_PROVIDER.claude,
@@ -60897,10 +60928,29 @@ function uploadChatTranscript(chatId, filePath, chat, capture) {
60897
60928
  return upload;
60898
60929
  }
60899
60930
  async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60900
- const versionBeforeStat = chat?.currentHistoryVersion?.();
60901
- const { size, mtimeMs } = await stat4(filePath);
60902
- if (size === 0) return null;
60903
- const historyVersion = versionBeforeStat === chat?.currentHistoryVersion?.() ? versionBeforeStat : void 0;
60931
+ const versionBeforeOpen = chat?.currentHistoryVersion?.();
60932
+ const opened = await (chat?.openHistory?.() ?? openWholeLog(filePath));
60933
+ if (!opened) return null;
60934
+ try {
60935
+ if (opened.size === 0) return null;
60936
+ const historyVersion = versionBeforeOpen === chat?.currentHistoryVersion?.() ? versionBeforeOpen : void 0;
60937
+ return await uploadOpenedTranscript(chatId, opened, historyVersion, chat, capture);
60938
+ } finally {
60939
+ await opened.file.close();
60940
+ }
60941
+ }
60942
+ async function* logBytes({ file, size }) {
60943
+ for (let at = 0; at < size; ) {
60944
+ const chunk = Buffer.allocUnsafe(Math.min(UPLOAD_CHUNK_BYTES, size - at));
60945
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, at);
60946
+ if (bytesRead === 0) return;
60947
+ at += bytesRead;
60948
+ yield chunk.subarray(0, bytesRead);
60949
+ }
60950
+ }
60951
+ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capture) {
60952
+ const { size } = opened;
60953
+ const { mtimeMs } = await opened.file.stat();
60904
60954
  const metadata = chat ? {
60905
60955
  provider: chat.provider,
60906
60956
  // Chats with no turn since this engine version fall back to the auth live at upload.
@@ -60937,7 +60987,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60937
60987
  }
60938
60988
  if (capture) {
60939
60989
  const hash = createHash8("sha256");
60940
- for await (const chunk of createReadStream3(filePath, { start: 0, end: size - 1 })) hash.update(chunk);
60990
+ for await (const chunk of logBytes(opened)) hash.update(chunk);
60941
60991
  metadata.captureId = capture.captureId;
60942
60992
  metadata.captureReason = capture.reason;
60943
60993
  metadata.sha256 = hash.digest("hex");
@@ -60954,7 +61004,7 @@ async function uploadChatTranscriptNow(chatId, filePath, chat, capture) {
60954
61004
  throw new Error("prepare failed: invalid response");
60955
61005
  }
60956
61006
  if (prepareBody.uploadUrl === null) return null;
60957
- await putPresignedFile(prepareBody.uploadUrl, filePath, size, "application/x-ndjson");
61007
+ await putPresignedFile(prepareBody.uploadUrl, Readable.from(logBytes(opened)), size, "application/x-ndjson");
60958
61008
  const finalizeResponse = await monolithRequest("/v1/engine/chat-transcripts/finalize", {
60959
61009
  body: uploadRequest
60960
61010
  });
@@ -61004,8 +61054,8 @@ async function flushRepoState() {
61004
61054
  }
61005
61055
 
61006
61056
  // src/services/upload-engine-logs.ts
61007
- import { createReadStream as createReadStream4 } from "fs";
61008
- import { readdir as readdir9, stat as stat5 } from "fs/promises";
61057
+ import { createReadStream } from "fs";
61058
+ import { readdir as readdir9, stat as stat4 } from "fs/promises";
61009
61059
  import { join as join28 } from "path";
61010
61060
  var MAX_ENGINE_LOG_FLUSH_SESSIONS = 10;
61011
61061
  var MAX_ENGINE_LOG_FLUSH_BYTES = 5 * 1024 * 1024;
@@ -61036,7 +61086,7 @@ async function flushAllEngineLogs() {
61036
61086
  try {
61037
61087
  const sessionId = filename.slice(0, -".log".length);
61038
61088
  const filePath = join28(LOG_DIR, filename);
61039
- const fileStat = await runBeforeDeadline(() => stat5(filePath), deadline);
61089
+ const fileStat = await runBeforeDeadline(() => stat4(filePath), deadline);
61040
61090
  if (!fileStat.isFile()) {
61041
61091
  skipped++;
61042
61092
  return null;
@@ -61068,7 +61118,7 @@ async function flushAllEngineLogs() {
61068
61118
  const content = await runBeforeDeadline(async (signal) => {
61069
61119
  if (candidate.length === 0) return Buffer.alloc(0);
61070
61120
  const chunks = [];
61071
- for await (const chunk of createReadStream4(candidate.filePath, {
61121
+ for await (const chunk of createReadStream(candidate.filePath, {
61072
61122
  start: candidate.offset,
61073
61123
  end: candidate.offset + candidate.length - 1,
61074
61124
  signal
@@ -61132,8 +61182,8 @@ async function uploadEngineLog(input, timeoutMs) {
61132
61182
 
61133
61183
  // src/services/chat/fork-handoff.ts
61134
61184
  import { createHash as createHash9 } from "crypto";
61135
- import { mkdir as mkdir18, open as open3, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
61136
- import { homedir as homedir9 } from "os";
61185
+ import { mkdir as mkdir14, readFile as readFile17, writeFile as writeFile8 } from "fs/promises";
61186
+ import { homedir as homedir8 } from "os";
61137
61187
  import { join as join29 } from "path";
61138
61188
  var EXCERPT_MAX_CHARS = 24e3;
61139
61189
  var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
@@ -61145,19 +61195,14 @@ function unansweredRequest(blocks) {
61145
61195
  const answered = blocks.slice(lastUser + 1).some((block) => block.startsWith("## Agent"));
61146
61196
  return answered ? null : lastUserBlockText(blocks);
61147
61197
  }
61148
- async function readHistoryTail(path7, maxBytes) {
61149
- let handle;
61150
- try {
61151
- handle = await open3(path7, "r");
61152
- } catch (error) {
61153
- if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return { content: "", truncated: false };
61154
- throw error;
61155
- }
61198
+ async function readHistoryTail(path7, maxBytes, openHistory = () => openWholeLog(path7)) {
61199
+ const opened = await openHistory();
61200
+ if (!opened) return { content: "", truncated: false };
61201
+ const { file: handle, size } = opened;
61156
61202
  try {
61157
- const { size } = await handle.stat();
61158
- if (size <= maxBytes) return { content: await handle.readFile("utf-8"), truncated: false };
61159
- const buffer = Buffer.alloc(maxBytes);
61160
- await handle.read(buffer, 0, maxBytes, size - maxBytes);
61203
+ const buffer = Buffer.alloc(Math.min(size, maxBytes));
61204
+ await handle.read(buffer, 0, buffer.length, size - buffer.length);
61205
+ if (size <= maxBytes) return { content: buffer.toString("utf-8"), truncated: false };
61161
61206
  const firstNewline = buffer.indexOf(10);
61162
61207
  return { content: buffer.subarray(firstNewline + 1).toString("utf-8"), truncated: true };
61163
61208
  } finally {
@@ -61203,7 +61248,7 @@ ${text}` : null;
61203
61248
  async function buildForkHandoff(input) {
61204
61249
  const sources = await Promise.all(input.segments.map(async (segment, index) => {
61205
61250
  const rawHistoryPath = join29(HISTORY_DIR_BY_PROVIDER[segment.provider], `${segment.chatId}.jsonl`);
61206
- const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
61251
+ const { content, truncated: truncated2 } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES, segment.openHistory);
61207
61252
  const last = index === input.segments.length - 1;
61208
61253
  const blocks2 = canonicalizeChatTranscriptBlocks(content, segment.provider, segment.senders, last ? input.beforeMessageId : void 0).filter((block) => !block.startsWith("## Agent reasoning"));
61209
61254
  return { rawHistoryPath, truncated: truncated2, blocks: index === 0 ? blocks2 : blocks2.flatMap((block) => unwrapHandoffBlock(block) ?? []) };
@@ -61217,7 +61262,7 @@ async function buildForkHandoff(input) {
61217
61262
  blocks = blocks.slice(Math.max(0, start));
61218
61263
  }
61219
61264
  const forkDir = join29(FORKS_DIR, input.targetChatId);
61220
- await mkdir18(forkDir, { recursive: true });
61265
+ await mkdir14(forkDir, { recursive: true });
61221
61266
  const transcriptPath = join29(forkDir, input.transcriptName ?? "source-transcript.md");
61222
61267
  const rawHistoryPaths = sources.map((source) => source.rawHistoryPath);
61223
61268
  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.` : ""}_
@@ -61237,7 +61282,7 @@ async function buildForkHandoff(input) {
61237
61282
  };
61238
61283
  }
61239
61284
  async function readPullRequestDecisions(notesPath) {
61240
- const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
61285
+ const notes = await readFile17(notesPath.replace(/^~(?=\/)/, homedir8()), "utf-8").catch(() => "");
61241
61286
  const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
61242
61287
  if (!decisions) return null;
61243
61288
  const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
@@ -61411,12 +61456,12 @@ var ChatService = class {
61411
61456
  persistPromise = null;
61412
61457
  persistQueued = false;
61413
61458
  async initialize() {
61414
- await mkdir19(ENGINE_DIR, { recursive: true });
61415
- await mkdir19(CLAUDE_HISTORY_DIR, { recursive: true });
61416
- await mkdir19(CODEX_HISTORY_DIR, { recursive: true });
61417
- await mkdir19(CURSOR_HISTORY_DIR, { recursive: true });
61418
- await mkdir19(OPENCODE_HISTORY_DIR, { recursive: true });
61419
- await mkdir19(CHAT_SENDERS_DIR, { recursive: true });
61459
+ await mkdir15(ENGINE_DIR, { recursive: true });
61460
+ await mkdir15(CLAUDE_HISTORY_DIR, { recursive: true });
61461
+ await mkdir15(CODEX_HISTORY_DIR, { recursive: true });
61462
+ await mkdir15(CURSOR_HISTORY_DIR, { recursive: true });
61463
+ await mkdir15(OPENCODE_HISTORY_DIR, { recursive: true });
61464
+ await mkdir15(CHAT_SENDERS_DIR, { recursive: true });
61420
61465
  const persisted = await this.loadChats();
61421
61466
  let fromOlderEngine = false;
61422
61467
  for (const chat of persisted) {
@@ -61445,7 +61490,7 @@ var ChatService = class {
61445
61490
  changed = true;
61446
61491
  }
61447
61492
  const runtime = this.createRuntimeChat(chat, commands);
61448
- const history = new CodexHistoryFile(this.historyPath(chat));
61493
+ const { history } = runtime;
61449
61494
  try {
61450
61495
  const accepted = /* @__PURE__ */ new Set();
61451
61496
  const removed = /* @__PURE__ */ new Set();
@@ -61460,11 +61505,11 @@ var ChatService = class {
61460
61505
  }
61461
61506
  if (state.running) {
61462
61507
  if (!lostRecorded) {
61463
- await runtime.provider.persistHistoryEvent({
61508
+ await history.record({
61464
61509
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61465
61510
  type: CHAT_TURN_LOST_EVENT_TYPE,
61466
61511
  payload: state.running.id ? { messageId: state.running.id } : {}
61467
- });
61512
+ }).written;
61468
61513
  }
61469
61514
  const owed = state.lost && !state.lost.reported ? state.lost.errorNotificationTargets : [];
61470
61515
  state.lost = {
@@ -61483,16 +61528,16 @@ var ChatService = class {
61483
61528
  for (const message of state.queue) {
61484
61529
  if (accepted.has(message.id)) continue;
61485
61530
  const { event, sender } = createTurnMetadata(message, message.id, message.queuedAt);
61486
- await runtime.provider.persistHistoryEvent(event);
61531
+ await history.record(event).written;
61487
61532
  if (sender) await this.appendSender(chat.id, sender);
61488
61533
  }
61489
61534
  const unrecorded = state.removing.filter((messageId) => !removed.has(messageId));
61490
61535
  if (unrecorded.length > 0) {
61491
- await runtime.provider.persistHistoryEvent({
61536
+ await history.record({
61492
61537
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61493
61538
  type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
61494
61539
  payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: unrecorded }
61495
- });
61540
+ }).written;
61496
61541
  }
61497
61542
  if (state.removing.length > 0) {
61498
61543
  state.removing = [];
@@ -61503,10 +61548,7 @@ var ChatService = class {
61503
61548
  }
61504
61549
  if (state.queue.length > 0 && !this.restartedChats.has(chat.id)) this.restartedChats.set(chat.id, false);
61505
61550
  if (changed) await commands.save();
61506
- if (chat.uploadedHistory) {
61507
- const size = await stat6(this.historyPath(chat)).then(({ size: size2 }) => size2, () => null);
61508
- if (size === chat.uploadedHistory.size) runtime.historyVersion = chat.uploadedHistory.version;
61509
- }
61551
+ if (chat.uploadedHistory?.size === history.historyEnd) runtime.historyVersion = chat.uploadedHistory.version;
61510
61552
  this.chats.set(chat.id, runtime);
61511
61553
  }
61512
61554
  if (fromOlderEngine) await this.persistAllChats();
@@ -61921,7 +61963,7 @@ ${decisions}` };
61921
61963
  const previousAccepted = idempotencyKey ? state.accepted.get(idempotencyKey) : void 0;
61922
61964
  if (idempotencyKey) state.accepted.set(idempotencyKey, { ...result, at: (/* @__PURE__ */ new Date()).toISOString() });
61923
61965
  if (!state.removed.includes(result.messageId)) {
61924
- if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
61966
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = chat.history.historyEnd;
61925
61967
  if (previousQueued) state.queue[state.queue.indexOf(previousQueued)] = queued;
61926
61968
  else state.queue.push(queued);
61927
61969
  if (!chat.pendingMessageIds.includes(result.messageId)) {
@@ -61940,7 +61982,7 @@ ${decisions}` };
61940
61982
  try {
61941
61983
  await chat.commands.save();
61942
61984
  await this.persistAllChats();
61943
- await chat.provider.persistHistoryEvent(acceptedEvent);
61985
+ await chat.history.record(acceptedEvent).written;
61944
61986
  } catch (error) {
61945
61987
  const index = state.queue.indexOf(queued);
61946
61988
  if (index !== -1) state.queue.splice(index, 1, ...previousQueued ? [previousQueued] : []);
@@ -61987,7 +62029,7 @@ ${decisions}` };
61987
62029
  }
61988
62030
  async appendSender(chatId, sender) {
61989
62031
  try {
61990
- await appendFile5(chatMessageSendersFilePath(chatId), JSON.stringify(sender) + "\n", "utf-8");
62032
+ await appendFile4(chatMessageSendersFilePath(chatId), JSON.stringify(sender) + "\n", "utf-8");
61991
62033
  } catch (error) {
61992
62034
  console.error("[ChatService] Failed to append sender record:", error);
61993
62035
  }
@@ -62098,8 +62140,7 @@ ${decisions}` };
62098
62140
  };
62099
62141
  }
62100
62142
  async withUnpublishedHistory(chat, run) {
62101
- const start = chat.provider.getHistoryEnd();
62102
- if (start === void 0) return run();
62143
+ const start = chat.history.end;
62103
62144
  chat.unpublishedHistoryStarts.push(start);
62104
62145
  try {
62105
62146
  return await run();
@@ -62132,12 +62173,12 @@ ${decisions}` };
62132
62173
  const newlyRemoved = messageIds.filter((id) => !state.removed.includes(id));
62133
62174
  const previousCheckFrom = state.checkFrom;
62134
62175
  state.queue = state.queue.filter(({ id }) => !removed.has(id));
62135
- if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = this.historySizeOnDisk(chat.persisted);
62176
+ if (state.queue.length === 0 && state.removing.length === 0) state.checkFrom = chat.history.historyEnd;
62136
62177
  state.removed.push(...newlyRemoved);
62137
62178
  state.removing.push(...messageIds);
62138
62179
  try {
62139
62180
  await chat.commands.save();
62140
- await chat.provider.persistHistoryEvent(event);
62181
+ await chat.history.record(event).written;
62141
62182
  } catch (error) {
62142
62183
  state.queue.push(...queued);
62143
62184
  state.checkFrom = previousCheckFrom;
@@ -62286,6 +62327,7 @@ ${decisions}` };
62286
62327
  }
62287
62328
  await this.releaseAgentProcess(target);
62288
62329
  if (!started) {
62330
+ await target.history.flush();
62289
62331
  await this.deleteHistoryFile(target.persisted);
62290
62332
  await target.commands.remove();
62291
62333
  }
@@ -62422,7 +62464,7 @@ ${decisions}` };
62422
62464
  async threadSegments(chat) {
62423
62465
  const thread = [...getChatThreadSources(this.listChats(), this.toSummary(chat)).map(({ id }) => this.requireChat(id)), chat];
62424
62466
  await chat.provider.getHistory({ limit: 1 });
62425
- return Promise.all(thread.map(async ({ persisted }) => ({ chatId: persisted.id, provider: persisted.provider, senders: await this.readSenders(persisted.id) })));
62467
+ return Promise.all(thread.map(async ({ persisted, history }) => ({ chatId: persisted.id, provider: persisted.provider, senders: await this.readSenders(persisted.id), openHistory: () => history.openAtFlushedEnd() })));
62426
62468
  }
62427
62469
  async createForkHandoffMessage(targetChatId, options) {
62428
62470
  const follows = options.trigger === "side" || options.followsSource;
@@ -62472,7 +62514,7 @@ ${wrapInTag(`The user edited one of their earlier messages: the conversation abo
62472
62514
  chat.persisted.providerSessionId = null;
62473
62515
  delete chat.persisted.pendingProviderFork;
62474
62516
  await this.persistAllChats();
62475
- chat.provider = this.createRuntimeChat(chat.persisted).provider;
62517
+ chat.provider = this.createRuntimeChat(chat.persisted, chat.commands, chat.history).provider;
62476
62518
  const note = handoff.blocks.length === 0 ? `The user edited their first message, so your session restarted and this is its edited version. ${files}` : `The user edited one of their earlier messages, so your session restarted. The conversation before that message is below (also saved at \`${handoff.transcriptPath}\`), and this is its edited version. ${files}
62477
62519
 
62478
62520
  ${handoff.excerptTruncated ? `${CHAT_FORK_EXCERPT_OMITTED_NOTICE}
@@ -62594,7 +62636,7 @@ ${note}`;
62594
62636
  return true;
62595
62637
  }
62596
62638
  async getChatHistoryRecord(chatId, record3) {
62597
- return new CodexHistoryFile(this.historyPath(this.requireChat(chatId).persisted)).readRecord(record3);
62639
+ return this.requireChat(chatId).history.readRecord(record3);
62598
62640
  }
62599
62641
  async getChatHistory(chatId, page2 = {}) {
62600
62642
  const chat = this.requireChat(chatId);
@@ -62674,6 +62716,7 @@ ${note}`;
62674
62716
  return {
62675
62717
  ...this.toSummary(chat),
62676
62718
  removedMessageIds: chat.commands.state.removed,
62719
+ openHistory: () => chat.history.openAtFlushedEnd(),
62677
62720
  transcriptAuth: chat.persisted.transcriptAuth,
62678
62721
  currentHistoryVersion: () => this.toSummary(chat).historyVersion
62679
62722
  };
@@ -62681,10 +62724,6 @@ ${note}`;
62681
62724
  historyPath(persisted) {
62682
62725
  return join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62683
62726
  }
62684
- /** 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. */
62685
- historySizeOnDisk(persisted) {
62686
- return statSync4(this.historyPath(persisted), { throwIfNoEntry: false })?.size ?? 0;
62687
- }
62688
62727
  async recordUploadedHistory(chatId, artifact) {
62689
62728
  const chat = this.getRuntimeChat(chatId);
62690
62729
  const version = artifact?.metadata.historyVersion;
@@ -62739,7 +62778,8 @@ ${note}`;
62739
62778
  mcpActivity: chatActivity.mcpActivity
62740
62779
  };
62741
62780
  }
62742
- createRuntimeChat(persisted, commands = new ChatCommands(persisted.id)) {
62781
+ /** `history` is passed when the chat already has its log: a second object on the same file would write over the first. */
62782
+ createRuntimeChat(persisted, commands = new ChatCommands(persisted.id), history = new CodexHistoryFile(this.historyPath(persisted))) {
62743
62783
  const saveSession = async (sessionId) => {
62744
62784
  persisted.providerSessionId = sessionId;
62745
62785
  delete persisted.pendingProviderFork;
@@ -62755,6 +62795,9 @@ ${note}`;
62755
62795
  const onProviderTurnComplete = async () => {
62756
62796
  await this.handleTurnFinished(persisted.id);
62757
62797
  };
62798
+ const record3 = (event) => {
62799
+ this.handleTurnEvent(persisted.id, event, history);
62800
+ };
62758
62801
  const onProviderEvent = (event) => {
62759
62802
  this.handleTurnEvent(persisted.id, event);
62760
62803
  };
@@ -62819,11 +62862,11 @@ ${note}`;
62819
62862
  chat = this.chats.get(next)?.persisted;
62820
62863
  }
62821
62864
  const baseProvider = persisted.provider;
62822
- const historyFilePath = join30(HISTORY_DIR_BY_PROVIDER[persisted.provider], `${persisted.id}.jsonl`);
62823
62865
  const managerOptions = {
62824
62866
  provider: baseProvider,
62825
62867
  workingDirectory: this.workingDirectory,
62826
- historyFilePath,
62868
+ history,
62869
+ record: record3,
62827
62870
  initialSessionId: persisted.providerSessionId,
62828
62871
  onSaveSessionId: saveSession,
62829
62872
  onTurnComplete: onProviderTurnComplete,
@@ -62889,6 +62932,8 @@ ${note}`;
62889
62932
  turnCompletion: null,
62890
62933
  publishedQueue: null,
62891
62934
  idleReleaseTimer: null,
62935
+ history,
62936
+ outbox: new AsyncLock(),
62892
62937
  unpublishedHistoryStarts: [],
62893
62938
  live: false,
62894
62939
  progressStep: null,
@@ -62992,9 +63037,11 @@ ${note}`;
62992
63037
  }
62993
63038
  });
62994
63039
  }
62995
- handleTurnEvent(chatId, event) {
63040
+ /** `log` is the chat's log when the event is a record. It is taken once its message id is stamped, and announced once on disk. */
63041
+ handleTurnEvent(chatId, event, log) {
62996
63042
  const chat = this.getRuntimeChat(chatId);
62997
63043
  if (!chat) {
63044
+ log?.record(event);
62998
63045
  return;
62999
63046
  }
63000
63047
  keepAliveService.noteActivity();
@@ -63069,6 +63116,7 @@ ${note}`;
63069
63116
  }
63070
63117
  }
63071
63118
  }
63119
+ const written = log?.record(event).written;
63072
63120
  if (event.type !== CLAUDE_PARTIAL_MESSAGE_EVENT_TYPE) {
63073
63121
  this.touch(chat);
63074
63122
  this.observeCurrentBranches(chat).catch(() => {
@@ -63081,7 +63129,7 @@ ${note}`;
63081
63129
  ...chat.activeMessageId ? { messageId: chat.activeMessageId } : {},
63082
63130
  event: eventToPublish
63083
63131
  }
63084
- }).catch(() => {
63132
+ }, written).catch(() => {
63085
63133
  });
63086
63134
  if (event.type === "replicas-tool-input-request" || event.type === "replicas-tool-input-resolved" || event.type === AUTH_RETRY_STATUS_EVENT_TYPE || event.type === AUTH_FALLBACK_EVENT_TYPE || event.type === CURSOR_CONNECTION_STATUS_EVENT_TYPE || event.type === CHAT_GOAL_EVENT_TYPE || event.type === "claude-result" || event.type === "claude-system" && (event.payload.subtype === "init" || event.payload.subtype === "session_state_changed" || event.payload.subtype === "background_tasks_changed" || coerceBackgroundTaskPayload(event.payload) !== null)) {
63087
63135
  this.publish({
@@ -63309,30 +63357,39 @@ ${note}`;
63309
63357
  });
63310
63358
  return this.persistPromise;
63311
63359
  }
63312
- async publish(input) {
63360
+ /**
63361
+ * A chat's events reach the stream in the order they were made, each one after every record taken before it is on disk,
63362
+ * so no client hears of something a crash could take back. `written` is the event's own record: a dropped one is not announced.
63363
+ */
63364
+ async publish(input, written) {
63313
63365
  const event = {
63314
63366
  id: randomUUID9(),
63315
63367
  ts: (/* @__PURE__ */ new Date()).toISOString(),
63316
63368
  ...input
63317
63369
  };
63318
63370
  const chatId = "chat" in event.payload && event.payload.chat ? event.payload.chat.id : "chatId" in event.payload ? event.payload.chatId : void 0;
63319
- if (event.type === "chat.queue.changed") {
63371
+ const chat = chatId ? this.chats.get(chatId) : void 0;
63372
+ if (!chat) {
63320
63373
  await eventService.publish(event);
63321
63374
  return;
63322
63375
  }
63323
- const chat = chatId ? this.chats.get(chatId) : void 0;
63324
- if (chat && event.type === "chat.turn.delta") {
63325
- const historyEnd = chat.provider.getHistoryEnd();
63326
- if (historyEnd !== void 0) event.payload.historyEnd = Math.min(historyEnd, ...chat.unpublishedHistoryStarts);
63327
- }
63328
- if (chat) {
63376
+ const end = chat.history.end;
63377
+ const recorded = written ?? chat.history.flush();
63378
+ const dropped = await chat.outbox.run(async () => {
63379
+ if (await recorded.then(() => false, () => true)) return true;
63380
+ if (event.type === "chat.queue.changed") {
63381
+ await eventService.publish(event);
63382
+ return false;
63383
+ }
63384
+ if (event.type === "chat.turn.delta") event.payload.historyEnd = Math.min(end, chat.history.historyEnd, ...chat.unpublishedHistoryStarts);
63329
63385
  chat.historyVersion = event.id;
63330
63386
  if (event.type === "chat.created" || event.type === "chat.updated") {
63331
63387
  event.payload.chat.historyVersion = this.toSummary(chat).historyVersion;
63332
63388
  }
63333
- }
63334
- await eventService.publish(event);
63335
- if (chatId) this.publishQueueIfChanged(chatId);
63389
+ await eventService.publish(event);
63390
+ return false;
63391
+ });
63392
+ if (!dropped && event.type !== "chat.queue.changed") this.publishQueueIfChanged(chat.persisted.id);
63336
63393
  }
63337
63394
  async observeCurrentBranches(chat) {
63338
63395
  try {
@@ -63406,14 +63463,14 @@ ${note}`;
63406
63463
  // src/services/repo-file-service.ts
63407
63464
  import { execFile as execFile7 } from "child_process";
63408
63465
  import { readFile as readFile19 } from "fs/promises";
63409
- import { homedir as homedir10 } from "os";
63466
+ import { homedir as homedir9 } from "os";
63410
63467
  import { extname as extname3, join as join32 } from "path";
63411
63468
 
63412
63469
  // src/services/language-server-service.ts
63413
63470
  import { spawn as spawn4 } from "child_process";
63414
63471
  import { existsSync as existsSync15, readFileSync as readFileSync6 } from "fs";
63415
63472
  import { createRequire as createRequire5 } from "module";
63416
- import { delimiter as delimiter2, dirname as dirname16, join as join31, relative as relative2 } from "path";
63473
+ import { delimiter as delimiter2, dirname as dirname13, join as join31, relative as relative2 } from "path";
63417
63474
  import { setTimeout as setTimeout3 } from "timers/promises";
63418
63475
  import { fileURLToPath as fileURLToPath5, pathToFileURL } from "url";
63419
63476
  import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
@@ -63454,7 +63511,7 @@ function packageBin(packageName, binName) {
63454
63511
  const packageJson = JSON.parse(readFileSync6(packageJsonPath, "utf8"));
63455
63512
  const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin[binName];
63456
63513
  if (!bin) throw new Error(`Missing ${binName} binary`);
63457
- return `${dirname16(packageJsonPath)}/${bin}`;
63514
+ return `${dirname13(packageJsonPath)}/${bin}`;
63458
63515
  }
63459
63516
  function markdownText(value) {
63460
63517
  if (typeof value === "string") return value;
@@ -63625,7 +63682,7 @@ function execGitAsync(args, cwd, timeoutMs) {
63625
63682
  });
63626
63683
  }
63627
63684
  var RepoFileService = class {
63628
- constructor(gitService2, homeDir = homedir10()) {
63685
+ constructor(gitService2, homeDir = homedir9()) {
63629
63686
  this.homeDir = homeDir;
63630
63687
  this.gitService = gitService2;
63631
63688
  }
@@ -63892,7 +63949,7 @@ var RepoFileService = class {
63892
63949
  // src/v1-routes.ts
63893
63950
  import { Hono } from "hono";
63894
63951
  import { z as z6 } from "zod";
63895
- import { readdir as readdir11, stat as stat7, readFile as readFile22 } from "fs/promises";
63952
+ import { readdir as readdir11, stat as stat5, readFile as readFile22 } from "fs/promises";
63896
63953
  import { openAsBlob } from "fs";
63897
63954
  import { join as join35, resolve as resolve5 } from "path";
63898
63955
 
@@ -63903,10 +63960,10 @@ import { existsSync as existsSync16 } from "fs";
63903
63960
  import { join as join34 } from "path";
63904
63961
 
63905
63962
  // src/services/warm-hook-logs-service.ts
63906
- import { mkdir as mkdir20, readFile as readFile20, writeFile as writeFile9, readdir as readdir10, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
63907
- import { homedir as homedir11 } from "os";
63963
+ import { mkdir as mkdir16, readFile as readFile20, writeFile as writeFile9, readdir as readdir10, appendFile as appendFile5, unlink as unlink2 } from "fs/promises";
63964
+ import { homedir as homedir10 } from "os";
63908
63965
  import { join as join33 } from "path";
63909
- var LOGS_DIR2 = join33(homedir11(), ".replicas", "warm-hook-logs");
63966
+ var LOGS_DIR2 = join33(homedir10(), ".replicas", "warm-hook-logs");
63910
63967
  var CURRENT_RUN_LOG = join33(LOGS_DIR2, "current-run.log");
63911
63968
  function withPreview2(stored) {
63912
63969
  const preview = buildHookOutputPreview(stored.output);
@@ -63914,7 +63971,7 @@ function withPreview2(stored) {
63914
63971
  }
63915
63972
  var WarmHookLogsService = class {
63916
63973
  async ensureDir() {
63917
- await mkdir20(LOGS_DIR2, { recursive: true });
63974
+ await mkdir16(LOGS_DIR2, { recursive: true });
63918
63975
  }
63919
63976
  async saveEnvironmentHookLog(entry) {
63920
63977
  await this.ensureDir();
@@ -63975,7 +64032,7 @@ var WarmHookLogsService = class {
63975
64032
  }
63976
64033
  async appendCurrentRunLog(chunk) {
63977
64034
  if (!chunk) return;
63978
- await appendFile6(CURRENT_RUN_LOG, chunk, "utf-8");
64035
+ await appendFile5(CURRENT_RUN_LOG, chunk, "utf-8");
63979
64036
  }
63980
64037
  async getCurrentRunLog() {
63981
64038
  try {
@@ -65383,7 +65440,7 @@ data: ${JSON.stringify("Terminal session not found")}
65383
65440
  const sessions = await Promise.all(
65384
65441
  logFiles.map(async (filename) => {
65385
65442
  const filePath = join35(LOG_DIR, filename);
65386
- const fileStat = await stat7(filePath);
65443
+ const fileStat = await stat5(filePath);
65387
65444
  const sessionId = filename.replace(/\.log$/, "");
65388
65445
  return {
65389
65446
  sessionId,
@@ -65608,7 +65665,7 @@ var ResourceMonitor = class {
65608
65665
  if (this.sampling) return;
65609
65666
  this.sampling = true;
65610
65667
  try {
65611
- const [stat8, meminfo, cpuPressure, memoryPressure, ioPressure] = await Promise.all([
65668
+ const [stat6, meminfo, cpuPressure, memoryPressure, ioPressure] = await Promise.all([
65612
65669
  readWithin("/proc/stat"),
65613
65670
  readWithin("/proc/meminfo"),
65614
65671
  readOptional("/proc/pressure/cpu"),
@@ -65616,7 +65673,7 @@ var ResourceMonitor = class {
65616
65673
  readOptional("/proc/pressure/io")
65617
65674
  ]);
65618
65675
  if (!this.timer) return;
65619
- const lines = stat8.split("\n");
65676
+ const lines = stat6.split("\n");
65620
65677
  const jiffies = lines[0].trim().split(/\s+/).slice(1, 9).map(Number);
65621
65678
  const total = jiffies.reduce((sum, value) => sum + value, 0);
65622
65679
  const cpu = { busy: total - jiffies[3] - jiffies[4], total };
@@ -65774,23 +65831,23 @@ var HeartbeatService = class _HeartbeatService {
65774
65831
  var heartbeatService = new HeartbeatService();
65775
65832
 
65776
65833
  // src/services/workspace-sdk-service.ts
65777
- import { cp, mkdir as mkdir21 } from "fs/promises";
65778
- import { dirname as dirname17, resolve as resolve6 } from "path";
65834
+ import { cp, mkdir as mkdir17 } from "fs/promises";
65835
+ import { dirname as dirname14, resolve as resolve6 } from "path";
65779
65836
  import { fileURLToPath as fileURLToPath6 } from "url";
65780
65837
  async function installWorkspaceSdk() {
65781
- const source = resolve6(dirname17(fileURLToPath6(import.meta.url)), "../../workspace-sdk");
65838
+ const source = resolve6(dirname14(fileURLToPath6(import.meta.url)), "../../workspace-sdk");
65782
65839
  const targets = [
65783
65840
  resolve6(ENGINE_ENV.HOME_DIR, "node_modules/@replicas/sdk"),
65784
65841
  "/tmp/node_modules/@replicas/sdk"
65785
65842
  ];
65786
65843
  await Promise.all(targets.map(async (target) => {
65787
- await mkdir21(target, { recursive: true });
65844
+ await mkdir17(target, { recursive: true });
65788
65845
  await cp(source, target, { recursive: true, force: true });
65789
65846
  }));
65790
65847
  }
65791
65848
 
65792
65849
  // src/services/git-push-tracker.ts
65793
- import { mkdir as mkdir22, rm as rm8 } from "fs/promises";
65850
+ import { mkdir as mkdir18, rm as rm8 } from "fs/promises";
65794
65851
  import { createServer as createServer3 } from "net";
65795
65852
  import { join as join36 } from "path";
65796
65853
  var SOCKET_PATH = join36(ENGINE_DIR, "git-trace2.sock");
@@ -65803,7 +65860,7 @@ function startGitPushTracker() {
65803
65860
  });
65804
65861
  }
65805
65862
  async function listen() {
65806
- await mkdir22(ENGINE_DIR, { recursive: true });
65863
+ await mkdir18(ENGINE_DIR, { recursive: true });
65807
65864
  await rm8(SOCKET_PATH, { force: true });
65808
65865
  const server3 = createServer3((socket) => {
65809
65866
  let buffered = "";