replicas-engine 0.1.1553 → 0.1.1556

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-QEF5YBHR.js";
30
+ } from "./chunk-6472CPIK.js";
31
31
  import {
32
32
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
33
33
  AGENT_MESSAGE_DELTA_METHOD,
@@ -65,10 +65,10 @@ import {
65
65
  spawnMuseMsp,
66
66
  startMuseSession,
67
67
  uuidV7
68
- } from "./chunk-FYJBMJ2J.js";
68
+ } from "./chunk-V5TNVG7G.js";
69
69
  import {
70
70
  publishedPullRequestUrls
71
- } from "./chunk-6E4YV4DR.js";
71
+ } from "./chunk-KZJFCAI3.js";
72
72
  import {
73
73
  ACCOUNT_RATE_LIMITS_READ_METHOD,
74
74
  AsyncLock,
@@ -143,7 +143,7 @@ import {
143
143
  timestampFromSeconds,
144
144
  upsertCredentialFileLines,
145
145
  writeSecureCredentialFile
146
- } from "./chunk-UZV2WIJD.js";
146
+ } from "./chunk-MTP7RHIL.js";
147
147
  import {
148
148
  ENGINE_ENV,
149
149
  UNQUOTED_PATHS_CONFIG,
@@ -154,15 +154,15 @@ import {
154
154
  resolveDiffBase,
155
155
  setAgentCredentialSnapshot,
156
156
  setLinearSessionId
157
- } from "./chunk-3N6VXGWZ.js";
157
+ } from "./chunk-JK2RX3SH.js";
158
158
  import {
159
159
  getCodexModelProvider
160
- } from "./chunk-HBGC6KZK.js";
160
+ } from "./chunk-6XQBNREH.js";
161
161
  import {
162
162
  SUBPROCESS_MAX_BUFFER,
163
163
  execAsync,
164
164
  execFileAsync
165
- } from "./chunk-CYXYSFKG.js";
165
+ } from "./chunk-ETGGD7MK.js";
166
166
  import {
167
167
  isRecord as isRecord2
168
168
  } from "./chunk-UZSNFLDQ.js";
