replicas-engine 0.1.1209 → 0.1.1211

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-CU2NG6MB.js";
30
+ } from "./chunk-VXX3QRLD.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-IYDRRR63.js";
67
+ } from "./chunk-TAJWPNZ6.js";
68
68
  import {
69
69
  publishedPullRequestUrls
70
- } from "./chunk-G5QLEN6P.js";
70
+ } from "./chunk-RJEDVMHT.js";
71
71
  import {
72
72
  ACCOUNT_RATE_LIMITS_READ_METHOD,
73
73
  AsyncLock,
@@ -89,6 +89,7 @@ import {
89
89
  SUBAGENT_MCP_TOOL_TIMEOUT_MS,
90
90
  THREAD_BACKGROUND_TERMINALS_CLEAN_METHOD,
91
91
  THREAD_COMPACT_START_METHOD,
92
+ THREAD_FORK_METHOD,
92
93
  THREAD_GOAL_CLEAR_METHOD,
93
94
  THREAD_GOAL_GET_METHOD,
94
95
  THREAD_GOAL_SET_METHOD,
@@ -139,7 +140,7 @@ import {
139
140
  timestampFromSeconds,
140
141
  upsertCredentialFileLines,
141
142
  writeSecureCredentialFile
142
- } from "./chunk-5WKJLYT2.js";
143
+ } from "./chunk-UK7CPOB5.js";
143
144
  import {
144
145
  ENGINE_ENV,
145
146
  monolithRequest,
@@ -148,15 +149,15 @@ import {
148
149
  reloadEngineEnv,
149
150
  resolveDiffBase,
150
151
  setAgentCredentialSnapshot
151
- } from "./chunk-GFD7IWB7.js";
152
+ } from "./chunk-EOZ72TUI.js";
152
153
  import {
153
154
  getCodexModelProvider
154
- } from "./chunk-64IZT5LX.js";
155
+ } from "./chunk-GTEOVCFK.js";
155
156
  import {
156
157
  SUBPROCESS_MAX_BUFFER,
157
158
  execAsync,
158
159
  execFileAsync
159
- } from "./chunk-IDVI5F7J.js";
160
+ } from "./chunk-JIZPT767.js";
160
161
  import {
161
162
  isRecord as isRecord2
162
163
  } from "./chunk-UZSNFLDQ.js";
@@ -295,7 +296,7 @@ import {
295
296
  fetchOpenCodeGoCatalog,
296
297
  forkChatRequestSchema,
297
298
  formatChatForkHandoffMessage,
298
- formatSideChatUpdateMessage,
299
+ formatChatForkUpdateMessage,
299
300
  getChatContinuation,
300
301
  getChatHistoryPageSenders,
301
302
  getClaudeModelContextWindow,
@@ -391,7 +392,7 @@ import {
391
392
  workspaceTokenRequestSchema,
392
393
  workspaceTokenResponseSchema,
393
394
  wrapInTag
394
- } from "./chunk-RG5UOHPJ.js";
395
+ } from "./chunk-DUEWTRSF.js";
395
396
  import {
396
397
  cloneMcpConfig,
397
398
  ensureCompatibilityImports,
@@ -10447,7 +10448,7 @@ async function registerDesktopPreview(signal) {
10447
10448
  }
10448
10449
 
10449
10450
  // src/services/chat/chat-service.ts
10450
- import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir17, readFile as readFile16, rename as rename3, rm as rm4, stat as stat6 } from "fs/promises";
10451
+ import { appendFile as appendFile5, copyFile as copyFile2, mkdir as mkdir17, readFile as readFile17, rename as rename3, rm as rm4, stat as stat6 } from "fs/promises";
10451
10452
  import { join as join28 } from "path";
10452
10453
  import { randomUUID as randomUUID10 } from "crypto";
10453
10454
 
