stratagate-dsh 0.3.31 → 0.3.32

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
@@ -3233,6 +3233,9 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3233
3233
  matchesMode(ids2, versions, mode, sectionBackfillTopicId) {
3234
3234
  return mode === "all" || ids2.some((id) => this.isBootstrap(id, versions.get(id), sectionBackfillTopicId) === (mode === "bootstrap"));
3235
3235
  }
3236
+ jobMatchesMode(job, versions, mode) {
3237
+ return job.manualAttemptPending === true ? mode !== "bootstrap" : this.matchesMode(job.sourceEventIds, versions, mode, job.sectionBackfillTopicId);
3238
+ }
3236
3239
  hasPending(events, now, mode = "all") {
3237
3240
  const sources2 = new Map(events.filter(visible).map((event) => [event.id, event]));
3238
3241
  const versions = sourceVersions(sources2);
@@ -3245,7 +3248,7 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3245
3248
  if (this.dreamingReservesDirectory()) return false;
3246
3249
  const running = this.state.jobs.find((job) => job.status === "running");
3247
3250
  if (running) return Date.parse(running.leaseUntil ?? running.updatedAt) <= now || !jobInputsCurrent(running, versions);
3248
- return this.pendingWork(events, versions).some(({ event, sectionBackfillTopicId }) => this.matchesMode([event.id], versions, mode, sectionBackfillTopicId)) || this.state.jobs.some((job) => !job.superseded && job.projectorVersion === MEMORY_TOPIC_PROJECTOR_VERSION && job.attempts < TOPIC_MAX_ATTEMPTS && (job.status === "pending" && (job.nextRetryAt === null || Date.parse(job.nextRetryAt) <= now) || job.status === "failed" && job.nextRetryAt !== null && Date.parse(job.nextRetryAt) <= now) && jobInputsCurrent(job, versions) && this.matchesMode(job.sourceEventIds, versions, mode, job.sectionBackfillTopicId));
3251
+ return this.pendingWork(events, versions).some(({ event, sectionBackfillTopicId }) => this.matchesMode([event.id], versions, mode, sectionBackfillTopicId)) || this.state.jobs.some((job) => !job.superseded && job.projectorVersion === MEMORY_TOPIC_PROJECTOR_VERSION && job.attempts < TOPIC_MAX_ATTEMPTS && (job.status === "pending" && (job.nextRetryAt === null || Date.parse(job.nextRetryAt) <= now) || job.status === "failed" && job.nextRetryAt !== null && Date.parse(job.nextRetryAt) <= now) && jobInputsCurrent(job, versions) && this.jobMatchesMode(job, versions, mode));
3249
3252
  }
3250
3253
  /** Derived wake time, using exactly the claim eligibility rules, including work without a Job. */
3251
3254
  nextWakeTimes(events, now) {
@@ -3274,9 +3277,9 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3274
3277
  if (this.state.jobs.some((job2) => job2.status === "running")) return null;
3275
3278
  const sources2 = new Map(events.filter(visible).map((event) => [event.id, event]));
3276
3279
  const versions = sourceVersions(sources2);
3277
- const eligible = this.state.jobs.filter((job2) => !job2.superseded && job2.attempts < TOPIC_MAX_ATTEMPTS && (job2.status === "pending" && (job2.nextRetryAt === null || Date.parse(job2.nextRetryAt) <= Date.parse(now)) || job2.status === "failed" && job2.nextRetryAt !== null && Date.parse(job2.nextRetryAt) <= Date.parse(now)) && jobInputsCurrent(job2, versions) && this.matchesMode(job2.sourceEventIds, versions, mode, job2.sectionBackfillTopicId)).sort((a, b) => Number(this.isBootstrap(a.sourceEventIds[0], versions.get(a.sourceEventIds[0]), a.sectionBackfillTopicId)) - Number(this.isBootstrap(b.sourceEventIds[0], versions.get(b.sourceEventIds[0]), b.sectionBackfillTopicId)))[0];
3280
+ const eligible = this.state.jobs.filter((job2) => !job2.superseded && job2.attempts < TOPIC_MAX_ATTEMPTS && (job2.status === "pending" && (job2.nextRetryAt === null || Date.parse(job2.nextRetryAt) <= Date.parse(now)) || job2.status === "failed" && job2.nextRetryAt !== null && Date.parse(job2.nextRetryAt) <= Date.parse(now)) && jobInputsCurrent(job2, versions) && this.jobMatchesMode(job2, versions, mode)).sort((a, b) => Number(b.manualAttemptPending === true) - Number(a.manualAttemptPending === true) || Number(this.isBootstrap(a.sourceEventIds[0], versions.get(a.sourceEventIds[0]), a.sectionBackfillTopicId)) - Number(this.isBootstrap(b.sourceEventIds[0], versions.get(b.sourceEventIds[0]), b.sectionBackfillTopicId)))[0];
3278
3281
  let job = eligible;
3279
- if (job && this.isBootstrap(job.sourceEventIds[0], versions.get(job.sourceEventIds[0]), job.sectionBackfillTopicId) && mode === "all" && this.pendingWork(events).some(({ event, sectionBackfillTopicId }) => !this.isBootstrap(event.id, versions.get(event.id), sectionBackfillTopicId))) job = void 0;
3282
+ if (job && !job.manualAttemptPending && this.isBootstrap(job.sourceEventIds[0], versions.get(job.sourceEventIds[0]), job.sectionBackfillTopicId) && mode === "all" && this.pendingWork(events).some(({ event, sectionBackfillTopicId }) => !this.isBootstrap(event.id, versions.get(event.id), sectionBackfillTopicId))) job = void 0;
3280
3283
  if (job?.status === "failed") {
3281
3284
  const previous = job;
3282
3285
  previous.nextRetryAt = null;
@@ -3399,6 +3402,7 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3399
3402
  ])]);