@@ -443,7 +443,7 @@ import {
443
443
  workspaceTokenRequestSchema,
444
444
  workspaceTokenResponseSchema,
445
445
  wrapInTag
446
- } from "./chunk-IDA22DYC.js";
446
+ } from "./chunk-IMHAG6WO.js";
447
447
  import {
448
448
  cloneMcpConfig,
449
449
  ensureCompatibilityImports,
@@ -11361,396 +11361,6 @@ function canSteerMessage(provider, request) {
11361
11361
  return !getGoalCommand(request.message, request.goalMode) && !(provider === "codex" && isCompactCommand(request.message));
11362
11362
  }
11363
11363
 
11364
- // src/managers/claude-manager.ts
11365
- import {
11366
- forkSession,
11367
- getSessionMessages,
11368
- query
11369
- } from "@anthropic-ai/claude-agent-sdk";
11370
- import { randomUUID as randomUUID3 } from "crypto";
11371
- import { join as join11 } from "path";
11372
- import { readdir as readdir4, readFile as readFile7 } from "fs/promises";
11373
-
11374
- // src/utils/linear-converter.ts
11375
- function linearThoughtToResponse(thought) {
11376
- return {
11377
- linearSessionId: thought.linearSessionId,
11378
- content: {
11379
- type: "response",
11380
- body: thought.content.body
11381
- }
11382
- };
11383
- }
11384
- function summarizeInput(input) {
11385
- if (!input) return "";
11386
- if (typeof input === "string") return input;
11387
- if (isRecord(input)) {
11388
- if (input.file_path) return String(input.file_path);
11389
- if (input.command) return String(input.command);
11390
- if (input.pattern) return `pattern: ${String(input.pattern)}`;
11391
- if (input.query) return String(input.query);
11392
- if (input.url) return String(input.url);
11393
- if (typeof input.activeForm === "string" && input.activeForm) return String(input.activeForm);
11394
- if (typeof input.subject === "string" && input.subject) return String(input.subject);
11395
- for (const [key, value] of Object.entries(input)) {
11396
- return `${key}: ${String(value)}`;
11397
- }
11398
- }
11399
- return "";
11400
- }
11401
- function summarizeResult(result) {
11402
- if (!result) return "";
11403
- if (typeof result === "string") return result;
11404
- if (isRecord(result)) {
11405
- if (typeof result.message === "string") return result.message;
11406
- if (typeof result.error === "string") return result.error;
11407
- if (typeof result.stdout === "string") return result.stdout;
11408
- if (typeof result.stderr === "string") return result.stderr;
11409
- if (typeof result.path === "string") return result.path;
11410
- }
11411
- try {
11412
- return JSON.stringify(result);
11413
- } catch {
11414
- return String(result);
11415
- }
11416
- }
11417
- function toolAction(toolName) {
11418
- switch (toolName) {
11419
- case "Bash":
11420
- case "bash":
11421
- case "shell":
11422
- return "Running command";
11423
- case "Edit":
11424
- case "edit":
11425
- return "Editing file";
11426
- case "Write":
11427
- case "write":
11428
- return "Writing file";
11429
- case "Read":
11430
- case "read":
11431
- return "Reading file";
11432
- case "Glob":
11433
- case "glob":
11434
- return "Searching files";
11435
- case "Grep":
11436
- case "grep":
11437
- case "semsearch":
11438
- return "Searching code";
11439
- case "WebSearch":
11440
- return "Web search";
11441
- case "WebFetch":
11442
- return "Fetching URL";
11443
- case "delete":
11444
- return "Deleting file";
11445
- case "Task":
11446
- case "task":
11447
- return "Spawning subagent";
11448
- case "TaskCreate":
11449
- case "TaskUpdate":
11450
- case "TaskList":
11451
- case "TaskGet":
11452
- case "update_todos":
11453
- case "create_plan":
11454
- return "Updating plan";
11455
- default:
11456
- return toolName;
11457
- }
11458
- }
11459
- function convertClaudeEvent(event, linearSessionId) {
11460
- if (event.type === "assistant") {
11461
- const contentBlocks = normalizeContentBlocks(event.message.content);
11462
- for (const block of contentBlocks) {
11463
- if (block.type === "text" && block.text) {
11464
- return {
11465
- linearSessionId,
11466
- content: {
11467
- type: "thought",
11468
- body: block.text
11469
- }
11470
- };
11471
- }
11472
- if (block.type === "thinking" && block.thinking) {
11473
- return {
11474
- linearSessionId,
11475
- content: {
11476
- type: "thought",
11477
- body: block.thinking
11478
- }
11479
- };
11480
- }
11481
- if (block.type === "tool_use" && block.name) {
11482
- const toolName = block.name;
11483
- const parameter = summarizeInput(block.input);
11484
- return {
11485
- linearSessionId,
11486
- content: {
11487
- type: "action",
11488
- action: toolAction(toolName),
11489
- parameter
11490
- }
11491
- };
11492
- }
11493
- }
11494
- }
11495
- if (event.type === "user") {
11496
- const contentBlocks = normalizeContentBlocks(event.message.content);
11497
- for (const block of contentBlocks) {
11498
- if (block.type === "tool_result") {
11499
- const resultText = extractToolResultText(block.content);
11500
- const isError = block.is_error || false;
11501
- const result = isError ? `Error: ${resultText}` : resultText || "Done";
11502
- return {
11503
- linearSessionId,
11504
- content: {
11505
- type: "action",
11506
- action: "Tool completed",
11507
- parameter: "",
11508
- result
11509
- }
11510
- };
11511
- }
11512
- }
11513
- }
11514
- return null;
11515
- }
11516
- function convertCursorEvent(event, linearSessionId) {
11517
- if (event.type === "assistant") {
11518
- for (const block of event.message.content) {
11519
- if (block.type === "text" && block.text) {
11520
- return {
11521
- linearSessionId,
11522
- content: {
11523
- type: "thought",
11524
- body: block.text
11525
- }
11526
- };
11527
- }
11528
- if (block.type === "tool_use" && block.name) {
11529
- return {
11530
- linearSessionId,
11531
- content: {
11532
- type: "action",
11533
- action: toolAction(block.name),
11534
- parameter: summarizeInput(block.input)
11535
- }
11536
- };
11537
- }
11538
- }
11539
- }
11540
- if (event.type === "thinking" && event.text) {
11541
- return {
11542
- linearSessionId,
11543
- content: {
11544
- type: "thought",
11545
- body: event.text
11546
- }
11547
- };
11548
- }
11549
- if (event.type === "tool_call") {
11550
- const result = event.status === "running" ? void 0 : event.status === "error" ? `Error: ${summarizeResult(event.result) || "Tool failed"}` : summarizeResult(event.result) || "Done";
11551
- return {
11552
- linearSessionId,
11553
- content: {
11554
- type: "action",
11555
- action: toolAction(event.name),
11556
- parameter: summarizeInput(event.args),
11557
- ...result ? { result } : {}
11558
- }
11559
- };
11560
- }
11561
- if (event.type === "task" && event.text) {
11562
- return {
11563
- linearSessionId,
11564
- content: {
11565
- type: "thought",
11566
- body: event.text
11567
- }
11568
- };
11569
- }
11570
- return null;
11571
- }
11572
- function isOpencodePartEnded(part) {
11573
- return "time" in part && isRecord(part.time) && "end" in part.time && part.time.end !== void 0;
11574
- }
11575
- function convertOpencodePart(part, linearSessionId) {
11576
- if ((part.type === "text" || part.type === "reasoning") && isOpencodePartEnded(part)) {
11577
- const body = typeof part.text === "string" ? part.text.trim() : "";
11578
- if (!body) return null;
11579
- return {
11580
- linearSessionId,
11581
- content: {
11582
- type: "thought",
11583
- body
11584
- }
11585
- };
11586
- }
11587
- if (part.type === "tool") {
11588
- const state = part.state;
11589
- const result = state.status === "completed" ? summarizeResult(state.output) || "Done" : state.status === "error" ? `Error: ${summarizeResult(state.error) || "Tool failed"}` : void 0;
11590
- return {
11591
- linearSessionId,
11592
- content: {
11593
- type: "action",
11594
- action: toolAction(typeof part.tool === "string" ? part.tool : "Tool"),
11595
- parameter: summarizeInput(state.input),
11596
- ...result ? { result } : {}
11597
- }
11598
- };
11599
- }
11600
- if (part.type === "patch") {
11601
- const files = "files" in part && Array.isArray(part.files) ? part.files.filter((file) => typeof file === "string") : [];
11602
- if (files.length === 0) return null;
11603
- return {
11604
- linearSessionId,
11605
- content: {
11606
- type: "action",
11607
- action: "File change",
11608
- parameter: files.join(", "),
11609
- result: "Done"
11610
- }
11611
- };
11612
- }
11613
- return null;
11614
- }
11615
- function mapTodoStatus(status) {
11616
- if (status === "in_progress") {
11617
- return "inProgress";
11618
- }
11619
- if (status === "completed") {
11620
- return "completed";
11621
- }
11622
- if (status === "cancelled" || status === "canceled") {
11623
- return "canceled";
11624
- }
11625
- return "pending";
11626
- }
11627
- function codexAspReasoningText(item) {
11628
- return [...item.summary, ...item.content].filter(Boolean).join("\n").trim();
11629
- }
11630
- function codexAspChangePaths(item) {
11631
- return item.changes.map((change) => change.path).filter(Boolean).join(", ");
11632
- }
11633
- function codexAspStatusResult(status) {
11634
- return status === "completed" ? "Done" : status || "Done";
11635
- }
11636
- function convertCodexAspItem(item, lifecycle2, linearSessionId) {
11637
- if (item.type === "agentMessage") {
11638
- if (!item.text) return null;
11639
- return {
11640
- linearSessionId,
11641
- content: {
11642
- type: "thought",
11643
- body: item.text
11644
- }
11645
- };
11646
- }
11647
- if (item.type === "reasoning") {
11648
- const text = codexAspReasoningText(item);
11649
- if (!text) return null;
11650
- return {
11651
- linearSessionId,
11652
- content: {
11653
- type: "thought",
11654
- body: text
11655
- }
11656
- };
11657
- }
11658
- if (item.type === "commandExecution") {
11659
- return {
11660
- linearSessionId,
11661
- content: {
11662
- type: "action",
11663
- action: "Running command",
11664
- parameter: item.command,
11665
- ...lifecycle2 === "completed" ? { result: item.exitCode !== null ? `Exit code: ${item.exitCode}` : item.aggregatedOutput || "Done" } : {}
11666
- }
11667
- };
11668
- }
11669
- if (item.type === "fileChange") {
11670
- return {
11671
- linearSessionId,
11672
- content: {
11673
- type: "action",
11674
- action: "File change",
11675
- parameter: codexAspChangePaths(item),
11676
- ...lifecycle2 === "completed" ? { result: codexAspStatusResult(item.status) } : {}
11677
- }
11678
- };
11679
- }
11680
- if (item.type === "mcpToolCall") {
11681
- return {
11682
- linearSessionId,
11683
- content: {
11684
- type: "action",
11685
- action: item.tool || "MCP tool call",
11686
- parameter: item.server,
11687
- ...lifecycle2 === "completed" ? { result: item.error?.message ?? codexAspStatusResult(item.status) } : {}
11688
- }
11689
- };
11690
- }
11691
- if (item.type === "dynamicToolCall") {
11692
- return {
11693
- linearSessionId,
11694
- content: {
11695
- type: "action",
11696
- action: item.tool,
11697
- parameter: item.namespace ?? "",
11698
- ...lifecycle2 === "completed" ? { result: item.success === false ? "Failed" : codexAspStatusResult(item.status) } : {}
11699
- }
11700
- };
11701
- }
11702
- if (item.type === "webSearch") {
11703
- return {
11704
- linearSessionId,
11705
- content: {
11706
- type: "action",
11707
- action: "Web search",
11708
- parameter: item.query,
11709
- ...lifecycle2 === "completed" ? { result: "Done" } : {}
11710
- }
11711
- };
11712
- }
11713
- if (item.type === "plan") {
11714
- return {
11715
- linearSessionId,
11716
- content: {
11717
- type: "action",
11718
- action: "Updating plan",
11719
- parameter: item.text,
11720
- ...lifecycle2 === "completed" ? { result: "Done" } : {}
11721
- }
11722
- };
11723
- }
11724
- return null;
11725
- }
11726
- function convertCodexAspNotification(notification, linearSessionId) {
11727
- if (notification.method === "turn/started") {
11728
- return {
11729
- linearSessionId,
11730
- content: {
11731
- type: "thought",
11732
- body: "Processing..."
11733
- }
11734
- };
11735
- }
11736
- if (notification.method === "item/started") {
11737
- return convertCodexAspItem(notification.params.item, "started", linearSessionId);
11738
- }
11739
- if (notification.method === "item/completed") {
11740
- return convertCodexAspItem(notification.params.item, "completed", linearSessionId);
11741
- }
11742
- return null;
11743
- }
11744
- function extractPlanFromCodexAspNotification(notification) {
11745
- if (notification.method !== "turn/plan/updated" || notification.params.plan.length === 0) {
11746
- return null;
11747
- }
11748
- return notification.params.plan.filter((item) => item.step.trim().length > 0).map((item) => ({
11749
- content: item.step.trim(),
11750
- status: item.status
11751
- }));
11752
- }
11753
-
11754
11364
  // src/managers/coding-agent-manager.ts
11755
11365
  import { existsSync as existsSync5 } from "fs";
11756
11366
  import { join as join9 } from "path";
@@ -12224,6 +11834,9 @@ function toQueuedMessageInfo(message) {
12224
11834
  };
12225
11835
  }
