replicas-engine 0.1.1225 → 0.1.1228

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.
@@ -8,12 +8,12 @@ import {
8
8
  listRunningCodexModels,
9
9
  restartCodexAspHost,
10
10
  restartCodexAspHostIfRunning
11
- } from "./chunk-UZ2QAPF2.js";
12
- import "./chunk-6ZM4T2RV.js";
13
- import "./chunk-UNNBJDIC.js";
14
- import "./chunk-4TXSP6DJ.js";
11
+ } from "./chunk-GFRFLS2A.js";
12
+ import "./chunk-SFEGIOZL.js";
13
+ import "./chunk-ULTPPI7M.js";
14
+ import "./chunk-EG7LG4JL.js";
15
15
  import "./chunk-UZSNFLDQ.js";
16
- import "./chunk-SE6ENDPR.js";
16
+ import "./chunk-QHUFRB7Y.js";
17
17
  import "./chunk-VEQXQN22.js";
18
18
  export {
19
19
  CODEX_ULTRAFAST_SERVICE_TIER,
@@ -5,14 +5,14 @@ import {
5
5
  getOriginDefaultBranch,
6
6
  monolithRequest,
7
7
  runGitCommand
8
- } from "./chunk-6ZM4T2RV.js";
8
+ } from "./chunk-SFEGIOZL.js";
9
9
  import {
10
10
  extractCommandProtectionCommandText,
11
11
  findCommandProtectionGitLookups,
12
12
  findGitCommitSignals,
13
13
  findPrMergeSignals,
14
14
  parseCommandProtectionRequest
15
- } from "./chunk-SE6ENDPR.js";
15
+ } from "./chunk-QHUFRB7Y.js";
16
16
 
17
17
  // src/services/command-protection-service.ts
18
18
  import { readFile, stat } from "fs/promises";
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  HOOK_EXEC_MAX_BUFFER_BYTES
6
- } from "./chunk-SE6ENDPR.js";
6
+ } from "./chunk-QHUFRB7Y.js";
7
7
 
8
8
  // src/utils/exec.ts
9
9
  import { exec, execFile } from "child_process";
@@ -5,7 +5,7 @@ import {
5
5
  extractCommandProtectionCommandText,
6
6
  isRecord,
7
7
  parseCodeHostPrUrl
8
- } from "./chunk-SE6ENDPR.js";
8
+ } from "./chunk-QHUFRB7Y.js";
9
9
 
10
10
  // src/services/published-pull-request-urls.ts
11
11
  function publishedPullRequestUrls(result) {
@@ -10,15 +10,15 @@ import {
10
10
  resolveDiffBase,
11
11
  runGitCommand,
12
12
  setAgentCredentialSnapshot
13
- } from "./chunk-6ZM4T2RV.js";
13
+ } from "./chunk-SFEGIOZL.js";
14
14
  import {
15
15
  AppServerProcess,
16
16
  buildCodexAgentEnv
17
- } from "./chunk-UNNBJDIC.js";
17
+ } from "./chunk-ULTPPI7M.js";
18
18
  import {
19
19
  SUBPROCESS_MAX_BUFFER,
20
20
  execFileAsync
21
- } from "./chunk-4TXSP6DJ.js";
21
+ } from "./chunk-EG7LG4JL.js";
22
22
  import {
23
23
  isRecord
24
24
  } from "./chunk-UZSNFLDQ.js";
@@ -55,7 +55,7 @@ import {
55
55
  resolveOpenAICompatibleModelsUrl,
56
56
  splitMothershipInstructions,
57
57
  withTimeout
58
- } from "./chunk-SE6ENDPR.js";
58
+ } from "./chunk-QHUFRB7Y.js";
59
59
 
60
60
  // src/managers/codex-token-manager.ts
61
61
  import { promises as fs } from "fs";
@@ -291,7 +291,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
291
291
  await this.applyCredentialUpdate(++this.credentialGeneration, async () => {
292
292
  await this.applyCredentialsResponse(data);
293
293
  setAgentCredentialSnapshot("codex", data);
294
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-HTNK63ET.js");
294
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-RLH2P5A6.js");
295
295
  await restartCodexAspHostIfRunning2();
296
296
  });
297
297
  await this.start(true);
@@ -313,7 +313,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
313
313
  const accountChanged = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex?.credentialId !== data.credentialId;
314
314
  await this.applyCredentialsResponse(data);
315
315
  if (restartOnChange && (accountChanged || CODEX_AUTH_ENV_KEYS.some((key, index) => process.env[key] !== previousEnv[index]))) {
316
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-HTNK63ET.js");
316
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-RLH2P5A6.js");
317
317
  await restartCodexAspHostIfRunning2();
318
318
  }
319
319
  setAgentCredentialSnapshot("codex", data);
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  AspClient
6
- } from "./chunk-UNNBJDIC.js";
6
+ } from "./chunk-ULTPPI7M.js";
7
7
  import {
8
8
  ASTER_BASE_URL,
9
9
  ASTER_PROVIDER,
@@ -13,7 +13,7 @@ import {
13
13
  isRecord,
14
14
  readOllamaAuthEnv,
15
15
  readOpenAICompatibleAuthEnv
16
- } from "./chunk-SE6ENDPR.js";
16
+ } from "./chunk-QHUFRB7Y.js";
17
17
 
18
18
  // src/managers/codex-asp/notification-dispatch.ts
19
19
  var TURN_STARTED_METHOD = "turn/started";
@@ -1501,6 +1501,7 @@ var CONTEXT_USAGE_EVENT_TYPE = "context-usage";
1501
1501
  // ../shared/src/engine/v1.ts
1502
1502
  import { z as z4 } from "zod";
1503
1503
  var MERGED_MESSAGE_SEPARATOR = "\n\n<!-- replicas:merged -->\n\n";
1504
+ var ENGINE_STREAM_LAST_EVENT_ID_HEADER = "Last-Event-ID";
1504
1505
  var ENGINE_HEALTH_WAIT_HEADER = "X-Replicas-Health-Wait";
1505
1506
  var ENGINE_HEALTH_WAIT_QUERY_PARAM = "wait_ms";
1506
1507
  var ENGINE_HEALTH_MAX_WAIT_MS = 2e3;
@@ -7979,10 +7980,161 @@ function parseAgentEventJsonl(content, options = {}) {
7979
7980
  return events;
7980
7981
  }
7981
7982
 
