stratagate-dsh 0.3.40 → 0.3.41

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +732 -732
  2. package/CONTRIBUTING.md +99 -88
  3. package/CONTRIBUTING.zh-CN.md +90 -88
  4. package/LICENSE +21 -21
  5. package/README.md +510 -489
  6. package/README.zh-CN.md +514 -493
  7. package/benchmarks/locomo-conv26-r8-final.json +146 -146
  8. package/cordis.patch.yml +16 -16
  9. package/dist/client.d.ts +1 -1
  10. package/dist/client.js +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/plugin.js +130 -49
  13. package/dist/plugin.js.map +1 -1
  14. package/dist/repair-profile.js +0 -0
  15. package/dist/repair-profile.js.map +1 -1
  16. package/docs/ARCHITECTURE.md +282 -282
  17. package/docs/DSH.md +337 -337
  18. package/docs/DSH.zh-CN.md +325 -325
  19. package/docs/EVALUATION.md +189 -189
  20. package/docs/EXTERNAL_MEMORY_IMPORT.zh-CN.md +99 -99
  21. package/docs/MEMORY_TOPICS.zh-CN.md +51 -51
  22. package/docs/benchmarks/issue-128-windows-review.json +104 -104
  23. package/docs/benchmarks/issue-128-windows.json +103 -103
  24. package/docs/database-access.md +32 -32
  25. package/docs/dreaming-agent.md +69 -69
  26. package/docs/event-extractor.md +48 -48
  27. package/docs/feedback.md +50 -50
  28. package/docs/issue-128-lease-cache-review-followup.md +55 -55
  29. package/docs/issue-128-review-followup.md +58 -58
  30. package/docs/knowledge-graph.md +38 -38
  31. package/docs/npm-release.md +55 -53
  32. package/docs/surface-maintenance.md +36 -36
  33. package/docs/user-operation-priority.md +46 -39
  34. package/docs/validation/issue119-after.json +30 -0
  35. package/docs/validation/issue119-before.json +94 -0
  36. package/docs/validation/issue119.md +41 -41
  37. package/docs/validation/workspace-cleanup-20261020.md +36 -36
  38. package/package.json +256 -255
  39. package/packages/core/examples/basic.ts +87 -87
  40. package/packages/core/src/blocks.ts +442 -442
  41. package/packages/core/src/weights.ts +21 -21
  42. package/screenshots.json +8 -8
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dsh-host-resolution.ts","../src/bootstrap.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\r\nimport { createRequire, registerHooks } from 'node:module'\r\nimport { dirname, isAbsolute, join, relative } from 'node:path'\r\nimport { fileURLToPath, pathToFileURL } from 'node:url'\r\n\r\nconst HOST_PACKAGES = [\r\n '@deepseek-ai/cordis',\r\n '@deepseek-ai/dsh-agent-default-model',\r\n '@deepseek-ai/dsh-client-ui-conversation',\r\n '@deepseek-ai/dsh-llm',\r\n '@deepseek-ai/dsh-native-command',\r\n '@deepseek-ai/dsh-session',\r\n '@deepseek-ai/dsh-session-format',\r\n '@deepseek-ai/dsh-session-format-catalog',\r\n '@deepseek-ai/dsh-session-format-v0-to-v1',\r\n '@deepseek-ai/dsh-settings',\r\n '@deepseek-ai/dsh-system-prompt',\r\n '@deepseek-ai/dsh-tools',\r\n '@deepseek-ai/schemastery',\r\n] as const\r\n\r\nconst installedHooks = Symbol.for('stratagate.dsh-host-resolution.v1')\r\n\r\nfunction isWithin(path: string, root: string): boolean {\r\n const child = relative(root, path)\r\n return child === '' || (!child.startsWith('..') && !isAbsolute(child))\r\n}\r\n\r\nfunction profileDirectory(start: string): string | undefined {\r\n let directory = start\r\n for (;;) {\r\n const manifestPath = join(directory, 'package.json')\r\n if (existsSync(manifestPath)) {\r\n try {\r\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dsh?: { profile?: unknown } }\r\n if (manifest.dsh?.profile && typeof manifest.dsh.profile === 'object') return directory\r\n } catch {}\r\n }\r\n const parent = dirname(directory)\r\n if (parent === directory) return undefined\r\n directory = parent\r\n }\r\n}\r\n\r\nfunction hostPackage(specifier: string): boolean {\r\n return HOST_PACKAGES.some((name) => specifier === name || specifier.startsWith(`${name}/`))\r\n}\r\n\r\n/**\r\n * Force only StrataGate's DSH imports through the installation-owned fallback\r\n * created by DSH. The hook neither deletes nor rewrites the profile's package\r\n * tree, and imports belonging to the host or other plugins are untouched.\r\n */\r\nexport function installDshHostResolution(moduleUrl: string): boolean {\r\n const packageDirectory = dirname(dirname(fileURLToPath(moduleUrl)))\r\n const profile = profileDirectory(packageDirectory)\r\n if (!profile) return false\r\n\r\n const globalState = globalThis as typeof globalThis & { [installedHooks]?: Set<string> }\r\n const installed = globalState[installedHooks] ??= new Set<string>()\r\n const key = `${profile}\\u0000${packageDirectory}`\r\n if (installed.has(key)) return true\r\n\r\n const fallbackModules = join(dirname(profile), 'node_modules')\r\n const hostRequire = createRequire(join(fallbackModules, '.stratagate-host-resolution.cjs'))\r\n registerHooks({\r\n resolve(specifier, context, nextResolve) {\r\n const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined\r\n if (!hostPackage(specifier) || !parent || !isWithin(parent, packageDirectory)) {\r\n return nextResolve(specifier, context)\r\n }\r\n try {\r\n return { url: pathToFileURL(hostRequire.resolve(specifier)).href, shortCircuit: true }\r\n } catch (cause) {\r\n if (specifier === '@deepseek-ai/dsh-session-format-v0-to-v1'\r\n || specifier === '@deepseek-ai/dsh-session-format-catalog') {\r\n return nextResolve(specifier, context)\r\n }\r\n throw new Error(\r\n `StrataGate cannot resolve host-provided DSH package ${JSON.stringify(specifier)} from ${fallbackModules}. `\r\n + 'Start StrataGate through the DSH profile launcher so the host can prepare its module fallback.',\r\n { cause },\r\n )\r\n }\r\n },\r\n })\r\n installed.add(key)\r\n return true\r\n}\r\n","import { installDshHostResolution } from './dsh-host-resolution.js'\r\n\r\n// DSH prepares its installation-owned module fallback before it imports a\r\n// profile bundle. Install the narrowly-scoped resolver first, then load the\r\n// implementation so stale profile-local peers cannot win ESM resolution.\r\ninstallDshHostResolution(import.meta.url)\r\n\r\n// This file and src/index.ts are separate tsup entries. The runtime path is\r\n// intentionally external so the implementation is instantiated only after\r\n// the resolver above is active.\r\n// @ts-expect-error dist/plugin.js is emitted from src/index.ts during build.\r\nconst plugin = await import('./plugin.js') as typeof import('./index.js')\r\n\r\nexport const name = plugin.name\r\nexport const inject = plugin.inject\r\nexport const STRATAGATE_SETTINGS_NAMESPACE = plugin.STRATAGATE_SETTINGS_NAMESPACE\r\nexport const Config = plugin.Config\r\nexport const apply = plugin.apply\r\nexport type PluginConfig = import('./index.js').PluginConfig\r\n"],"mappings":";AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe,qBAAqB;AAC7C,SAAS,SAAS,YAAY,MAAM,gBAAgB;AACpD,SAAS,eAAe,qBAAqB;AAE7C,IAAM,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,iBAAiB,uBAAO,IAAI,mCAAmC;AAErE,SAAS,SAAS,MAAc,MAAuB;AACrD,QAAM,QAAQ,SAAS,MAAM,IAAI;AACjC,SAAO,UAAU,MAAO,CAAC,MAAM,WAAW,IAAI,KAAK,CAAC,WAAW,KAAK;AACtE;AAEA,SAAS,iBAAiB,OAAmC;AAC3D,MAAI,YAAY;AAChB,aAAS;AACP,UAAM,eAAe,KAAK,WAAW,cAAc;AACnD,QAAI,WAAW,YAAY,GAAG;AAC5B,UAAI;AACF,cAAM,WAAW,KAAK,MAAM,aAAa,cAAc,MAAM,CAAC;AAC9D,YAAI,SAAS,KAAK,WAAW,OAAO,SAAS,IAAI,YAAY,SAAU,QAAO;AAAA,MAChF,QAAQ;AAAA,MAAC;AAAA,IACX;AACA,UAAM,SAAS,QAAQ,SAAS;AAChC,QAAI,WAAW,UAAW,QAAO;AACjC,gBAAY;AAAA,EACd;AACF;AAEA,SAAS,YAAY,WAA4B;AAC/C,SAAO,cAAc,KAAK,CAACA,UAAS,cAAcA,SAAQ,UAAU,WAAW,GAAGA,KAAI,GAAG,CAAC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M,QAAQ,OAAO;","names":["name"]}
1
+ {"version":3,"sources":["../src/dsh-host-resolution.ts","../src/bootstrap.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { createRequire, registerHooks } from 'node:module'\nimport { dirname, isAbsolute, join, relative } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nconst HOST_PACKAGES = [\n '@deepseek-ai/cordis',\n '@deepseek-ai/dsh-agent-default-model',\n '@deepseek-ai/dsh-client-ui-conversation',\n '@deepseek-ai/dsh-llm',\n '@deepseek-ai/dsh-native-command',\n '@deepseek-ai/dsh-session',\n '@deepseek-ai/dsh-session-format',\n '@deepseek-ai/dsh-session-format-catalog',\n '@deepseek-ai/dsh-session-format-v0-to-v1',\n '@deepseek-ai/dsh-settings',\n '@deepseek-ai/dsh-system-prompt',\n '@deepseek-ai/dsh-tools',\n '@deepseek-ai/schemastery',\n] as const\n\nconst installedHooks = Symbol.for('stratagate.dsh-host-resolution.v1')\n\nfunction isWithin(path: string, root: string): boolean {\n const child = relative(root, path)\n return child === '' || (!child.startsWith('..') && !isAbsolute(child))\n}\n\nfunction profileDirectory(start: string): string | undefined {\n let directory = start\n for (;;) {\n const manifestPath = join(directory, 'package.json')\n if (existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dsh?: { profile?: unknown } }\n if (manifest.dsh?.profile && typeof manifest.dsh.profile === 'object') return directory\n } catch {}\n }\n const parent = dirname(directory)\n if (parent === directory) return undefined\n directory = parent\n }\n}\n\nfunction hostPackage(specifier: string): boolean {\n return HOST_PACKAGES.some((name) => specifier === name || specifier.startsWith(`${name}/`))\n}\n\n/**\n * Force only StrataGate's DSH imports through the installation-owned fallback\n * created by DSH. The hook neither deletes nor rewrites the profile's package\n * tree, and imports belonging to the host or other plugins are untouched.\n */\nexport function installDshHostResolution(moduleUrl: string): boolean {\n const packageDirectory = dirname(dirname(fileURLToPath(moduleUrl)))\n const profile = profileDirectory(packageDirectory)\n if (!profile) return false\n\n const globalState = globalThis as typeof globalThis & { [installedHooks]?: Set<string> }\n const installed = globalState[installedHooks] ??= new Set<string>()\n const key = `${profile}\\u0000${packageDirectory}`\n if (installed.has(key)) return true\n\n const fallbackModules = join(dirname(profile), 'node_modules')\n const hostRequire = createRequire(join(fallbackModules, '.stratagate-host-resolution.cjs'))\n registerHooks({\n resolve(specifier, context, nextResolve) {\n const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined\n if (!hostPackage(specifier) || !parent || !isWithin(parent, packageDirectory)) {\n return nextResolve(specifier, context)\n }\n try {\n return { url: pathToFileURL(hostRequire.resolve(specifier)).href, shortCircuit: true }\n } catch (cause) {\n if (specifier === '@deepseek-ai/dsh-session-format-v0-to-v1'\n || specifier === '@deepseek-ai/dsh-session-format-catalog') {\n return nextResolve(specifier, context)\n }\n throw new Error(\n `StrataGate cannot resolve host-provided DSH package ${JSON.stringify(specifier)} from ${fallbackModules}. `\n + 'Start StrataGate through the DSH profile launcher so the host can prepare its module fallback.',\n { cause },\n )\n }\n },\n })\n installed.add(key)\n return true\n}\n","import { installDshHostResolution } from './dsh-host-resolution.js'\n\n// DSH prepares its installation-owned module fallback before it imports a\n// profile bundle. Install the narrowly-scoped resolver first, then load the\n// implementation so stale profile-local peers cannot win ESM resolution.\ninstallDshHostResolution(import.meta.url)\n\n// This file and src/index.ts are separate tsup entries. The runtime path is\n// intentionally external so the implementation is instantiated only after\n// the resolver above is active.\n// @ts-expect-error dist/plugin.js is emitted from src/index.ts during build.\nconst plugin = await import('./plugin.js') as typeof import('./index.js')\n\nexport const name = plugin.name\nexport const inject = plugin.inject\nexport const STRATAGATE_SETTINGS_NAMESPACE = plugin.STRATAGATE_SETTINGS_NAMESPACE\nexport const Config = plugin.Config\nexport const apply = plugin.apply\nexport type PluginConfig = import('./index.js').PluginConfig\n"],"mappings":";AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe,qBAAqB;AAC7C,SAAS,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B,QAAM,kBAAkB,KAAK,QAAQ,OAAO,GAAG,cAAc;AAC7D,QAAM,cAAc,cAAc,KAAK,iBAAiB,iCAAiC,CAAC;AAC1F,gBAAc;AAAA,IACZ,QAAQ,WAAW,SAAS,aAAa;AACvC,YAAM,SAAS,QAAQ,WAAW,WAAW,OAAO,IAAI,cAAc,QAAQ,SAAS,IAAI;AAC3F,UAAI,CAAC,YAAY,SAAS,KAAK,CAAC,UAAU,CAAC,SAAS,QAAQ,gBAAgB,GAAG;AAC7E,eAAO,YAAY,WAAW,OAAO;AAAA,MACvC;AACA,UAAI;AACF,eAAO,EAAE,KAAK,cAAc,YAAY,QAAQ,SAAS,CAAC,EAAE,MAAM,cAAc,KAAK;AAAA,MACvF,SAAS,OAAO;AACd,YAAI,cAAc,8CACb,cAAc,2CAA2C;AAC5D,iBAAO,YAAY,WAAW,OAAO;AAAA,QACvC;AACA,cAAM,IAAI;AAAA,UACR,uDAAuD,KAAK,UAAU,SAAS,CAAC,SAAS,eAAe;AAAA,UAExG,EAAE,MAAM;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACD,YAAU,IAAI,GAAG;AACjB,SAAO;AACT;;;ACnFA,yBAAyB,YAAY,GAAG;AAMxC,IAAM,SAAS,MAAM,OAAO,aAAa;AAElC,IAAM,OAAO,OAAO;AACpB,IAAM,SAAS,OAAO;AACtB,IAAM,gCAAgC,OAAO;AAC7C,IAAM,SAAS,OAAO;AACtB,IAAM,QAAQ,OAAO;","names":["name"]}
package/dist/plugin.js CHANGED
@@ -13729,6 +13729,7 @@ var DRAIN_BASE_BACKOFF_MS = 2e3;
13729
13729
  var DRAIN_MAX_BACKOFF_MS = 6e4;
