stratagate-dsh 0.3.42 → 0.3.44

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
@@ -431,6 +431,28 @@ function formatRawTranscript(messages) {
431
431
  ...(message.toolCalls ?? []).map(renderRawToolTrace)
432
432
  ]).join("\n\n");
433
433
  }
434
+ var ATTACHMENT_REFERENCE_PREFIX = "[StrataGate attachment] ";
435
+ function attachmentReferenceLines(value) {
436
+ return value.split(/\r?\n/u).filter((line) => line.startsWith(ATTACHMENT_REFERENCE_PREFIX));
437
+ }
438
+ function attachmentReferences(messages) {
439
+ const lines = [];
440
+ for (const message of messages) {
441
+ lines.push(...attachmentReferenceLines(message.content));
442
+ for (const trace of message.toolCalls ?? []) {
443
+ if (typeof trace.result === "string") lines.push(...attachmentReferenceLines(trace.result));
444
+ }
445
+ }
446
+ return [...new Set(lines)];
447
+ }
448
+ function preserveAttachmentReferences(content, messages) {
449
+ const missing2 = attachmentReferences(messages).filter((reference) => !content.includes(reference));
450
+ if (missing2.length === 0) return content;
451
+ return `${content}
452
+
453
+ Attachments retained in source:
454
+ ${missing2.join("\n")}`;
455
+ }
434
456
  function estimateTokens(value) {
435
457
  let tokens = 0;
436
458
  let asciiRun = 0;
@@ -897,7 +919,8 @@ function applyGraphProjection(options) {
897
919
  warnings.push(`Dropped current edge "${relation}" because it has no active Event provenance.`);
898
920
  continue;
899
921
  }
900
- 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)) {
901
924
  old.status = "superseded";
902
925
  if (!old.validTo) old.validTo = validFrom;
903
926
  old.updatedAt = options.now;
@@ -6545,18 +6568,28 @@ function renderBlock(block, level) {
6545
6568
  if (block.processingStatus !== "ready" || !block.l0Title || !block.l0Tags || !block.l1Summary || !block.l2Keypoints) {
6546
6569
  throw new Error(`Block ${block.id} is not ready for rendering`);
6547
6570
  }
6548
- if (level === 0) return `${block.l0Title}
6571
+ let body;
6572
+ if (level === 0) body = `${block.l0Title}
6549
6573
  Tags: ${block.l0Tags.join(", ") || "none"}`;
6550
- if (level === 1) return block.l1Summary;
6551
- if (level === 2) return block.l2Keypoints.map((point) => `- ${point}`).join("\n") || block.l1Summary;
6552
- const deterministic = deterministicBlockLayers(block.l5Raw);
6553
- if (level === 3) return deterministic.l3Condensed;
6554
- if (level === 4) return deterministic.l4Readable;
6555
- return formatRawTranscript(block.l5Raw);
6574
+ else if (level === 1) body = block.l1Summary;
6575
+ else if (level === 2) body = block.l2Keypoints.map((point) => `- ${point}`).join("\n") || block.l1Summary;
6576
+ else {
6577
+ const deterministic = deterministicBlockLayers(block.l5Raw);
6578
+ body = level === 3 ? deterministic.l3Condensed : level === 4 ? deterministic.l4Readable : formatRawTranscript(block.l5Raw);
6579
+ }
6580
+ return preserveAttachmentReferences(body, block.l5Raw);
6556
6581
  }
6557
6582
  function sameIds(left, right) {
6558
6583
  return left.length === right.length && left.every((id, index) => id === right[index]);
6559
6584
  }
6585
+ function userTurnHasAssistant(messages, userIndex) {
6586
+ for (let index = userIndex + 1; index < messages.length; index += 1) {
6587
+ const role = messages[index].role;
6588
+ if (role === "user") return false;
6589
+ if (role === "assistant") return true;
6590
+ }
6591
+ return false;
6592
+ }
6560
6593
  function errorMessage(error) {
6561
6594
  if (error && typeof error === "object" && "fullMessage" in error) {
6562
6595
  const fullMessage = error.fullMessage;
@@ -7281,8 +7314,16 @@ var StrataGate = class _StrataGate {
7281
7314
  throw new TypeError("Turn threadId must not be empty");
7282
7315
  }
7283
7316
  const createdAt = toUtc8Iso(input.createdAt ?? this.now());
7284
- const userMessage = {
7285
- id: this.idFactory("msg"),
7317
+ const requestedUserMessageId = input.userMessageId?.trim();
7318
+ if (input.userMessageId !== void 0 && !requestedUserMessageId) {
7319
+ throw new TypeError("Turn userMessageId must not be empty");
7320
+ }
7321
+ const existingUserMessage = requestedUserMessageId ? this.openTail.find((message) => message.id === requestedUserMessageId && message.role === "user") : void 0;
7322
+ if (existingUserMessage && (existingUserMessage.content !== input.user || existingUserMessage.threadId !== threadId)) {
7323
+ throw new Error(`Reserved user message ${requestedUserMessageId} does not match the appended turn`);
7324
+ }
7325
+ const userMessage = existingUserMessage ?? {
7326
+ id: requestedUserMessageId ?? this.idFactory("msg"),
7286
7327
  role: "user",
7287
7328
  content: input.user,
7288
7329
  createdAt,
@@ -7297,30 +7338,42 @@ var StrataGate = class _StrataGate {
7297
7338
  ...threadId ? { threadId } : {},
7298
7339
  ...input.assistantToolCalls ? { toolCalls: structuredClone(input.assistantToolCalls) } : {}
7299
7340
  };
7341
+ const messagesToAppend = existingUserMessage ? [assistantMessage] : [userMessage, assistantMessage];
7342
+ const placeTurnMessages = (tail, capture) => {
7343
+ const assistant = capture ? captureRawMessage(assistantMessage) : assistantMessage;
7344
+ if (!existingUserMessage) {
7345
+ tail.push(capture ? captureRawMessage(userMessage) : userMessage, assistant);
7346
+ return;
7347
+ }
7348
+ const index = tail.findIndex((message) => message.id === existingUserMessage.id);
7349
+ if (index < 0) tail.push(assistant);
7350
+ else tail.splice(index + 1, 0, assistant);
7351
+ };
7300
7352
  const appendInMemory = () => {
7301
7353
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7302
7354
  this.currentTurn += 1;
7303
- this.openTail.push(userMessage, assistantMessage);
7355
+ placeTurnMessages(this.openTail, false);
7304
7356
  if (receiptId) this.ingestionReceipts.set(receiptId, { id: receiptId, createdAt });
7305
7357
  return true;
7306
7358
  };
7307
7359
  const appended = this.storage?.commitRecords ? await this.withMutationQueue(async () => {
7308
- if (this.hasPendingRecordChanges()) return this.applyMutation(appendInMemory);
7360
+ const reservedIsLast = !existingUserMessage || this.openTail.at(-1)?.id === existingUserMessage.id;
7361
+ if (this.hasPendingRecordChanges() || !reservedIsLast) return this.applyMutation(appendInMemory);
7309
7362
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7310
7363
  const receipt = receiptId ? { id: receiptId, createdAt } : void 0;
7311
7364
  const committed = await this.storage.commitRecords(this.namespace, this.revision, {
7312
7365
  kind: "append",
7313
- messages: [userMessage, assistantMessage],
7366
+ messages: messagesToAppend,
7314
7367
  updatedAt: createdAt,
7315
7368
  ...receipt ? { receipt } : {}
7316
7369
  });
7317
7370
  if (committed.changed) {
7318
7371
  this.currentTurn += 1;
7319
- this.openTail.push(userMessage, assistantMessage);
7372
+ placeTurnMessages(this.openTail, false);
7320
7373
  if (receipt) this.ingestionReceipts.set(receipt.id, receipt);
7321
7374
  const baseline = this.committedMetadata;
7322
7375
  baseline.currentTurn = this.currentTurn;
7323
- baseline.openTail.push(captureRawMessage(userMessage), captureRawMessage(assistantMessage));
7376
+ placeTurnMessages(baseline.openTail, true);
7324
7377
  if (receipt) baseline.ingestionReceipts.push(structuredClone(receipt));
7325
7378
  }
7326
7379
  this.revision = committed.revision;
@@ -7330,7 +7383,7 @@ var StrataGate = class _StrataGate {
7330
7383
  if (options.deferProcessing === true) {
7331
7384
  return { sealedBlock: null, readyBlocks: [], extractedEvents: [], projectedElements: [] };
7332
7385
  }
7333
- if (this.threadOpenTail(threadId).filter((message) => message.role === "user").length < this.blockTurnSize) {
7386
+ if (this.completeOpenUserCount(threadId) < this.blockTurnSize) {
7334
7387
  const projectedElements2 = await this.projectEligibleElements() ?? [];
7335
7388
  await this.projectEligibleGraph();
7336
7389
  return { sealedBlock: null, readyBlocks: [], extractedEvents: [], projectedElements: projectedElements2 };
@@ -7346,6 +7399,33 @@ var StrataGate = class _StrataGate {
7346
7399
  await this.projectEligibleGraph();
7347
7400
  return { sealedBlock, readyBlocks, extractedEvents, projectedElements };
7348
7401
  }
7402
+ /**
7403
+ * Persist the current user message before a tool call needs to cite it.
7404
+ * The message stays in the open tail but does not count as a sealable turn
7405
+ * until appendTurn stores its assistant reply immediately after it.
7406
+ * That call reuses this message by userMessageId and counts the turn once.
7407
+ */
7408
+ async reserveUserMessage(input) {
7409
+ const id = input.id.trim();
7410
+ if (!id) throw new TypeError("Reserved user message id must not be empty");
7411
+ const content = input.content;
7412
+ if (!content.trim()) throw new TypeError("Reserved user message content must not be empty");
7413
+ const threadId = input.threadId?.trim();
7414
+ if (input.threadId !== void 0 && !threadId) throw new TypeError("Reserved user message threadId must not be empty");
7415
+ const createdAt = toUtc8Iso(input.createdAt ?? this.now());
7416
+ return this.commitMutation(() => {
7417
+ const existing = this.openTail.find((message2) => message2.id === id);
7418
+ if (existing) {
7419
+ if (existing.role !== "user" || existing.content !== content || existing.threadId !== threadId) {
7420
+ throw new Error(`Reserved user message ${id} already exists with different content`);
7421
+ }
7422
+ return existing;
7423
+ }
7424
+ const message = { id, role: "user", content, createdAt, ...threadId ? { threadId } : {} };
7425
+ this.openTail.push(message);
7426
+ return message;
7427
+ });
7428
+ }
7349
7429
  async resumePendingWork(options = {}) {
7350
7430
  const sealedBlocks = [];
7351
7431
  const readyBlocks = [];
@@ -8863,7 +8943,15 @@ ${duplicate.summary}` : duplicate.summary;
8863
8943
  resolveAgentEventProvenance(candidate, threadId, now) {
8864
8944
  const real = threadId ? this.listOpenTail(threadId).filter((message) => message.role === "user" || message.role === "assistant") : [];
8865
8945
  if (real.length > 0) {
8866
- return { messageIds: real.slice(-AGENT_EVENT_PROVENANCE_LIMIT).map(({ id }) => id), synthetic: false };
8946
+ let latestUser = -1;
8947
+ for (let index = real.length - 1; index >= 0; index -= 1) {
8948
+ if (real[index].role === "user") {
8949
+ latestUser = index;
8950
+ break;
8951
+ }
8952
+ }
8953
+ const currentTurn = latestUser >= 0 ? real.slice(latestUser) : real;
8954
+ return { messageIds: currentTurn.slice(-AGENT_EVENT_PROVENANCE_LIMIT).map(({ id }) => id), synthetic: false };
8867
8955
  }
8868
8956
  const sealed = threadId ? this.blocks.filter((block) => block.threadId === threadId && block.l5Raw.length > 0) : [];
8869
8957
  const last = sealed.at(-1);
@@ -9339,6 +9427,15 @@ ${duplicate.summary}` : duplicate.summary;
9339
9427
  threadOpenTail(threadId) {
9340
9428
  return this.openTail.filter((message) => message.threadId === threadId);
9341
9429
  }
9430
+ /** User messages that already have their assistant reply in this thread. */
9431
+ completeOpenUserCount(threadId) {
9432
+ const messages = this.threadOpenTail(threadId);
9433
+ let count = 0;
9434
+ for (let index = 0; index < messages.length; index += 1) {
9435
+ if (messages[index].role === "user" && userTurnHasAssistant(messages, index)) count += 1;
9436
+ }
9437
+ return count;
9438
+ }
9342
9439
  threadBlocks(threadId) {
9343
9440
  return this.blocks.filter((block) => block.threadId === threadId);
9344
9441
  }
@@ -9351,16 +9448,11 @@ ${duplicate.summary}` : duplicate.summary;
9351
9448
  return this.nextSealableThread() !== null;
9352
9449
  }
9353
9450
  nextSealableThread() {
9354
- const counts = [];
9451
+ const seen = /* @__PURE__ */ new Set();
9355
9452
  for (const message of this.openTail) {
9356
- if (message.role !== "user") continue;
9357
- let entry = counts.find((candidate) => candidate.threadId === message.threadId);
9358
- if (!entry) {
9359
- entry = { threadId: message.threadId, users: 0 };
9360
- counts.push(entry);
9361
- }
9362
- entry.users += 1;
9363
- if (entry.users >= this.blockTurnSize) return { threadId: entry.threadId };
9453
+ if (seen.has(message.threadId)) continue;
9454
+ seen.add(message.threadId);
9455
+ if (this.completeOpenUserCount(message.threadId) >= this.blockTurnSize) return { threadId: message.threadId };
9364
9456
  }
9365
9457
  return null;
9366
9458
  }
@@ -9371,9 +9463,10 @@ ${duplicate.summary}` : duplicate.summary;
9371
9463
  pendingBlockMessages(threadId) {
9372
9464
  const messages = this.threadOpenTail(threadId);
9373
9465
  let users = 0;
9374
- let end = messages.length;
9466
+ let end = 0;
9375
9467
  for (const [index, message] of messages.entries()) {
9376
9468
  if (message.role !== "user") continue;
9469
+ if (!userTurnHasAssistant(messages, index)) break;
9377
9470
  users += 1;
9378
9471
  if (users !== this.blockTurnSize) continue;
9379
9472
  const nextUserOffset = messages.slice(index + 1).findIndex((candidate) => candidate.role === "user");
@@ -11313,6 +11406,7 @@ var GRAPH_EDGE = {
11313
11406
  fromRef: { type: "string", required: true },
11314
11407
  toRef: { type: "string", required: true },
11315
11408
  relation: { type: "string", required: true },
11409
+ supersedesEdgeIds: STRING_ARRAY,
11316
11410
  status: { type: "string", enum: ["active", "superseded", "disputed", "archived"] },
11317
11411
  validFrom: { type: "string" },
11318
11412
  validTo: { type: "string" },
@@ -11524,7 +11618,9 @@ function compactGraphProjectionContext(context) {
11524
11618
  status: node.status,
11525
11619
  sourceEventIds: node.sourceEventIds.slice(-16)
11526
11620
  })),
11621
+ // id is the handle for explicit supersedesEdgeIds. Timestamps and confidence stay off the prompt.
11527
11622
  existingEdges: context.existingEdges.slice(-60).map((edge) => ({
11623
+ id: edge.id,
11528
11624
  fromNodeId: edge.fromNodeId,
11529
11625
  toNodeId: edge.toNodeId,
11530
11626
  relation: edge.relation,
@@ -11940,7 +12036,7 @@ Use project scope for repository decisions, user scope for stable preferences/id
11940
12036
  const eventIds = new Set(context.events.map((event) => event.id));
11941
12037
  const raw = object(await this.callStructured(
11942
12038
  "graphProjector",
11943
- `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.`,
12039
+ `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.`,
11944
12040
  compactGraphProjectionContext(context),
11945
12041
  void 0,
11946
12042
  void 0,
@@ -12005,6 +12101,7 @@ Use project scope for repository decisions, user scope for stable preferences/id
12005
12101
  fromRef,
12006
12102
  toRef,
12007
12103
  relation,
12104
+ ...strings2(item.supersedesEdgeIds).length > 0 ? { supersedesEdgeIds: strings2(item.supersedesEdgeIds).slice(0, 32) } : {},
12008
12105
  ...typeof item.status === "string" ? { status: item.status } : {},
12009
12106
  ...text2(item.validFrom) ? { validFrom: text2(item.validFrom) } : {},
12010
12107
  ...text2(item.validTo) ? { validTo: text2(item.validTo) } : {},
@@ -13139,6 +13236,24 @@ async function listEndpointModels(url, key) {
13139
13236
  }
13140
13237
 
13141
13238
  // src/fold.ts
13239
+ function renderAttachment(block) {
13240
+ const payload = block.type === "image" ? {
13241
+ type: "image",
13242
+ ...block.attachment.name ? { name: block.attachment.name } : {},
13243
+ attachmentId: String(block.attachment.attachmentId),
13244
+ mediaType: block.attachment.mediaType,
13245
+ bytes: block.attachment.bytes,
13246
+ width: block.attachment.width,
13247
+ height: block.attachment.height,
13248
+ ...block.attachment.originalDimensions ? { originalDimensions: block.attachment.originalDimensions } : {}
13249
+ } : {
13250
+ type: "file",
13251
+ name: block.attachment.name,
13252
+ attachmentId: String(block.attachment.attachmentId),
13253
+ bytes: block.attachment.bytes
13254
+ };
13255
+ return `[StrataGate attachment] ${JSON.stringify(payload)}`;
13256
+ }
13142
13257
  function renderBlocks(blocks) {
13143
13258
  const output = [];
13144
13259
  for (const block of blocks) {
@@ -13149,7 +13264,8 @@ function renderBlocks(blocks) {
13149
13264
  case "reasoning":
13150
13265
  break;
13151
13266
  case "image":
13152
- output.push("[image]");
13267
+ case "file":
13268
+ output.push(renderAttachment(block));
13153
13269
  break;
13154
13270
  case "tool-call":
13155
13271
  break;
@@ -13232,6 +13348,7 @@ var TurnFolder = class {
13232
13348
  user: pending.user.join("\n\n"),
13233
13349
  assistant: pending.assistant.join("\n\n") || reasonLabel(event.data.reason),
13234
13350
  threadId: sessionId,
13351
+ userMessageId: pending.userMessageId,
13235
13352
  assistantToolCalls: [...pending.tools.values()],
13236
13353
  createdAt: toUtc8Iso(event.time),
13237
13354
  receiptId: `dsh:${sessionId}:turn:${event.data.turn}`,
@@ -13250,7 +13367,14 @@ var TurnFolder = class {
13250
13367
  }
13251
13368
  let pending = byTurn.get(turn);
13252
13369
  if (!pending) {
13253
- pending = { turn, user: [], assistant: [], tools: /* @__PURE__ */ new Map(), ignoredTools: /* @__PURE__ */ new Set() };
13370
+ pending = {
13371
+ turn,
13372
+ userMessageId: `dsh:${sessionId}:turn:${turn}:user`,
13373
+ user: [],
13374
+ assistant: [],
13375
+ tools: /* @__PURE__ */ new Map(),
13376
+ ignoredTools: /* @__PURE__ */ new Set()
13377
+ };
13254
13378
  byTurn.set(turn, pending);
13255
13379
  }
13256
13380
  return pending;
@@ -14542,6 +14666,18 @@ var StrataGateRuntime = class _StrataGateRuntime {
14542
14666
  if (result.sealedBlock) this.scheduleBlockDerivation(session, memory);
14543
14667
  }
14544
14668
  } catch (error) {
14669
+ if (error instanceof StorageConflictError && memory) {
14670
+ try {
14671
+ await memory.reloadFromStorage();
14672
+ const remaining2 = turns.slice(completed);
14673
+ if (remaining2.length > 0) {
14674
+ this.pendingTurns.set(key, [...remaining2, ...this.pendingTurns.get(key) ?? []]);
14675
+ }
14676
+ return;
14677
+ } catch (reloadError) {
14678
+ error = reloadError;
14679
+ }
14680
+ }
14545
14681
  const remaining = turns.slice(completed);
14546
14682
  if (remaining.length > 0) {
14547
14683
  this.pendingTurns.set(key, [...remaining, ...this.pendingTurns.get(key) ?? []]);
@@ -15131,7 +15267,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15131
15267
  if (!sourceEventSeqs) return false;
15132
15268
  const selected = selectCompressedBlockSurface(session, sourceEventSeqs, block, context);
15133
15269
  if (!selected) return false;
15134
- appendBlockSurface(session, block.id, selected, sourceEventSeqs);
15270
+ appendBlockSurface(session, block, selected, sourceEventSeqs);
15135
15271
  this.surfaceFlushPending.add(session);
15136
15272
  levels.set(block.id, checkpointLevel(selected) ?? context.level);
15137
15273
  return true;
@@ -15184,7 +15320,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15184
15320
  );
15185
15321
  if (!text3) continue;
15186
15322
  if (node.text !== text3) {
15187
- appendBlockSurface(session, block.id, text3, [node.seq]);
15323
+ appendBlockSurface(session, block, text3, [node.seq]);
15188
15324
  this.surfaceFlushPending.add(session);
15189
15325
  changed = true;
15190
15326
  }
@@ -15206,7 +15342,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15206
15342
  const node = current.get(block.id);
15207
15343
  const endTurn = node ? null : dshTurnAtBlockEnd(session, block);
15208
15344
  const seqs = node ? [node.seq] : endTurn === null ? null : sealedSurfaceSeqs(session, endTurn, block);
15209
- if (!seqs?.length || !safeBlockSurfaceRange(session, block.id, seqs)) return {
15345
+ if (!seqs?.length || !safeBlockSurfaceRange(session, block, seqs)) return {
15210
15346
  status: "blocked",
15211
15347
  reason: "source-unavailable",
15212
15348
  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"
@@ -15292,13 +15428,15 @@ var StrataGateRuntime = class _StrataGateRuntime {
15292
15428
  }
15293
15429
  const { text: text3, seqs, relief } = plan;
15294
15430
  for (const replacement of relief) {
15295
- appendBlockSurface(session, replacement.id, replacement.text, [replacement.seq]);
15431
+ const replacementBlock = memory.listBlocks().find((candidate) => candidate.id === replacement.id);
15432
+ if (!replacementBlock) continue;
15433
+ appendBlockSurface(session, replacementBlock, replacement.text, [replacement.seq]);
15296
15434
  levels.set(replacement.id, replacement.level);
15297
15435
  this.surfaceFlushPending.add(session);
15298
15436
  }
15299
15437
  const node = currentBlockSurfaceMessages(session).get(block.id);
15300
15438
  if (node?.text !== text3) {
15301
- appendBlockSurface(session, block.id, text3, seqs);
15439
+ appendBlockSurface(session, block, text3, seqs);
15302
15440
  this.surfaceFlushPending.add(session);
15303
15441
  }
15304
15442
  levels.set(block.id, context.level);
@@ -15742,6 +15880,8 @@ var StrataGateRuntime = class _StrataGateRuntime {
15742
15880
  throw new Error("StrataGate agent memory is disabled by configuration (agentMemoryEnabled=false).");
15743
15881
  }
15744
15882
  const memory = await this.space(session);
15883
+ const current = currentTurnUserInput(session);
15884
+ if (current) await memory.reserveUserMessage(current);
15745
15885
  const hasDecider = typeof this.models.externalMemoryDecider === "function";
15746
15886
  const deciderBudgetMs = Math.min(this.config.structuredTaskTimeoutMs ?? 12e4, 3e4);
15747
15887
  const result = await this.models.run(session, () => memory.recordAgentEvent({
@@ -17161,31 +17301,40 @@ var StrataGateRuntime = class _StrataGateRuntime {
17161
17301
  ].join(" ");
17162
17302
  }
17163
17303
  };
17304
+ function currentTurnUserInput(session) {
17305
+ const events = session.snapshotEvents();
17306
+ let start = -1;
17307
+ let turn;
17308
+ for (let index = events.length - 1; index >= 0; index -= 1) {
17309
+ const event = events[index];
17310
+ if (event?.type === "turn/start") {
17311
+ start = index;
17312
+ turn = event.data.turn;
17313
+ break;
17314
+ }
17315
+ if (event?.type === "turn/end" || event?.type === "session/end-seed") return null;
17316
+ }
17317
+ if (start < 0 || turn === void 0) return null;
17318
+ const messages = events.slice(start + 1).filter((event) => event.type === "user/message" && event.data.source.kind === "user");
17319
+ const content = messages.map((event) => renderBlocks(event.data.content)).filter(Boolean).join("\n\n").trim();
17320
+ if (!content) return null;
17321
+ const firstTime = messages[0]?.time;
17322
+ return {
17323
+ id: `dsh:${String(session.id)}:turn:${turn}:user`,
17324
+ content,
17325
+ threadId: String(session.id),
17326
+ ...typeof firstTime === "number" && Number.isFinite(firstTime) ? { createdAt: new Date(firstTime).toISOString() } : {}
17327
+ };
17328
+ }
17164
17329
  function currentUserMessage(session) {
17165
17330
  const messages = typeof session.deriveMessages === "function" ? session.deriveMessages() : [];
17166
17331
  for (let index = messages.length - 1; index >= 0; index -= 1) {
17167
17332
  const message = messages[index];
17168
17333
  if (message?.role !== "user" || message.source.kind !== "user") continue;
17169
- return renderContent(message.content);
17334
+ return renderBlocks(message.content);
17170
17335
  }
17171
17336
  return "";
17172
17337
  }
17173
- function renderContent(content) {
17174
- const output = [];
17175
- for (const block of content) {
17176
- if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
17177
- output.push(block.text.trim());
17178
- } else if (block.type === "image") {
17179
- output.push("[image]");
17180
- } else {
17181
- const legacy = block;
17182
- if (legacy.type === "tool-result" && Array.isArray(legacy.content)) {
17183
- output.push(renderContent(legacy.content));
17184
- }
17185
- }
17186
- }
17187
- return output.filter(Boolean).join("\n");
17188
- }
17189
17338
  function recentTurns(messages, count) {
17190
17339
  let remaining = count;
17191
17340
  for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -17282,8 +17431,9 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17282
17431
  nodes: currentSurface.filter((seq) => {
17283
17432
  const current = session.eventAt(seq);
17284
17433
  if (!replaceableBlockEvent(current, block.id)) return false;
17434
+ if ((current?.type === "assistant/message" || current?.type === "tool/result") && !surfaceEventBelongsToTurn(session, current, open2.turn)) return false;
17285
17435
  if (seq > open2.start && seq < event.seq) return true;
17286
- return current?.type === "tool/result" && current.surfaceOp !== "append" && current.sourceEventSeqs?.some((source) => source > open2.start && source < event.seq);
17436
+ 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);
17287
17437
  })
17288
17438
  });
17289
17439
  }
@@ -17307,19 +17457,62 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17307
17457
  const endIndex = currentSurface.indexOf(end);
17308
17458
  if (startIndex < 0 || endIndex < startIndex) return null;
17309
17459
  const range = currentSurface.slice(startIndex, endIndex + 1);
17310
- return safeBlockSurfaceRange(session, block.id, range) ? range : null;
17460
+ return safeBlockSurfaceRange(session, block, range) ? range : null;
17311
17461
  }
17312
17462
  function replaceableBlockEvent(event, blockId) {
17313
17463
  if (event?.type === "assistant/message" || event?.type === "tool/result") return true;
17314
17464
  return event?.type === "user/message" && (event.data.source.kind === "user" || blockSurfaceMessage(event)?.id === blockId);
17315
17465
  }
17316
- function safeBlockSurfaceRange(session, blockId, seqs) {
17466
+ function turnAtSurfaceSeq(session, seq) {
17467
+ let turn;
17468
+ for (const event of session.snapshotEvents()) {
17469
+ if (event.seq >= seq) break;
17470
+ if (event.type === "turn/start") turn = event.data.turn;
17471
+ else if (event.type === "turn/end") turn = void 0;
17472
+ }
17473
+ return turn;
17474
+ }
17475
+ function sourceTurnsForBlock(session, block) {
17476
+ const sourceTimes = new Set(block.l5Raw.filter((message) => message.role === "user").map((message) => Date.parse(message.createdAt)));
17477
+ return new Set(session.snapshotEvents().filter((event) => event.type === "turn/end" && sourceTimes.has(event.time)).map((event) => event.data.turn));
17478
+ }
17479
+ function surfaceEventTurns(session, event) {
17480
+ if (event.surfaceOp !== "append" && event.sourceEventSeqs?.length) {
17481
+ const sourceTurns = event.sourceEventSeqs.flatMap((source) => {
17482
+ const original = session.eventAt(source);
17483
+ return original?.type === "assistant/message" || original?.type === "tool/result" ? [original.data.turn] : [];
17484
+ });
17485
+ if (sourceTurns.length > 0) return new Set(sourceTurns);
17486
+ }
17487
+ return /* @__PURE__ */ new Set([event.data.turn]);
17488
+ }
17489
+ function surfaceEventBelongsToTurn(session, event, turn) {
17490
+ const turns = surfaceEventTurns(session, event);
17491
+ return turns.size === 1 && turns.has(turn);
17492
+ }
17493
+ function safeBlockSurfaceRange(session, block, seqs) {
17317
17494
  if (seqs.length === 0) return false;
17318
17495
  const start = session.surface.nodes.indexOf(seqs[0]);
17319
- return start >= 0 && seqs.every((seq, index) => session.surface.nodes[start + index] === seq && replaceableBlockEvent(session.eventAt(seq), blockId));
17496
+ if (start < 0) return false;
17497
+ const sourceTurns = sourceTurnsForBlock(session, block);
17498
+ return seqs.every((seq, index) => {
17499
+ if (session.surface.nodes[start + index] !== seq) return false;
17500
+ const event = session.eventAt(seq);
17501
+ if (!replaceableBlockEvent(event, block.id)) return false;
17502
+ const checkpoint = blockSurfaceMessage(event);
17503
+ if (checkpoint) return checkpoint.id === block.id;
17504
+ if (event?.type === "assistant/message" || event?.type === "tool/result") {
17505
+ const eventTurns = surfaceEventTurns(session, event);
17506
+ return eventTurns.size > 0 && [...eventTurns].every((turn) => sourceTurns.has(turn));
17507
+ }
17508
+ if (event?.type === "user/message" && event.data.source.kind === "user") {
17509
+ return sourceTurns.has(turnAtSurfaceSeq(session, seq) ?? -1);
17510
+ }
17511
+ return false;
17512
+ });
17320
17513
  }
17321
- function appendBlockSurface(session, blockId, text3, seqs) {
17322
- if (!safeBlockSurfaceRange(session, blockId, seqs)) {
17514
+ function appendBlockSurface(session, block, text3, seqs) {
17515
+ if (!safeBlockSurfaceRange(session, block, seqs)) {
17323
17516
  throw Object.assign(new Error("StrataGate surface replacement no longer owns its complete source range"), { retryable: false });
17324
17517
  }
17325
17518
  session.append("user/message", createUserMessage2({
@@ -17516,6 +17709,7 @@ function compactEvent2(event, score) {
17516
17709
  temporal: compactTemporal(event),
17517
17710
  ...event.sourceBlockId !== void 0 ? { sourceBlockId: event.sourceBlockId } : {},
17518
17711
  status: event.status,
17712
+ ...event.supersededBy ? { supersededBy: event.supersededBy } : {},
17519
17713
  scope: event.scope,
17520
17714
  criticality: event.criticality,
17521
17715
  ...agentRecorded ? { source: "agent-recorded" } : {},
@@ -17649,9 +17843,12 @@ function renderActivatedMemory(events, graphResults) {
17649
17843
  id: event.id,
17650
17844
  title: event.title,
17651
17845
  summary: event.summary,
17846
+ status: event.status,
17847
+ supersededBy: event.supersededBy,
17848
+ scope: event.scope,
17652
17849
  happenedStart: event.temporal.happenedStart,
17653
17850
  happenedEnd: event.temporal.happenedEnd,
17654
- temporal: { status: event.temporal.status }
17851
+ temporal: event.temporal
17655
17852
  });
17656
17853
  const cost = estimateTokens(`
17657
17854
  Events:
@@ -18605,19 +18802,19 @@ function blockLayers(block) {
18605
18802
  const deterministic = deterministicBlockLayers(block.l5Raw);
18606
18803
  if (block.processingStatus !== "ready" || !block.l0Title || !block.l0Tags || !block.l1Summary || !block.l2Keypoints) {
18607
18804
  return withLayerMetrics([
18608
- { level: 3, content: deterministic.l3Condensed },
18609
- { level: 4, content: deterministic.l4Readable },
18610
- { level: 5, content: formatRawTranscript(block.l5Raw) }
18805
+ { level: 3, content: preserveAttachmentReferences(deterministic.l3Condensed, block.l5Raw) },
18806
+ { level: 4, content: preserveAttachmentReferences(deterministic.l4Readable, block.l5Raw) },
18807
+ { level: 5, content: preserveAttachmentReferences(formatRawTranscript(block.l5Raw), block.l5Raw) }
18611
18808
  ]);
18612
18809
  }
18613
18810
  return withLayerMetrics([
18614
- { level: 0, content: `${block.l0Title}
18615
- Tags: ${block.l0Tags.join(", ") || "none"}` },
18616
- { level: 1, content: block.l1Summary || block.l0Title },
18617
- { level: 2, content: block.l2Keypoints.map((point) => `- ${point}`).join("\n") || block.l1Summary || block.l0Title },
18618
- { level: 3, content: deterministic.l3Condensed || block.l2Keypoints.join("\n") || block.l1Summary },
18619
- { level: 4, content: deterministic.l4Readable || deterministic.l3Condensed },
18620
- { level: 5, content: formatRawTranscript(block.l5Raw) }
18811
+ { level: 0, content: preserveAttachmentReferences(`${block.l0Title}
18812
+ Tags: ${block.l0Tags.join(", ") || "none"}`, block.l5Raw) },
18813
+ { level: 1, content: preserveAttachmentReferences(block.l1Summary || block.l0Title, block.l5Raw) },
18814
+ { level: 2, content: preserveAttachmentReferences(block.l2Keypoints.map((point) => `- ${point}`).join("\n") || block.l1Summary || block.l0Title, block.l5Raw) },
18815
+ { level: 3, content: preserveAttachmentReferences(deterministic.l3Condensed || block.l2Keypoints.join("\n") || block.l1Summary, block.l5Raw) },
18816
+ { level: 4, content: preserveAttachmentReferences(deterministic.l4Readable || deterministic.l3Condensed, block.l5Raw) },
18817
+ { level: 5, content: preserveAttachmentReferences(formatRawTranscript(block.l5Raw), block.l5Raw) }
18621
18818
  ]);
18622
18819
  }
18623
18820
  function sampledEventWeight(event, turn, lastAdoptedTurn, mentionCount) {