7983
+ // ../shared/src/chat-transcript-pages.ts
7984
+ var decoder = new TextDecoder("utf-8", { fatal: true });
7985
+ var encoder = new TextEncoder();
7986
+ var MAX_SOURCE_PAGE_BYTES = 4 * 1024 * 1024;
7987
+ var SOURCE_RANGE_BYTES = 256 * 1024;
7988
+ var CHAT_HISTORY_PAGE_MAX_BYTES = 1024 * 1024;
7989
+ async function readExactRange(readRange, startByte, endByte, error) {
7990
+ const bytes = await readRange(startByte, endByte);
7991
+ if (bytes.length !== endByte - startByte) throw new Error(error);
7992
+ return bytes;
7993
+ }
7994
+ async function readJsonlPage(args) {
7995
+ const maxBytes = args.maxBytes ?? Infinity;
7996
+ let endByte = args.size;
7997
+ if (args.before === null) endByte = 0;
7998
+ else if (args.before !== void 0) {
7999
+ endByte = /^(0|[1-9]\d*)$/.test(args.before) ? Number(args.before) : Number.NaN;
8000
+ }
8001
+ if (!Number.isSafeInteger(endByte) || endByte < 0 || endByte > args.size || !Number.isSafeInteger(args.limit) || args.limit < 1) {
8002
+ throw new RangeError("Invalid JSONL page");
8003
+ }
8004
+ let startByte = endByte;
8005
+ let head = new Uint8Array();
8006
+ let headTerminated = false;
8007
+ let lineBreaks = 0;
8008
+ let endsWithLineBreak = false;
8009
+ const pages = [];
8010
+ const recordStarts = [];
8011
+ let itemCount = 0;
8012
+ let itemBytes = 0;
8013
+ while (startByte > 0 && (recordStarts.flat().length < args.limit || itemCount < args.limit && itemBytes < maxBytes) && (endByte - startByte < MAX_SOURCE_PAGE_BYTES || lineBreaks - (endsWithLineBreak ? 1 : 0) === 0)) {
8014
+ const read = endByte - startByte;
8015
+ const nextStartByte = Math.max(0, startByte - (read < MAX_SOURCE_PAGE_BYTES ? Math.min(Math.max(SOURCE_RANGE_BYTES, read), MAX_SOURCE_PAGE_BYTES - read) : SOURCE_RANGE_BYTES));
8016
+ const chunk = await readExactRange(
8017
+ args.readRange,
8018
+ nextStartByte,
8019
+ startByte,
8020
+ "Incomplete JSONL page read"
8021
+ );
8022
+ if (startByte === endByte) endsWithLineBreak = chunk[chunk.length - 1] === 10;
8023
+ for (let index = chunk.indexOf(10); index !== -1; index = chunk.indexOf(10, index + 1)) lineBreaks++;
8024
+ const bytes = new Uint8Array(chunk.length + head.length + (headTerminated ? 1 : 0));
8025
+ bytes.set(chunk);
8026
+ bytes.set(head, chunk.length);
8027
+ if (headTerminated) bytes[bytes.length - 1] = 10;
8028
+ startByte = nextStartByte;
8029
+ const firstLineEnd = bytes.indexOf(10);
8030
+ const page = [];
8031
+ const pageRecordStarts = [];
8032
+ let lineStart = startByte > 0 ? firstLineEnd + 1 : 0;
8033
+ for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
8034
+ try {
8035
+ const value = JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd)));
8036
+ pageRecordStarts.push(startByte + lineStart);
8037
+ const item = args.parse(value);
8038
+ if (item !== void 0) {
8039
+ const itemSize = item === value ? lineEnd - lineStart : encoder.encode(JSON.stringify(item)).byteLength;
8040
+ page.push({ item, startByte: startByte + lineStart, bytes: itemSize });
8041
+ itemBytes += itemSize;
8042
+ }
8043
+ } catch {
8044
+ }
8045
+ lineStart = lineEnd + 1;
8046
+ }
8047
+ head = firstLineEnd === -1 ? bytes : bytes.subarray(0, startByte > 0 ? firstLineEnd : 0);
8048
+ headTerminated = firstLineEnd !== -1;
8049
+ pages.push(page);
8050
+ recordStarts.push(pageRecordStarts);
8051
+ itemCount += page.length;
8052
+ }
8053
+ const candidates = pages.reverse().flat();
8054
+ let selectedBytes = 0;
8055
+ let first = candidates.length;
8056
+ while (first > 0 && candidates.length - first < args.limit && (first === candidates.length || selectedBytes + candidates[first - 1].bytes <= maxBytes)) {
8057
+ first--;
8058
+ selectedBytes += candidates[first].bytes;
8059
+ }
8060
+ const records = recordStarts.reverse().flat();
8061
+ const floor = records[Math.max(0, records.length - args.limit)] ?? Infinity;
8062
+ while (first > 0 && candidates[first - 1].startByte >= floor) first--;
8063
+ const selected = candidates.slice(first);
8064
+ const firstCompleteLine = headTerminated ? head.length + 1 : 0;
8065
+ let before = 0;
8066
+ if (first > 0 || selected.length === args.limit || itemBytes >= maxBytes) before = selected[0].startByte;
8067
+ else if (startByte > 0) {
8068
+ const nextBefore = startByte + firstCompleteLine;
8069
+ before = nextBefore < endByte ? nextBefore : startByte;
8070
+ }
8071
+ return {
8072
+ items: selected.map(({ item }) => item),
8073
+ before: before > 0 ? String(before) : null
8074
+ };
8075
+ }
8076
+ var MAX_APPENDED_BYTES = 4 * 1024 * 1024;
8077
+ async function readJsonlAppended(args) {
8078
+ const start = /^(0|[1-9]\d*)$/.test(args.after) ? Number(args.after) : Number.NaN;
8079
+ if (!Number.isSafeInteger(start) || start > args.size || args.size - start > MAX_APPENDED_BYTES) return null;
8080
+ if (start === args.size) return { items: [], after: args.after };
8081
+ const from = Math.max(0, start - 1);
8082
+ const bytes = await readExactRange(args.readRange, from, args.size, "Incomplete JSONL append read");
8083
+ if (start > 0 && bytes[0] !== 10) return null;
8084
+ const items = [];
8085
+ let lineStart = start - from;
8086
+ for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
8087
+ try {
8088
+ const item = args.parse(JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd))));
8089
+ if (item !== void 0) items.push(item);
8090
+ } catch {
8091
+ }
8092
+ lineStart = lineEnd + 1;
8093
+ }
8094
+ return { items, after: String(from + lineStart) };
8095
+ }
8096
+ function parseChatTranscriptHistoryIndex(value) {
8097
+ if (!isRecord(value) || value.version !== 2 || !isNonNegativeInteger(value.sourceSize)) return void 0;
8098
+ const removedMessageIds = Array.isArray(value.removedMessageIds) ? value.removedMessageIds.filter((id) => typeof id === "string") : [];
8099
+ if (value.codexAspTranscript === void 0) {
8100
+ return { version: 2, sourceSize: value.sourceSize, ...removedMessageIds.length ? { removedMessageIds } : {} };
8101
+ }
8102
+ if (!isRecord(value.codexAspTranscript) || typeof value.codexAspTranscript.threadId !== "string" || typeof value.codexAspTranscript.updatedAt !== "string" || !isNonNegativeInteger(value.codexAspTranscript.size)) return void 0;
8103
+ return {
8104
+ version: 2,
8105
+ sourceSize: value.sourceSize,
8106
+ ...removedMessageIds.length ? { removedMessageIds } : {},
8107
+ codexAspTranscript: {
8108
+ threadId: value.codexAspTranscript.threadId,
8109
+ updatedAt: value.codexAspTranscript.updatedAt,
8110
+ size: value.codexAspTranscript.size
8111
+ }
8112
+ };
8113
+ }
8114
+ function isNonNegativeInteger(value) {
8115
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
8116
+ }
8117
+
7982
8118
  // ../shared/src/codex-history.ts
