replicas-engine 0.1.1226 → 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-R7MHJUBF.js";
12
- import "./chunk-MRAUGYDC.js";
13
- import "./chunk-ATHUSFGB.js";
14
- import "./chunk-LF7ND553.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-OPV7WB6E.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-MRAUGYDC.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-OPV7WB6E.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-OPV7WB6E.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-OPV7WB6E.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-MRAUGYDC.js";
13
+ } from "./chunk-SFEGIOZL.js";
14
14
  import {
15
15
  AppServerProcess,
16
16
  buildCodexAgentEnv
17
- } from "./chunk-ATHUSFGB.js";
17
+ } from "./chunk-ULTPPI7M.js";
18
18
  import {
19
19
  SUBPROCESS_MAX_BUFFER,
20
20
  execFileAsync
21
- } from "./chunk-LF7ND553.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-OPV7WB6E.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-E47NGZRP.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-E47NGZRP.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-ATHUSFGB.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-OPV7WB6E.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";
@@ -7980,10 +7980,161 @@ function parseAgentEventJsonl(content, options = {}) {
7980
7980
  return events;
7981
7981
  }
7982
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
+
7983
8118
  // ../shared/src/codex-history.ts
7984
8119
  function isChatHistoryEvent(value) {
7985
8120
  return isAgentBackendEvent(value) && value.type !== CODEX_ASP_TRANSCRIPT_UPDATED_EVENT_TYPE && value.type !== CODEX_HISTORY_FORMAT_EVENT_TYPE;
7986
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
+ }
7987
8138
  function codexHistoryFormatEvent() {
7988
8139
  return { timestamp: (/* @__PURE__ */ new Date()).toISOString(), type: CODEX_HISTORY_FORMAT_EVENT_TYPE, payload: { version: 2 } };
7989
8140
  }