13730
13730
  var BACKGROUND_WORKER_INITIAL_DELAY_MS = 250;
13731
13731
  var BACKGROUND_WORKER_INTERVAL_MS = 3e3;
13732
+ var SURFACE_MAINTENANCE_MAX_ATTEMPTS = 3;
13732
13733
  function graphProjectionCanRun(job, now = Date.now()) {
13733
13734
  return job.attempts < DERIVATION_MAX_ATTEMPTS && (job.status === "pending" || job.status === "failed" && job.nextRetryAt != null && Date.parse(job.nextRetryAt) <= now);
13734
13735
  }
@@ -14442,8 +14443,19 @@ var StrataGateRuntime = class _StrataGateRuntime {
14442
14443
  this.scheduleSurfaceMaintenance(surface);
14443
14444
  } else if (event.type === "request/context") {
14444
14445
  const limit = surfaceCheckpointLimit(session);
14445
- if (surface.checkpointLimit !== limit) {
14446
- surface.checkpointLimit = limit;
14446
+ const capacityKey = surfaceCapacityKey(session);
14447
+ const limitChanged = surface.checkpointLimit !== limit;
14448
+ const capacityChanged = surface.capacityKey !== void 0 && surface.capacityKey !== capacityKey;
14449
+ surface.checkpointLimit = limit;
14450
+ surface.capacityKey = capacityKey;
14451
+ if (limitChanged || capacityChanged || surface.blockedAt !== void 0 && surface.blockedAt !== surfaceMaintenanceInput(surface)) {
14452
+ this.markSurfaceDirty(session, surface.memory);
14453
+ }
14454
+ } else if (event.type === "request/header") {
14455
+ const capacityKey = surfaceCapacityKey(session);
14456
+ const capacityChanged = surface.capacityKey !== void 0 && surface.capacityKey !== capacityKey;
14457
+ surface.capacityKey = capacityKey;
14458
+ if (capacityChanged || surface.blockedAt !== void 0 && surface.blockedAt !== surfaceMaintenanceInput(surface)) {
14447
14459
  this.markSurfaceDirty(session, surface.memory);
14448
14460
  }
14449
14461
  } else if (String(event.type).startsWith("compaction/") || event.type === "session/end-seed" || event.type === "user/message" && event.surfaceOp !== void 0 && event.surfaceOp !== "append" && !isStrataGateMessageSource(event.data.source)) {
@@ -15115,18 +15127,9 @@ var StrataGateRuntime = class _StrataGateRuntime {
15115
15127
  if (endTurn === null || hostCompactionActive(session)) return false;
15116
15128
  const sourceEventSeqs = sources2 ?? sealedSurfaceSeqs(session, endTurn, block);
15117
15129
  if (!sourceEventSeqs) return false;
15118
- const start = sourceEventSeqs[0];
15119
- const end = sourceEventSeqs.at(-1);
15120
- if (start === void 0 || end === void 0) return false;
15121
15130
  const selected = selectCompressedBlockSurface(session, sourceEventSeqs, block, context);
15122
15131
  if (!selected) return false;
15123
- session.append("user/message", createUserMessage2({
15124
- content: [{ type: "text", text: selected }],
15125
- source: dshMessageSource()
15126
- }), {
15127
- surfaceOp: dshReplaceSurfaceOp(start, end),
15128
- sourceEventSeqs
15129
- });
15132
+ appendBlockSurface(session, block.id, selected, sourceEventSeqs);
15130
15133
  this.surfaceFlushPending.add(session);
15131
15134
  levels.set(block.id, checkpointLevel(selected) ?? context.level);
15132
15135
  return true;
@@ -15179,13 +15182,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15179
15182
  );
15180
15183
  if (!text3) continue;
15181
15184
  if (node.text !== text3) {
15182
- session.append("user/message", createUserMessage2({
15183
- content: [{ type: "text", text: text3 }],
15184
- source: dshMessageSource()
15185
- }), {
15186
- surfaceOp: dshReplaceSurfaceOp(node.seq, node.seq),
15187
- sourceEventSeqs: [node.seq]
15188
- });
15185
+ appendBlockSurface(session, block.id, text3, [node.seq]);
15189
15186
  this.surfaceFlushPending.add(session);
15190
15187
  changed = true;
15191
15188
  }
@@ -15207,12 +15204,15 @@ var StrataGateRuntime = class _StrataGateRuntime {
15207
15204
  const node = current.get(block.id);
15208
15205
  const endTurn = node ? null : dshTurnAtBlockEnd(session, block);
15209
15206
  const seqs = node ? [node.seq] : endTurn === null ? null : sealedSurfaceSeqs(session, endTurn, block);
15210
- 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" };
15207
+ if (!seqs?.length || !safeBlockSurfaceRange(session, block.id, seqs)) return {
15208
+ status: "blocked",
15209
+ reason: "source-unavailable",
15210
+ 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"
15211
+ };
15211
15212
  const relief = [];
15212
15213
  const window = session.requestContext?.()?.contextWindow;
15213
15214
  if (node?.text !== text3 && typeof window === "number" && Number.isInteger(window) && window > 0) {
15214
- const start = seqs[0];
15215
- const end = seqs.at(-1);
15215
+ const replaced = new Set(seqs);
15216
15216
  let before = 0;
15217
15217
  let removed = 0;
15218
15218
  for (const seq of session.surface.nodes) {
@@ -15220,7 +15220,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15220
15220
  const message = event && session.deriveEventMessage(event);
15221
15221
  const tokens = message ? estimateTokens(JSON.stringify(message)) : 0;
15222
15222
  before += tokens;
15223
- if (seq >= start && seq <= end) removed += tokens;
15223
+ if (replaced.has(seq)) removed += tokens;
15224
15224
  }
15225
15225
  const header = session.requestHeader?.();
15226
15226
  const reserved = (header?.config.maxTokens ?? 0) + (header?.tools?.length ? estimateTokens(JSON.stringify(header.tools)) : 0);
@@ -15230,7 +15230,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15230
15230
  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);
15231
15231
  for (const candidate of candidates) {
15232
15232
  const checkpoint = current.get(candidate.id);
15233
- if (!checkpoint || checkpoint.seq >= start && checkpoint.seq <= end) continue;
15233
+ if (!checkpoint || replaced.has(checkpoint.seq)) continue;
15234
15234
  const level = checkpointLevel(checkpoint.text);
15235
15235
  if (level === void 0 || level === 0) continue;
15236
15236
  const original = this.cachedCheckpointTokens(session, checkpoint);
@@ -15290,22 +15290,13 @@ var StrataGateRuntime = class _StrataGateRuntime {
15290
15290
  }
15291
15291
  const { text: text3, seqs, relief } = plan;
15292
15292
  for (const replacement of relief) {
15293
- session.append("user/message", createUserMessage2({
15294
- content: [{ type: "text", text: replacement.text }],
15295
- source: dshMessageSource()
15296
- }), { surfaceOp: dshReplaceSurfaceOp(replacement.seq, replacement.seq), sourceEventSeqs: [replacement.seq] });
15293
+ appendBlockSurface(session, replacement.id, replacement.text, [replacement.seq]);
15297
15294
  levels.set(replacement.id, replacement.level);
15298
15295
  this.surfaceFlushPending.add(session);
15299
15296
  }
15300
15297
  const node = currentBlockSurfaceMessages(session).get(block.id);
15301
15298
  if (node?.text !== text3) {
15302
- const start = seqs[0];
15303
- const end = seqs.at(-1);
15304
- if (start === void 0 || end === void 0) return false;
15305
- session.append("user/message", createUserMessage2({
15306
- content: [{ type: "text", text: text3 }],
15307
- source: dshMessageSource()
15308
- }), { surfaceOp: dshReplaceSurfaceOp(start, end), sourceEventSeqs: seqs });
15299
+ appendBlockSurface(session, block.id, text3, seqs);
15309
15300
  this.surfaceFlushPending.add(session);
15310
15301
  }
15311
15302
  levels.set(block.id, context.level);
@@ -15357,13 +15348,19 @@ var StrataGateRuntime = class _StrataGateRuntime {
15357
15348
  return tokens;
15358
15349
  }
15359
15350
  /** Finish deferred sealing or user expansion only after the target surface is applied. */
15360
- async syncPendingRetrySurface(session, memory, userOnly = false) {
15351
+ async syncPendingRetrySurface(session, memory, userOnly = false, force = false) {
15352
+ if (!force && this.surfaceRetryBlocked(session, memory)) return;
15361
15353
  const levels = /* @__PURE__ */ new Map();
15362
- const completed = this.applyPendingRetrySurface(session, memory, levels, userOnly);
15363
- if (completed.length === 0) return;
15364
- await this.commitSurfaceLevels(memory, levels);
15365
- await this.flushSurface(session);
15366
- this.completeSurfaceRequests(completed);
15354
+ try {
15355
+ const completed = this.applyPendingRetrySurface(session, memory, levels, userOnly);
15356
+ if (completed.length === 0) return;
15357
+ await this.commitSurfaceLevels(memory, levels);
15358
+ await this.flushSurface(session);
15359
+ this.completeSurfaceRequests(completed);
15360
+ } catch (error) {
15361
+ this.recordSurfaceFailure(session, memory, error);
15362
+ throw error;
15363
+ }
15367
15364
  }
15368
15365
  applyPendingRetrySurface(session, memory, levels, userOnly = false, recoverable) {
15369
15366
  const namespace = this.namespaceFor(session);
@@ -15427,6 +15424,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15427
15424
  /** Read-only in the common case; render only explicit lifts or oversized checkpoints. */
15428
15425
  async syncRequestSurface(session, memory) {
15429
15426
  if (hostCompactionActive(session)) return;
15427
+ if (this.surfaceRetryBlocked(session, memory)) return;
15430
15428
  const current = currentBlockSurfaceMessages(session);
15431
15429
  const limit = surfaceCheckpointLimit(session);
15432
15430
  const repair = /* @__PURE__ */ new Set();
@@ -15455,20 +15453,61 @@ var StrataGateRuntime = class _StrataGateRuntime {
15455
15453
  }
15456
15454
  markSurfaceDirty(session, memory) {
15457
15455
  if (this.closed) return;
15456
+ const state = this.ensureSurfaceMaintenanceState(session, memory);
15457
+ state.dirty = true;
15458
+ state.generation += 1;
15459
+ if (state.blockedAt !== void 0 && state.blockedAt !== surfaceMaintenanceInput(state)) {
15460
+ delete state.blockedAt;
15461
+ state.failures = 0;
15462
+ }
15463
+ this.scheduleSurfaceMaintenance(state);
15464
+ }
15465
+ ensureSurfaceMaintenanceState(session, memory) {
15458
15466
  const key = String(session.id);
15459
15467
  let state = this.surfaceMaintenance.get(key);
15460
15468
  if (!state || state.session !== session || state.memory !== memory) {
15461
15469
  if (state?.timer) clearTimeout(state.timer);
15462
15470
  if (state) state.generation += 1;
15463
- state = { session, memory, dirty: true, generation: 0, busy: hostTurnActive(session), failures: 0, checkpointLimit: surfaceCheckpointLimit(session) };
15471
+ state = {
15472
+ session,
15473
+ memory,
15474
+ dirty: true,
15475
+ generation: 0,
15476
+ busy: hostTurnActive(session),
15477
+ failures: 0,
15478
+ checkpointLimit: surfaceCheckpointLimit(session)
15479
+ };
15464
15480
  this.surfaceMaintenance.set(key, state);
15465
15481
  }
15482
+ return state;
15483
+ }
15484
+ clearSurfaceFailure(session, memory) {
15485
+ const state = this.surfaceMaintenance.get(String(session.id));
15486
+ if (state?.session !== session || state.memory !== memory) return;
15487
+ delete state.blockedAt;
15488
+ state.failures = 0;
15489
+ }
15490
+ surfaceRetryBlocked(session, memory) {
15491
+ const state = this.surfaceMaintenance.get(String(session.id));
15492
+ if (state?.session !== session || state.memory !== memory || state.blockedAt === void 0) return false;
15493
+ if (state.blockedAt !== surfaceMaintenanceInput(state)) {
15494
+ this.clearSurfaceFailure(session, memory);
15495
+ return false;
15496
+ }
15497
+ return true;
15498
+ }
15499
+ recordSurfaceFailure(session, memory, error) {
15500
+ const state = this.ensureSurfaceMaintenanceState(session, memory);
15466
15501
  state.dirty = true;
15467
- state.generation += 1;
15468
- this.scheduleSurfaceMaintenance(state);
15502
+ state.failures += 1;
15503
+ if (surfaceFailureIsPermanent(error) || state.failures >= SURFACE_MAINTENANCE_MAX_ATTEMPTS) {
15504
+ state.blockedAt = surfaceMaintenanceInput(state);
15505
+ if (state.timer) clearTimeout(state.timer);
15506
+ state.timer = void 0;
15507
+ }
15469
15508
  }
15470
15509
  scheduleSurfaceMaintenance(state, delay2 = 25) {
15471
- if (this.closed || this.surfaceMaintenance.get(String(state.session.id)) !== state || !state.dirty || state.busy || state.timer || state.run || this.surfaceAssemblyReaders.get(state.session)) return;
15510
+ if (this.closed || this.surfaceMaintenance.get(String(state.session.id)) !== state || !state.dirty || state.blockedAt !== void 0 || state.busy || state.timer || state.run || this.surfaceAssemblyReaders.get(state.session)) return;
15472
15511
  state.timer = setTimeout(() => {
15473
15512
  state.timer = void 0;
15474
15513
  void this.runSurfaceMaintenance(state.session);
@@ -15482,7 +15521,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
15482
15521
  if (state.run) return state.run;
15483
15522
  if (state.timer) clearTimeout(state.timer);
15484
15523
  state.timer = void 0;
15485
- if (!state.dirty || state.busy || this.surfaceAssemblyReaders.get(session) || hostTurnActive(session) || hostCompactionActive(session)) return;
15524
+ if (!state.dirty || state.blockedAt !== void 0 || state.busy || this.surfaceAssemblyReaders.get(session) || hostTurnActive(session) || hostCompactionActive(session)) return;
15486
15525
  const generation = state.generation;
15487
15526
  const run = (async () => {
15488
15527
  await this.drainTails.get(String(session.id));
@@ -15512,6 +15551,11 @@ var StrataGateRuntime = class _StrataGateRuntime {
15512
15551
  if (error instanceof StorageConflictError) {
15513
15552
  await state.memory.reloadFromStorage().catch((reloadError) => this.onIngestError(reloadError));
15514
15553
  }
15554
+ if (state.generation !== generation) {
15555
+ state.failures = 0;
15556
+ } else if (surfaceFailureIsPermanent(error) || state.failures >= SURFACE_MAINTENANCE_MAX_ATTEMPTS) {
15557
+ state.blockedAt = surfaceMaintenanceInput(state);
15558
+ }
15515
15559
  this.onIngestError(error);
15516
15560
  }).finally(() => {
15517
15561
  state.run = void 0;
@@ -16643,10 +16687,11 @@ var StrataGateRuntime = class _StrataGateRuntime {
16643
16687
  if (plan.status === "blocked") throw Object.assign(new Error(plan.message), { code: "BLOCK_SELECTION_REJECTED" });
16644
16688
  }
16645
16689
  const result = await memory.expandBlock(id, target, "user");
16690
+ if (session && this.namespaceFor(session) === key) this.clearSurfaceFailure(session, memory);
16646
16691
  this.pendingSurfaceSync.delete(`${key}\0${id}`);
16647
16692
  this.queueSurfaceSync(key, id, "user-expansion");
16648
16693
  if (session && this.namespaceFor(session) === key) {
16649
- await this.syncPendingRetrySurface(session, memory);
16694
+ await this.syncPendingRetrySurface(session, memory, false, true);
16650
16695
  }
16651
16696
  return {
16652
16697
  ...result,
@@ -17233,8 +17278,9 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17233
17278
  start: open2.start,
17234
17279
  end: event.seq,
17235
17280
  nodes: currentSurface.filter((seq) => {
17236
- if (seq > open2.start && seq < event.seq) return true;
17237
17281
  const current = session.eventAt(seq);
17282
+ if (!replaceableBlockEvent(current, block.id)) return false;
17283
+ if (seq > open2.start && seq < event.seq) return true;
17238
17284
  return current?.type === "tool/result" && current.surfaceOp !== "append" && current.sourceEventSeqs?.some((source) => source > open2.start && source < event.seq);
17239
17285
  })
17240
17286
  });
@@ -17258,7 +17304,42 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17258
17304
  const startIndex = currentSurface.indexOf(start);
17259
17305
  const endIndex = currentSurface.indexOf(end);
17260
17306
  if (startIndex < 0 || endIndex < startIndex) return null;
17261
- return currentSurface.slice(startIndex, endIndex + 1);
17307
+ const range = currentSurface.slice(startIndex, endIndex + 1);
17308
+ return safeBlockSurfaceRange(session, block.id, range) ? range : null;
17309
+ }
17310
+ function replaceableBlockEvent(event, blockId) {
17311
+ if (event?.type === "assistant/message" || event?.type === "tool/result") return true;
17312
+ return event?.type === "user/message" && (event.data.source.kind === "user" || blockSurfaceMessage(event)?.id === blockId);
17313
+ }
17314
+ function safeBlockSurfaceRange(session, blockId, seqs) {
17315
+ if (seqs.length === 0) return false;
17316
+ const start = session.surface.nodes.indexOf(seqs[0]);
17317
+ return start >= 0 && seqs.every((seq, index) => session.surface.nodes[start + index] === seq && replaceableBlockEvent(session.eventAt(seq), blockId));
17318
+ }
17319
+ function appendBlockSurface(session, blockId, text3, seqs) {
17320
+ if (!safeBlockSurfaceRange(session, blockId, seqs)) {
17321
+ throw Object.assign(new Error("StrataGate surface replacement no longer owns its complete source range"), { retryable: false });
17322
+ }
17323
+ session.append("user/message", createUserMessage2({
17324
+ content: [{ type: "text", text: text3 }],
17325
+ source: dshMessageSource()
17326
+ }), {
17327
+ surfaceOp: dshReplaceSurfaceOp(seqs[0], seqs.at(-1)),
17328
+ sourceEventSeqs: seqs
17329
+ });
17330
+ }
17331
+ function surfaceMaintenanceInput(state) {
17332
+ return `${state.memory.storageRevision}:${surfaceCapacityKey(state.session)}:${state.session.surface?.nodes.join(",") ?? ""}`;
17333
+ }
17334
+ function surfaceFailureIsPermanent(error) {
17335
+ const seen = /* @__PURE__ */ new Set();
17336
+ for (let current = error; current && typeof current === "object" && !seen.has(current); ) {
17337
+ seen.add(current);
17338
+ const failure = current;
17339
+ if (failure.retryable === false || typeof failure.message === "string" && /^surface replace:/.test(failure.message)) return true;
17340
+ current = failure.cause;
17341
+ }
17342
+ return false;
17262
17343
  }
17263
17344
  function checkpointLevel(text3) {
17264
17345
  const match = text3.match(/(?:^|\n)Block: [^|\n]+ \| Turns: \d+-\d+ \| Level: L([0-5])(?:\s|$)/mu);