7983
8119
  function isChatHistoryEvent(value) {
7984
8120
  return isAgentBackendEvent(value) && value.type !== CODEX_ASP_TRANSCRIPT_UPDATED_EVENT_TYPE && value.type !== CODEX_HISTORY_FORMAT_EVENT_TYPE;
7985
8121
  }
8122
+ var UNRENDERED_CLAUDE_SYSTEM_SUBTYPES = /* @__PURE__ */ new Set(["init", "commands_changed", "session_state_changed"]);
8123
+ function toChatHistoryPageEvent(value) {
8124
+ if (!isChatHistoryEvent(value)) return void 0;
8125
+ const { payload } = value;
8126
+ if (value.type === "claude-system" && (UNRENDERED_CLAUDE_SYSTEM_SUBTYPES.has(payload.subtype) || payload.subtype === "status" && payload.status !== "compacting" && payload.compact_result === void 0)) {
8127
+ return void 0;
8128
+ }
8129
+ if (value.type === "claude-user" && "tool_use_result" in payload) {
8130
+ const { tool_use_result: _duplicate, ...rest } = payload;
8131
+ return { ...value, payload: rest };
8132
+ }
8133
+ return value;
8134
+ }
8135
+ function readChatHistoryPage(args) {
8136
+ return readJsonlPage({ ...args, maxBytes: CHAT_HISTORY_PAGE_MAX_BYTES, parse: toChatHistoryPageEvent });
8137
+ }
7986
8138
  function codexHistoryFormatEvent() {
7987
8139
  return { timestamp: (/* @__PURE__ */ new Date()).toISOString(), type: CODEX_HISTORY_FORMAT_EVENT_TYPE, payload: { version: 2 } };
7988
8140
  }
@@ -9768,118 +9920,6 @@ var EMAIL_KEYS = [
9768
9920
  var MANUAL_EMAIL_TEMPLATE_KEYS = ["product_update"];
9769
9921
  var EMAIL_TEMPLATE_KEYS = [...EMAIL_KEYS, ...MANUAL_EMAIL_TEMPLATE_KEYS];
9770
9922
 
9771
- // ../shared/src/chat-transcript-pages.ts
9772
- var decoder = new TextDecoder("utf-8", { fatal: true });
9773
- var MAX_SOURCE_PAGE_BYTES = 4 * 1024 * 1024;
9774
- var SOURCE_RANGE_BYTES = 256 * 1024;
9775
- async function readExactRange(readRange, startByte, endByte, error) {
9776
- const bytes = await readRange(startByte, endByte);
9777
- if (bytes.length !== endByte - startByte) throw new Error(error);
9778
- return bytes;
9779
- }
9780
- async function readJsonlPage(args) {
9781
- let endByte = args.size;
9782
- if (args.before === null) endByte = 0;
9783
- else if (args.before !== void 0) {
9784
- endByte = /^(0|[1-9]\d*)$/.test(args.before) ? Number(args.before) : Number.NaN;
9785
- }
9786
- if (!Number.isSafeInteger(endByte) || endByte < 0 || endByte > args.size || !Number.isSafeInteger(args.limit) || args.limit < 1) {
9787
- throw new RangeError("Invalid JSONL page");
9788
- }
9789
- let startByte = endByte;
9790
- let head = new Uint8Array();
9791
- let headTerminated = false;
9792
- let lineBreaks = 0;
9793
- let endsWithLineBreak = false;
9794
- const pages = [];
9795
- let itemCount = 0;
9796
- while (startByte > 0 && itemCount < args.limit && (endByte - startByte < MAX_SOURCE_PAGE_BYTES || lineBreaks - (endsWithLineBreak ? 1 : 0) === 0)) {
9797
- const read = endByte - startByte;
9798
- const nextStartByte = Math.max(0, startByte - (read < MAX_SOURCE_PAGE_BYTES ? Math.min(Math.max(SOURCE_RANGE_BYTES, read), MAX_SOURCE_PAGE_BYTES - read) : SOURCE_RANGE_BYTES));
9799
- const chunk = await readExactRange(
9800
- args.readRange,
9801
- nextStartByte,
9802
- startByte,
9803
- "Incomplete JSONL page read"
9804
- );
9805
- if (startByte === endByte) endsWithLineBreak = chunk[chunk.length - 1] === 10;
9806
- for (let index = chunk.indexOf(10); index !== -1; index = chunk.indexOf(10, index + 1)) lineBreaks++;
9807
- const bytes = new Uint8Array(chunk.length + head.length + (headTerminated ? 1 : 0));
9808
- bytes.set(chunk);
9809
- bytes.set(head, chunk.length);
9810
- if (headTerminated) bytes[bytes.length - 1] = 10;
9811
- startByte = nextStartByte;
9812
- const firstLineEnd = bytes.indexOf(10);
9813
- const page = [];
9814
- let lineStart = startByte > 0 ? firstLineEnd + 1 : 0;
9815
- for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
9816
- try {
9817
- const item = args.parse(JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd))));
9818
- if (item !== void 0) page.push({ item, startByte: startByte + lineStart });
9819
- } catch {
9820
- }
9821
- lineStart = lineEnd + 1;
9822
- }
9823
- head = firstLineEnd === -1 ? bytes : bytes.subarray(0, startByte > 0 ? firstLineEnd : 0);
9824
- headTerminated = firstLineEnd !== -1;
9825
- pages.push(page);
9826
- itemCount += page.length;
9827
- }
9828
- const selected = pages.reverse().flat().slice(-args.limit);
9829
- const firstCompleteLine = headTerminated ? head.length + 1 : 0;
9830
- let before = 0;
9831
- if (selected.length === args.limit) before = selected[0].startByte;
9832
- else if (startByte > 0) {
9833
- const nextBefore = startByte + firstCompleteLine;
9834
- before = nextBefore < endByte ? nextBefore : startByte;
9835
- }
9836
- return {
9837
- items: selected.map(({ item }) => item),
9838
- before: before > 0 ? String(before) : null
9839
- };
9840
- }
9841
- var MAX_APPENDED_BYTES = 4 * 1024 * 1024;
9842
- async function readJsonlAppended(args) {
9843
- const start = /^(0|[1-9]\d*)$/.test(args.after) ? Number(args.after) : Number.NaN;
9844
- if (!Number.isSafeInteger(start) || start > args.size || args.size - start > MAX_APPENDED_BYTES) return null;
9845
- if (start === args.size) return { items: [], after: args.after };
9846
- const from = Math.max(0, start - 1);
9847
- const bytes = await readExactRange(args.readRange, from, args.size, "Incomplete JSONL append read");
9848
- if (start > 0 && bytes[0] !== 10) return null;
9849
- const items = [];
9850
- let lineStart = start - from;
9851
- for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
9852
- try {
9853
- const item = args.parse(JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd))));
9854
- if (item !== void 0) items.push(item);
9855
- } catch {
9856
- }
9857
- lineStart = lineEnd + 1;
9858
- }
9859
- return { items, after: String(from + lineStart) };
9860
- }
9861
- function parseChatTranscriptHistoryIndex(value) {
9862
- if (!isRecord(value) || value.version !== 2 || !isNonNegativeInteger(value.sourceSize)) return void 0;
9863
- const removedMessageIds = Array.isArray(value.removedMessageIds) ? value.removedMessageIds.filter((id) => typeof id === "string") : [];
9864
- if (value.codexAspTranscript === void 0) {
9865
- return { version: 2, sourceSize: value.sourceSize, ...removedMessageIds.length ? { removedMessageIds } : {} };
9866
- }
9867
- if (!isRecord(value.codexAspTranscript) || typeof value.codexAspTranscript.threadId !== "string" || typeof value.codexAspTranscript.updatedAt !== "string" || !isNonNegativeInteger(value.codexAspTranscript.size)) return void 0;
9868
- return {
9869
- version: 2,
9870
- sourceSize: value.sourceSize,
9871
- ...removedMessageIds.length ? { removedMessageIds } : {},
9872
- codexAspTranscript: {
9873
- threadId: value.codexAspTranscript.threadId,
9874
- updatedAt: value.codexAspTranscript.updatedAt,
9875
- size: value.codexAspTranscript.size
9876
- }
9877
- };
9878
- }
9879
- function isNonNegativeInteger(value) {
9880
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
9881
- }
9882
-
9883
9923
  // ../shared/src/object-store/types.ts