@@ -9769,118 +9920,6 @@ var EMAIL_KEYS = [
9769
9920
  var MANUAL_EMAIL_TEMPLATE_KEYS = ["product_update"];
9770
9921
  var EMAIL_TEMPLATE_KEYS = [...EMAIL_KEYS, ...MANUAL_EMAIL_TEMPLATE_KEYS];
9771
9922
 
9772
- // ../shared/src/chat-transcript-pages.ts
9773
- var decoder = new TextDecoder("utf-8", { fatal: true });
9774
- var MAX_SOURCE_PAGE_BYTES = 4 * 1024 * 1024;
9775
- var SOURCE_RANGE_BYTES = 256 * 1024;
9776
- async function readExactRange(readRange, startByte, endByte, error) {
9777
- const bytes = await readRange(startByte, endByte);
9778
- if (bytes.length !== endByte - startByte) throw new Error(error);
9779
- return bytes;
9780
- }
9781
- async function readJsonlPage(args) {
9782
- let endByte = args.size;
9783
- if (args.before === null) endByte = 0;
9784
- else if (args.before !== void 0) {
9785
- endByte = /^(0|[1-9]\d*)$/.test(args.before) ? Number(args.before) : Number.NaN;
9786
- }
9787
- if (!Number.isSafeInteger(endByte) || endByte < 0 || endByte > args.size || !Number.isSafeInteger(args.limit) || args.limit < 1) {
9788
- throw new RangeError("Invalid JSONL page");
9789
- }
9790
- let startByte = endByte;
9791
- let head = new Uint8Array();
9792
- let headTerminated = false;
9793
- let lineBreaks = 0;
9794
- let endsWithLineBreak = false;
9795
- const pages = [];
9796
- let itemCount = 0;
9797
- while (startByte > 0 && itemCount < args.limit && (endByte - startByte < MAX_SOURCE_PAGE_BYTES || lineBreaks - (endsWithLineBreak ? 1 : 0) === 0)) {
9798
- const read = endByte - startByte;
9799
- 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));
9800
- const chunk = await readExactRange(
9801
- args.readRange,
9802
- nextStartByte,
9803
- startByte,
9804
- "Incomplete JSONL page read"
9805
- );
9806
- if (startByte === endByte) endsWithLineBreak = chunk[chunk.length - 1] === 10;
9807
- for (let index = chunk.indexOf(10); index !== -1; index = chunk.indexOf(10, index + 1)) lineBreaks++;
9808
- const bytes = new Uint8Array(chunk.length + head.length + (headTerminated ? 1 : 0));
9809
- bytes.set(chunk);
9810
- bytes.set(head, chunk.length);
9811
- if (headTerminated) bytes[bytes.length - 1] = 10;
9812
- startByte = nextStartByte;
9813
- const firstLineEnd = bytes.indexOf(10);
9814
- const page = [];
9815
- let lineStart = startByte > 0 ? firstLineEnd + 1 : 0;
9816
- for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
9817
- try {
9818
- const item = args.parse(JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd))));
9819
- if (item !== void 0) page.push({ item, startByte: startByte + lineStart });
9820
- } catch {
9821
- }
9822
- lineStart = lineEnd + 1;
9823
- }
9824
- head = firstLineEnd === -1 ? bytes : bytes.subarray(0, startByte > 0 ? firstLineEnd : 0);
9825
- headTerminated = firstLineEnd !== -1;
9826
- pages.push(page);
9827
- itemCount += page.length;
9828
- }
9829
- const selected = pages.reverse().flat().slice(-args.limit);
9830
- const firstCompleteLine = headTerminated ? head.length + 1 : 0;
9831
- let before = 0;
9832
- if (selected.length === args.limit) before = selected[0].startByte;
9833
- else if (startByte > 0) {
9834
- const nextBefore = startByte + firstCompleteLine;
9835
- before = nextBefore < endByte ? nextBefore : startByte;
9836
- }
9837
- return {
9838
- items: selected.map(({ item }) => item),
9839
- before: before > 0 ? String(before) : null
9840
- };
9841
- }
9842
- var MAX_APPENDED_BYTES = 4 * 1024 * 1024;
9843
- async function readJsonlAppended(args) {
9844
- const start = /^(0|[1-9]\d*)$/.test(args.after) ? Number(args.after) : Number.NaN;
9845
- if (!Number.isSafeInteger(start) || start > args.size || args.size - start > MAX_APPENDED_BYTES) return null;
9846
- if (start === args.size) return { items: [], after: args.after };
9847
- const from = Math.max(0, start - 1);
9848
- const bytes = await readExactRange(args.readRange, from, args.size, "Incomplete JSONL append read");
9849
- if (start > 0 && bytes[0] !== 10) return null;
9850
- const items = [];
9851
- let lineStart = start - from;
9852
- for (let lineEnd = bytes.indexOf(10, lineStart); lineEnd !== -1; lineEnd = bytes.indexOf(10, lineStart)) {
9853
- try {
9854
- const item = args.parse(JSON.parse(decoder.decode(bytes.subarray(lineStart, lineEnd))));
9855
- if (item !== void 0) items.push(item);
9856
- } catch {
9857
- }
9858
- lineStart = lineEnd + 1;
9859
- }
9860
- return { items, after: String(from + lineStart) };
9861
- }
9862
- function parseChatTranscriptHistoryIndex(value) {
9863
- if (!isRecord(value) || value.version !== 2 || !isNonNegativeInteger(value.sourceSize)) return void 0;
9864
- const removedMessageIds = Array.isArray(value.removedMessageIds) ? value.removedMessageIds.filter((id) => typeof id === "string") : [];
9865
- if (value.codexAspTranscript === void 0) {
9866
- return { version: 2, sourceSize: value.sourceSize, ...removedMessageIds.length ? { removedMessageIds } : {} };
9867
- }
9868
- if (!isRecord(value.codexAspTranscript) || typeof value.codexAspTranscript.threadId !== "string" || typeof value.codexAspTranscript.updatedAt !== "string" || !isNonNegativeInteger(value.codexAspTranscript.size)) return void 0;
9869
- return {
9870
- version: 2,
9871
- sourceSize: value.sourceSize,
9872
- ...removedMessageIds.length ? { removedMessageIds } : {},
9873
- codexAspTranscript: {
9874
- threadId: value.codexAspTranscript.threadId,
9875
- updatedAt: value.codexAspTranscript.updatedAt,
9876
- size: value.codexAspTranscript.size
9877
- }
9878
- };
9879
- }
9880
- function isNonNegativeInteger(value) {
9881
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
9882
- }
9883
-
9884
9923
  // ../shared/src/object-store/types.ts
