stratagate-dsh 0.3.43 → 0.3.45

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/plugin.js CHANGED
@@ -653,8 +653,8 @@ function effectiveGraphNodeView(node, edges, events) {
653
653
  if ((record3.status === "active" || record3.status === "disputed") && activeSources.length > 0) {
654
654
  return { current: { ...record3, sourceEventIds: activeSources } };
655
655
  }
656
- if (visibleSources.length > 0 && record3.status === "superseded") {
657
- return { historical: { ...record3, sourceEventIds: visibleSources } };
656
+ if (visibleSources.length > 0 && (record3.status === "superseded" || activeSources.length === 0)) {
657
+ return { historical: { ...record3, status: "superseded", sourceEventIds: visibleSources } };
658
658
  }
659
659
  return {};
660
660
  };
@@ -919,7 +919,8 @@ function applyGraphProjection(options) {
919
919
  warnings.push(`Dropped current edge "${relation}" because it has no active Event provenance.`);
920
920
  continue;
921
921
  }
922
- for (const old of options.edges.filter((edge2) => edge2.status === "active" && edge2.fromNodeId === from.id && edge2.relation === relation && edge2.toNodeId !== to.id)) {
922
+ const supersededIds = new Set(strings(proposal.supersedesEdgeIds, 64));
923
+ for (const old of options.edges.filter((edge2) => supersededIds.has(edge2.id) && edge2.status === "active" && edge2.fromNodeId === from.id && edge2.relation === relation && edge2.toNodeId !== to.id)) {
923
924
  old.status = "superseded";
924
925
  if (!old.validTo) old.validTo = validFrom;
925
926
  old.updatedAt = options.now;
@@ -7318,7 +7319,7 @@ var StrataGate = class _StrataGate {
7318
7319
  throw new TypeError("Turn userMessageId must not be empty");
7319
7320
  }
7320
7321
  const existingUserMessage = requestedUserMessageId ? this.openTail.find((message) => message.id === requestedUserMessageId && message.role === "user") : void 0;
7321
- if (existingUserMessage && (existingUserMessage.content !== input.user || existingUserMessage.threadId !== threadId)) {
7322
+ if (existingUserMessage && existingUserMessage.threadId !== threadId) {
7322
7323
  throw new Error(`Reserved user message ${requestedUserMessageId} does not match the appended turn`);
7323
7324
  }
7324
7325
  const userMessage = existingUserMessage ?? {
@@ -7348,8 +7349,13 @@ var StrataGate = class _StrataGate {
7348
7349
  if (index < 0) tail.push(assistant);
7349
7350
  else tail.splice(index + 1, 0, assistant);
7350
7351
  };
7352
+ const reservedContentChanged = existingUserMessage !== void 0 && existingUserMessage.content !== input.user;
7351
7353
  const appendInMemory = () => {
7352
7354
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7355
+ if (existingUserMessage) {
7356
+ existingUserMessage.content = input.user;
7357
+ if (input.userToolCalls !== void 0) existingUserMessage.toolCalls = structuredClone(input.userToolCalls);
7358
+ }
7353
7359
  this.currentTurn += 1;
7354
7360
  placeTurnMessages(this.openTail, false);
7355
7361
  if (receiptId) this.ingestionReceipts.set(receiptId, { id: receiptId, createdAt });
@@ -7357,7 +7363,7 @@ var StrataGate = class _StrataGate {
7357
7363
  };
7358
7364
  const appended = this.storage?.commitRecords ? await this.withMutationQueue(async () => {
7359
7365
  const reservedIsLast = !existingUserMessage || this.openTail.at(-1)?.id === existingUserMessage.id;
7360
- if (this.hasPendingRecordChanges() || !reservedIsLast) return this.applyMutation(appendInMemory);
7366
+ if (this.hasPendingRecordChanges() || !reservedIsLast || reservedContentChanged) return this.applyMutation(appendInMemory);
7361
7367
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7362
7368
  const receipt = receiptId ? { id: receiptId, createdAt } : void 0;
7363
7369
  const committed = await this.storage.commitRecords(this.namespace, this.revision, {
@@ -9462,17 +9468,18 @@ ${duplicate.summary}` : duplicate.summary;
9462
9468
  pendingBlockMessages(threadId) {
9463
9469
  const messages = this.threadOpenTail(threadId);
9464
9470
  let users = 0;
9465
- let end = 0;
9471
+ const selected = [];
9466
9472
  for (const [index, message] of messages.entries()) {
9467
9473
  if (message.role !== "user") continue;
9468
- if (!userTurnHasAssistant(messages, index)) break;
9474
+ if (!userTurnHasAssistant(messages, index)) continue;
9469
9475
  users += 1;
9470
- if (users !== this.blockTurnSize) continue;
9471
9476
  const nextUserOffset = messages.slice(index + 1).findIndex((candidate) => candidate.role === "user");
9472
- end = nextUserOffset === -1 ? messages.length : index + 1 + nextUserOffset;
9477
+ const end = nextUserOffset === -1 ? messages.length : index + 1 + nextUserOffset;
9478
+ selected.push(...messages.slice(index, end));
9479
+ if (users !== this.blockTurnSize) continue;
9473
9480
  break;
9474
9481
  }
9475
- return messages.slice(0, end);
9482
+ return selected;
9476
9483
  }
9477
9484
  async sealOpenTail(threadId) {
9478
9485
  const raw = this.pendingBlockMessages(threadId);
@@ -11405,6 +11412,7 @@ var GRAPH_EDGE = {
11405
11412
  fromRef: { type: "string", required: true },
11406
11413
  toRef: { type: "string", required: true },
11407
11414
  relation: { type: "string", required: true },
11415
+ supersedesEdgeIds: STRING_ARRAY,
11408
11416
  status: { type: "string", enum: ["active", "superseded", "disputed", "archived"] },
11409
11417
  validFrom: { type: "string" },
11410
11418
  validTo: { type: "string" },
@@ -11616,7 +11624,9 @@ function compactGraphProjectionContext(context) {
11616
11624
  status: node.status,
11617
11625
  sourceEventIds: node.sourceEventIds.slice(-16)
11618
11626
  })),
11627
+ // id is the handle for explicit supersedesEdgeIds. Timestamps and confidence stay off the prompt.
11619
11628
  existingEdges: context.existingEdges.slice(-60).map((edge) => ({
11629
+ id: edge.id,
11620
11630
  fromNodeId: edge.fromNodeId,
11621
11631
  toNodeId: edge.toNodeId,
11622
11632
  relation: edge.relation,
@@ -12032,7 +12042,7 @@ Use project scope for repository decisions, user scope for stable preferences/id
12032
12042
  const eventIds = new Set(context.events.map((event) => event.id));
12033
12043
  const raw = object(await this.callStructured(
12034
12044
  "graphProjector",
12035
- `Project the supplied Events into the current Knowledge Graph, then call ${STRUCTURED_TOOLS.graphProjector.name} exactly once. Events are the sole source of truth; never use legacy Element data. Return only nodes and edges touched by the supplied Events; never echo unchanged historical graph records. Return at most 24 nodes and 32 edges. Use stable entity nodes for people, projects, organizations, tools, and places. Use aliases to merge spelling/case/separator variants. Give every returned node 1-6 concise semantic role tags such as benchmark, evaluation, memory-plugin, parser, or development-tool; tags describe the node's specific role and never replace its person/project/organization/tool/place type. Reuse stable tag wording when possible. For every node name, alias, and tag, include metadataProvenance with the exact supplied Event ids that support that individual value; never use an unrelated active Event as a substitute. The shapes are different: metadataProvenance.name is an Event ID string array, e.g. ["evt_x"], supporting node.name; it is never an array of objects. Only metadataProvenance.aliases and metadataProvenance.tags are arrays of { value, sourceEventIds: ["evt_x"] } objects for each alias/tag. Example for node.name="StrataGate": metadataProvenance={"name":["evt_x"],"aliases":[{"value":"strata_gate","sourceEventIds":["evt_x"]}],"tags":[{"value":"memory-plugin","sourceEventIds":["evt_x"]}]}. Put attributes in node facts and every relationship in a directed edge using fromRef/toRef\u2014never encode a relationship as a fact string. Prefer concise canonical Chinese relation labels such as \u4F7F\u7528\u3001\u5C5E\u4E8E\u3001\u521B\u5EFA\u3001\u53C2\u4E0E\u3001\u8D21\u732E\u3001\u4F9D\u8D56\u3001\u4F4D\u4E8E\u3001\u76F8\u5173. Every node, fact, edge, and metadata provenance id must cite only supplied Event ids. Do not return text.`,
12045
+ `Project the supplied Events into the current Knowledge Graph, then call ${STRUCTURED_TOOLS.graphProjector.name} exactly once. Events are the sole source of truth; never use legacy Element data. Return only nodes and edges touched by the supplied Events; never echo unchanged historical graph records. Return at most 24 nodes and 32 edges. Use stable entity nodes for people, projects, organizations, tools, and places. Use aliases to merge spelling/case/separator variants. Give every returned node 1-6 concise semantic role tags such as benchmark, evaluation, memory-plugin, parser, or development-tool; tags describe the node's specific role and never replace its person/project/organization/tool/place type. Reuse stable tag wording when possible. For every node name, alias, and tag, include metadataProvenance with the exact supplied Event ids that support that individual value; never use an unrelated active Event as a substitute. The shapes are different: metadataProvenance.name is an Event ID string array, e.g. ["evt_x"], supporting node.name; it is never an array of objects. Only metadataProvenance.aliases and metadataProvenance.tags are arrays of { value, sourceEventIds: ["evt_x"] } objects for each alias/tag. Example for node.name="StrataGate": metadataProvenance={"name":["evt_x"],"aliases":[{"value":"strata_gate","sourceEventIds":["evt_x"]}],"tags":[{"value":"memory-plugin","sourceEventIds":["evt_x"]}]}. Put attributes in node facts and every relationship in a directed edge using fromRef/toRef\u2014never encode a relationship as a fact string. Prefer concise canonical Chinese relation labels such as \u4F7F\u7528\u3001\u5C5E\u4E8E\u3001\u521B\u5EFA\u3001\u53C2\u4E0E\u3001\u8D21\u732E\u3001\u4F9D\u8D56\u3001\u4F4D\u4E8E\u3001\u76F8\u5173. Multiple targets for one relation may all be current at once. Only when supplied Events explicitly document a replacement or correction should an edge include supersedesEdgeIds copied from existingEdges.id; never supersede a same-relation edge merely because its target differs. Every node, fact, edge, and metadata provenance id must cite only supplied Event ids. Do not return text.`,
12036
12046
  compactGraphProjectionContext(context),
12037
12047
  void 0,
12038
12048
  void 0,
@@ -12097,6 +12107,7 @@ Use project scope for repository decisions, user scope for stable preferences/id
12097
12107
  fromRef,
12098
12108
  toRef,
12099
12109
  relation,
12110
+ ...strings2(item.supersedesEdgeIds).length > 0 ? { supersedesEdgeIds: strings2(item.supersedesEdgeIds).slice(0, 32) } : {},
12100
12111
  ...typeof item.status === "string" ? { status: item.status } : {},
12101
12112
  ...text2(item.validFrom) ? { validFrom: text2(item.validFrom) } : {},
12102
12113
  ...text2(item.validTo) ? { validTo: text2(item.validTo) } : {},
@@ -14661,6 +14672,18 @@ var StrataGateRuntime = class _StrataGateRuntime {
14661
14672
  if (result.sealedBlock) this.scheduleBlockDerivation(session, memory);
14662
14673
  }
14663
14674
  } catch (error) {
14675
+ if (error instanceof StorageConflictError && memory) {
14676
+ try {
14677
+ await memory.reloadFromStorage();
14678
+ const remaining2 = turns.slice(completed);
14679
+ if (remaining2.length > 0) {
14680
+ this.pendingTurns.set(key, [...remaining2, ...this.pendingTurns.get(key) ?? []]);
14681
+ }
14682
+ return;
14683
+ } catch (reloadError) {
14684
+ error = reloadError;
14685
+ }
14686
+ }
14664
14687
  const remaining = turns.slice(completed);
14665
14688
  if (remaining.length > 0) {
14666
14689
  this.pendingTurns.set(key, [...remaining, ...this.pendingTurns.get(key) ?? []]);
@@ -15250,7 +15273,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15250
15273
  if (!sourceEventSeqs) return false;
15251
15274
  const selected = selectCompressedBlockSurface(session, sourceEventSeqs, block, context);
15252
15275
  if (!selected) return false;
15253
- appendBlockSurface(session, block.id, selected, sourceEventSeqs);
15276
+ appendBlockSurface(session, block, selected, sourceEventSeqs);
15254
15277
  this.surfaceFlushPending.add(session);
15255
15278
  levels.set(block.id, checkpointLevel(selected) ?? context.level);
15256
15279
  return true;
@@ -15303,7 +15326,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15303
15326
  );
15304
15327
  if (!text3) continue;
15305
15328
  if (node.text !== text3) {
15306
- appendBlockSurface(session, block.id, text3, [node.seq]);
15329
+ appendBlockSurface(session, block, text3, [node.seq]);
15307
15330
  this.surfaceFlushPending.add(session);
15308
15331
  changed = true;
15309
15332
  }
@@ -15325,7 +15348,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15325
15348
  const node = current.get(block.id);
15326
15349
  const endTurn = node ? null : dshTurnAtBlockEnd(session, block);
15327
15350
  const seqs = node ? [node.seq] : endTurn === null ? null : sealedSurfaceSeqs(session, endTurn, block);
15328
- if (!seqs?.length || !safeBlockSurfaceRange(session, block.id, seqs)) return {
15351
+ if (!seqs?.length || !safeBlockSurfaceRange(session, block, seqs)) return {
15329
15352
  status: "blocked",
15330
15353
  reason: "source-unavailable",
15331
15354
  message: "\u8FD9\u6BB5\u5386\u53F2\u5DF2\u88AB\u6574\u7406\uFF0C\u6216\u5939\u6709\u9700\u8981\u4FDD\u7559\u7684\u7CFB\u7EDF\u3001\u5DE5\u5177\u6216\u63D2\u4EF6\u5185\u5BB9\uFF0C\u65E0\u6CD5\u5728\u8FD9\u91CC\u5207\u6362\u5C42\u7EA7\u3002\u53EF\u4EE5\u8BA9\u52A9\u624B\u67E5\u627E\u8FD9\u6BB5\u5386\u53F2\u3002"
@@ -15411,13 +15434,15 @@ var StrataGateRuntime = class _StrataGateRuntime {
15411
15434
  }
15412
15435
  const { text: text3, seqs, relief } = plan;
15413
15436
  for (const replacement of relief) {
15414
- appendBlockSurface(session, replacement.id, replacement.text, [replacement.seq]);
15437
+ const replacementBlock = memory.listBlocks().find((candidate) => candidate.id === replacement.id);
15438
+ if (!replacementBlock) continue;
15439
+ appendBlockSurface(session, replacementBlock, replacement.text, [replacement.seq]);
15415
15440
  levels.set(replacement.id, replacement.level);
15416
15441
  this.surfaceFlushPending.add(session);
15417
15442
  }
15418
15443
  const node = currentBlockSurfaceMessages(session).get(block.id);
15419
15444
  if (node?.text !== text3) {
15420
- appendBlockSurface(session, block.id, text3, seqs);
15445
+ appendBlockSurface(session, block, text3, seqs);
15421
15446
  this.surfaceFlushPending.add(session);
15422
15447
  }
15423
15448
  levels.set(block.id, context.level);
@@ -17333,6 +17358,8 @@ function renderMessages(messages) {
17333
17358
  }).join("\n\n");
17334
17359
  }
17335
17360
  function dshTurnAtBlockEnd(session, block) {
17361
+ const sourceTurns = sourceTurnNumbersForBlock(block);
17362
+ if (sourceTurns.length > 0) return sourceTurns.at(-1) ?? null;
17336
17363
  const blockEnd = Date.parse(block.createdAt);
17337
17364
  const events = session.snapshotEvents();
17338
17365
  for (let index = events.length - 1; index >= 0; index -= 1) {
@@ -17353,6 +17380,7 @@ function recoverableSealedSurfaceSources(session, blocks) {
17353
17380
  }
17354
17381
  const ends = /* @__PURE__ */ new Map();
17355
17382
  const visibleEnds = /* @__PURE__ */ new Set();
17383
+ const visibleTurns = /* @__PURE__ */ new Set();
17356
17384
  const compactedBlocks = /* @__PURE__ */ new Set();
17357
17385
  let open2;
17358
17386
  for (const event of session.snapshotEvents()) {
@@ -17368,6 +17396,7 @@ function recoverableSealedSurfaceSources(session, blocks) {
17368
17396
  if (open2?.turn === event.data.turn) {
17369
17397
  ends.set(event.time, event.data.turn);
17370
17398
  if (open2.visible) visibleEnds.add(event.time);
17399
+ if (open2.visible) visibleTurns.add(event.data.turn);
17371
17400
  }
17372
17401
  open2 = void 0;
17373
17402
  } else if (open2 && visible2.has(event.seq)) open2.visible = true;
@@ -17377,10 +17406,11 @@ function recoverableSealedSurfaceSources(session, blocks) {
17377
17406
  result.retired.add(block.id);
17378
17407
  continue;
17379
17408
  }
17409
+ const sourceTurns = sourceTurnNumbersForBlock(block);
17380
17410
  const endTime = Date.parse(block.createdAt);
17381
- const endTurn = ends.get(endTime);
17411
+ const endTurn = sourceTurns.at(-1) ?? ends.get(endTime);
17382
17412
  if (endTurn === void 0) continue;
17383
- if (!visibleEnds.has(endTime)) {
17413
+ if (sourceTurns.length > 0 ? !visibleTurns.has(endTurn) : !visibleEnds.has(endTime)) {
17384
17414
  result.retired.add(block.id);
17385
17415
  continue;
17386
17416
  }
@@ -17395,6 +17425,8 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17395
17425
  const completed = [];
17396
17426
  let open2;
17397
17427
  const events = session.snapshotEvents();
17428
+ const sourceTurnNumbers = sourceTurnNumbersForBlock(block);
17429
+ const sourceTurnSet = new Set(sourceTurnNumbers);
17398
17430
  for (const event of events) {
17399
17431
  if (event.type === "turn/start") {
17400
17432
  open2 = { turn: event.data.turn, start: event.seq };
@@ -17403,7 +17435,7 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17403
17435
  if (event.type !== "turn/end" || !open2 || event.data.turn !== open2.turn) continue;
17404
17436
  const turnEvents = events.slice(open2.start + 1, event.seq);
17405
17437
  const hasHumanMessage = turnEvents.some((candidate) => candidate.type === "user/message" && candidate.data.source.kind === "user");
17406
- if (hasHumanMessage && event.data.turn <= endTurn) {
17438
+ if (hasHumanMessage && (sourceTurnSet.size > 0 ? sourceTurnSet.has(event.data.turn) : event.data.turn <= endTurn)) {
17407
17439
  completed.push({
17408
17440
  turn: event.data.turn,
17409
17441
  endTime: event.time,
@@ -17412,17 +17444,17 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17412
17444
  nodes: currentSurface.filter((seq) => {
17413
17445
  const current = session.eventAt(seq);
17414
17446
  if (!replaceableBlockEvent(current, block.id)) return false;
17447
+ if ((current?.type === "assistant/message" || current?.type === "tool/result") && !surfaceEventBelongsToTurn(session, current, open2.turn)) return false;
17415
17448
  if (seq > open2.start && seq < event.seq) return true;
17416
- return current?.type === "tool/result" && current.surfaceOp !== "append" && current.sourceEventSeqs?.some((source) => source > open2.start && source < event.seq);
17449
+ return (current?.type === "tool/result" || current?.type === "assistant/message") && surfaceEventBelongsToTurn(session, current, open2.turn) && current.surfaceOp !== "append" && current.sourceEventSeqs?.some((source) => source > open2.start && source < event.seq);
17417
17450
  })
17418
17451
  });
17419
17452
  }
17420
17453
  open2 = void 0;
17421
17454
  }
17422
- const sourceTimes = block.l5Raw.filter((message) => message.role === "user").map((message) => Date.parse(message.createdAt));
17423
17455
  const turnCount = block.endTurn - block.startTurn + 1;
17424
- const selected = completed.slice(-turnCount);
17425
- if (selected.length !== turnCount || selected.at(-1)?.turn !== endTurn || sourceTimes.length !== turnCount || selected.some((turn, index) => turn.endTime !== sourceTimes[index])) return null;
17456
+ const selected = sourceTurnNumbers.length === turnCount ? sourceTurnNumbers.flatMap((turn) => completed.find((candidate) => candidate.turn === turn) ?? []) : completed.slice(-turnCount);
17457
+ if (selected.length !== turnCount || selected.at(-1)?.turn !== (sourceTurnNumbers.at(-1) ?? endTurn) || sourceTurnNumbers.length !== turnCount && selected.some((turn, index) => turn.endTime !== Date.parse(block.l5Raw.filter((message) => message.role === "user")[index].createdAt))) return null;
17426
17458
  const firstTurn = selected[0];
17427
17459
  const lastTurn = selected.at(-1);
17428
17460
  if (events.some((event) => {
@@ -17437,29 +17469,101 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17437
17469
  const endIndex = currentSurface.indexOf(end);
17438
17470
  if (startIndex < 0 || endIndex < startIndex) return null;
17439
17471
  const range = currentSurface.slice(startIndex, endIndex + 1);
17440
- return safeBlockSurfaceRange(session, block.id, range) ? range : null;
17472
+ return safeBlockSurfaceRange(session, block, range) ? range : null;
17441
17473
  }
17442
17474
  function replaceableBlockEvent(event, blockId) {
17443
17475
  if (event?.type === "assistant/message" || event?.type === "tool/result") return true;
17444
17476
  return event?.type === "user/message" && (event.data.source.kind === "user" || blockSurfaceMessage(event)?.id === blockId);
17445
17477
  }
17446
- function safeBlockSurfaceRange(session, blockId, seqs) {
17478
+ function turnAtSurfaceSeq(session, seq) {
17479
+ let turn;
17480
+ for (const event of session.snapshotEvents()) {
17481
+ if (event.seq >= seq) break;
17482
+ if (event.type === "turn/start") turn = event.data.turn;
17483
+ else if (event.type === "turn/end") turn = void 0;
17484
+ }
17485
+ return turn;
17486
+ }
17487
+ function sourceTurnsForBlock(session, block) {
17488
+ const stableTurns = sourceTurnNumbersForBlock(block);
17489
+ if (stableTurns.length > 0) return new Set(stableTurns);
17490
+ const sourceTimes = new Set(block.l5Raw.filter((message) => message.role === "user").map((message) => Date.parse(message.createdAt)));
17491
+ return new Set(session.snapshotEvents().filter((event) => event.type === "turn/end" && sourceTimes.has(event.time)).map((event) => event.data.turn));
17492
+ }
17493
+ function sourceTurnNumbersForBlock(block) {
17494
+ const turns = [];
17495
+ for (const message of block.l5Raw) {
17496
+ if (message.role !== "user") continue;
17497
+ const match = message.id.match(/:turn:(\d+):user$/u);
17498
+ if (!match) continue;
17499
+ const turn = Number(match[1]);
17500
+ if (Number.isSafeInteger(turn) && !turns.includes(turn)) turns.push(turn);
17501
+ }
17502
+ return turns;
17503
+ }
17504
+ function surfaceEventTurns(session, event) {
17505
+ if (event.surfaceOp !== "append" && event.sourceEventSeqs?.length) {
17506
+ const sourceTurns = event.sourceEventSeqs.flatMap((source) => {
17507
+ const original = session.eventAt(source);
17508
+ return original?.type === "assistant/message" || original?.type === "tool/result" ? [original.data.turn] : [];
17509
+ });
17510
+ if (sourceTurns.length > 0) return new Set(sourceTurns);
17511
+ }
17512
+ return /* @__PURE__ */ new Set([event.data.turn]);
17513
+ }
17514
+ function surfaceEventBelongsToTurn(session, event, turn) {
17515
+ const turns = surfaceEventTurns(session, event);
17516
+ return turns.size === 1 && turns.has(turn);
17517
+ }
17518
+ function safeBlockSurfaceRange(session, block, seqs) {
17447
17519
  if (seqs.length === 0) return false;
17448
17520
  const start = session.surface.nodes.indexOf(seqs[0]);
17449
- return start >= 0 && seqs.every((seq, index) => session.surface.nodes[start + index] === seq && replaceableBlockEvent(session.eventAt(seq), blockId));
17521
+ if (start < 0) return false;
17522
+ const sourceTurns = sourceTurnsForBlock(session, block);
17523
+ return seqs.every((seq, index) => {
17524
+ if (session.surface.nodes[start + index] !== seq) return false;
17525
+ const event = session.eventAt(seq);
17526
+ if (!replaceableBlockEvent(event, block.id)) return false;
17527
+ const checkpoint = blockSurfaceMessage(event);
17528
+ if (checkpoint) return checkpoint.id === block.id;
17529
+ if (event?.type === "assistant/message" || event?.type === "tool/result") {
17530
+ const eventTurns = surfaceEventTurns(session, event);
17531
+ return eventTurns.size > 0 && [...eventTurns].every((turn) => sourceTurns.has(turn));
17532
+ }
17533
+ if (event?.type === "user/message" && event.data.source.kind === "user") {
17534
+ return sourceTurns.has(turnAtSurfaceSeq(session, seq) ?? -1);
17535
+ }
17536
+ return false;
17537
+ });
17450
17538
  }
17451
- function appendBlockSurface(session, blockId, text3, seqs) {
17452
- if (!safeBlockSurfaceRange(session, blockId, seqs)) {
17539
+ function appendBlockSurface(session, block, text3, seqs) {
17540
+ if (!safeBlockSurfaceRange(session, block, seqs)) {
17453
17541
  throw Object.assign(new Error("StrataGate surface replacement no longer owns its complete source range"), { retryable: false });
17454
17542
  }
17455
17543
  session.append("user/message", createUserMessage2({
17456
- content: [{ type: "text", text: text3 }],
17544
+ content: [{ type: "text", text: text3 }, ...sourceAttachmentBlocks(session, seqs)],
17457
17545
  source: dshMessageSource()
17458
17546
  }), {
17459
17547
  surfaceOp: dshReplaceSurfaceOp(seqs[0], seqs.at(-1)),
17460
17548
  sourceEventSeqs: seqs
17461
17549
  });
17462
17550
  }
17551
+ function sourceAttachmentBlocks(session, seqs) {
17552
+ const attachments = [];
17553
+ const seen = /* @__PURE__ */ new Set();
17554
+ for (const seq of seqs) {
17555
+ const event = session.eventAt(seq);
17556
+ if (event?.type !== "user/message") continue;
17557
+ for (const block of event.data.content) {
17558
+ if (block.type !== "image" && block.type !== "file") continue;
17559
+ const key = `${block.type}:${String(block.attachment.attachmentId)}`;
17560
+ if (seen.has(key)) continue;
17561
+ seen.add(key);
17562
+ attachments.push(structuredClone(block));
17563
+ }
17564
+ }
17565
+ return attachments;
17566
+ }
17463
17567
  function surfaceMaintenanceInput(state) {
17464
17568
  return `${state.memory.storageRevision}:${surfaceCapacityKey(state.session)}:${state.session.surface?.nodes.join(",") ?? ""}`;
17465
17569
  }