9884
9924
  var MEDIA_KIND = {
9885
9925
  IMAGE: "image",
@@ -10123,6 +10163,7 @@ export {
10123
10163
  coerceChatGoalPayload,
10124
10164
  CONTEXT_USAGE_EVENT_TYPE,
10125
10165
  MERGED_MESSAGE_SEPARATOR,
10166
+ ENGINE_STREAM_LAST_EVENT_ID_HEADER,
10126
10167
  ENGINE_HEALTH_WAIT_HEADER,
10127
10168
  ENGINE_HEALTH_WAIT_QUERY_PARAM,
10128
10169
  ENGINE_HEALTH_MAX_WAIT_MS,
@@ -10201,7 +10242,9 @@ export {
10201
10242
  getEventTimestampMs,
10202
10243
  areSameUserMessageEvents,
10203
10244
  parseAgentEventJsonlLine,
10204
- isChatHistoryEvent,
10245
+ readJsonlAppended,
10246
+ toChatHistoryPageEvent,
10247
+ readChatHistoryPage,
10205
10248
  codexHistoryFormatEvent,
10206
10249
  CodexHistoryEventFolder,
10207
10250
  canonicalizeChatTranscriptBlocks,
@@ -10264,8 +10307,6 @@ export {
10264
10307
  searchRepoFileIndex,
10265
10308
  isExcludedRepoFilePath,
10266
10309
  ENVIRONMENT_HOOK_RUN_LOG_LIMIT,
10267
- readJsonlPage,
10268
- readJsonlAppended,
10269
10310
  normalizeChatTranscriptMetadata,
10270
10311
  parseChatTranscriptArtifact,
10271
10312
  readSseStream,
@@ -4,7 +4,7 @@ const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  SUBPROCESS_MAX_BUFFER,
6
6
  execFileAsync
7
- } from "./chunk-4TXSP6DJ.js";
7
+ } from "./chunk-EG7LG4JL.js";
8
8
  import {
9
9
  isRecord as isRecord2
10
10
  } from "./chunk-UZSNFLDQ.js";
@@ -18,7 +18,7 @@ import {
18
18
  isValidAgentProvider,
19
19
  parsePosixEnvFile,
20
20
  readReplicasRuntimeEnv
21
- } from "./chunk-SE6ENDPR.js";
21
+ } from "./chunk-QHUFRB7Y.js";
22
22
 
23
23
  // src/runtime-env-loader.ts
24
24
  import { readFileSync } from "fs";
@@ -3,10 +3,10 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  execFileAsync
6
- } from "./chunk-4TXSP6DJ.js";
6
+ } from "./chunk-EG7LG4JL.js";
7
7
  import {
8
8
  isVersionBelow
9
- } from "./chunk-SE6ENDPR.js";
9
+ } from "./chunk-QHUFRB7Y.js";
10
10
 
11
11
  // src/utils/codex-agent-env.ts
12
12
  function buildCodexAgentEnv(source = process.env) {
@@ -240,7 +240,7 @@ function getCodexModelProvider(method) {
240
240
  if (method === "foundry") return "azure";
241
241
  return method === "ollama" || method === "openai-compatible" ? "replicas_openai_compatible" : "openai";
242
242
  }
243
- var ENGINE_PACKAGE_VERSION = "0.1.1225";
243
+ var ENGINE_PACKAGE_VERSION = "0.1.1228";
244
244
  var INITIALIZE_METHOD = "initialize";
245
245
  var INITIALIZED_NOTIFICATION = "initialized";
246
246
  var ACCOUNT_LOGIN_START_METHOD = "account/login/start";
@@ -3,13 +3,13 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  evaluateCommandProtection
6
- } from "./chunk-XVG3AOGM.js";
7
- import "./chunk-6ZM4T2RV.js";
8
- import "./chunk-4TXSP6DJ.js";
6
+ } from "./chunk-DCLSGOQT.js";
7
+ import "./chunk-SFEGIOZL.js";
8
+ import "./chunk-EG7LG4JL.js";
9
9
  import {
10
10
  isRecord
11
11
  } from "./chunk-UZSNFLDQ.js";
12
- import "./chunk-SE6ENDPR.js";
12
+ import "./chunk-QHUFRB7Y.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/command-protection-hook.ts
@@ -13,12 +13,12 @@ import {
13
13
  recoverCompletedTurn,
14
14
  spawnMuseMsp,
15
15
  startMuseSession
16
- } from "./chunk-HOOI54LZ.js";
16
+ } from "./chunk-MXGP2NFY.js";
17
17
  import {
18
18
  AppServerProcess,
19
19
  buildCodexAgentEnv
20
- } from "./chunk-UNNBJDIC.js";
21
- import "./chunk-4TXSP6DJ.js";
20
+ } from "./chunk-ULTPPI7M.js";
21
+ import "./chunk-EG7LG4JL.js";
22
22
  import {
23
23
  AGENT,
24
24
  OPENCODE_GO_PROVIDER,
@@ -28,7 +28,7 @@ import {
28
28
  headlessAgentUsagePath,
29
29
  isRecord,
30
30
  withTimeout
31
- } from "./chunk-SE6ENDPR.js";
31
+ } from "./chunk-QHUFRB7Y.js";
32
32
  import "./chunk-VEQXQN22.js";