9885
9924
  var MEDIA_KIND = {
9886
9925
  IMAGE: "image",
@@ -10203,7 +10242,9 @@ export {
10203
10242
  getEventTimestampMs,
10204
10243
  areSameUserMessageEvents,
10205
10244
  parseAgentEventJsonlLine,
10206
- isChatHistoryEvent,
10245
+ readJsonlAppended,
10246
+ toChatHistoryPageEvent,
10247
+ readChatHistoryPage,
10207
10248
  codexHistoryFormatEvent,
10208
10249
  CodexHistoryEventFolder,
10209
10250
  canonicalizeChatTranscriptBlocks,
@@ -10266,8 +10307,6 @@ export {
10266
10307
  searchRepoFileIndex,
10267
10308
  isExcludedRepoFilePath,
10268
10309
  ENVIRONMENT_HOOK_RUN_LOG_LIMIT,
10269
- readJsonlPage,
10270
- readJsonlAppended,
10271
10310
  normalizeChatTranscriptMetadata,
10272
10311
  parseChatTranscriptArtifact,
10273
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-LF7ND553.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-OPV7WB6E.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-LF7ND553.js";
6
+ } from "./chunk-EG7LG4JL.js";
7
7
  import {
8
8
  isVersionBelow
9
- } from "./chunk-OPV7WB6E.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.1226";
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-47SSCZMG.js";
7
- import "./chunk-MRAUGYDC.js";
8
- import "./chunk-LF7ND553.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-OPV7WB6E.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-LE7CVJC2.js";
16
+ } from "./chunk-MXGP2NFY.js";
17
17
  import {
18
18
  AppServerProcess,
19
19
  buildCodexAgentEnv
20
- } from "./chunk-ATHUSFGB.js";
21
- import "./chunk-LF7ND553.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-OPV7WB6E.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-47SSCZMG.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-LE7CVJC2.js";
67
+ } from "./chunk-MXGP2NFY.js";
68
68
  import {
69
69
  publishedPullRequestUrls
70
- } from "./chunk-K77ILXKH.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-R7MHJUBF.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-MRAUGYDC.js";
152
+ } from "./chunk-SFEGIOZL.js";
153
153
  import {
154
154
  getCodexModelProvider
155
- } from "./chunk-ATHUSFGB.js";
155
+ } from "./chunk-ULTPPI7M.js";
156
156
  import {
157
157
  SUBPROCESS_MAX_BUFFER,
158
158
  execAsync,
159
159
  execFileAsync
160
- } from "./chunk-LF7ND553.js";
160
+ } from "./chunk-EG7LG4JL.js";
161
161
  import {
162
162
  isRecord as isRecord2
163
163
  } from "./chunk-UZSNFLDQ.js";