@@ -10625,6 +10626,7 @@ function insertChronologically(existing, additions) {
10625
10626
 
10626
10627
  // src/managers/claude-manager.ts
10627
10628
  import {
10629
+ forkSession,
10628
10630
  getSessionMessages,
10629
10631
  query
10630
10632
  } from "@anthropic-ai/claude-agent-sdk";
@@ -12686,6 +12688,10 @@ function appendUserContent(earlier, later) {
12686
12688
  }
12687
12689
  var TOOL_TARGET = /^\s*\{\s*"(\w+)"\s*:\s*(?:"((?:[^"\\]|\\.)*)(")?)?/;
12688
12690
  var JSON_FIRST_LINE = /^(?:[^\\]|\\[^n])*?(?=\\n)/;
12691
+ function isPromptMessage(message) {
12692
+ const content = isRecord(message) ? message.content : void 0;
12693
+ return typeof content === "string" || Array.isArray(content) && content.some((block) => !isRecord(block) || block.type !== "tool_result");
12694
+ }
12689
12695
  function toSlashCommands(command) {
12690
12696
  const names = [command.name, ...command.aliases ?? []];
12691
12697
  return names.flatMap((name) => {
@@ -13715,6 +13721,24 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13715
13721
  await this.abortAllPendingToolInputs();
13716
13722
  await this.tearDownSession();
13717
13723
  }
13724
+ async forkPoint() {
13725
+ await this.initialized;
13726
+ const sessionId = this.sessionId;
13727
+ if (!sessionId) return null;
13728
+ const messages = await getSessionMessages(sessionId, { dir: this.workingDirectory });
13729
+ const turnUuids = this.pendingTurn?.userMessageUuids;
13730
+ const turnStart = turnUuids ? messages.findIndex((entry) => turnUuids.has(entry.uuid)) : -1;
13731
+ const end = turnStart >= 0 ? turnStart : this.isProcessing() ? Math.max(0, messages.findLastIndex((entry) => entry.type === "user" && isPromptMessage(entry.message))) : messages.length;
13732
+ const throughTurn = messages[end - 1]?.uuid;
13733
+ return throughTurn ? { sessionId, throughTurn } : null;
13734
+ }
13735
+ async forkFrom(point) {
13736
+ await this.initialized;
13737
+ const { sessionId } = await forkSession(point.sessionId, { dir: this.workingDirectory, upToMessageId: point.throughTurn });
13738
+ await this.tearDownSession();
13739
+ this.sessionId = sessionId;
13740
+ await this.onSaveSessionId(sessionId);
13741
+ }
13718
13742
  clearBackgroundContinuationTimer() {
13719
13743
  if (!this.backgroundContinuationTimer) return;
13720
13744
  clearTimeout(this.backgroundContinuationTimer);
@@ -14155,6 +14179,7 @@ function isCompactCommand(message) {
14155
14179
  }
14156
14180
  var CodexAspManager = class extends CodingAgentManager {
14157
14181
  currentThreadId = null;
14182
+ pendingFork = null;
14158
14183
  activeTurnId = null;
14159
14184
  lastTurnFailure = null;
14160
14185
  attachedClient = null;
@@ -14189,6 +14214,7 @@ var CodexAspManager = class extends CodingAgentManager {
14189
14214
  constructor(options) {
14190
14215
  super({ ...options, provider: AGENT.CODEX });
14191
14216
  this.historyFile = options.historyFilePath ? new CodexHistoryFile(options.historyFilePath) : null;
14217
+ this.pendingFork = options.pendingFork ?? null;
14192
14218
  this.onCodexTurnStarted = options.onCodexTurnStarted;
14193
14219
  this.onCodexTokenUsage = options.onCodexTokenUsage;
14194
14220
  this.onCodexModelRerouted = options.onCodexModelRerouted;
@@ -14317,6 +14343,22 @@ var CodexAspManager = class extends CodingAgentManager {
14317
14343
  }
14318
14344
  return true;
14319
14345
  }
14346
+ async forkPoint() {
14347
+ await this.initialized;
14348
+ const sessionId = this.currentThreadId;
14349
+ if (!sessionId) return null;
14350
+ const { thread } = await (await getCodexAspHost()).client.request(
14351
+ THREAD_READ_METHOD,
14352
+ { threadId: sessionId, includeTurns: true }
14353
+ );
14354
+ const throughTurn = thread.turns.findLast((turn) => turn.status !== "inProgress")?.id;
14355
+ return throughTurn ? { sessionId, throughTurn } : null;
14356
+ }
14357
+ /** The fork happens on the next turn: Codex keeps a loaded thread's settings, so it must be created with this chat's own. */
14358
+ async forkFrom(point) {
14359
+ await this.initialized;
14360
+ this.pendingFork = point;
14361
+ }
14320
14362
  async getHistory(page2 = {}) {
14321
14363
  await this.initialized;
14322
14364
  await this.historyFile?.flush();
@@ -14578,17 +14620,18 @@ var CodexAspManager = class extends CodingAgentManager {
14578
14620
  const existingThreadId = this.currentThreadId;
14579
14621
  const requestedModel = request.model ?? DEFAULT_MODEL;
14580
14622
  const subagentMcpParentChatId = this.subagentMcpParentChatId();
14581
- if (existingThreadId) {
14623
+ const fork = this.pendingFork;
14624
+ if (existingThreadId && !fork) {
14582
14625
  if (this.attachedClient !== host.client || requestedModel !== this.attachedModel || (developerInstructions ?? null) !== this.attachedDeveloperInstructions) {
14583
14626
  const serviceTier2 = await this.resolveRequestedServiceTier(host, request);
14584
14627
  const coldResume = this.attachedClient !== host.client;
14585
14628
  const previous = coldResume ? await host.client.request(THREAD_READ_METHOD, { threadId: existingThreadId, includeTurns: true }).catch(() => null) : null;
14586
- const response = previous?.thread.modelProvider && previous.thread.modelProvider !== getCodexModelProvider(ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD) ? await this.continueWithNewProvider(host, previous.thread, request, developerInstructions, serviceTier2) : await host.client.request(
14629
+ const response2 = previous?.thread.modelProvider && previous.thread.modelProvider !== getCodexModelProvider(ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD) ? await this.continueWithNewProvider(host, previous.thread, request, developerInstructions, serviceTier2) : await host.client.request(
14587
14630
  THREAD_RESUME_METHOD,
14588
14631
  await buildThreadResumeParams(this.workingDirectory, existingThreadId, request, developerInstructions, serviceTier2, subagentMcpParentChatId, this.autoCompactTokens, this.originChatId)
14589
14632
  );
14590
- this.currentThreadId = response.thread.id;
14591
- this.activeServiceTier = response.serviceTier;
14633
+ this.currentThreadId = response2.thread.id;
14634
+ this.activeServiceTier = response2.serviceTier;
14592
14635
  if (this.attachedClient === host.client && developerInstructions && developerInstructions !== this.attachedDeveloperInstructions) {
14593
14636
  await host.client.request(THREAD_INJECT_ITEMS_METHOD, {
14594
14637
  threadId: this.currentThreadId,
@@ -14604,13 +14647,23 @@ var CodexAspManager = class extends CodingAgentManager {
14604
14647
  return this.currentThreadId ?? existingThreadId;
14605
14648
  }
14606
14649
  const serviceTier = await this.resolveRequestedServiceTier(host, request);
14607
- const threadStartResponse = await host.client.request(
14608
- THREAD_START_METHOD,
14609
- await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier, subagentMcpParentChatId, this.autoCompactTokens, this.originChatId)
14610
- );
14611
- const threadId = threadStartResponse.thread.id;
14650
+ let response;
14651
+ if (fork) {
14652
+ const { threadId: sourceThreadId, ...settings2 } = await buildThreadResumeParams(this.workingDirectory, fork.sessionId, request, developerInstructions, serviceTier, subagentMcpParentChatId, this.autoCompactTokens, this.originChatId);
14653
+ response = await host.client.request(
14654
+ THREAD_FORK_METHOD,
14655
+ { ...settings2, threadId: sourceThreadId, lastTurnId: fork.throughTurn, excludeTurns: true }
14656
+ );
14657
+ this.pendingFork = null;
14658
+ } else {
14659
+ response = await host.client.request(
14660
+ THREAD_START_METHOD,
14661
+ await buildThreadStartParams(this.workingDirectory, request, developerInstructions, serviceTier, subagentMcpParentChatId, this.autoCompactTokens, this.originChatId)
14662
+ );
14663
+ }
14664
+ const threadId = response.thread.id;
14612
14665
  this.currentThreadId = threadId;
14613
- this.activeServiceTier = threadStartResponse.serviceTier;
14666
+ this.activeServiceTier = response.serviceTier;
14614
14667
  this.attachedClient = host.client;
14615
14668
  this.attachedModel = requestedModel;
14616
14669
  this.attachedDeveloperInstructions = developerInstructions ?? null;
@@ -59348,9 +59401,12 @@ async function uploadEngineLog(input, timeoutMs) {
59348
59401
 
59349
59402
  // src/services/chat/fork-handoff.ts
59350
59403
  import { createHash as createHash8 } from "crypto";
59351
- import { mkdir as mkdir16, open as open3, writeFile as writeFile8 } from "fs/promises";
59404
+ import { mkdir as mkdir16, open as open3, readFile as readFile16, writeFile as writeFile8 } from "fs/promises";
59405
+ import { homedir as homedir9 } from "os";
59352
59406
  import { join as join27 } from "path";
59353
59407
  var EXCERPT_MAX_CHARS = 24e3;
59408
+ var CONVERSATION_UPDATE_MAX_CHARS = 8e3;
59409
+ var PULL_REQUEST_DECISIONS_MAX_CHARS = 4e3;
59354
59410
  var MAX_SANITIZED_SOURCE_BYTES = 32 * 1024 * 1024;
59355
59411
  function unansweredRequest(blocks) {
59356
59412
  const lastUser = blocks.findLastIndex((block) => block.startsWith("## User"));
@@ -59386,16 +59442,26 @@ function tailBlocks(blocks, maxChars) {
59386
59442
  function hashTranscriptBlocks(blocks) {
59387
59443
  return blocks.map((block) => createHash8("sha1").update(block).digest("base64"));
59388
59444
  }
59389
- function unseenTurnsExcerpt(seenHashes, blocks) {
59445
+ function unseenBlocks(seenHashes, blocks) {
59390
59446
  const hashes = hashTranscriptBlocks(blocks);
59391
59447
  let common = 0;
59392
59448
  while (common < seenHashes.length && common < blocks.length && seenHashes[common] === hashes[common]) common++;
59393
- if (common === blocks.length) return null;
59394
- const { excerpt, truncated } = tailBlocks(blocks.slice(common), EXCERPT_MAX_CHARS);
59449
+ return blocks.slice(common);
59450
+ }
59451
+ function excerptOf(blocks, maxChars) {
59452
+ if (blocks.length === 0) return null;
59453
+ const { excerpt, truncated } = tailBlocks(blocks, maxChars);
59395
59454
  return truncated ? `${CHAT_FORK_EXCERPT_OMITTED_NOTICE}
59396
59455
 
59397
59456
  ${excerpt}` : excerpt;
59398
59457
  }
59458
+ function unseenTurnsExcerpt(seenHashes, blocks) {
59459
+ return excerptOf(unseenBlocks(seenHashes, blocks), EXCERPT_MAX_CHARS);
59460
+ }
59461
+ function unseenConversationExcerpt(seenHashes, blocks) {
59462
+ const conversation = unseenBlocks(seenHashes, blocks).filter((block) => block.startsWith("## User") || block.startsWith("## Agent\n"));
59463
+ return excerptOf(conversation, CONVERSATION_UPDATE_MAX_CHARS);
59464
+ }
59399
59465
  async function buildForkHandoff(input) {
59400
59466
  const rawHistoryPath = join27(HISTORY_DIR_BY_PROVIDER[input.sourceProvider], `${input.sourceChatId}.jsonl`);
59401
59467
  const { content, truncated: sourceTruncated } = await readHistoryTail(rawHistoryPath, MAX_SANITIZED_SOURCE_BYTES);
@@ -59424,6 +59490,15 @@ async function buildForkHandoff(input) {
59424
59490
  rawHistoryPath: input.turnLimit === void 0 ? rawHistoryPath : void 0
59425
59491
  };
59426
59492
  }
59493
+ async function readPullRequestDecisions(notesPath) {
59494
+ const notes = await readFile16(notesPath.replace(/^~(?=\/)/, homedir9()), "utf-8").catch(() => "");
59495
+ const decisions = /^## Decisions[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(notes)?.[1].trim();
59496
+ if (!decisions) return null;
59497
+ const body = decisions.length > PULL_REQUEST_DECISIONS_MAX_CHARS ? `${decisions.slice(0, PULL_REQUEST_DECISIONS_MAX_CHARS)}
59498
+ \u2026(more in the file)` : decisions;
59499
+ return wrapInTag(`Decisions recorded for this PR in \`${notesPath}\`. Never undo these:
59500
+ ${body}`, REPLICAS_INSTRUCTIONS_TAG);
59501
+ }
59427
59502
 
59428
59503
  // src/services/chat/chat-service.ts
59429
59504
  var CHATS_BACKUP_FILE = `${CHATS_FILE}.bak`;
@@ -59531,6 +59606,9 @@ function normalizePersistedChat(chat) {
59531
59606
  deletedAt: chat.deletedAt ?? null,
59532
59607
  fork: coerceChatForkInfo(chat.fork),
59533
59608
  pendingForkHandoff: chat.pendingForkHandoff === true,
59609
+ ...typeof chat.pullRequestNotesPath === "string" ? { pullRequestNotesPath: chat.pullRequestNotesPath } : {},
59610
+ ...typeof chat.forkedThroughTurn === "string" ? { forkedThroughTurn: chat.forkedThroughTurn } : {},
59611
+ ...typeof chat.pendingProviderFork?.sessionId === "string" && typeof chat.pendingProviderFork.throughTurn === "string" ? { pendingProviderFork: chat.pendingProviderFork } : {},
59534
59612
  ...chat.chatCredential === "workspace" || agentCredentialSnapshotSchema.safeParse(chat.chatCredential).success ? { chatCredential: chat.chatCredential } : {},
59535
59613
  transcriptAuth: normalizeTranscriptAuth(chat.transcriptAuth),
59536
59614
  ...typeof chat.lastSenderKey === "string" ? { lastSenderKey: chat.lastSenderKey } : {},
@@ -59566,7 +59644,7 @@ var ChatService = class {
59566
59644
  agentChatActivityTrackerService;
59567
59645
  agentTokenUsageTracker;
59568
59646
  chats = /* @__PURE__ */ new Map();
59569
- sideChatSeenBlocks = /* @__PURE__ */ new Map();
59647
+ forkSourceSeenBlocks = /* @__PURE__ */ new Map();
59570
59648
  persistPromise = null;
59571
59649
  persistQueued = false;
59572
59650
  async initialize() {
@@ -59617,7 +59695,7 @@ var ChatService = class {
59617
59695
  const [discovered, learnedSkills] = await Promise.all([
59618
59696
  chat.provider.listSlashCommands?.() ?? [],
59619
59697
  // Learned skills work in the background, so they stay out of the slash menu.
59620
- readFile16(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
59698
+ readFile17(LEARNED_SKILLS_MANIFEST_PATH, "utf-8").then((content) => new Set(learnedSkillsManifestSchema.parse(JSON.parse(content)).skills.flatMap(({ name }) => [`/${name}`, `/${LEARNED_SKILL_DIR_PREFIX}${name}`]))).catch(() => /* @__PURE__ */ new Set())
59621
59699
  ]);
59622
59700
  const providerCommands = discovered.filter(({ command }) => !learnedSkills.has(command)).map((command) => ({
59623
59701
  ...command,
@@ -59669,6 +59747,7 @@ var ChatService = class {
59669
59747
  displayName: request.title?.trim() || void 0,
59670
59748
  model: source.persisted.provider === request.provider ? source.persisted.model : void 0,
59671
59749
  pendingForkHandoff: true,
59750
+ ...request.pullRequestNotesPath ? { pullRequestNotesPath: request.pullRequestNotesPath } : {},
59672
59751
  fork: createForkInfo(source.persisted, request.sideChat ? "side" : "manual", now)
59673
59752
  } : {}
59674
59753
  };
@@ -59806,16 +59885,21 @@ var ChatService = class {
59806
59885
  });
59807
59886
  await chat.release;
59808
59887
  this.requireChat(chatId);
59809
- seenBeforeSend = this.sideChatSeenBlocks.get(chatId);
59810
- if (chat.persisted.fork && (chat.persisted.pendingForkHandoff || chat.persisted.fork.trigger === "side")) {
59888
+ seenBeforeSend = this.forkSourceSeenBlocks.get(chatId);
59889
+ const fork = chat.persisted.fork;
59890
+ if (fork && (chat.persisted.pendingForkHandoff || fork.trigger === "side")) {
59811
59891
  request = {
59812
59892
  ...request,
59813
- message: await this.createForkHandoffMessage(chatId, {
59814
- source: chat.persisted.fork.source,
59815
- trigger: chat.persisted.fork.trigger,
59816
- message: request.message
59817
- })
59893
+ message: await this.createForkHandoffMessage(chatId, { source: fork.source, trigger: fork.trigger, message: request.message })
59818
59894
  };
59895
+ } else if (fork && chat.persisted.pullRequestNotesPath && this.getChat(fork.source.chatId)) {
59896
+ request = { ...request, message: await this.followForkSource(chat, fork, request.message) };
59897
+ }
59898
+ if (chat.persisted.pullRequestNotesPath) {
59899
+ const decisions = await readPullRequestDecisions(chat.persisted.pullRequestNotesPath);
59900
+ if (decisions) request = { ...request, message: `${request.message}
59901
+
59902
+ ${decisions}` };
59819
59903
  }
59820
59904
  const savedModel = chat.persisted.model ?? (!request.model ? extractLatestContextUsage((await chat.provider.getHistory()).events, chat.persisted.provider)?.model : void 0);
59821
59905
  request = {
@@ -59835,8 +59919,8 @@ var ChatService = class {
59835
59919
  )
59836
59920
  );
59837
59921
  } catch (error) {
59838
- if (seenBeforeSend) this.sideChatSeenBlocks.set(chatId, seenBeforeSend);
59839
- else this.sideChatSeenBlocks.delete(chatId);
59922
+ if (seenBeforeSend) this.forkSourceSeenBlocks.set(chatId, seenBeforeSend);
59923
+ else this.forkSourceSeenBlocks.delete(chatId);
59840
59924
  throw error;
59841
59925
  } finally {
59842
59926
  chat.acceptingMessages -= 1;
@@ -59960,7 +60044,7 @@ var ChatService = class {
59960
60044
  }
59961
60045
  }
59962
60046
  async readSenders(chatId) {
59963
- return readFile16(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
60047
+ return readFile17(chatMessageSendersFilePath(chatId), "utf-8").then(parseChatMessageSendersJsonl).catch((error) => {
59964
60048
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
59965
60049
  console.error("[ChatService] Failed to read sender records:", error);
59966
60050
  return [];
@@ -60082,6 +60166,7 @@ var ChatService = class {
60082
60166
  await chat.provider.persistHistoryEvent(event);
60083
60167
  chat.persisted.removedMessageIds = [.../* @__PURE__ */ new Set([...chat.persisted.removedMessageIds ?? [], ...removed])].slice(-MAX_REMOVED_MESSAGE_IDS);
60084
60168
  chat.pendingMessageIds = chat.pendingMessageIds.filter((messageId) => !removed.has(messageId));
60169
+ this.forkSourceSeenBlocks.delete(chat.persisted.id);
60085
60170
  for (const messageId of removed) {
60086
60171
  chat.acceptedUserEvents.delete(messageId);
60087
60172
  chat.errorNotificationTargets.delete(messageId);
@@ -60292,12 +60377,51 @@ var ChatService = class {
60292
60377
  senders: await this.readSenders(options.source.chatId),
60293
60378
  turnLimit: options.turnLimit
60294
60379
  });
60295
- if (options.trigger !== "side") return formatChatForkHandoffMessage({ ...handoff, ...options });
60296
- const seen = this.sideChatSeenBlocks.get(targetChatId);
60297
- this.sideChatSeenBlocks.set(targetChatId, hashTranscriptBlocks(handoff.blocks));
60380
+ if (!options.subagent && !options.followsSource && options.trigger !== "side" && await this.forkProviderSession(source, this.requireChat(targetChatId))) {
60381
+ const note = wrapInTag(`This chat is a fork of "${options.source.title}": the conversation so far is that chat's history up to when you were forked, also saved at \`${handoff.transcriptPath}\`. The original chat carries on separately in this workspace, so files and git state may have changed since.`, REPLICAS_INSTRUCTIONS_TAG);
60382
+ return `${options.message?.trim() || "Confirm in a sentence that you have the context, then wait for the next request."}
60383
+
60384
+ ${note}`;
60385
+ }
60386
+ if (options.trigger !== "side" && !options.followsSource) return formatChatForkHandoffMessage({ ...handoff, ...options });
60387
+ const seen = this.forkSourceSeenBlocks.get(targetChatId);
60388
+ this.forkSourceSeenBlocks.set(targetChatId, hashTranscriptBlocks(handoff.blocks));
60298
60389
  if (!seen) return formatChatForkHandoffMessage({ ...handoff, ...options });
60299
- const unseen = unseenTurnsExcerpt(seen, handoff.blocks);
60300
- return unseen ? formatSideChatUpdateMessage(options.source, unseen, options.message ?? "") : options.message ?? "";
60390
+ const unseen = options.followsSource ? unseenConversationExcerpt(seen, handoff.blocks) : unseenTurnsExcerpt(seen, handoff.blocks);
60391
+ return unseen ? formatChatForkUpdateMessage(options.source, options.trigger, unseen, options.message ?? "") : options.message ?? "";
60392
+ }
60393
+ async forkProviderSession(source, target, point) {
60394
+ if (source.persisted.provider !== target.persisted.provider || !source.provider.forkPoint || !target.provider.forkFrom) return false;
60395
+ const { forkedThroughTurn, pendingProviderFork } = target.persisted;
60396
+ try {
60397
+ point ??= await source.provider.forkPoint() ?? void 0;
60398
+ if (!point) return false;
60399
+ target.persisted.forkedThroughTurn = point.throughTurn;
60400
+ target.persisted.pendingProviderFork = point;
60401
+ await this.persistAllChats();
60402
+ await target.provider.forkFrom(point);
60403
+ return true;
60404
+ } catch (error) {
60405
+ target.persisted.forkedThroughTurn = forkedThroughTurn;
60406
+ target.persisted.pendingProviderFork = pendingProviderFork;
60407
+ console.warn("[ChatService] Native fork failed; using the transcript handoff:", { sourceChatId: source.persisted.id, targetChatId: target.persisted.id, error });
60408
+ return false;
60409
+ }
60410
+ }
60411
+ async followForkSource(chat, fork, message) {
60412
+ const source = this.requireChat(fork.source.chatId);
60413
+ if (source.persisted.provider === chat.persisted.provider && source.provider.forkPoint && chat.provider.forkFrom) {
60414
+ if (chat.provider.isProcessing() || chat.provider.getQueue().length > 0) return message;
60415
+ const point = await source.provider.forkPoint().catch(() => null);
60416
+ if (!point || point.throughTurn === chat.persisted.forkedThroughTurn) return message;
60417
+ if (await this.forkProviderSession(source, chat, point)) {
60418
+ const note = wrapInTag(`Replicas re-forked this chat from "${fork.source.title}" so you have its latest context. Your own earlier turns are not in this history: your earlier fixes are in git and the notes file.`, REPLICAS_INSTRUCTIONS_TAG);
60419
+ return `${message}
60420
+
60421
+ ${note}`;
60422
+ }
60423
+ }
60424
+ return this.createForkHandoffMessage(chat.persisted.id, { source: fork.source, trigger: fork.trigger, message, followsSource: true });
60301
60425
  }
60302
60426
  async runFork(targetId, request, errorNotificationTargets) {
60303
60427
  const target = this.chats.get(targetId);
@@ -60520,6 +60644,7 @@ var ChatService = class {
60520
60644
  createRuntimeChat(persisted) {
60521
60645
  const saveSession = async (sessionId) => {
60522
60646
  persisted.providerSessionId = sessionId;
60647
+ delete persisted.pendingProviderFork;
60523
60648
  persisted.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
60524
60649
  await this.persistAllChats();
60525
60650
  const chat = this.getRuntimeChat(persisted.id);
@@ -60629,6 +60754,7 @@ var ChatService = class {
60629
60754
  (event) => this.agentTokenUsageTracker.recordEvent(event)
60630
60755
  );
60631
60756
  provider = new CodexAspManager({
60757
+ pendingFork: persisted.pendingProviderFork,
60632
60758
  ...managerOptions,
60633
60759
  onCodexTurnStarted: codexTokenUsage.onTurnStarted,
60634
60760
  onCodexTokenUsage: codexTokenUsage.onTokenUsage,
@@ -60950,7 +61076,7 @@ var ChatService = class {
60950
61076
  }
60951
61077
  async loadChats() {
60952
61078
  try {
60953
- const content = await readFile16(CHATS_FILE, "utf-8");
61079
+ const content = await readFile17(CHATS_FILE, "utf-8");
60954
61080
  return parsePersistedChatsContent(content);
60955
61081
  } catch (error) {
60956
61082
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
@@ -60965,7 +61091,7 @@ var ChatService = class {
60965
61091
  console.error("[ChatService] Failed to quarantine corrupt chats file:", renameError);
60966
61092
  }
60967
61093
  try {
60968
- const backupContent = await readFile16(CHATS_BACKUP_FILE, "utf-8");
61094
+ const backupContent = await readFile17(CHATS_BACKUP_FILE, "utf-8");
60969
61095
  return parsePersistedChatsContent(backupContent);
60970
61096
  } catch (backupError) {
60971
61097
  if (backupError && typeof backupError === "object" && "code" in backupError && backupError.code === "ENOENT") {
@@ -61084,8 +61210,8 @@ var ChatService = class {
61084
61210
 
61085
61211
  // src/services/repo-file-service.ts
61086
61212
  import { execFile as execFile7 } from "child_process";
61087
- import { readFile as readFile17 } from "fs/promises";
61088
- import { homedir as homedir9 } from "os";
61213
+ import { readFile as readFile18 } from "fs/promises";
61214
+ import { homedir as homedir10 } from "os";
61089
61215
  import { extname as extname3, join as join30 } from "path";
61090
61216
 
61091
61217
  // src/services/language-server-service.ts
@@ -61304,7 +61430,7 @@ function execGitAsync(args, cwd, timeoutMs) {
61304
61430
  });
61305
61431
  }
61306
61432
  var RepoFileService = class {
61307
- constructor(gitService2, homeDir = homedir9()) {
61433
+ constructor(gitService2, homeDir = homedir10()) {
61308
61434
  this.homeDir = homeDir;
61309
61435
  this.gitService = gitService2;
61310
61436
  }
@@ -61392,7 +61518,7 @@ var RepoFileService = class {
61392
61518
  sizeBytes,
61393
61519
  binary: true,
61394
61520
  tooLarge: false,
61395
- base64: (await readFile17(fullPath)).toString("base64"),
61521
+ base64: (await readFile18(fullPath)).toString("base64"),
61396
61522
  mimeType
61397
61523
  };
61398
61524
  }
@@ -61417,7 +61543,7 @@ var RepoFileService = class {
61417
61543
  tooLarge: true
61418
61544
  };
61419
61545
  }
61420
- const content = await readFile17(fullPath, "utf-8");
61546
+ const content = await readFile18(fullPath, "utf-8");
61421
61547
  return {
61422
61548
  repoName,
61423
61549
  path: filePath,
@@ -61448,7 +61574,7 @@ var RepoFileService = class {
61448
61574
  async inspectSymbol(repoName, filePath, line, character, action) {
61449
61575
  const resolved = await this.resolveFile(repoName, filePath);
61450
61576
  if (!resolved || line < 1 || character < 0 || isBinaryExtension(filePath)) return null;
61451
- const content = await readFile17(resolved.fullPath, "utf8");
61577
+ const content = await readFile18(resolved.fullPath, "utf8");
61452
61578
  const sourceLine = content.split("\n")[line - 1];
61453
61579
  if (sourceLine === void 0) return null;
61454
61580
  const symbolMatch = Array.from(sourceLine.matchAll(/[\p{L}_$][\p{L}\p{N}_$]*/gu)).find((match) => character >= match.index && character <= match.index + match[0].length);
@@ -61571,20 +61697,20 @@ var RepoFileService = class {
61571
61697
  // src/v1-routes.ts
61572
61698
  import { Hono } from "hono";
61573
61699
  import { z as z4 } from "zod";
61574
- import { readdir as readdir10, stat as stat7, readFile as readFile20 } from "fs/promises";
61700
+ import { readdir as readdir10, stat as stat7, readFile as readFile21 } from "fs/promises";
61575
61701
  import { join as join33, resolve as resolve5 } from "path";
61576
61702
 
61577
61703
  // src/services/warm-hooks-service.ts
61578
61704
  import { spawn as spawn5 } from "child_process";
61579
- import { readFile as readFile19 } from "fs/promises";
61705
+ import { readFile as readFile20 } from "fs/promises";
61580
61706
  import { existsSync as existsSync16 } from "fs";
61581
61707
  import { join as join32 } from "path";
61582
61708
 
61583
61709
  // src/services/warm-hook-logs-service.ts
61584
- import { mkdir as mkdir18, readFile as readFile18, writeFile as writeFile9, readdir as readdir9, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
61585
- import { homedir as homedir10 } from "os";
61710
+ import { mkdir as mkdir18, readFile as readFile19, writeFile as writeFile9, readdir as readdir9, appendFile as appendFile6, unlink as unlink2 } from "fs/promises";
61711
+ import { homedir as homedir11 } from "os";
61586
61712
  import { join as join31 } from "path";
61587
- var LOGS_DIR2 = join31(homedir10(), ".replicas", "warm-hook-logs");
61713
+ var LOGS_DIR2 = join31(homedir11(), ".replicas", "warm-hook-logs");
61588
61714
  var CURRENT_RUN_LOG = join31(LOGS_DIR2, "current-run.log");
61589
61715
  function withPreview2(stored) {
61590
61716
  const preview = buildHookOutputPreview(stored.output);
@@ -61630,7 +61756,7 @@ var WarmHookLogsService = class {
61630
61756
  continue;
61631
61757
  }
61632
61758
  try {
61633
- const raw = await readFile18(join31(LOGS_DIR2, file), "utf-8");
61759
+ const raw = await readFile19(join31(LOGS_DIR2, file), "utf-8");
61634
61760
  const stored = JSON.parse(raw);
61635
61761
  if (stored.hookType !== "environment" && stored.hookType !== "repository") continue;
61636
61762
  logs.push(withPreview2(stored));
@@ -61657,7 +61783,7 @@ var WarmHookLogsService = class {
61657
61783
  }
61658
61784
  async getCurrentRunLog() {
61659
61785
  try {
61660
- return await readFile18(CURRENT_RUN_LOG, "utf-8");
61786
+ return await readFile19(CURRENT_RUN_LOG, "utf-8");
61661
61787
  } catch (err) {
61662
61788
  if (err.code === "ENOENT") return null;
61663
61789
  throw err;
@@ -61666,7 +61792,7 @@ var WarmHookLogsService = class {
61666
61792
  async getFullOutput(hookType, hookName) {
61667
61793
  const filename = hookType === "environment" ? ENVIRONMENT_HOOK_LOG_FILENAME : repoHookLogFilename(hookName);
61668
61794
  try {
61669
- const raw = await readFile18(join31(LOGS_DIR2, filename), "utf-8");
61795
+ const raw = await readFile19(join31(LOGS_DIR2, filename), "utf-8");
61670
61796
  const stored = JSON.parse(raw);
61671
61797
  if (stored.hookType !== hookType || stored.hookName !== hookName) {
61672
61798
  return null;
@@ -61690,7 +61816,7 @@ async function readRepoWarmHook(repoPath) {
61690
61816
  continue;
61691
61817
  }
61692
61818
  try {
61693
- const raw = await readFile19(configPath, "utf-8");
61819
+ const raw = await readFile20(configPath, "utf-8");
61694
61820
  const config = parseReplicasConfigString(raw, filename);
61695
61821
  if (!config.warmHook) {
61696
61822
  return null;
@@ -63083,7 +63209,7 @@ data: ${JSON.stringify("Terminal session not found")}
63083
63209
  }
63084
63210
  let content;
63085
63211
  try {
63086
- content = await readFile20(filePath, "utf-8");
63212
+ content = await readFile21(filePath, "utf-8");
63087
63213
  } catch {
63088
63214
  return c.json(jsonError("Log session not found"), 404);
63089
63215
  }
@@ -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-G5QLEN6P.js";
6
+ } from "./chunk-RJEDVMHT.js";
7
7
  import {
8
8
  isRecord
9
9
  } from "./chunk-UZSNFLDQ.js";
10
10
  import {
11
11
  shouldRefreshPullRequests
12
- } from "./chunk-RG5UOHPJ.js";
12
+ } from "./chunk-DUEWTRSF.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-RG5UOHPJ.js";
12
+ } from "./chunk-DUEWTRSF.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.1209",
3
+ "version": "0.1.1211",
4
4
  "description": "Lightweight API server for Replicas workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",