33
33
 
34
34
  // src/headless-agent.ts
package/dist/src/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  evaluateCommandProtection,
28
28
  extractToolCommand,
29
29
  reportCommandProtectionBlock
30
- } from "./chunk-XVG3AOGM.js";
30
+ } from "./chunk-DCLSGOQT.js";
31
31
  import {
32
32
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
33
33
  AGENT_MESSAGE_DELTA_METHOD,
@@ -64,10 +64,10 @@ import {
64
64
  spawnMuseMsp,
65
65
  startMuseSession,
66
66
  uuidV7
67
- } from "./chunk-HOOI54LZ.js";
67
+ } from "./chunk-MXGP2NFY.js";
68
68
  import {
69
69
  publishedPullRequestUrls
70
- } from "./chunk-C2I3YQ5R.js";
70
+ } from "./chunk-FAMHG6VD.js";
71
71
  import {
72
72
  ACCOUNT_RATE_LIMITS_READ_METHOD,
73
73
  AsyncLock,
@@ -140,7 +140,7 @@ import {
140
140
  timestampFromSeconds,
141
141
  upsertCredentialFileLines,
142
142
  writeSecureCredentialFile
143
- } from "./chunk-UZ2QAPF2.js";
143
+ } from "./chunk-GFRFLS2A.js";
144
144
  import {
145
145
  ENGINE_ENV,
146
146
  monolithRequest,
@@ -149,15 +149,15 @@ import {
149
149
  reloadEngineEnv,
150
150
  resolveDiffBase,
151
151
  setAgentCredentialSnapshot
152
- } from "./chunk-6ZM4T2RV.js";
152
+ } from "./chunk-SFEGIOZL.js";
153
153
  import {
154
154
  getCodexModelProvider
155
- } from "./chunk-UNNBJDIC.js";
155
+ } from "./chunk-ULTPPI7M.js";
156
156
  import {
157
157
  SUBPROCESS_MAX_BUFFER,
158
158
  execAsync,
159
159
  execFileAsync
160
- } from "./chunk-4TXSP6DJ.js";
160
+ } from "./chunk-EG7LG4JL.js";
161
161
  import {
162
162
  isRecord as isRecord2
163
163
  } from "./chunk-UZSNFLDQ.js";