@@ -322,7 +322,6 @@ import {
322
322
  isAgentChatSkillActivityRecord,
323
323
  isAgentChatTurnActivityRecord,
324
324
  isCanvasTextKind,
325
- isChatHistoryEvent,
326
325
  isChatMessageSender,
327
326
  isClaudeAuthErrorText,
328
327
  isClaudeResultError,
@@ -367,8 +366,8 @@ import {
367
366
  parseReplicasConfigString,
368
367
  percentage,
369
368
  raceWithTimeout,
369
+ readChatHistoryPage,
370
370
  readJsonlAppended,
371
- readJsonlPage,
372
371
  readOllamaAuthEnv,
373
372
  readOpenAICompatibleAuthEnv,
374
373
  readReplicasRuntimeEnv,
@@ -385,6 +384,7 @@ import {
385
384
  spawnSubagentRequestSchema,
386
385
  splitMothershipInstructions,
387
386
  stripAgentDiagnosticErrors,
387
+ toChatHistoryPageEvent,
388
388
  toClaudeCodeModel,
389
389
  updateChatDisplayNameRequestSchema,
390
390
  waitSubagentRequestSchema,
@@ -394,7 +394,7 @@ import {
394
394
  workspaceTokenRequestSchema,
395
395
  workspaceTokenResponseSchema,
396
396
  wrapInTag
397
- } from "./chunk-OPV7WB6E.js";
397
+ } from "./chunk-QHUFRB7Y.js";
398
398
  import {
399
399
  cloneMcpConfig,
400
400
  ensureCompatibilityImports,
@@ -11680,6 +11680,9 @@ ${request.message}` }, senderKey };
11680
11680
  subagentMcpParentChatId() {
11681
11681
  return this.subagentMcpEnabledForTurn ? this.subagentMcpChatId : void 0;
11682
11682
  }
11683
+ getHistoryEnd() {
11684
+ return this.getHistorySink()?.historyEnd;
11685
+ }
11683
11686
  async persistHistoryEvent(event) {
11684
11687
  const history = this.getHistorySink();
11685
11688
  if (!history?.appendDurably) throw new Error("Chat history is unavailable");
@@ -12360,7 +12363,7 @@ function isNotFoundError(error) {
12360
12363
  }
12361
12364
 
12362
12365
  // src/managers/codex-asp/codex-history-file.ts
12363
- import { createReadStream } from "fs";
12366
+ import { createReadStream, statSync } from "fs";
12364
12367
  import { appendFile as appendFile2, open, rename } from "fs/promises";
12365
12368
  import { createInterface } from "readline";
12366
12369
  var MIGRATION_FLUSH_CHARS = 1 << 20;
@@ -12370,9 +12373,20 @@ function isMissingFile(error) {
12370
12373
  var CodexHistoryFile = class {
12371
12374
  constructor(filePath) {
12372
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
+ }
12373
12382
  }
12374
12383
  filePath;
12375
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
+ }
12376
12390
  /** Best-effort ordered append; failures must not disrupt the turn. */
12377
12391
  append(event) {
12378
12392
  void this.appendDurably(event).catch((error) => {
@@ -12380,8 +12394,18 @@ var CodexHistoryFile = class {
12380
12394
  });
12381
12395
  }
12382
12396
  appendDurably(event) {
12383
- return this.writeLock.run(() => appendFile2(this.filePath, `${JSON.stringify(event)}
12384
- `));
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
+ });
12385
12409
  }
12386
12410
  async flush() {
12387
12411
  await this.writeLock.drain();
@@ -12399,6 +12423,7 @@ var CodexHistoryFile = class {
12399
12423
  return;
12400
12424
  }
12401
12425
  if (parseAgentEventJsonlLine(firstLine)?.type === CODEX_HISTORY_FORMAT_EVENT_TYPE) return;
12426
+ this.reservedSize = void 0;
12402
12427
  await this.writeLock.run(async () => {
12403
12428
  const events = await this.loadAll();
12404
12429
  const rewritten = `${this.filePath}.migrating`;
@@ -12483,12 +12508,11 @@ var CodexHistoryFile = class {
12483
12508
  const { bytesRead } = await file.read(bytes, 0, bytes.length, startByte);
12484
12509
  return bytes.subarray(0, bytesRead);
12485
12510
  };
12486
- const parse2 = (value) => isChatHistoryEvent(value) ? value : void 0;
12487
12511
  if (page2.afterCursor !== void 0 && cursor === void 0) {
12488
- const appended = await readJsonlAppended({ size, after: page2.afterCursor, readRange, parse: parse2 });
12512
+ const appended = await readJsonlAppended({ size, after: page2.afterCursor, readRange, parse: toChatHistoryPageEvent });
12489
12513
  if (appended) return { events: appended.items, afterCursor: appended.after, appendsAfter: page2.afterCursor };
12490
12514
  }
12491
- 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 });
12492
12516
  return {
12493
12517
  events: result.items,
12494
12518
  beforeCursor: createChatHistoryCursor({ events: result.before, turns: null }),
@@ -14146,11 +14170,13 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14146
14170
  async recordEvent(event, replicasMessageId) {
14147
14171
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
14148
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;
14149
14175
  const jsonEvent = {
14150
14176
  timestamp,
14151
14177
  type: `claude-${event.type}`,
14152
14178
  payload: {
14153
- ...event,
14179
+ ...payload,
14154
14180
  ...restampAmbient ? { ambient: true } : {},
14155
14181
  ...replicasMessageId ? { [USER_MESSAGE_ID_PAYLOAD_KEY]: replicasMessageId } : {}
14156
14182
  }
@@ -14342,7 +14368,8 @@ var CodexAspManager = class extends CodingAgentManager {
14342
14368
  appendDurably: (event) => {
14343
14369
  if (!this.historyFile) throw new Error("Chat history is unavailable");
14344
14370
  return this.historyFile.appendDurably(event);
14345
- }
14371
+ },
14372
+ historyEnd: this.historyFile?.historyEnd
14346
14373
  };
14347
14374
  }
14348
14375
  async subagentMcpForTurn(enabled) {
@@ -14545,10 +14572,10 @@ var CodexAspManager = class extends CodingAgentManager {
14545
14572
  }
14546
14573
  recordUserMessageEvent(request, extraPayload = {}) {
14547
14574
  const images = imageContentToUserMessageImages(request.images);
14548
- this.recordCodexHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, {
14575
+ this.onEvent(this.recordCodexHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, {
14549
14576
  ...images ? { images } : {},
14550
14577
  ...extraPayload
14551
- }));
14578
+ })));
14552
14579
  }
14553
14580
  async processMessageInternal(request, signal) {
14554
14581
  let userMessageRecorded = false;
@@ -39184,7 +39211,7 @@ var StreamableHTTPClientTransport = class {
39184
39211
  };
39185
39212
 
39186
39213
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/server-manager.ts
39187
- import { mkdirSync as mkdirSync3, statSync as statSync2 } from "fs";
39214
+ import { mkdirSync as mkdirSync3, statSync as statSync3 } from "fs";
39188
39215
  import { isDeepStrictEqual } from "util";
39189
39216
 
39190
39217
  // ../node_modules/.bun/@modelcontextprotocol+client@2.0.0/node_modules/@modelcontextprotocol/client/dist/stdio.mjs
@@ -39617,7 +39644,7 @@ async function probeMcpEndpoint(url3) {
39617
39644
  }
39618
39645
 
39619
39646
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/npx-resolver.ts
39620
- 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";
39621
39648
  import { join as join15, dirname as dirname8, extname as extname2, resolve as resolve2, sep } from "path";
39622
39649
 
39623
39650
  // ../node_modules/.bun/pi-mcp-adapter@2.32.1+04b0d7b0bc944965/node_modules/pi-mcp-adapter/abort.ts
@@ -40068,7 +40095,7 @@ function safeRealpath(path7) {
40068
40095
  }
40069
40096
  function safeStatMtime(path7) {
40070
40097
  try {
40071
- return statSync(path7).mtimeMs;
40098
+ return statSync2(path7).mtimeMs;
40072
40099
  } catch {
40073
40100
  return 0;
40074
40101
  }
@@ -44720,7 +44747,7 @@ var McpServerManager = class {
44720
44747
  let args = (definition.args ?? []).map((argument) => interpolateEnvVars(argument));
44721
44748
  const cwd = resolveConfigPath(definition.cwd) ?? this.defaultCwd;
44722
44749
  if (cwd !== void 0) {
44723
- const cwdStats = statSync2(cwd, { throwIfNoEntry: false });
44750
+ const cwdStats = statSync3(cwd, { throwIfNoEntry: false });
44724
44751
  if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
44725
44752
  if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
44726
44753
  }
@@ -60034,14 +60061,14 @@ ${decisions}` };
60034
60061
  };
60035
60062
  return await chat.provider.enqueueMessage(
60036
60063
  request,
60037
- (result, acceptedMessage) => this.handleMessageAccepted(
60064
+ (result, acceptedMessage) => this.withUnpublishedHistory(chat, () => this.handleMessageAccepted(
60038
60065
  chatId,
60039
60066
  chat,
60040
60067
  request,
60041
60068
  acceptedMessage,
60042
60069
  result,
60043
60070
  typedMessage
60044
- )
60071
+ ))
60045
60072
  );
60046
60073
  } catch (error) {
60047
60074
  if (seenBeforeSend) this.forkSourceSeenBlocks.set(chatId, seenBeforeSend);
@@ -60266,6 +60293,16 @@ ${decisions}` };
60266
60293
  queue: chat.provider.getQueue()
60267
60294
  };
60268
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
+ }
60269
60306
  publishQueueIfChanged(chatId) {
60270
60307
  const chat = this.getRuntimeChat(chatId);
60271
60308
  if (!chat) return;
@@ -60279,33 +60316,35 @@ ${decisions}` };
60279
60316
  }