12226
11836
  var subagentMcpConfigRequest = null;
11837
+ function takesTurnNotes(request) {
11838
+ return !request.goalMode && !request.message.trimStart().startsWith("/");
11839
+ }
12227
11840
  var CodingAgentManager = class _CodingAgentManager {
12228
11841
  workingDirectory;
12229
11842
  messageQueue;
@@ -12353,7 +11966,7 @@ var CodingAgentManager = class _CodingAgentManager {
12353
11966
  if (stopped && (request.engineTurn || !await this.keepStoppedRequest(delivered))) return;
12354
11967
  await this.saveLastSenderKey(senderKey);
12355
11968
  if (stopped) return;
12356
- const takesNotes = !request.goalMode && !request.message.trimStart().startsWith("/");
11969
+ const takesNotes = takesTurnNotes(request);
12357
11970
  const instructionsChanged = takesNotes && this.sentTurn && this.lastCustomInstructions !== request.customInstructions;
12358
11971
  this.sentTurn = true;
12359
11972
  this.lastCustomInstructions = request.customInstructions;
@@ -12390,7 +12003,7 @@ var CodingAgentManager = class _CodingAgentManager {
12390
12003
  }
12391
12004
  // Integration turns (Slack, GitHub, Linear) carry no sender fields and name their sender in the text, so they reset the key.
12392
12005
  withSenderLine(request) {
12393
- if (request.goalMode || request.message.trimStart().startsWith("/")) return { request, senderKey: this.lastSenderKey };
12006
+ if (!takesTurnNotes(request)) return { request, senderKey: this.lastSenderKey };
12394
12007
  if (!request.senderUserId || !request.senderEmail) return { request, senderKey: null };
12395
12008
  const via = request.source && !isClientMessageSource(request.source) ? request.source : void 0;
12396
12009
  const senderKey = `${request.senderUserId}:${via ?? ""}`;
@@ -12555,7 +12168,7 @@ ${request.message}` }, senderKey };
12555
12168
  let steered = false;
12556
12169
  const { request: withSender, senderKey } = this.withSenderLine(taken.message);
12557
12170
  const note = wrapInTag("You received this message while working. The chat folds everything before your last message of this turn, so that message must answer it too, even if you already did earlier.", REPLICAS_INSTRUCTIONS_TAG);
12558
- const command = withSender.goalMode || withSender.message.trimStart().startsWith("/");
12171
+ const command = !takesTurnNotes(withSender);
12559
12172
  const delivered = command ? withSender : { ...withSender, message: `${withSender.message}
12560
12173
 
12561
12174
  ${note}` };
@@ -12750,6 +12363,396 @@ ${note}` };
12750
12363
  }
12751
12364
  };
12752
12365
 