3400
3403
  job.dependencyVersions = Object.fromEntries(dependencyIds.map((id) => [id, versions.get(id)]));
3401
3404
  job.diagnostics = void 0;
3405
+ delete job.manualAttemptPending;
3402
3406
  job.status = "running";
3403
3407
  job.attempts += 1;
3404
3408
  job.lastError = null;
@@ -3644,6 +3648,7 @@ var MemoryTopicDirectory = class _MemoryTopicDirectory {
3644
3648
  throw new Error("Topic retry conflict: failure is no longer current or retryable.");
3645
3649
  }
3646
3650
  const job = this.requeue(previous, ids2, versions, now);
3651
+ job.manualAttemptPending = true;
3647
3652
  this.synchronize(events, now);
3648
3653
  return { jobId: job.id, status: "pending" };
3649
3654
  }
@@ -7435,19 +7440,14 @@ var StrataGate = class _StrataGate {
7435
7440
  });
7436
7441
  }
7437
7442
  async expandBlock(id, target = "next", source = "agent") {
7438
- return this.commitMutation(() => {
7443
+ return this.withMutationQueue(async () => {
7439
7444
  const block = this.blocks.find((candidate) => candidate.id === id);
7440
7445
  if (!block) throw new Error(`Unknown block: ${id}`);
7441
7446
  if (block.processingStatus !== "ready") throw new Error(`Block ${id} is not ready for decay or expansion`);
7442
7447
  const position = buildBlockTimeline(this.threadBlocks(block.threadId)).get(block.id);
7443
7448
  const { age, level: current } = getBlockDecayView(block, position, this.blockDecayLambda);
7444
7449
  const level = normalizeBlockLevel(target, current);
7445
- block.pointerCurrentLevel = level;
7446
- block.pointerAnchorLevel = level;
7447
- block.pointerAnchorBlockPosition = position.latestBlockPosition;
7448
- block.lastLiftedAt = toUtc8Iso(this.now());
7449
- block.lastLiftedBy = source;
7450
- return {
7450
+ const result = {
7451
7451
  id: block.id,
7452
7452
  ...block.threadId ? { threadId: block.threadId } : {},
7453
7453
  turnRange: [block.startTurn, block.endTurn],
@@ -7457,6 +7457,15 @@ var StrataGate = class _StrataGate {
7457
7457
  label: blockLevelLabel(level),
7458
7458
  content: renderBlock(block, level)
7459
7459
  };
7460
+ if (source === "agent" && block.lastLiftedBy === "user") return result;
7461
+ return this.applyMutation(() => {
7462
+ block.pointerCurrentLevel = level;
7463
+ block.pointerAnchorLevel = level;
7464
+ block.pointerAnchorBlockPosition = position.latestBlockPosition;
7465
+ block.lastLiftedAt = toUtc8Iso(this.now());
7466
+ block.lastLiftedBy = source;
7467
+ return result;
7468
+ });
7460
7469
  });
7461
7470
  }
7462
7471
  assessRetrieval(input, batchEvidenceRefs) {
@@ -12918,6 +12927,8 @@ var StrataGateRuntime = class {
12918
12927
  if (this.isDreamingSession(session)) return;
12919
12928
  if (this.closed) return;
12920
12929
  if (!this.config.ingestSubagents && session.header.origin === "subagent") return;
12930
+ if (event.type === "request/context" || event.type === "request/header") this.retryCapacityBlockedSurface(session);
12931
+ if (event.type === "compaction/end" || event.type === "session/end-seed" || event.type === "user/message" && event.surfaceOp !== void 0 && event.surfaceOp !== "append" && !isStrataGateMessageSource(event.data.source)) this.retryCapacityBlockedSurface(session, true);
12921
12932
  const surface = this.surfaceMaintenance.get(String(session.id));
12922
12933
  if (surface?.session === session) {
12923
12934
  if (event.type === "turn/start") {
@@ -13499,12 +13510,15 @@ var StrataGateRuntime = class {
13499
13510
  async syncDecayedBlockSurface(session, memory, contexts) {
13500
13511
  const levels = /* @__PURE__ */ new Map();
13501
13512
  const changed = this.applyDecayedBlockSurface(session, memory, contexts, levels);
13513
+ const applied = this.appliedSurfaceRequests(session);
13502
13514
  await this.commitSurfaceLevels(memory, levels);
13515
+ await this.flushSurface(session);
13516
+ this.completeSurfaceRequests(applied);
13503
13517
  return changed;
13504
13518
  }
13505
13519
  applyDecayedBlockSurface(session, memory, contexts, levels) {
13506
13520
  if (hostCompactionActive(session)) return false;
13507
- const current = currentBlockSurfaceMessages(session);
13521
+ let current = currentBlockSurfaceMessages(session);
13508
13522
  const blocks = new Map(memory.listBlocks().map((block) => [block.id, block]));
13509
13523
  const checkpointLimit = surfaceCheckpointLimit(session);
13510
13524
  let changed = false;
@@ -13518,9 +13532,14 @@ var StrataGateRuntime = class {
13518
13532
  const block = blocks.get(context.id);
13519
13533
  if (!block) continue;
13520
13534
  if (currentLevel >= 0) levels.set(context.id, currentLevel);
13521
- const userLift = block.lastLiftedBy === "user" && currentLevel >= 0 && context.level > currentLevel;
13522
- if (userLift) {
13523
- changed = this.applyExpandedSurface(session, block, context, levels) || changed;
13535
+ const userSelection = block.lastLiftedBy === "user" && context.level === block.pointerAnchorLevel;
13536
+ if (userSelection) {
13537
+ if (context.level !== currentLevel) {
13538
+ this.queueSurfaceSync(this.namespaceFor(session), block.id, "user-expansion");
13539
+ const applied = this.applyExpandedSurface(session, memory, block, context, levels);
13540
+ changed = applied || changed;
13541
+ if (applied) current = currentBlockSurfaceMessages(session);
13542
+ }
13524
13543
  continue;
13525
13544
  }
13526
13545
  if (context.level >= currentLevel && currentLevel >= 0 && !violatesLimit) continue;
@@ -13551,19 +13570,110 @@ var StrataGateRuntime = class {
13551
13570
  }
13552
13571
  queueSurfaceSync(namespace, blockId, reason) {
13553
13572
  const key = `${namespace}\0${blockId}`;
13554
- if (!reason && this.pendingSurfaceSync.has(key)) return;
13573
+ const previous = this.pendingSurfaceSync.get(key);
13574
+ if (previous && (!reason || previous.reason === reason)) return;
13555
13575
  this.pendingSurfaceSync.set(key, { namespace, blockId, ...reason ? { reason } : {} });
13556
13576
  }
13557
- /** Apply an explicit user request without the automatic decay size-reduction gate. */
13558
- applyExpandedSurface(session, block, context, levels) {
13559
- if (hostCompactionActive(session) || block.threadId !== String(session.id)) return false;
13577
+ expandedSurfacePlan(session, memory, block, context) {
13578
+ if (hostCompactionActive(session)) return { status: "pending", reason: "compaction", message: "\u6B63\u5728\u6574\u7406\u8FD9\u6BB5\u5BF9\u8BDD\uFF0C\u5B8C\u6210\u540E\u4F1A\u5E94\u7528\u4F60\u7684\u9009\u62E9\u3002" };
13579
+ if (block.threadId !== String(session.id)) return { status: "pending", reason: "session-unloaded", message: "\u5DF2\u4FDD\u5B58\u9009\u62E9\uFF0C\u6253\u5F00\u8FD9\u6BB5\u5BF9\u8BDD\u540E\u751F\u6548\u3002" };
13560
13580
  const text3 = renderBlockSurfaceMessage(context);
13561
- if (surfaceCheckpointTokens(text3) > surfaceCheckpointLimit(session)) return false;
13581
+ const current = currentBlockSurfaceMessages(session);
13582
+ const node = current.get(block.id);
13583
+ const endTurn = node ? null : dshTurnAtBlockEnd(session, block);
13584
+ const seqs = node ? [node.seq] : endTurn === null ? null : sealedSurfaceSeqs(session, endTurn, block);
13585
+ if (!seqs?.length) return { status: "blocked", reason: "source-unavailable", message: "\u8FD9\u6BB5\u5386\u53F2\u5DF2\u88AB\u6574\u7406\uFF0C\u65E0\u6CD5\u5728\u8FD9\u91CC\u5207\u6362\u5C42\u7EA7\u3002\u53EF\u4EE5\u8BA9\u52A9\u624B\u67E5\u627E\u8FD9\u6BB5\u5386\u53F2\u3002" };
13586
+ const relief = [];
13587
+ const window = session.requestContext?.()?.contextWindow;
13588
+ if (node?.text !== text3 && typeof window === "number" && Number.isInteger(window) && window > 0) {
13589
+ const start = seqs[0];
13590
+ const end = seqs.at(-1);
13591
+ let before = 0;
13592
+ let removed = 0;
13593
+ for (const seq of session.surface.nodes) {
13594
+ const event = session.eventAt(seq);
13595
+ const message = event && session.deriveEventMessage(event);
13596
+ const tokens = message ? estimateTokens(JSON.stringify(message)) : 0;
13597
+ before += tokens;
13598
+ if (seq >= start && seq <= end) removed += tokens;
13599
+ }
13600
+ const header = session.requestHeader?.();
13601
+ const reserved = (header?.config.maxTokens ?? 0) + (header?.tools?.length ? estimateTokens(JSON.stringify(header.tools)) : 0);
13602
+ const after = before - removed + surfaceCheckpointTokens(text3);
13603
+ if (after > before && after + reserved > window) {
13604
+ let needed = after + reserved - window;
13605
+ const candidates = memory.listBlocks().filter((candidate) => candidate.id !== block.id && candidate.threadId === block.threadId && candidate.processingStatus === "ready" && candidate.lastLiftedBy !== "user").sort((a, b) => a.sequence - b.sequence);
13606
+ for (const candidate of candidates) {
13607
+ const checkpoint = current.get(candidate.id);
13608
+ if (!checkpoint || checkpoint.seq >= start && checkpoint.seq <= end) continue;
13609
+ const level = checkpointLevel(checkpoint.text);
13610
+ if (level === void 0 || level === 0) continue;
13611
+ const original = this.cachedCheckpointTokens(session, checkpoint);
13612
+ let best;
13613
+ let saved = 0;
13614
+ for (let lower = level - 1; lower >= 0; lower--) {
13615
+ const candidateLevel = lower;
13616
+ const candidateText = renderBlockSurfaceMessage({
13617
+ id: candidate.id,
13618
+ threadId: candidate.threadId,
13619
+ turnRange: [candidate.startTurn, candidate.endTurn],
13620
+ age: 0,
13621
+ level: candidateLevel,
13622
+ label: blockLevelLabel(candidateLevel),
13623
+ content: renderBlock(candidate, candidateLevel)
13624
+ });
13625
+ const reduction = original - surfaceCheckpointTokens(candidateText);
13626
+ if (reduction > saved) {
13627
+ best = { id: candidate.id, seq: checkpoint.seq, level: candidateLevel, text: candidateText };
13628
+ saved = reduction;
13629
+ }
13630
+ if (saved >= needed) break;
13631
+ }
13632
+ if (best) {
13633
+ relief.push(best);
13634
+ needed -= saved;
13635
+ }
13636
+ if (needed <= 0) break;
13637
+ }
13638
+ if (needed > 0) return {
13639
+ status: "blocked",
13640
+ reason: "capacity",
13641
+ message: `L${context.level} \u5185\u5BB9\u592A\u957F\uFF0C\u5F53\u524D\u6A21\u578B\u9884\u8BA1\u653E\u4E0D\u4E0B\uFF0C\u5176\u4ED6\u53EF\u7B80\u7565\u7684\u5386\u53F2\u4E5F\u4E0D\u8DB3\u4EE5\u817E\u51FA\u7A7A\u95F4\u3002\u8BF7\u9009\u66F4\u7B80\u7565\u7684\u5C42\u7EA7\uFF0C\u6216\u5207\u6362\u5230\u5BB9\u91CF\u66F4\u5927\u7684\u6A21\u578B\u3002`
13642
+ };
13643
+ }
13644
+ }
13645
+ return { status: "ready", text: text3, seqs, relief };
13646
+ }
13647
+ /** Explicit user requests bypass automatic per-checkpoint compression limits. */
13648
+ applyExpandedSurface(session, memory, block, context, levels) {
13649
+ const request = this.pendingSurfaceSync.get(`${this.namespaceFor(session)}\0${block.id}`);
13650
+ if (request?.blocked) return false;
13651
+ const plan = this.expandedSurfacePlan(session, memory, block, context);
13652
+ if (plan.status === "pending") {
13653
+ if (request) request.waitingFor = plan.reason;
13654
+ return false;
13655
+ }
13656
+ if (plan.status === "blocked") {
13657
+ if (request) request.blocked = {
13658
+ reason: plan.reason,
13659
+ message: plan.message,
13660
+ sessionId: String(session.id),
13661
+ capacityKey: surfaceCapacityKey(session)
13662
+ };
13663
+ this.onIngestError(new Error(`Block ${block.id}: ${plan.message}`));
13664
+ return false;
13665
+ }
13666
+ const { text: text3, seqs, relief } = plan;
13667
+ for (const replacement of relief) {
13668
+ session.append("user/message", createUserMessage2({
13669
+ content: [{ type: "text", text: replacement.text }],
13670
+ source: dshMessageSource()
13671
+ }), { surfaceOp: dshReplaceSurfaceOp(replacement.seq, replacement.seq), sourceEventSeqs: [replacement.seq] });
13672
+ levels.set(replacement.id, replacement.level);
13673
+ this.surfaceFlushPending.add(session);
13674
+ }
13562
13675
  const node = currentBlockSurfaceMessages(session).get(block.id);
13563
13676
  if (node?.text !== text3) {
13564
- const endTurn = node ? null : dshTurnAtBlockEnd(session, block);
13565
- const seqs = node ? [node.seq] : endTurn === null ? null : sealedSurfaceSeqs(session, endTurn, block);
13566
- if (!seqs) return false;
13567
13677
  const start = seqs[0];
13568
13678
  const end = seqs.at(-1);
13569
13679
  if (start === void 0 || end === void 0) return false;
@@ -13574,8 +13684,31 @@ var StrataGateRuntime = class {
13574
13684
  this.surfaceFlushPending.add(session);
13575
13685
  }
13576
13686
  levels.set(block.id, context.level);
13687
+ const knownIds = new Set(memory.listBlocks().filter((candidate) => candidate.threadId === block.threadId).map((candidate) => candidate.id));
13688
+ for (const [id, checkpoint] of currentBlockSurfaceMessages(session)) {
13689
+ const level = checkpointLevel(checkpoint.text);
13690
+ if (knownIds.has(id) && level !== void 0) levels.set(id, level);
13691
+ }
13692
+ if (request) {
13693
+ request.appliedSessionId = String(session.id);
13694
+ request.waitingFor = "saving";
13695
+ }
13577
13696
  return true;
13578
13697
  }
13698
+ retryCapacityBlockedSurface(session, force = false) {
13699
+ const namespace = this.namespaceFor(session);
13700
+ let capacityKey;
13701
+ for (const item of this.pendingSurfaceSync.values()) {
13702
+ if (item.namespace !== namespace || item.blocked?.reason !== "capacity" || item.blocked.sessionId !== String(session.id)) continue;
13703
+ capacityKey ??= surfaceCapacityKey(session);
13704
+ if (force || item.blocked.capacityKey !== capacityKey) delete item.blocked;
13705
+ }
13706
+ }
13707
+ adminBlockSurfaceSync(namespace, blockId) {
13708
+ const request = this.pendingSurfaceSync.get(`${namespace}\0${blockId}`);
13709
+ if (!request || request.reason !== "user-expansion") return void 0;
13710
+ return request.blocked ? { status: "blocked", reason: request.blocked.reason, message: request.blocked.message } : { status: "pending", reason: request.waitingFor ?? "session-unloaded", message: request.waitingFor === "compaction" ? "\u6B63\u5728\u6574\u7406\u8FD9\u6BB5\u5BF9\u8BDD\uFF0C\u5B8C\u6210\u540E\u4F1A\u5E94\u7528\u4F60\u7684\u9009\u62E9\u3002" : request.waitingFor === "saving" ? "\u6B63\u5728\u4FDD\u5B58\u8FD9\u6BB5\u5BF9\u8BDD\uFF0C\u5B8C\u6210\u540E\u53EF\u4F9B\u52A9\u624B\u53C2\u8003\u3002" : "\u5DF2\u4FDD\u5B58\u9009\u62E9\uFF0C\u6253\u5F00\u8FD9\u6BB5\u5BF9\u8BDD\u540E\u751F\u6548\u3002" };
13711
+ }
13579
13712
  async commitSurfaceLevels(memory, levels) {
13580
13713
  if (levels.size > 0) await memory.setBlockSurfaceLevels([...levels].map(([id, level]) => ({ id, level })));
13581
13714
  }
@@ -13608,10 +13741,16 @@ var StrataGateRuntime = class {
13608
13741
  this.completeSurfaceRequests(completed);
13609
13742
  }
13610
13743
  applyPendingRetrySurface(session, memory, levels, userOnly = false, recoverable) {
13611
- if (hostCompactionActive(session)) return [];
13612
13744
  const namespace = this.namespaceFor(session);
13613
13745
  const threadId = String(session.id);
13614
- let pending = [...this.pendingSurfaceSync.entries()].filter(([, item]) => item.namespace === namespace && (!userOnly || item.reason === "user-expansion"));
13746
+ if (hostCompactionActive(session)) {
13747
+ const blockIds = new Set(memory.listBlocks().filter((block) => block.threadId === threadId).map((block) => block.id));
13748
+ for (const request of this.pendingSurfaceSync.values()) {
13749
+ if (request.namespace === namespace && blockIds.has(request.blockId) && !request.blocked) request.waitingFor = "compaction";
13750
+ }
13751
+ return [];
13752
+ }
13753
+ let pending = [...this.pendingSurfaceSync.entries()].filter(([, item]) => item.namespace === namespace && !item.blocked && (!userOnly || item.reason === "user-expansion"));
13615
13754
  if (pending.length === 0) return [];
13616
13755
  const existing = currentBlockSurfaceMessages(session);
13617
13756
  const blocks = new Map(memory.listBlocks().filter((block) => block.threadId === threadId).map((block) => [block.id, block]));
@@ -13631,12 +13770,13 @@ var StrataGateRuntime = class {
13631
13770
  let changed = false;
13632
13771
  const completed = [];
13633
13772
  for (const [key, item] of pending) {
13773
+ if (item.blocked) continue;
13634
13774
  const { blockId } = item;
13635
13775
  const block = blocks.get(blockId);
13636
13776
  const context = contexts.get(blockId);
13637
13777
  if (!block || block.processingStatus !== "ready" || !context) continue;
13638
13778
  if (item.reason === "user-expansion") {
13639
- if (!this.applyExpandedSurface(session, block, context, levels)) continue;
13779
+ if (!this.applyExpandedSurface(session, memory, block, context, levels)) continue;
13640
13780
  changed = true;
13641
13781
  } else if (!existing.has(blockId)) {
13642
13782
  const source = recovery.sources.get(blockId);
@@ -13656,6 +13796,9 @@ var StrataGateRuntime = class {
13656
13796
  if (this.pendingSurfaceSync.get(key) === item) this.pendingSurfaceSync.delete(key);
13657
13797
  }
13658
13798
  }
13799
+ appliedSurfaceRequests(session) {
13800
+ return [...this.pendingSurfaceSync.entries()].filter(([, item]) => item.appliedSessionId === String(session.id));
13801
+ }
13659
13802
  /** Read-only in the common case; render only explicit lifts or oversized checkpoints. */
13660
13803
  async syncRequestSurface(session, memory) {
13661
13804
  if (hostCompactionActive(session)) return;
@@ -13663,11 +13806,14 @@ var StrataGateRuntime = class {
13663
13806
  const limit = surfaceCheckpointLimit(session);
13664
13807
  const repair = /* @__PURE__ */ new Set();
13665
13808
  const namespace = this.namespaceFor(session);
13809
+ const timeline = buildBlockTimeline(memory.listBlocks());
13666
13810
  for (const block of memory.listBlocks()) {
13667
13811
  if (block.threadId !== String(session.id) || block.processingStatus !== "ready") continue;
13668
13812
  const node = current.get(block.id);
13669
- if (node && this.cachedCheckpointTokens(session, node) > limit) repair.add(block.id);
13670
- if (block.lastLiftedBy === "user" && (!node || block.pointerCurrentLevel > (checkpointLevel(node.text) ?? 5))) {
13813
+ const target = getBlockDecayView(block, timeline.get(block.id), memory.blockDecayLambda).level;
13814
+ const userSelection = block.lastLiftedBy === "user" && target === block.pointerAnchorLevel;
13815
+ if (node && !userSelection && this.cachedCheckpointTokens(session, node) > limit) repair.add(block.id);
13816
+ if (userSelection && (!node || target !== checkpointLevel(node.text))) {
13671
13817
  this.queueSurfaceSync(namespace, block.id, "user-expansion");
13672
13818
  }
13673
13819
  }
@@ -13728,9 +13874,11 @@ var StrataGateRuntime = class {
13728
13874
  const completed = this.applyPendingRetrySurface(session, state.memory, levels, false, recoverable);
13729
13875
  const live2 = new Set(currentBlockSurfaceMessages(session).keys());
13730
13876
  if (live2.size > 0) this.applyDecayedBlockSurface(session, state.memory, state.memory.getBlockContext(String(session.id), live2), levels);
13877
+ const applied = this.appliedSurfaceRequests(session);
13731
13878
  await this.commitSurfaceLevels(state.memory, levels);
13732
13879
  await this.flushSurface(session);
13733
13880
  this.completeSurfaceRequests(completed);
13881
+ this.completeSurfaceRequests(applied);
13734
13882
  if (state.generation === generation) state.dirty = false;
13735
13883
  state.failures = 0;
13736
13884
  })().catch(async (error) => {
@@ -14639,18 +14787,37 @@ var StrataGateRuntime = class {
14639
14787
  await this.flush();
14640
14788
  const { memory, owned } = await this.openAdminMemory(key);
14641
14789
  try {
14642
- const result = await memory.expandBlock(id, target, "user");
14643
- if (result.threadId) {
14644
- this.queueSurfaceSync(key, id, "user-expansion");
14790
+ const block = memory.listBlocks().find((candidate) => candidate.id === id);
14791
+ if (!block) throw new Error(`Unknown block: ${id}`);
14792
+ if (block.processingStatus !== "ready") throw new Error(`Block ${id} is not ready for expansion`);
14793
+ if (!block.threadId) throw new Error("\u65E0\u6CD5\u786E\u8BA4\u8FD9\u6BB5\u5386\u53F2\u6240\u5C5E\u7684\u5BF9\u8BDD\uFF0C\u6682\u65F6\u4E0D\u80FD\u5E94\u7528\u3002\u53EF\u4EE5\u8BA9\u52A9\u624B\u67E5\u627E\u8FD9\u6BB5\u5386\u53F2\u3002");
14794
+ const session = this.knownSessions.get(block.threadId)?.deref();
14795
+ if (session && this.namespaceFor(session) === key) {
14796
+ const position = buildBlockTimeline(memory.listBlocks()).get(id);
14797
+ const current = getBlockDecayView(block, position, memory.blockDecayLambda);
14798
+ const level = normalizeBlockLevel(target, current.level);
14799
+ const plan = this.expandedSurfacePlan(session, memory, block, {
14800
+ id,
14801
+ threadId: block.threadId,
14802
+ turnRange: [block.startTurn, block.endTurn],
14803
+ age: current.age,
14804
+ level,
14805
+ label: blockLevelLabel(level),
14806
+ content: renderBlock(block, level)
14807
+ });
14808
+ if (plan.status === "blocked") throw Object.assign(new Error(plan.message), { code: "BLOCK_SELECTION_REJECTED" });
14645
14809
  }
14646
- const session = result.threadId ? this.knownSessions.get(result.threadId)?.deref() : void 0;
14810
+ const result = await memory.expandBlock(id, target, "user");
14811
+ this.pendingSurfaceSync.delete(`${key}\0${id}`);
14812
+ this.queueSurfaceSync(key, id, "user-expansion");
14647
14813
  if (session && this.namespaceFor(session) === key) {
14648
14814
  await this.syncPendingRetrySurface(session, memory);
14649
- if (this.pendingSurfaceSync.has(`${key}\0${id}`)) {
14650
- throw new Error(`\u65E0\u6CD5\u5C06 Block ${id} \u7684\u5F53\u524D\u4F1A\u8BDD\u4E0A\u4E0B\u6587\u5C55\u5F00\u5230 L${result.level}\uFF1B\u76EE\u6807\u5185\u5BB9\u8D85\u8FC7\u5F53\u524D\u4E0A\u4E0B\u6587\u5BB9\u91CF\u6216\u4F1A\u8BDD\u6B63\u5728\u6574\u7406`);
14651
- }
14652
14815
  }
14653
- return { ...result, surfaceLevel: memory.listBlocks().find(({ id: blockId }) => blockId === id)?.surfaceCurrentLevel };
14816
+ return {
14817
+ ...result,
14818
+ surfaceLevel: memory.listBlocks().find(({ id: blockId }) => blockId === id)?.surfaceCurrentLevel,
14819
+ surfaceSync: this.adminBlockSurfaceSync(key, id) ?? { status: "applied", message: `\u5DF2\u5E94\u7528 L${result.level}\uFF0C\u4F9B\u52A9\u624B\u540E\u7EED\u56DE\u590D\u53C2\u8003\u3002` }
14820
+ };
14654
14821
  } finally {
14655
14822
  if (owned) await memory.close();
14656
14823
  }
@@ -15294,6 +15461,11 @@ function surfaceCheckpointTokens(text3) {
15294
15461
  source: dshMessageSource()
15295
15462
  })));
15296
15463
  }
15464
+ function surfaceCapacityKey(session) {
15465
+ const context = session.requestContext?.();
15466
+ const header = session.requestHeader?.();
15467
+ return JSON.stringify([context?.provider, context?.model, context?.contextWindow, header?.config.maxTokens, header?.tools]);
15468
+ }
15297
15469
  function originalCheckpointSourceTokens(session, seq) {
15298
15470
  const visited = /* @__PURE__ */ new Set();
15299
15471
  const visit = (sourceSeq) => {
@@ -17489,6 +17661,7 @@ async function memories(runtime, url) {
17489
17661
  summary: source.l1Summary,
17490
17662
  keypoints: source.l2Keypoints,
17491
17663
  currentLevel,
17664
+ surfaceLevelKnown: source.surfaceCurrentLevel !== void 0,
17492
17665
  targetLevel,
17493
17666
  currentTokens: currentMetrics?.tokens ?? 0,
17494
17667
  l5Tokens,
@@ -17496,6 +17669,7 @@ async function memories(runtime, url) {
17496
17669
  layerTokens,
17497
17670
  distanceFromLatest: age,
17498
17671
  expansionSource: source.lastLiftedAt ? source.lastLiftedBy ?? "legacy" : null,
17672
+ surfaceSync: source.lastLiftedBy === "user" ? runtime.adminBlockSurfaceSync?.(namespace, source.id) ?? (source.surfaceCurrentLevel === void 0 || currentLevel !== targetLevel && targetLevel === source.pointerAnchorLevel ? { status: "pending", reason: "session-unloaded", message: "\u5DF2\u4FDD\u5B58\u9009\u62E9\uFF0C\u6253\u5F00\u8FD9\u6BB5\u5BF9\u8BDD\u540E\u751F\u6548\u3002" } : { status: "applied", message: "\u5DF2\u5E94\u7528\uFF0C\u4F9B\u52A9\u624B\u540E\u7EED\u56DE\u590D\u53C2\u8003\u3002" }) : null,
17499
17673
  lastLiftedAt: source.lastLiftedAt,
17500
17674
  sourceMessages: block.messages.length,
17501
17675
  createdAt: source.createdAt,
@@ -17647,7 +17821,14 @@ async function expandBlock(runtime, url) {
17647
17821
  if (!blockId) throw new AdminHttpError(400, "blockId is required");
17648
17822
  if (blockId.startsWith("virtual:")) throw new AdminHttpError(409, "Recovered legacy fragments are read-only display data");
17649
17823
  if (!/^L?[0-5]$/i.test(target)) throw new AdminHttpError(400, "level must be L0 through L5");
17650
- return runtime.adminExpandBlock(namespace, blockId, target);
17824
+ try {
17825
+ return await runtime.adminExpandBlock(namespace, blockId, target);
17826
+ } catch (error) {
17827
+ if (error instanceof Error && "code" in error && error.code === "BLOCK_SELECTION_REJECTED") {
17828
+ throw new AdminHttpError(409, error.message, { code: "BLOCK_SELECTION_REJECTED" });
17829
+ }
17830
+ throw error;
17831
+ }
17651
17832
  }
17652
17833
  async function retryBlockSummary(runtime, url) {
17653
17834
  const namespace = url.searchParams.get("namespace")?.trim() ?? "";