60280
60317
  async forgetPendingMessages(chat, messageIds) {
60281
60318
  if (messageIds.length === 0) return;
60282
- const removed = new Set(messageIds);
60283
- const event = {
60284
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
60285
- type: QUEUED_MESSAGE_REMOVED_EVENT_TYPE,
60286
- payload: { [REMOVED_MESSAGE_IDS_PAYLOAD_KEY]: [...removed] }
60287
- };
60288
- await chat.provider.persistHistoryEvent(event);
60289
- chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
60290
- chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
60291
- this.forkSourceSeenBlocks.delete(chat.persisted.id);
60292
- for (const messageId of removed) {
60293
- chat.acceptedUserEvents.delete(messageId);
60294
- chat.errorNotificationTargets.delete(messageId);
60295
- }
60296
- await this.persistAllChats().catch((error) => {
60297
- console.error("[ChatService] Failed to persist queued-message removals:", error);
60298
- });
60299
- await this.publish({
60300
- type: "chat.turn.delta",
60301
- payload: { chatId: chat.persisted.id, event }
60302
- }).catch((error) => {
60303
- console.error("[ChatService] Failed to publish queued-message removals:", error);
60304
- });
60305
- this.publish({
60306
- type: "chat.updated",
60307
- payload: { chat: this.toSummary(chat) }
60308
- }).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
+ });
60309
60348
  });
60310
60349
  }
60311
60350
  async removeFromQueue(chatId, messageId) {
@@ -60902,6 +60941,7 @@ ${note}`;
60902
60941
  turnCompletion: null,
60903
60942
  publishedQueue: null,
60904
60943
  idleReleaseTimer: null,
60944
+ unpublishedHistoryStarts: [],
60905
60945
  live: false,
60906
60946
  release: null,
60907
60947
  errorNotificationTargets: /* @__PURE__ */ new Map(),
@@ -61260,6 +61300,10 @@ ${note}`;
61260
61300
  return;
61261
61301
  }
61262
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
+ }
61263
61307
  if (chat) {
61264
61308
  chat.historyVersion = event.id;
61265
61309
  if (event.type === "chat.created" || event.type === "chat.updated") {
@@ -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-K77ILXKH.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-OPV7WB6E.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-OPV7WB6E.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.1226",
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",