12366
+ // src/managers/claude-manager.ts
12367
+ import {
12368
+ forkSession,
12369
+ getSessionMessages,
12370
+ query
12371
+ } from "@anthropic-ai/claude-agent-sdk";
12372
+ import { randomUUID as randomUUID3 } from "crypto";
12373
+ import { join as join11 } from "path";
12374
+ import { readdir as readdir4, readFile as readFile7 } from "fs/promises";
12375
+
12376
+ // src/utils/linear-converter.ts
12377
+ function linearThoughtToResponse(thought) {
12378
+ return {
12379
+ linearSessionId: thought.linearSessionId,
12380
+ content: {
12381
+ type: "response",
12382
+ body: thought.content.body
12383
+ }
12384
+ };
12385
+ }
12386
+ function summarizeInput(input) {
12387
+ if (!input) return "";
12388
+ if (typeof input === "string") return input;
12389
+ if (isRecord(input)) {
12390
+ if (input.file_path) return String(input.file_path);
12391
+ if (input.command) return String(input.command);
12392
+ if (input.pattern) return `pattern: ${String(input.pattern)}`;
12393
+ if (input.query) return String(input.query);
12394
+ if (input.url) return String(input.url);
12395
+ if (typeof input.activeForm === "string" && input.activeForm) return String(input.activeForm);
12396
+ if (typeof input.subject === "string" && input.subject) return String(input.subject);
12397
+ for (const [key, value] of Object.entries(input)) {
12398
+ return `${key}: ${String(value)}`;
12399
+ }
12400
+ }
12401
+ return "";
12402
+ }
12403
+ function summarizeResult(result) {
12404
+ if (!result) return "";
12405
+ if (typeof result === "string") return result;
12406
+ if (isRecord(result)) {
12407
+ if (typeof result.message === "string") return result.message;
12408
+ if (typeof result.error === "string") return result.error;
12409
+ if (typeof result.stdout === "string") return result.stdout;
12410
+ if (typeof result.stderr === "string") return result.stderr;
12411
+ if (typeof result.path === "string") return result.path;
12412
+ }
12413
+ try {
12414
+ return JSON.stringify(result);
12415
+ } catch {
12416
+ return String(result);
12417
+ }
12418
+ }
12419
+ function toolAction(toolName) {
12420
+ switch (toolName) {
12421
+ case "Bash":
12422
+ case "bash":
12423
+ case "shell":
12424
+ return "Running command";
12425
+ case "Edit":
12426
+ case "edit":
12427
+ return "Editing file";
12428
+ case "Write":
12429
+ case "write":
12430
+ return "Writing file";
12431
+ case "Read":
12432
+ case "read":
12433
+ return "Reading file";
12434
+ case "Glob":
12435
+ case "glob":
12436
+ return "Searching files";
12437
+ case "Grep":
12438
+ case "grep":
12439
+ case "semsearch":
12440
+ return "Searching code";
12441
+ case "WebSearch":
12442
+ return "Web search";
12443
+ case "WebFetch":
12444
+ return "Fetching URL";
12445
+ case "delete":
12446
+ return "Deleting file";
12447
+ case "Task":
12448
+ case "task":
12449
+ return "Spawning subagent";
12450
+ case "TaskCreate":
12451
+ case "TaskUpdate":
12452
+ case "TaskList":
12453
+ case "TaskGet":
12454
+ case "update_todos":
12455
+ case "create_plan":
12456
+ return "Updating plan";
12457
+ default:
12458
+ return toolName;
12459
+ }
12460
+ }
12461
+ function convertClaudeEvent(event, linearSessionId) {
12462
+ if (event.type === "assistant") {
12463
+ const contentBlocks = normalizeContentBlocks(event.message.content);
12464
+ for (const block of contentBlocks) {
12465
+ if (block.type === "text" && block.text) {
12466
+ return {
12467
+ linearSessionId,
12468
+ content: {
12469
+ type: "thought",
12470
+ body: block.text
12471
+ }
12472
+ };
12473
+ }
12474
+ if (block.type === "thinking" && block.thinking) {
12475
+ return {
12476
+ linearSessionId,
12477
+ content: {
12478
+ type: "thought",
12479
+ body: block.thinking
12480
+ }
12481
+ };
12482
+ }
12483
+ if (block.type === "tool_use" && block.name) {
12484
+ const toolName = block.name;
12485
+ const parameter = summarizeInput(block.input);
12486
+ return {
12487
+ linearSessionId,
12488
+ content: {
12489
+ type: "action",
12490
+ action: toolAction(toolName),
12491
+ parameter
12492
+ }
12493
+ };
12494
+ }
12495
+ }
12496
+ }
12497
+ if (event.type === "user") {
12498
+ const contentBlocks = normalizeContentBlocks(event.message.content);
12499
+ for (const block of contentBlocks) {
12500
+ if (block.type === "tool_result") {
12501
+ const resultText = extractToolResultText(block.content);
12502
+ const isError = block.is_error || false;
12503
+ const result = isError ? `Error: ${resultText}` : resultText || "Done";
12504
+ return {
12505
+ linearSessionId,
12506
+ content: {
12507
+ type: "action",
12508
+ action: "Tool completed",
12509
+ parameter: "",
12510
+ result
12511
+ }
12512
+ };
12513
+ }
12514
+ }
12515
+ }
12516
+ return null;
12517
+ }
12518
+ function convertCursorEvent(event, linearSessionId) {
12519
+ if (event.type === "assistant") {
12520
+ for (const block of event.message.content) {
12521
+ if (block.type === "text" && block.text) {
12522
+ return {
12523
+ linearSessionId,
12524
+ content: {
12525
+ type: "thought",
12526
+ body: block.text
12527
+ }
12528
+ };
12529
+ }
12530
+ if (block.type === "tool_use" && block.name) {
12531
+ return {
12532
+ linearSessionId,
12533
+ content: {
12534
+ type: "action",
12535
+ action: toolAction(block.name),
12536
+ parameter: summarizeInput(block.input)
12537
+ }
12538
+ };
12539
+ }
12540
+ }
12541
+ }
12542
+ if (event.type === "thinking" && event.text) {
12543
+ return {
12544
+ linearSessionId,
12545
+ content: {
12546
+ type: "thought",
12547
+ body: event.text
12548
+ }
12549
+ };
12550
+ }
12551
+ if (event.type === "tool_call") {
12552
+ const result = event.status === "running" ? void 0 : event.status === "error" ? `Error: ${summarizeResult(event.result) || "Tool failed"}` : summarizeResult(event.result) || "Done";
12553
+ return {
12554
+ linearSessionId,
12555
+ content: {
12556
+ type: "action",
12557
+ action: toolAction(event.name),
12558
+ parameter: summarizeInput(event.args),
12559
+ ...result ? { result } : {}
12560
+ }
12561
+ };
12562
+ }
12563
+ if (event.type === "task" && event.text) {
12564
+ return {
12565
+ linearSessionId,
12566
+ content: {
12567
+ type: "thought",
12568
+ body: event.text
12569
+ }
12570
+ };
12571
+ }
12572
+ return null;
12573
+ }
12574
+ function isOpencodePartEnded(part) {
12575
+ return "time" in part && isRecord(part.time) && "end" in part.time && part.time.end !== void 0;
12576
+ }
12577
+ function convertOpencodePart(part, linearSessionId) {
12578
+ if ((part.type === "text" || part.type === "reasoning") && isOpencodePartEnded(part)) {
12579
+ const body = typeof part.text === "string" ? part.text.trim() : "";
12580
+ if (!body) return null;
12581
+ return {
12582
+ linearSessionId,
12583
+ content: {
12584
+ type: "thought",
12585
+ body
12586
+ }
12587
+ };
12588
+ }
12589
+ if (part.type === "tool") {
12590
+ const state = part.state;
12591
+ const result = state.status === "completed" ? summarizeResult(state.output) || "Done" : state.status === "error" ? `Error: ${summarizeResult(state.error) || "Tool failed"}` : void 0;
12592
+ return {
12593
+ linearSessionId,
12594
+ content: {
12595
+ type: "action",
12596
+ action: toolAction(typeof part.tool === "string" ? part.tool : "Tool"),
12597
+ parameter: summarizeInput(state.input),
12598
+ ...result ? { result } : {}
12599
+ }
12600
+ };
12601
+ }
12602
+ if (part.type === "patch") {
12603
+ const files = "files" in part && Array.isArray(part.files) ? part.files.filter((file) => typeof file === "string") : [];
12604
+ if (files.length === 0) return null;
12605
+ return {
12606
+ linearSessionId,
12607
+ content: {
12608
+ type: "action",
12609
+ action: "File change",
12610
+ parameter: files.join(", "),
12611
+ result: "Done"
12612
+ }
12613
+ };
12614
+ }
12615
+ return null;
12616
+ }
12617
+ function mapTodoStatus(status) {
12618
+ if (status === "in_progress") {
12619
+ return "inProgress";
12620
+ }
12621
+ if (status === "completed") {
12622
+ return "completed";
12623
+ }
12624
+ if (status === "cancelled" || status === "canceled") {
12625
+ return "canceled";
12626
+ }
12627
+ return "pending";
12628
+ }
12629
+ function codexAspReasoningText(item) {
12630
+ return [...item.summary, ...item.content].filter(Boolean).join("\n").trim();
12631
+ }
12632
+ function codexAspChangePaths(item) {
12633
+ return item.changes.map((change) => change.path).filter(Boolean).join(", ");
12634
+ }
12635
+ function codexAspStatusResult(status) {
12636
+ return status === "completed" ? "Done" : status || "Done";
12637
+ }
12638
+ function convertCodexAspItem(item, lifecycle2, linearSessionId) {
12639
+ if (item.type === "agentMessage") {
12640
+ if (!item.text) return null;
12641
+ return {
12642
+ linearSessionId,
12643
+ content: {
12644
+ type: "thought",
12645
+ body: item.text
12646
+ }
12647
+ };
12648
+ }
12649
+ if (item.type === "reasoning") {
12650
+ const text = codexAspReasoningText(item);
12651
+ if (!text) return null;
12652
+ return {
12653
+ linearSessionId,
12654
+ content: {
12655
+ type: "thought",
12656
+ body: text
12657
+ }
12658
+ };
12659
+ }
12660
+ if (item.type === "commandExecution") {
12661
+ return {
12662
+ linearSessionId,
12663
+ content: {
12664
+ type: "action",
12665
+ action: "Running command",
12666
+ parameter: item.command,
12667
+ ...lifecycle2 === "completed" ? { result: item.exitCode !== null ? `Exit code: ${item.exitCode}` : item.aggregatedOutput || "Done" } : {}
12668
+ }
12669
+ };
12670
+ }
12671
+ if (item.type === "fileChange") {
12672
+ return {
12673
+ linearSessionId,
12674
+ content: {
12675
+ type: "action",
12676
+ action: "File change",
12677
+ parameter: codexAspChangePaths(item),
12678
+ ...lifecycle2 === "completed" ? { result: codexAspStatusResult(item.status) } : {}
12679
+ }
12680
+ };
12681
+ }
12682
+ if (item.type === "mcpToolCall") {
12683
+ return {
12684
+ linearSessionId,
12685
+ content: {
12686
+ type: "action",
12687
+ action: item.tool || "MCP tool call",
12688
+ parameter: item.server,
12689
+ ...lifecycle2 === "completed" ? { result: item.error?.message ?? codexAspStatusResult(item.status) } : {}
12690
+ }
12691
+ };
12692
+ }
12693
+ if (item.type === "dynamicToolCall") {
12694
+ return {
12695
+ linearSessionId,
12696
+ content: {
12697
+ type: "action",
12698
+ action: item.tool,
12699
+ parameter: item.namespace ?? "",
12700
+ ...lifecycle2 === "completed" ? { result: item.success === false ? "Failed" : codexAspStatusResult(item.status) } : {}
12701
+ }
12702
+ };
12703
+ }
12704
+ if (item.type === "webSearch") {
12705
+ return {
12706
+ linearSessionId,
12707
+ content: {
12708
+ type: "action",
12709
+ action: "Web search",
12710
+ parameter: item.query,
12711
+ ...lifecycle2 === "completed" ? { result: "Done" } : {}
12712
+ }
12713
+ };
12714
+ }
12715
+ if (item.type === "plan") {
12716
+ return {
12717
+ linearSessionId,
12718
+ content: {
12719
+ type: "action",
12720
+ action: "Updating plan",
12721
+ parameter: item.text,
12722
+ ...lifecycle2 === "completed" ? { result: "Done" } : {}
12723
+ }
12724
+ };
12725
+ }
12726
+ return null;
12727
+ }
12728
+ function convertCodexAspNotification(notification, linearSessionId) {
12729
+ if (notification.method === "turn/started") {
12730
+ return {
12731
+ linearSessionId,
12732
+ content: {
12733
+ type: "thought",
12734
+ body: "Processing..."
12735
+ }
12736
+ };
12737
+ }
12738
+ if (notification.method === "item/started") {
12739
+ return convertCodexAspItem(notification.params.item, "started", linearSessionId);
12740
+ }
12741
+ if (notification.method === "item/completed") {
12742
+ return convertCodexAspItem(notification.params.item, "completed", linearSessionId);
12743
+ }
12744
+ return null;
12745
+ }
12746
+ function extractPlanFromCodexAspNotification(notification) {
12747
+ if (notification.method !== "turn/plan/updated" || notification.params.plan.length === 0) {
12748
+ return null;
12749
+ }
12750
+ return notification.params.plan.filter((item) => item.step.trim().length > 0).map((item) => ({
12751
+ content: item.step.trim(),
12752
+ status: item.status
12753
+ }));
12754
+ }
12755
+
12753
12756
  // src/utils/agent-env.ts