@@ -212,6 +212,7 @@ import {
212
212
  ENGINE_HEALTH_WAIT_QUERY_PARAM,
213
213
  ENGINE_SEND_MESSAGE_FAILED_ERROR,
214
214
  ENGINE_SLEEP_PATH,
215
+ ENGINE_STREAM_LAST_EVENT_ID_HEADER,
215
216
  ENVIRONMENT_HOOK_RUN_LOG_LIMIT,
216
217
  GITHUB_CREDENTIAL_REFRESH_PATH,
217
218
  GITLAB_CREDENTIAL_REFRESH_PATH,
@@ -321,7 +322,6 @@ import {
321
322
  isAgentChatSkillActivityRecord,
322
323
  isAgentChatTurnActivityRecord,
323
324
  isCanvasTextKind,
324
- isChatHistoryEvent,
325
325
  isChatMessageSender,
326
326
  isClaudeAuthErrorText,
327
327
  isClaudeResultError,
@@ -366,8 +366,8 @@ import {
366
366
  parseReplicasConfigString,
367
367
  percentage,
368
368
  raceWithTimeout,
369
+ readChatHistoryPage,
369
370
  readJsonlAppended,
370
- readJsonlPage,
371
371
  readOllamaAuthEnv,
372
372
  readOpenAICompatibleAuthEnv,
373
373
  readReplicasRuntimeEnv,
@@ -384,6 +384,7 @@ import {
384
384
  spawnSubagentRequestSchema,
385
385
  splitMothershipInstructions,
386
386
  stripAgentDiagnosticErrors,
387
+ toChatHistoryPageEvent,
387
388
  toClaudeCodeModel,
388
389
  updateChatDisplayNameRequestSchema,
389
390
  waitSubagentRequestSchema,
@@ -393,7 +394,7 @@ import {
393
394
  workspaceTokenRequestSchema,
394
395
  workspaceTokenResponseSchema,
395
396
  wrapInTag
396
- } from "./chunk-SE6ENDPR.js";
397
+ } from "./chunk-QHUFRB7Y.js";
397
398
  import {
398
399
  cloneMcpConfig,
399
400
  ensureCompatibilityImports,
@@ -10300,32 +10301,97 @@ import { mkdir as mkdir5 } from "fs/promises";
10300
10301
  import { join as join6 } from "path";
10301
10302
  import { randomUUID as randomUUID2 } from "crypto";
10302
10303
  var EVENTS_FILE = join6(ENGINE_DIR, "events.jsonl");
10304
+ var MAX_REPLAY_EVENTS = 2e3;
10305
+ var MAX_REPLAY_CHARS = 4 * 1024 * 1024;
10306
+ function partialKey(event) {
10307
+ if (event.type !== "chat.turn.delta") return null;
10308
+ const { type } = event.payload.event;
10309
+ if (type !== CLAUDE_PARTIAL_MESSAGE_EVENT_TYPE && type !== CODEX_ITEM_PARTIAL_EVENT_TYPE) return null;
10310
+ const streamId = getEventStreamId(event.payload.event);
10311
+ return streamId ? `${event.payload.chatId}:${type}:${streamId}` : null;
10312
+ }
10303
10313
  var EventService = class {
10304
- subscribers = /* @__PURE__ */ new Map();
10314
+ subscribers = /* @__PURE__ */ new Set();
10305
10315
  writer = new StreamWriter();
10316
+ epoch = randomUUID2();
10317
+ seq = 0;
10318
+ replay = [];
10319
+ replayChars = 0;
10320
+ // Newest seq dropped for space: a client that last saw an older seq cannot resume.
10321
+ replayFloor = 0;
10322
+ latestPartials = /* @__PURE__ */ new Map();
10306
10323
  async initialize() {
10307
10324
  await mkdir5(ENGINE_DIR, { recursive: true });
10308
10325
  this.writer.open(EVENTS_FILE);
10309
10326
  }
10310
- subscribe(subscriber) {
10311
- const id = randomUUID2();
10312
- this.subscribers.set(id, subscriber);
10327
+ subscribe(subscriber, lastEventId) {
10328
+ const separator = lastEventId?.lastIndexOf(":") ?? -1;
10329
+ const after = lastEventId ? Number(lastEventId.slice(separator + 1)) : Number.NaN;
10330
+ const resumed = separator > 0 && lastEventId?.slice(0, separator) === this.epoch && Number.isSafeInteger(after) && after >= this.replayFloor && after <= this.seq;
10331
+ const opened = {
10332
+ id: randomUUID2(),
10333
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
10334
+ type: "engine.stream.opened",
10335
+ payload: { epoch: this.epoch, seq: this.seq, resumed }
10336
+ };
10337
+ subscriber(`id: ${this.epoch}:${resumed ? after : this.seq}
10338
+ event: ${opened.type}
10339
+ data: ${JSON.stringify(opened)}
10340
+
10341
+ `);
10342
+ if (resumed) {
10343
+ for (const entry of this.replay) {
10344
+ if (entry.seq > after) subscriber(entry.frame);
10345
+ }
10346
+ }
10347
+ this.subscribers.add(subscriber);
10313
10348
  return () => {
10314
- this.subscribers.delete(id);
10349
+ this.subscribers.delete(subscriber);
10315
10350
  };
10316
10351
  }
10317
10352
  getSubscriberCount() {
10318
10353
  return this.subscribers.size;
10319
10354
  }
10320
10355
  async publish(event) {
10321
- this.writer.write(JSON.stringify(event) + "\n");
10322
- for (const subscriber of this.subscribers.values()) {
10356
+ const seq = ++this.seq;
10357
+ const data = JSON.stringify({ ...event, seq });
10358
+ this.writer.write(data + "\n");
10359
+ const entry = { seq, frame: `id: ${this.epoch}:${seq}
10360
+ event: ${event.type}
10361
+ data: ${data}
10362
+
10363
+ `, partialKey: partialKey(event) };
10364
+ this.remember(entry);
10365
+ for (const subscriber of this.subscribers) {
10323
10366
  try {
10324
- subscriber(event);
10367
+ subscriber(entry.frame);
10325
10368
  } catch {
10326
10369
  }
10327
10370
  }
10328
10371
  }
10372
+ // A newer partial carries the whole message so far, so only the latest one per message is replayed.
10373
+ remember(entry) {
10374
+ if (entry.partialKey) {
10375
+ const superseded = this.latestPartials.get(entry.partialKey);
10376
+ if (superseded) {
10377
+ const index = this.replay.indexOf(superseded);
10378
+ if (index !== -1) {
10379
+ this.replay.splice(index, 1);
10380
+ this.replayChars -= superseded.frame.length;
10381
+ }
10382
+ }
10383
+ this.latestPartials.set(entry.partialKey, entry);
10384
+ }
10385
+ this.replay.push(entry);
10386
+ this.replayChars += entry.frame.length;
10387
+ while (this.replay.length > MAX_REPLAY_EVENTS || this.replayChars > MAX_REPLAY_CHARS && this.replay.length > 1) {
10388
+ const evicted = this.replay.shift();
10389
+ if (!evicted) break;
10390
+ this.replayChars -= evicted.frame.length;
10391
+ this.replayFloor = evicted.seq;
10392
+ if (evicted.partialKey && this.latestPartials.get(evicted.partialKey) === evicted) this.latestPartials.delete(evicted.partialKey);
10393
+ }
10394
+ }
10329
10395
  };
10330
10396
  var eventService = new EventService();
10331
10397
 
@@ -11614,6 +11680,9 @@ ${request.message}` }, senderKey };
11614
11680
  subagentMcpParentChatId() {
11615
11681
  return this.subagentMcpEnabledForTurn ? this.subagentMcpChatId : void 0;
11616
11682
  }
11683
+ getHistoryEnd() {
11684
+ return this.getHistorySink()?.historyEnd;
11685
+ }
11617
11686
  async persistHistoryEvent(event) {
11618
11687
  const history = this.getHistorySink();
11619
11688
  if (!history?.appendDurably) throw new Error("Chat history is unavailable");
@@ -12294,7 +12363,7 @@ function isNotFoundError(error) {
12294
12363
  }
12295
12364
 
12296
12365
  // src/managers/codex-asp/codex-history-file.ts
12297
- import { createReadStream } from "fs";
12366
+ import { createReadStream, statSync } from "fs";
12298
12367
  import { appendFile as appendFile2, open, rename } from "fs/promises";
12299
12368
  import { createInterface } from "readline";
12300
12369
  var MIGRATION_FLUSH_CHARS = 1 << 20;
@@ -12304,9 +12373,20 @@ function isMissingFile(error) {
12304
12373
  var CodexHistoryFile = class {
12305
12374
  constructor(filePath) {
12306
12375
  this.filePath = filePath;
12376
+ try {
12377
+ this.reservedSize = statSync(filePath).size;
12378
+ } catch (error) {
12379
+ if (!isMissingFile(error)) throw error;
12380
+ this.reservedSize = 0;
12381
+ }
12307
12382
  }
12308
12383
  filePath;
12309
12384
  writeLock = new AsyncLock();
12385
+ // Bytes the file holds once every queued append lands; unknown after a failed write or a rewrite.
12386
+ reservedSize;
12387
+ get historyEnd() {
12388
+ return this.reservedSize;
12389
+ }
12310
12390
  /** Best-effort ordered append; failures must not disrupt the turn. */
12311
12391
  append(event) {
12312
12392
  void this.appendDurably(event).catch((error) => {
@@ -12314,8 +12394,18 @@ var CodexHistoryFile = class {
12314
12394
  });
12315
12395
  }
12316
12396
  appendDurably(event) {
12317
- return this.writeLock.run(() => appendFile2(this.filePath, `${JSON.stringify(event)}
12318
- `));
12397
+ const reserved = `${JSON.stringify(event)}
12398
+ `;
12399
+ if (this.reservedSize !== void 0) this.reservedSize += Buffer.byteLength(reserved);
12400
+ return this.writeLock.run(() => {
12401
+ const line = `${JSON.stringify(event)}
12402
+ `;
12403
+ if (line !== reserved) this.reservedSize = void 0;
12404
+ return appendFile2(this.filePath, line);
12405
+ }).catch((error) => {
12406
+ this.reservedSize = void 0;
12407
+ throw error;
12408
+ });
12319
12409
  }
12320
12410
  async flush() {
12321
12411
  await this.writeLock.drain();
@@ -12333,6 +12423,7 @@ var CodexHistoryFile = class {
12333
12423
  return;
12334
12424
  }
12335
12425
  if (parseAgentEventJsonlLine(firstLine)?.type === CODEX_HISTORY_FORMAT_EVENT_TYPE) return;
12426
+ this.reservedSize = void 0;
12336
12427
  await this.writeLock.run(async () => {
12337
12428
  const events = await this.loadAll();
12338
12429
  const rewritten = `${this.filePath}.migrating`;
@@ -12417,12 +12508,11 @@ var CodexHistoryFile = class {
12417
12508
  const { bytesRead } = await file.read(bytes, 0, bytes.length, startByte);
12418
12509
  return bytes.subarray(0, bytesRead);
12419
12510
  };
12420
- const parse2 = (value) => isChatHistoryEvent(value) ? value : void 0;
12421
12511
  if (page2.afterCursor !== void 0 && cursor === void 0) {
12422
- const appended = await readJsonlAppended({ size, after: page2.afterCursor, readRange, parse: parse2 });
12512
+ const appended = await readJsonlAppended({ size, after: page2.afterCursor, readRange, parse: toChatHistoryPageEvent });
12423
12513
  if (appended) return { events: appended.items, afterCursor: appended.after, appendsAfter: page2.afterCursor };
12424
12514
  }
12425
- const result = await readJsonlPage({ size, limit: page2.limit, before: cursor?.events, readRange, parse: parse2 });
12515
+ const result = await readChatHistoryPage({ size, limit: page2.limit, before: cursor?.events, readRange });
12426
12516
  return {
12427
12517
  events: result.items,
12428
12518
  beforeCursor: createChatHistoryCursor({ events: result.before, turns: null }),
@@ -14080,11 +14170,13 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14080
14170
  async recordEvent(event, replicasMessageId) {
14081
14171
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
14082
14172
  const restampAmbient = event.type === "system" && "task_id" in event && this.ambientTaskIds.has(event.task_id);
14173
+ const payload = { ...event };
14174
+ delete payload.tool_use_result;
14083
14175
  const jsonEvent = {
14084
14176
  timestamp,
14085
14177
  type: `claude-${event.type}`,
14086
14178
  payload: {
14087
- ...event,
14179
+ ...payload,
14088
14180
  ...restampAmbient ? { ambient: true } : {},
14089
14181
  ...replicasMessageId ? { [USER_MESSAGE_ID_PAYLOAD_KEY]: replicasMessageId } : {}
14090
14182
  }
@@ -14276,7 +14368,8 @@ var CodexAspManager = class extends CodingAgentManager {
14276
14368
  appendDurably: (event) => {
14277
14369
  if (!this.historyFile) throw new Error("Chat history is unavailable");
14278
14370
  return this.historyFile.appendDurably(event);
14279
- }
14371
+ },
14372
+ historyEnd: this.historyFile?.historyEnd
14280
14373
  };
14281
14374
  }
14282
14375
  async subagentMcpForTurn(enabled) {
@@ -14479,10 +14572,10 @@ var CodexAspManager = class extends CodingAgentManager {
14479
14572
  }
14480
14573
  recordUserMessageEvent(request, extraPayload = {}) {
14481
14574
  const images = imageContentToUserMessageImages(request.images);
14482
- this.recordCodexHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, {
14575
+ this.onEvent(this.recordCodexHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, {
14483
14576
  ...images ? { images } : {},
14484
14577
  ...extraPayload
14485
- }));
14578
+ })));
14486
14579
  }
14487
14580
  async processMessageInternal(request, signal) {
14488
14581
  let userMessageRecorded = false;
@@ -39118,7 +39211,7 @@ var StreamableHTTPClientTransport = class {
39118
39211
  };
39119
39212
 
39120
39213
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/server-manager.ts
39121
- import { mkdirSync as mkdirSync3, statSync as statSync2 } from "fs";
39214
+ import { mkdirSync as mkdirSync3, statSync as statSync3 } from "fs";
39122
39215
  import { isDeepStrictEqual } from "util";
39123
39216
 
39124
39217
  // ../node_modules/.bun/@modelcontextprotocol+client@2.0.0/node_modules/@modelcontextprotocol/client/dist/stdio.mjs
@@ -39551,7 +39644,7 @@ async function probeMcpEndpoint(url3) {
39551
39644
  }
39552
39645
 
39553
39646
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
39554
- import { existsSync as existsSync9, readFileSync as readFileSync2, realpathSync, readdirSync, statSync, writeFileSync as writeFileSync2, renameSync, mkdirSync as mkdirSync2, openSync, readSync, closeSync, unlinkSync } from "fs";
39647
+ import { existsSync as existsSync9, readFileSync as readFileSync2, realpathSync, readdirSync, statSync as statSync2, writeFileSync as writeFileSync2, renameSync, mkdirSync as mkdirSync2, openSync, readSync, closeSync, unlinkSync } from "fs";
39555
39648
  import { join as join15, dirname as dirname8, extname as extname2, resolve as resolve2, sep } from "path";
39556
39649
 
39557
39650
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
@@ -40002,7 +40095,7 @@ function safeRealpath(path7) {
40002
40095
  }
40003
40096
  function safeStatMtime(path7) {
40004
40097
  try {
40005
- return statSync(path7).mtimeMs;
40098
+ return statSync2(path7).mtimeMs;
40006
40099
  } catch {
40007
40100
  return 0;
40008
40101
  }
@@ -44654,7 +44747,7 @@ var McpServerManager = class {
44654
44747
  let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
44655
44748
  const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
44656
44749
  if (cwd !== void 0) {
44657
- const cwdStats = statSync2(cwd, { throwIfNoEntry: false });
44750
+ const cwdStats = statSync3(cwd, { throwIfNoEntry: false });
44658
44751
  if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
44659
44752
  if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
44660
44753
  }
@@ -59968,14 +60061,14 @@ ${decisions}` };
59968
60061
  };
59969
60062
  return await chat.provider.enqueueMessage(
59970
60063
  request,
59971
- (result, acceptedMessage) => this.handleMessageAccepted(
60064
+ (result, acceptedMessage) => this.withUnpublishedHistory(chat, () => this.handleMessageAccepted(
59972
60065
  chatId,
59973
60066
  chat,
59974
60067
  request,
59975
60068
  acceptedMessage,
59976
60069
  result,
59977
60070
  typedMessage
59978
- )
60071
+ ))
59979
60072
  );
59980
60073
  } catch (error) {
59981
60074
  if (seenBeforeSend) this.forkSourceSeenBlocks.set(chatId, seenBeforeSend);
@@ -60200,6 +60293,16 @@ ${decisions}` };
60200
60293
  queue: chat.provider.getQueue()
60201
60294
  };
60202
60295
  }
60296
+ async withUnpublishedHistory(chat, run) {
60297
+ const start = chat.provider.getHistoryEnd();
60298
+ if (start === void 0) return run();
60299
+ chat.unpublishedHistoryStarts.push(start);
60300
+ try {
60301
+ return await run();
60302
+ } finally {
60303
+ chat.unpublishedHistoryStarts.splice(chat.unpublishedHistoryStarts.indexOf(start), 1);
60304
+ }
60305
+ }
60203
60306
  publishQueueIfChanged(chatId) {
60204
60307
  const chat = this.getRuntimeChat(chatId);
60205
60308
  if (!chat) return;
@@ -60213,33 +60316,35 @@ ${decisions}` };
60213
60316
  }
60214
60317
  async forgetPendingMessages(chat, messageIds) {
60215
60318
  if (messageIds.length === 0) return;
60216
- const removed = new Set(messageIds);
60217
- const event = {
60218
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
60219
- type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
60220
- payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: [...removed] }
60221
- };
60222
- await chat.provider.persistHistoryEvent(event);
60223
- chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
60224
- chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
60225
- this.forkSourceSeenBlocks.delete(chat.persisted.id);
60226
- for (const messageId of removed) {
60227
- chat.acceptedUserEvents.delete(messageId);
60228
- chat.errorNotificationTargets.delete(messageId);
60229
- }
60230
- await this.persistAllChats().catch((error) => {
60231
- console.error("[ChatService] Failed to persist queued-message removals:", error);
60232
- });
60233
- await this.publish({
60234
- type: "chat.turn.delta",
60235
- payload: { chatId: chat.persisted.id, event }
60236
- }).catch((error) => {
60237
- console.error("[ChatService] Failed to publish queued-message removals:", error);
60238
- });
60239
- this.publish({
60240
- type: "chat.updated",
60241
- payload: { chat: this.toSummary(chat) }
60242
- }).catch(() => {
60319
+ await this.withUnpublishedHistory(chat, async () => {
60320
+ const removed = new Set(messageIds);
60321
+ const event = {
60322
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
60323
+ type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
60324
+ payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: [...removed] }
60325
+ };
60326
+ await chat.provider.persistHistoryEvent(event);
60327
+ chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
60328
+ chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
60329
+ this.forkSourceSeenBlocks.delete(chat.persisted.id);
60330
+ for (const messageId of removed) {
60331
+ chat.acceptedUserEvents.delete(messageId);
60332
+ chat.errorNotificationTargets.delete(messageId);
60333
+ }
60334
+ await this.persistAllChats().catch((error) => {
60335
+ console.error("[ChatService] Failed to persist queued-message removals:", error);
60336
+ });
60337
+ await this.publish({
60338
+ type: "chat.turn.delta",
60339
+ payload: { chatId: chat.persisted.id, event }
60340
+ }).catch((error) => {
60341
+ console.error("[ChatService] Failed to publish queued-message removals:", error);
60342
+ });
60343
+ this.publish({
60344
+ type: "chat.updated",
60345
+ payload: { chat: this.toSummary(chat) }
60346
+ }).catch(() => {
60347
+ });
60243
60348
  });
60244
60349
  }
60245
60350
  async removeFromQueue(chatId, messageId) {
@@ -60836,6 +60941,7 @@ ${note}`;
60836
60941
  turnCompletion: null,
60837
60942
  publishedQueue: null,
60838
60943
  idleReleaseTimer: null,
60944
+ unpublishedHistoryStarts: [],
60839
60945
  live: false,
60840
60946
  release: null,
60841
60947
  errorNotificationTargets: /* @__PURE__ */ new Map(),
@@ -61194,6 +61300,10 @@ ${note}`;
61194
61300
  return;
61195
61301
  }
61196
61302
  const chat = chatId ? this.chats.get(chatId) : void 0;
61303
+ if (chat && event.type === "chat.turn.delta") {
61304
+ const historyEnd = chat.provider.getHistoryEnd();
61305
+ if (historyEnd !== void 0) event.payload.historyEnd = Math.min(historyEnd, ...chat.unpublishedHistoryStarts);
61306
+ }
61197
61307
  if (chat) {
61198
61308
  chat.historyVersion = event.id;
61199
61309
  if (event.type === "chat.created" || event.type === "chat.updated") {
@@ -62100,7 +62210,7 @@ import { randomUUID as randomUUID11 } from "crypto";
62100
62210
  import { existsSync as existsSync17 } from "fs";
62101
62211
  import { spawn as spawn6 } from "node-pty";
62102
62212
  import { z as z3 } from "zod";
62103
- var MAX_REPLAY_CHARS = 1024 * 1024;
62213
+ var MAX_REPLAY_CHARS2 = 1024 * 1024;
62104
62214
  var MAX_TERMINAL_SESSIONS = 8;
62105
62215
  var MAX_PENDING_INPUT = 64;
62106
62216
  var terminalSizeSchema = z3.object({
@@ -62151,7 +62261,7 @@ var TerminalService = class {
62151
62261
  };
62152
62262
  this.sessions.set(id, session);
62153
62263
  pty.onData((data) => {
62154
- session.replay = (session.replay + data).slice(-MAX_REPLAY_CHARS);
62264
+ session.replay = (session.replay + data).slice(-MAX_REPLAY_CHARS2);
62155
62265
  for (const subscriber of session.subscribers) subscriber(data);
62156
62266
  });
62157
62267
  pty.onExit(({ exitCode }) => {
@@ -62160,7 +62270,7 @@ var TerminalService = class {
62160
62270
  const data = `\r
62161
62271
  \x1B[2m[Process exited with code ${exitCode}]\x1B[0m\r
62162
62272
  `;
62163
- session.replay = (session.replay + data).slice(-MAX_REPLAY_CHARS);
62273
+ session.replay = (session.replay + data).slice(-MAX_REPLAY_CHARS2);
62164
62274
  for (const subscriber of session.subscribers) subscriber(data);
62165
62275
  });
62166
62276
  return createSuccessResult(this.publicSession(session));
@@ -62331,8 +62441,9 @@ function createV1Routes(deps) {
62331
62441
  ), status);
62332
62442
  }
62333
62443
  };
62334
- app2.get("/events", async () => {
62444
+ app2.get("/events", async (c) => {
62335
62445
  const encoder2 = new TextEncoder();
62446
+ const lastEventId = c.req.header(ENGINE_STREAM_LAST_EVENT_ID_HEADER);
62336
62447
  let unsubscribe = null;
62337
62448
  let heartbeat = null;
62338
62449
  const cleanup = () => {
@@ -62356,20 +62467,10 @@ function createV1Routes(deps) {
62356
62467
  return false;
62357
62468
  }
62358
62469
  };
62359
- const writeEvent = (event) => {
62360
- if (!safeEnqueue(`id: ${event.id}
62361
- `)) return;
62362
- if (!safeEnqueue(`event: ${event.type}
62363
- `)) return;
62364
- safeEnqueue(`data: ${JSON.stringify(event)}
62365
-
62366
- `);
62367
- };
62368
- unsubscribe = eventService.subscribe(writeEvent);
62470
+ unsubscribe = eventService.subscribe(safeEnqueue, lastEventId);
62369
62471
  heartbeat = setInterval(() => {
62370
62472
  safeEnqueue(": ping\n\n");
62371
62473
  }, 15e3);
62372
- safeEnqueue(": connected\n\n");
62373
62474
  },
62374
62475
  cancel: () => {
62375
62476
  cleanup();
@@ -3,13 +3,13 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  publishedPullRequestUrls
6
- } from "./chunk-C2I3YQ5R.js";
6
+ } from "./chunk-FAMHG6VD.js";
7
7
  import {
8
8
  isRecord
9
9
  } from "./chunk-UZSNFLDQ.js";
10
10
  import {
11
11
  shouldRefreshPullRequests
12
- } from "./chunk-SE6ENDPR.js";
12
+ } from "./chunk-QHUFRB7Y.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/services/post-tool-pr-notifier.ts
@@ -9,7 +9,7 @@ import {
9
9
  spawnSubagentRequestSchema,
10
10
  subagentResponseSchema,
11
11
  waitSubagentRequestSchema
12
- } from "./chunk-SE6ENDPR.js";
12
+ } from "./chunk-QHUFRB7Y.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/subagent-mcp.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replicas-engine",
3
- "version": "0.1.1225",
3
+ "version": "0.1.1228",
4
4
  "description": "Lightweight API server for Replicas workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",