12754
12757
  function resolveClaudeAuthMethodForMessage(env = ENGINE_ENV) {
12755
12758
  const method = env.REPLICAS_CLAUDE_AUTH_METHOD;
@@ -16368,6 +16371,7 @@ var MIGRATION_FLUSH_CHARS = 1 << 20;
16368
16371
  var WRITE_RETRY_DELAYS_MS = [100, 400, 1500, 3e3, 5e3];
16369
16372
  var NEWLINE = Buffer.from("\n");
16370
16373
  var READ_CHUNK_BYTES = 1 << 18;
16374
+ var STREAM_SYNC_DELAY_MS = 50;
16371
16375
  function isMissingFile(error) {
16372
16376
  return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
16373
16377
  }
@@ -16387,8 +16391,9 @@ async function openWholeLog(path7) {
16387
16391
  }
16388
16392
  }
16389
16393
  var CodexHistoryFile = class {
16390
- constructor(filePath) {
16394
+ constructor(filePath, isStream = () => false) {
16391
16395
  this.filePath = filePath;
16396
+ this.isStream = isStream;
16392
16397
  try {
16393
16398
  const file = openSync(filePath, "r");
16394
16399
  try {
@@ -16402,22 +16407,31 @@ var CodexHistoryFile = class {
16402
16407
  if (!isMissingFile(error)) throw error;
16403
16408
  mkdirSync2(dirname3(filePath), { recursive: true });
16404
16409
  }
16410
+ this.writtenEnd = this.flushedEnd;
16405
16411
  this.nextOffset = this.firstFreeOffset();
16406
16412
  }
16407
16413
  filePath;
16414
+ isStream;
16408
16415
  queued = [];
16409
16416
  writing = null;
16410
16417
  taken = Promise.resolve();
16411
16418
  // Every byte before this is on disk. Reads and the position clients are told stop here, so nothing outside the engine ever sees an offset a crash could take back.
16412
16419
  flushedEnd = 0;
16420
+ // Stream records between the flushed end and here are written but not yet synced: a machine crash can take them back, so no position reaches them.
16421
+ writtenEnd = 0;
16422
+ unsynced = [];
16423
+ syncDue = false;
16424
+ syncTimer = null;
16413
16425
  nextOffset = 0;
16426
+ latestRecordedAt = 0;
16414
16427
  // The file ends in a record with no newline (a write cut short): the next batch starts with one, so readers lose that fragment alone.
16415
16428
  tornTail = false;
16416
16429
  // Part of a dropped batch may have reached the disk. Until the file is cut back to the flushed end, a crash would bring those records back.
16417
16430
  cutPending = false;
16418
16431
  // Set while a rewritten file takes the old one's place, so a read never pairs one file with the other's flushed end.
16419
16432
  swapping = null;
16420
- // Counts those swaps: an open that began before one and returned after it holds the old file.
16433
+ // Goes up when a swap starts and again when the offsets become the rewritten file's: an open that began before a swap and
16434
+ // returned after it holds the old file, and an offset taken while the swap was under way is still the old file's.
16421
16435
  swaps = 0;
16422
16436
  get historyEnd() {
16423
16437
  return this.flushedEnd;
@@ -16426,61 +16440,94 @@ var CodexHistoryFile = class {
16426
16440
  get end() {
16427
16441
  return this.nextOffset;
16428
16442
  }
16443
+ get swapCount() {
16444
+ return this.swaps;
16445
+ }
16429
16446
  record(event) {
16447
+ const recordedAt = Date.parse(event.timestamp);
16448
+ if (recordedAt > this.latestRecordedAt) this.latestRecordedAt = recordedAt;
16430
16449
  const bytes = Buffer.from(`${JSON.stringify(event)}
16431
16450
  `);
16432
16451
  const at = this.nextOffset;
16433
16452
  this.nextOffset += bytes.length;
16453
+ const synced = Promise.withResolvers();
16454
+ this.taken = synced.promise;
16434
16455
  const written = new Promise((resolve7, reject) => {
16435
- this.queued.push({ bytes, resolve: resolve7, reject });
16456
+ this.queued.push({ bytes, stream: this.isStream(event), resolve: resolve7, reject, synced: synced.resolve });
16436
16457
  });
16437
- this.taken = written.catch(() => {
16458
+ written.catch(() => {
16438
16459
  });
16439
16460
  this.writing ??= this.writeQueued();
16440
16461
  return { at, written };
16441
16462
  }
16442
16463
  /** Settles once every record taken so far is on disk or dropped. */
16443
16464
  flush() {
16465
+ if (this.writing || this.queued.length > 0 || this.writtenEnd > this.flushedEnd) this.syncNow();
16444
16466
  return this.taken;
16445
16467
  }
16468
+ syncNow() {
16469
+ this.syncDue = true;
16470
+ this.writing ??= this.writeQueued();
16471
+ }
16446
16472
  firstFreeOffset() {
16447
16473
  return this.flushedEnd + (this.tornTail ? NEWLINE.length : 0);
16448
16474
  }
16449
16475
  async writeQueued() {
16450
16476
  try {
16451
- while (this.queued.length > 0) {
16477
+ while (this.queued.length > 0 || this.syncDue) {
16452
16478
  const batch = this.queued.splice(0);
16453
- const bytes = Buffer.concat([...this.tornTail ? [NEWLINE] : [], ...batch.map((record3) => record3.bytes)]);
16479
+ const sync = this.syncDue || batch.some((record3) => !record3.stream);
16480
+ this.syncDue = false;
16481
+ if (batch.length === 0 && this.writtenEnd === this.flushedEnd) continue;
16482
+ const startsLine = this.tornTail && this.writtenEnd === this.flushedEnd && batch.length > 0;
16483
+ const bytes = Buffer.concat([...startsLine ? [NEWLINE] : [], ...batch.map((record3) => record3.bytes)]);
16454
16484
  try {
16455
- await this.writeAtFlushedEnd(bytes);
16485
+ await this.write(bytes, sync);
16456
16486
  } catch (error) {
16457
16487
  const dropped = [...batch, ...this.queued.splice(0)];
16458
16488
  console.error(`[CodexHistoryFile] Dropped ${dropped.length} records that could not be written:`, error);
16489
+ this.writtenEnd = this.flushedEnd;
16459
16490
  this.nextOffset = this.firstFreeOffset();
16460
16491
  this.cutPending = true;
16461
16492
  await this.cutToFlushedEnd().catch(() => {
16462
16493
  });
16463
- for (const record3 of dropped) record3.reject(error);
16494
+ for (const record3 of this.unsynced.splice(0)) record3.synced();
16495
+ for (const record3 of dropped) {
16496
+ record3.reject(error);
16497
+ record3.synced();
16498
+ }
16464
16499
  continue;
16465
16500
  }
16466
- this.tornTail = false;
16467
- this.flushedEnd += bytes.length;
16501
+ this.writtenEnd += bytes.length;
16502
+ this.unsynced.push(...batch);
16503
+ if (sync) {
16504
+ if (this.syncTimer) clearTimeout(this.syncTimer);
16505
+ this.syncTimer = null;
16506
+ this.tornTail = false;
16507
+ this.flushedEnd = this.writtenEnd;
16508
+ for (const record3 of this.unsynced.splice(0)) record3.synced();
16509
+ } else {
16510
+ this.syncTimer ??= setTimeout(() => {
16511
+ this.syncTimer = null;
16512
+ this.syncNow();
16513
+ }, STREAM_SYNC_DELAY_MS).unref();
16514
+ }
16468
16515
  for (const record3 of batch) record3.resolve();
16469
16516
  }
16470
16517
  } finally {
16471
16518
  this.writing = null;
16472
16519
  }
16473
16520
  }
16474
- async writeAtFlushedEnd(bytes) {
16521
+ async write(bytes, sync) {
16475
16522
  for (let attempt = 0; ; attempt += 1) {
16476
16523
  try {
16477
16524
  if (this.cutPending) await this.cutToFlushedEnd();
16478
16525
  const file = await open(this.filePath, constants.O_WRONLY | constants.O_CREAT);
16479
16526
  try {
16480
16527
  for (let written = 0; written < bytes.length; ) {
16481
- written += (await file.write(bytes, written, bytes.length - written, this.flushedEnd + written)).bytesWritten;
16528
+ written += (await file.write(bytes, written, bytes.length - written, this.writtenEnd + written)).bytesWritten;
16482
16529
  }
16483
- await file.datasync();
16530
+ if (sync) await file.datasync();
16484
16531
  } finally {
16485
16532
  await file.close();
16486
16533
  }
@@ -16516,7 +16563,10 @@ var CodexHistoryFile = class {
16516
16563
  return;
16517
16564
  }
16518
16565
  if (parseAgentEventJsonlLine(firstLine)?.type === CODEX_HISTORY_FORMAT_EVENT_TYPE) return;
16519
- while (this.writing) await this.writing;
16566
+ while (this.writing || this.writtenEnd > this.flushedEnd) {
16567
+ this.syncNow();
16568
+ await this.writing;
16569
+ }
16520
16570
  const rewrite = this.rewriteAsItemEvents();
16521
16571
  this.writing = rewrite.then(() => this.writeQueued(), () => this.writeQueued());
16522
16572
  this.taken = this.writing;
@@ -16550,8 +16600,10 @@ var CodexHistoryFile = class {
16550
16600
  try {
16551
16601
  await swap;
16552
16602
  this.flushedEnd = size;
16603
+ this.writtenEnd = size;
16553
16604
  this.tornTail = false;
16554
16605
  this.nextOffset = size + this.queued.reduce((total, record3) => total + record3.bytes.length, 0);
16606
+ this.swaps += 1;
16555
16607
  } finally {
16556
16608
  this.swapping = null;
16557
16609
  }
@@ -16607,6 +16659,7 @@ var CodexHistoryFile = class {
16607
16659
  return folder.finish();
16608
16660
  }
16609
16661
  async loadEventsPage(page2) {
16662
+ if (this.writtenEnd > this.flushedEnd) await this.flush();
16610
16663
  if (page2.subagents) {
16611
16664
  const events = await this.read((size, readRange) => readChatSubagentHistory({ size, compact: page2.compact, readRange }));
16612
16665
  return { events: events ?? [], beforeCursor: null };
@@ -59493,6 +59546,7 @@ var PiManager = class extends CodingAgentManager {
59493
59546
  this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) });
59494
59547
  throw error;
59495
59548
  } finally {
59549
+ await this.historyFile.flush();
59496
59550
  await this.onTurnComplete();
59497
59551
  }
59498
59552
  }
@@ -61350,6 +61404,7 @@ function terminalErrorsFromEvent(event, provider) {
61350
61404
  var LAST_MESSAGE_PREVIEW_MAX = 200;
61351
61405
  var FINAL_MESSAGE_MAX = 6e3;
61352
61406
  var PROGRESS_INTERVAL_MS = 2e4;
61407
+ var STREAM_RECORD_TYPES = /* @__PURE__ */ new Set(["pi-message_update", "opencode-message.part.delta", "muse-item-delta", "cursor-assistant", "cursor-thinking"]);
61353
61408
  var PROGRESS_STEP_MAX = 120;
61354
61409
  var TURN_REQUEST_MAX = 8e3;
61355
61410
  var toolInputRequestSchema = z4.object({
@@ -61373,6 +61428,9 @@ function createForkInfo(source, trigger, startedAt, reason) {
61373
61428
  startedAt
61374
61429
  };
61375
61430
  }
61431
+ function withNotificationTargets(targets, added) {
61432
+ return [...targets, ...added.filter((target) => !targets.some((other) => JSON.stringify(other) === JSON.stringify(target)))];
61433
+ }
61376
61434
  function isForkPreparing(chat) {
61377
61435
  return chat.persisted.fork?.state === "preparing";
61378
61436
  }
@@ -61510,15 +61568,10 @@ var ChatService = class {
61510
61568
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
61511
61569
  type: CHAT_TURN_LOST_EVENT_TYPE,
61512
61570
  payload: state.running.id ? { messageId: state.running.id } : {}
61513
- }).written;
61571
+ }).written.catch((error) => console.error("[ChatService] Failed to record a turn lost to an engine restart:", { chatId: chat.id, error }));
61514
61572
  }
61515
61573
  const owed = state.lost && !state.lost.reported ? state.lost.errorNotificationTargets : [];
61516
- state.lost = {
61517
- errorNotificationTargets: [
61518
- ...owed,
61519
- ...state.running.errorNotificationTargets.filter((target) => !owed.some((other) => JSON.stringify(other) === JSON.stringify(target)))
61520
- ]
61521
- };
61574
+ state.lost = { errorNotificationTargets: withNotificationTargets(owed, state.running.errorNotificationTargets) };
61522
61575
  delete state.running;
61523
61576
  changed = true;
61524
61577
  }
@@ -61930,21 +61983,19 @@ ${decisions}` };
61930
61983
  }
61931
61984
  }
61932
61985
  async handleMessageAccepted(chatId, chat, request, acceptedMessage, result, typedMessage = request.message) {
61933
- const submittedAt = request.submittedAt ?? (/* @__PURE__ */ new Date()).toISOString();
61986
+ const now = Date.now();
61987
+ const submittedAt = request.submittedAt && Date.parse(request.submittedAt) < now ? request.submittedAt : new Date(now).toISOString();
61934
61988
  const { event: acceptedEvent, sender: recordedSender } = createTurnMetadata(
61935
61989
  acceptedMessage,
61936
61990
  result.messageId,
61937
- submittedAt
61991
+ Date.parse(submittedAt) < chat.history.latestRecordedAt ? new Date(chat.history.latestRecordedAt).toISOString() : submittedAt
61938
61992
  );
61939
61993
  const { state } = chat.commands;
61940
61994
  const existingTargets = chat.errorNotificationTargets.get(result.messageId) ?? [];
61941
- const notificationTargets = [
61942
- ...existingTargets,
61943
- ...[
61944
- ...request.errorNotificationTargets ?? [],
61945
- ...request.errorNotificationTarget ? [request.errorNotificationTarget] : []
61946
- ].filter((target) => !existingTargets.some((existing) => JSON.stringify(existing) === JSON.stringify(target)))
61947
- ];
61995
+ const notificationTargets = withNotificationTargets(existingTargets, [
61996
+ ...request.errorNotificationTargets ?? [],
61997
+ ...request.errorNotificationTarget ? [request.errorNotificationTarget] : []
61998
+ ]);
61948
61999
  const previousQueued = state.queue.find(({ id }) => id === result.messageId);
61949
62000
  const queued = {
61950
62001
  ...acceptedMessage,
@@ -62058,7 +62109,12 @@ ${decisions}` };
62058
62109
  }
62059
62110
  async stopTurn(chat, stoppedAt) {
62060
62111
  const stopped = new Set(chat.provider.isProcessing() ? chat.commands.state.queue.map(({ id }) => id) : []);
62061
- const result = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds), stoppedAt);
62112
+ const pending = chat.pendingMessageIds;
62113
+ chat.pendingMessageIds = [];
62114
+ const result = await chat.provider.interrupt((messageIds) => this.forgetPendingMessages(chat, messageIds), stoppedAt).catch((error) => {
62115
+ chat.pendingMessageIds = [.../* @__PURE__ */ new Set([...pending, ...chat.pendingMessageIds])];
62116
+ throw error;
62117
+ });
62062
62118
  const kept = new Set(chat.provider.getQueue().map(({ id }) => id));
62063
62119
  const { state } = chat.commands;
62064
62120
  const queue = state.queue.filter(({ id }) => kept.has(id) || !stopped.has(id));
@@ -62069,7 +62125,6 @@ ${decisions}` };
62069
62125
  this.endTrackedTurn(chat);
62070
62126
  chat.hasActiveTurn = false;
62071
62127
  chat.activeMessageId = null;
62072
- chat.pendingMessageIds = [];
62073
62128
  chat.acceptedUserEvents.clear();
62074
62129
  chat.turnAnswer = null;
62075
62130
  return result;
@@ -62141,7 +62196,7 @@ ${decisions}` };
62141
62196
  };
62142
62197
  }
62143
62198
  async withUnpublishedHistory(chat, run) {
62144
- const start = chat.history.end;
62199
+ const start = { at: chat.history.end, swapCount: chat.history.swapCount };
62145
62200
  chat.unpublishedHistoryStarts.push(start);
62146
62201
  try {
62147
62202
  return await run();
@@ -62780,7 +62835,7 @@ ${note}`;
62780
62835
  };
62781
62836
  }
62782
62837
  /** `history` is passed when the chat already has its log: a second object on the same file would write over the first. */
62783
- createRuntimeChat(persisted, commands = new ChatCommands(persisted.id), history = new CodexHistoryFile(this.historyPath(persisted))) {
62838
+ createRuntimeChat(persisted, commands = new ChatCommands(persisted.id), history = new CodexHistoryFile(this.historyPath(persisted), ({ type }) => STREAM_RECORD_TYPES.has(type))) {
62784
62839
  const saveSession = async (sessionId) => {
62785
62840
  persisted.providerSessionId = sessionId;
62786
62841
  delete persisted.pendingProviderFork;
@@ -62991,9 +63046,10 @@ ${note}`;
62991
63046
  chat.activeErrorNotificationTargets = chat.errorNotificationTargets.get(messageId) ?? [];
62992
63047
  chat.errorNotificationTargets.delete(messageId);
62993
63048
  const { state } = chat.commands;
63049
+ const starting = state.queue.find(({ id }) => id === messageId);
62994
63050
  state.queue = state.queue.filter(({ id }) => id !== messageId);
62995
63051
  state.running = { id: messageId, errorNotificationTargets: chat.activeErrorNotificationTargets };
62996
- this.settleLostTurn(chat, "told");
63052
+ if (starting && takesTurnNotes(starting)) this.settleLostTurn(chat, "told");
62997
63053
  const saved = chat.commands.save();
62998
63054
  this.touch(chat);
62999
63055
  chat.live = !!chat.provider.dispose;
@@ -63038,7 +63094,7 @@ ${note}`;
63038
63094
  }
63039
63095
  });
63040
63096
  }
63041
- /** `log` is the chat's log when the event is a record. It is taken once its message id is stamped, and announced once on disk. */
63097
+ /** `log` is the chat's log when the event is a record. It is taken once its message id is stamped. */
63042
63098
  handleTurnEvent(chatId, event, log) {
63043
63099
  const chat = this.getRuntimeChat(chatId);
63044
63100
  if (!chat) {
@@ -63063,6 +63119,28 @@ ${note}`;
63063
63119
  }).catch(() => {
63064
63120
  });
63065
63121
  }
63122
+ const { state } = chat.commands;
63123
+ const readMessageId = event.payload[USER_MESSAGE_ID_PAYLOAD_KEY];
63124
+ let eventToPublish = event;
63125
+ if (event.type === "event_msg" && event.payload.type === "user_message") {
63126
+ if (chat.activeMessageId && !event.payload[USER_MESSAGE_ID_PAYLOAD_KEY]) {
63127
+ event.payload[USER_MESSAGE_ID_PAYLOAD_KEY] = chat.activeMessageId;
63128
+ eventToPublish = {
63129
+ ...event,
63130
+ payload: {
63131
+ ...event.payload,
63132
+ [USER_MESSAGE_ID_PAYLOAD_KEY]: chat.activeMessageId
63133
+ }
63134
+ };
63135
+ }
63136
+ for (const [messageId, acceptedEvent] of chat.acceptedUserEvents) {
63137
+ if (isSameAcceptedUserEvent(event, acceptedEvent)) {
63138
+ chat.acceptedUserEvents.delete(messageId);
63139
+ break;
63140
+ }
63141
+ }
63142
+ }
63143
+ const taken = log?.record(event);
63066
63144
  this.agentTokenUsageTracker.noteAgentEvent(chatId, event);
63067
63145
  const parentToolUseId = typeof event.payload.parent_tool_use_id === "string" ? event.payload.parent_tool_use_id : null;
63068
63146
  const messages = parseDisplayMessages([event], chat.persisted.provider, { filter: false, parentToolUseId });
@@ -63090,34 +63168,14 @@ ${note}`;
63090
63168
  if (event.type === AGENT_QUOTA_EXHAUSTED_EVENT_TYPE) {
63091
63169
  chat.quotaExhaustion = agentQuotaExhaustedPayloadSchema.safeParse(event.payload).data ?? null;
63092
63170
  }
63093
- const { state } = chat.commands;
63094
- const readMessageId = event.payload[USER_MESSAGE_ID_PAYLOAD_KEY];
63095
- if (state.queue.some(({ id }) => id === readMessageId)) {
63171
+ const read = state.queue.find(({ id }) => id === readMessageId);
63172
+ if (read) {
63096
63173
  state.queue = state.queue.filter(({ id }) => id !== readMessageId);
63174
+ if (state.running) state.running = { ...state.running, errorNotificationTargets: withNotificationTargets(state.running.errorNotificationTargets, read.errorNotificationTargets ?? []) };
63097
63175
  chat.commands.save().catch((error) => {
63098
63176
  console.error("[ChatService] Failed to save a steered message as read:", { chatId, error });
63099
63177
  });
63100
63178
  }
63101
- let eventToPublish = event;
63102
- if (event.type === "event_msg" && event.payload.type === "user_message") {
63103
- if (chat.activeMessageId && !event.payload[USER_MESSAGE_ID_PAYLOAD_KEY]) {
63104
- event.payload[USER_MESSAGE_ID_PAYLOAD_KEY] = chat.activeMessageId;
63105
- eventToPublish = {
63106
- ...event,
63107
- payload: {
63108
- ...event.payload,
63109
- [USER_MESSAGE_ID_PAYLOAD_KEY]: chat.activeMessageId
63110
- }
63111
- };
63112
- }
63113
- for (const [messageId, acceptedEvent] of chat.acceptedUserEvents) {
63114
- if (isSameAcceptedUserEvent(event, acceptedEvent)) {
63115
- chat.acceptedUserEvents.delete(messageId);
63116
- break;
63117
- }
63118
- }
63119
- }
63120
- const written = log?.record(event).written;
63121
63179
  if (event.type !== CLAUDE_PARTIAL_MESSAGE_EVENT_TYPE) {
63122
63180
  this.touch(chat);
63123
63181
  this.observeCurrentBranches(chat).catch(() => {
@@ -63130,7 +63188,7 @@ ${note}`;
63130
63188
  ...chat.activeMessageId ? { messageId: chat.activeMessageId } : {},
63131
63189
  event: eventToPublish
63132
63190
  }
63133
- }, written).catch(() => {
63191
+ }, taken).catch(() => {
63134
63192
  });
63135
63193
  if (event.type === "replicas-tool-input-request" || event.type === "replicas-tool-input-resolved" || event.type === AUTH_RETRY_STATUS_EVENT_TYPE || event.type === AUTH_FALLBACK_EVENT_TYPE || event.type === CURSOR_CONNECTION_STATUS_EVENT_TYPE || event.type === CHAT_GOAL_EVENT_TYPE || event.type === "claude-result" || event.type === "claude-system" && (event.payload.subtype === "init" || event.payload.subtype === "session_state_changed" || event.payload.subtype === "background_tasks_changed" || coerceBackgroundTaskPayload(event.payload) !== null)) {
63136
63194
  this.publish({
@@ -63359,10 +63417,10 @@ ${note}`;
63359
63417
  return this.persistPromise;
63360
63418
  }
63361
63419
  /**
63362
- * A chat's events reach the stream in the order they were made, each one after every record taken before it is on disk,
63363
- * so no client hears of something a crash could take back. `written` is the event's own record: a dropped one is not announced.
63420
+ * A chat's events reach the stream in the order they were made, each one after every record taken before it is on disk.
63421
+ * The exception is the text of a message still being written, announced once written. `taken` is the event's own record: a dropped one is not announced.
63364
63422
  */
63365
- async publish(input, written) {
63423
+ async publish(input, taken) {
63366
63424
  const event = {
63367
63425
  id: randomUUID9(),
63368
63426
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -63374,18 +63432,23 @@ ${note}`;
63374
63432
  await eventService.publish(event);
63375
63433
  return;
63376
63434
  }
63377
- const end = chat.history.end;
63378
- const recorded = written ?? chat.history.flush();
63435
+ const { end, swapCount } = chat.history;
63436
+ const recorded = taken?.written ?? chat.history.flush();
63379
63437
  const dropped = await chat.outbox.run(async () => {
63380
63438
  if (await recorded.then(() => false, () => true)) return true;
63381
63439
  if (event.type === "chat.queue.changed") {
63382
63440
  await eventService.publish(event);
63383
63441
  return false;
63384
63442
  }
63385
- if (event.type === "chat.turn.delta") event.payload.historyEnd = Math.min(end, chat.history.historyEnd, ...chat.unpublishedHistoryStarts);
63443
+ if (event.type === "chat.turn.delta") {
63444
+ const { historyEnd } = chat.history;
63445
+ if ((!taken || taken.at <= historyEnd) && [swapCount, ...chat.unpublishedHistoryStarts.map((start) => start.swapCount)].every((count) => count === chat.history.swapCount)) {
63446
+ event.payload.historyEnd = Math.min(end, historyEnd, ...chat.unpublishedHistoryStarts.map((start) => start.at));
63447
+ }
63448
+ }
63386
63449
  chat.historyVersion = event.id;
63387
63450
  if (event.type === "chat.created" || event.type === "chat.updated") {
63388
- event.payload.chat.historyVersion = this.toSummary(chat).historyVersion;
63451
+ event.payload.chat.historyVersion = event.payload.chat.processing ? void 0 : this.toSummary(chat).historyVersion;
63389
63452
  }
63390
63453
  await eventService.publish(event);
63391
63454
  return false;