dsh-boost 0.0.0-stage → 0.1.0

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 (110) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.en.md +476 -0
  4. package/README.md +408 -2
  5. package/cordis.patch.yml +40 -0
  6. package/dist/admission/fixed-cost.d.ts +23 -0
  7. package/dist/admission/fixed-cost.js +61 -0
  8. package/dist/admission/fixed-cost.js.map +1 -0
  9. package/dist/admission/ledger.d.ts +113 -0
  10. package/dist/admission/ledger.js +176 -0
  11. package/dist/admission/ledger.js.map +1 -0
  12. package/dist/admission/retrieval.d.ts +65 -0
  13. package/dist/admission/retrieval.js +162 -0
  14. package/dist/admission/retrieval.js.map +1 -0
  15. package/dist/admission/usage.d.ts +75 -0
  16. package/dist/admission/usage.js +124 -0
  17. package/dist/admission/usage.js.map +1 -0
  18. package/dist/config.d.ts +43 -0
  19. package/dist/config.js +103 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/gate/binding.d.ts +113 -0
  22. package/dist/gate/binding.js +297 -0
  23. package/dist/gate/binding.js.map +1 -0
  24. package/dist/gate/decide.d.ts +82 -0
  25. package/dist/gate/decide.js +163 -0
  26. package/dist/gate/decide.js.map +1 -0
  27. package/dist/gate/guard.d.ts +69 -0
  28. package/dist/gate/guard.js +195 -0
  29. package/dist/gate/guard.js.map +1 -0
  30. package/dist/gate/invalidate.d.ts +112 -0
  31. package/dist/gate/invalidate.js +111 -0
  32. package/dist/gate/invalidate.js.map +1 -0
  33. package/dist/gate/plan.d.ts +86 -0
  34. package/dist/gate/plan.js +222 -0
  35. package/dist/gate/plan.js.map +1 -0
  36. package/dist/hooks/clock.d.ts +68 -0
  37. package/dist/hooks/clock.js +82 -0
  38. package/dist/hooks/clock.js.map +1 -0
  39. package/dist/hooks/execute.d.ts +79 -0
  40. package/dist/hooks/execute.js +128 -0
  41. package/dist/hooks/execute.js.map +1 -0
  42. package/dist/hooks/llm-stream.d.ts +276 -0
  43. package/dist/hooks/llm-stream.js +1008 -0
  44. package/dist/hooks/llm-stream.js.map +1 -0
  45. package/dist/hooks/pending.d.ts +89 -0
  46. package/dist/hooks/pending.js +115 -0
  47. package/dist/hooks/pending.js.map +1 -0
  48. package/dist/hooks/post-execute.d.ts +247 -0
  49. package/dist/hooks/post-execute.js +1776 -0
  50. package/dist/hooks/post-execute.js.map +1 -0
  51. package/dist/hooks/session-state.d.ts +158 -0
  52. package/dist/hooks/session-state.js +168 -0
  53. package/dist/hooks/session-state.js.map +1 -0
  54. package/dist/hooks/synthesize.d.ts +74 -0
  55. package/dist/hooks/synthesize.js +100 -0
  56. package/dist/hooks/synthesize.js.map +1 -0
  57. package/dist/host/loader.d.ts +23 -0
  58. package/dist/host/loader.js +31 -0
  59. package/dist/host/loader.js.map +1 -0
  60. package/dist/host/platform.d.ts +18 -0
  61. package/dist/host/platform.js +19 -0
  62. package/dist/host/platform.js.map +1 -0
  63. package/dist/host/root.d.ts +18 -0
  64. package/dist/host/root.js +43 -0
  65. package/dist/host/root.js.map +1 -0
  66. package/dist/index.d.ts +13 -0
  67. package/dist/index.js +866 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/projection/apply.d.ts +174 -0
  70. package/dist/projection/apply.js +137 -0
  71. package/dist/projection/apply.js.map +1 -0
  72. package/dist/projection/canonicalise.d.ts +43 -0
  73. package/dist/projection/canonicalise.js +43 -0
  74. package/dist/projection/canonicalise.js.map +1 -0
  75. package/dist/projection/counters.d.ts +65 -0
  76. package/dist/projection/counters.js +88 -0
  77. package/dist/projection/counters.js.map +1 -0
  78. package/dist/projection/truncate.d.ts +47 -0
  79. package/dist/projection/truncate.js +57 -0
  80. package/dist/projection/truncate.js.map +1 -0
  81. package/dist/prompt/protocol.d.ts +45 -0
  82. package/dist/prompt/protocol.js +56 -0
  83. package/dist/prompt/protocol.js.map +1 -0
  84. package/dist/receipts/store.d.ts +198 -0
  85. package/dist/receipts/store.js +734 -0
  86. package/dist/receipts/store.js.map +1 -0
  87. package/dist/scope/doc.d.ts +117 -0
  88. package/dist/scope/doc.js +158 -0
  89. package/dist/scope/doc.js.map +1 -0
  90. package/dist/scope/resolve.d.ts +91 -0
  91. package/dist/scope/resolve.js +146 -0
  92. package/dist/scope/resolve.js.map +1 -0
  93. package/dist/scope/store.d.ts +135 -0
  94. package/dist/scope/store.js +573 -0
  95. package/dist/scope/store.js.map +1 -0
  96. package/dist/selector/jev.d.ts +93 -0
  97. package/dist/selector/jev.js +171 -0
  98. package/dist/selector/jev.js.map +1 -0
  99. package/dist/tools/boost.d.ts +367 -0
  100. package/dist/tools/boost.js +768 -0
  101. package/dist/tools/boost.js.map +1 -0
  102. package/dist/tools/family.d.ts +26 -0
  103. package/dist/tools/family.js +26 -0
  104. package/dist/tools/family.js.map +1 -0
  105. package/dist/types.d.ts +113 -0
  106. package/dist/types.js +21 -0
  107. package/dist/types.js.map +1 -0
  108. package/locale/en.json +6 -0
  109. package/locale/zh.json +6 -0
  110. package/package.json +75 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAA;AAC5D,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAA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,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,yCAAyC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;IACjF,CAAC;AACH,CAAC","sourcesContent":["/**\n * dsh-boost cordis plugin entry point.\n *\n * The plugin is a plain function plugin: cordis reads `name` and `inject` from\n * the module and calls `apply(ctx, config)`. Only the production assembly lives\n * here — configuration resolution, the two stores the hooks and the control\n * tool share, the hook mounts, the lifecycle events that warm visibility,\n * drive the clock, flush receipts at turn end and clean up on session\n * disposal, and the `boost` tool, all wired once per plugin instance.\n *\n * Wiring failures are contained: a host that lacks the services a mount point\n * lives on must load the plugin with a warning, not die loading it. The data\n * root is `<dshHome>/boost` (`config.dshHome` when the row supplies it, else\n * `$DSH_HOME`), falling back to `~/.dsh/boost`.\n *\n * ## Why the mount disposers are dropped\n *\n * `ctx.on`, `ctx.systemPrompt.section` and `ctx.tools.register` all return a\n * disposer. Every one is deliberately discarded. A cordis plugin entry is\n * mounted in its own context, and disposing that entry tears down everything\n * registered through it; a retained disposer would add nothing except the\n * chance that a stale closure removes a mount owned by a later instance. The\n * assumption is exactly that per-entry ownership — if this plugin is ever\n * mounted into a context it does not own (a shared host context), the\n * disposers, or an explicit teardown, become required (review row 76).\n *\n * @module dsh-boost\n */\nimport { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport type { ToolDefinition } from '@deepseek-ai/dsh-tools'\nimport { measureBoostFixedOverhead } from './tools/boost.js'\nimport { RuntimeStepHorizon, StepBudget } from './admission/ledger.js'\nimport { RetrievalLedger } from './admission/retrieval.js'\nimport { UsageLedger } from './admission/usage.js'\nimport { resolveConfig } from './config.js'\nimport { AnchorStore } from './gate/invalidate.js'\nimport type { Plan } from './gate/plan.js'\nimport { resolveBoostRoot } from './host/root.js'\nimport { clearSession, SessionRuntime } from './hooks/llm-stream.js'\nimport { TurnClock } from './hooks/clock.js'\nimport { PendingQueue } from './hooks/pending.js'\nimport { registerHooks } from './hooks/post-execute.js'\nimport type { HookDeps, SelectorRoute } from './hooks/post-execute.js'\nimport type { SpillBackend } from './projection/apply.js'\nimport { ProjectionCounters } from './projection/counters.js'\nimport { PROTOCOL_NAME, PROTOCOL_TEXT } from './prompt/protocol.js'\nimport { ReceiptStore } from './receipts/store.js'\nimport { SELECTOR_PURPOSE } from './selector/jev.js'\nimport type { LlmLike } from './selector/jev.js'\nimport { resolveWorkspace } from './scope/resolve.js'\nimport type { WorkspaceRegistry } from './scope/resolve.js'\nimport { ScopeStore } from './scope/store.js'\nimport { boostTool } from './tools/boost.js'\nimport type { BoostDeps, BoostHostFacts } from './tools/boost.js'\nimport type { PluginContext } from './types.js'\n\nexport const name = 'dsh-boost'\n\n/**\n * Required host services.\n *\n * `llm` is deliberately absent: projection and admission use no model, and\n * only the selector does. A hard injection would leave the whole plugin\n * pending — no hooks, no tool, no warning — on a composition without the LLM\n * runtime, even though it could still project. The selector resolves `llm`\n * lazily and fails closed with `selector-unavailable` when it is absent.\n */\nexport const inject = ['tools', 'systemPrompt'] as const\n\n/** Whether the host exposes both services the hook mounts attach to. */\nfunction canRegister(ctx: PluginContext): boolean {\n return typeof ctx.on === 'function' && typeof ctx.systemPrompt?.section === 'function'\n}\n\n/** One-line detail for a contained wiring failure. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** The dsh host line this build was verified against (`engines.dsh`). */\nconst VERIFIED_HOST_VERSION = '0.2.2-rc.4'\n\n/**\n * Stable host code: the resolved host version is not the verified one.\n *\n * A warning, never a hard failure: an unverified version is a risk, not proof\n * that an API this build uses has moved. It belongs to the `ERR_HOST_*` family\n * this module already logs (`ERR_HOST_NO_AGENT_REQUEST`,\n * `ERR_HOST_COMPLETE_SECTION`).\n */\nconst ERR_HOST_VERSION_MISMATCH = 'ERR_HOST_VERSION_MISMATCH'\n\n/** The app-boot package whose version IS the dsh runtime version. */\nconst HOST_VERSION_PACKAGE = '@deepseek-ai/dsh-app-boot'\n\n/** The host's package resolver (`pluginPackages` in a profile process). */\ntype PackageResolver = {\n packageOf?(specifier: string, parentURL: string): { version?: unknown } | undefined\n}\n\n/** Node's resolver, used only when the host service is unavailable. */\nconst requireFromHere = createRequire(import.meta.url)\n\n/**\n * The resolved dsh host version, or `undefined` when it cannot be determined.\n *\n * `dsh-app-boot`'s own manifest is the runtime version the compatibility\n * preflight compares `engines.dsh` against, so it is the authority here too.\n * The profile's `pluginPackages` service is preferred because it resolves\n * through the same runtime interception the host used (a linked or mixed tree\n * reports the version actually loaded); a plain Node resolve from this module\n * is the fallback for an embedded composition without that service. Reading a\n * manifest is not a host import: the package is never loaded, and nothing in\n * `dist/` statically imports it.\n *\n * Never throws: an absent service, an unresolvable package and a malformed\n * manifest all mean \"unknown\", which is logged but not warned about.\n */\nfunction hostVersionOf(ctx: PluginContext): string | undefined {\n try {\n const packages = serviceOf<PackageResolver>(ctx, 'pluginPackages')\n const pkg = packages?.packageOf?.(HOST_VERSION_PACKAGE, import.meta.url)\n if (typeof pkg?.version === 'string' && pkg.version !== '') return pkg.version\n } catch {\n // A foreign resolver is the same as no resolver.\n }\n try {\n const manifest = requireFromHere.resolve(`${HOST_VERSION_PACKAGE}/package.json`)\n const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as { version?: unknown }\n return typeof parsed.version === 'string' && parsed.version !== '' ? parsed.version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Log the resolved host version once and warn on a mismatch.\n *\n * The version guard is deliberately advisory. npm does not read `engines.dsh`;\n * the host enforces it only through the managed-install compatibility preflight,\n * which does not run for every composition. A warning here is the only signal\n * an embedded or mixed tree gets, and it must never stop the plugin: a version\n * this build did not verify may still work.\n */\nfunction reportHostVersion(ctx: PluginContext): void {\n const version = hostVersionOf(ctx)\n if (version === undefined) {\n ctx.logger?.info?.(\n `dsh-boost: dsh host version unknown (verified against ${VERIFIED_HOST_VERSION}); compatibility cannot be checked`,\n )\n return\n }\n if (version === VERIFIED_HOST_VERSION) {\n ctx.logger?.info?.(`dsh-boost: dsh host ${version} (verified)`)\n return\n }\n ctx.logger?.warn?.(\n `dsh-boost: ${ERR_HOST_VERSION_MISMATCH}: this build is verified against dsh ${VERIFIED_HOST_VERSION}, but the host reports ${version}; continuing, but a renamed host API may make the plugin inert`,\n )\n}\n\n/**\n * Duplicate applies observed in this process.\n *\n * The host exposes no stable duplicate-mount code for a prompt section, so the\n * only evidence is the plain Error's message. A throw counts as \"this plugin is\n * already wired\" only when that message names OUR section and says it is\n * already registered; every other failure is a wiring error with its own code\n * (see `isDuplicateSectionError`). The counter makes repeated applies visible\n * in the log without changing the mounts.\n */\nlet duplicateMountAttempts = 0\n\n/**\n * Whether a section-registration throw is the host's genuine duplicate error.\n *\n * `dsh-system-prompt` builds a plain `Error` whose message starts with\n * `prompt section \"<name>\" is already registered` (global and scoped variants\n * both start that way) and exposes no code. Matching that prefix for our own\n * section is the only duplicate evidence available; a future wording change\n * falls through to the generic branch, which warns with the raw error and keeps\n * the control tool mountable instead of silently disabling everything.\n */\nfunction isDuplicateSectionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.startsWith(`prompt section \"${PROTOCOL_NAME}\" is already registered`)\n )\n}\n\n/**\n * Read a soft host service through `ctx.get`.\n *\n * `workspaceRegistry`, `spillStore` and `tokenMeter` are optional peers: a\n * static injection would make the plugin fail to load on a host that does not\n * provide them, so they are fetched, never declared in `inject`. A host whose\n * `get` throws is the same as one without the service (the plugin-load test\n * pins that the data root is never resolved this way).\n */\nfunction serviceOf<T>(ctx: PluginContext, name: string): T | undefined {\n try {\n if (typeof ctx.get !== 'function') return undefined\n return ctx.get<T>(name) ?? undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * A memoising, retrying service getter.\n *\n * `ctx.get(name, strict=true)` answers `undefined` until the provider fiber is\n * ACTIVE, and cordis starts sibling plugin entries concurrently, so a service\n * read once in `apply` may simply not exist yet. A success is memoised; an\n * absence is never cached, because the provider may become active one tick\n * later. Every call site reads the getter, so the plugin recovers on the next\n * request instead of staying inert for the process lifetime.\n */\nfunction lazyService<T>(ctx: PluginContext, name: string): () => T | undefined {\n let resolved: T | undefined\n return () => {\n if (resolved !== undefined) return resolved\n resolved = serviceOf<T>(ctx, name)\n return resolved\n }\n}\n\n/**\n * The session id behind an agent or a `Session`.\n *\n * An agent exposes `session.header.id`; the `session/disposed` payload is the\n * `Session` itself and exposes `header.id` (and `id`). Anything else is\n * `undefined`, which makes every caller fail closed.\n */\nfunction sessionIdOf(value: unknown): string | undefined {\n const carrier = value as\n | {\n session?: { header?: { id?: unknown } }\n header?: { id?: unknown }\n id?: unknown\n }\n | undefined\n const agentId = carrier?.session?.header?.id\n if (typeof agentId === 'string') return agentId\n const headerId = carrier?.header?.id\n if (typeof headerId === 'string') return headerId\n return typeof carrier?.id === 'string' ? carrier.id : undefined\n}\n\n/**\n * The host token meter's synchronous message estimator, resolved lazily.\n *\n * `ctx.tokenMeter` is a cordis service with a synchronous `estimateMessage`\n * method, so `ctx.get('tokenMeter')` is a real synchronous seam. Like every\n * soft service it may become active after this plugin's `apply`, so the\n * estimator is probed on first use and re-probed while absent; a success is\n * memoised. Presence is not capability: a service that throws or returns a\n * non-finite number is a broken meter, not a meter, and substitution is\n * refused exactly as when no service exists (review R5). A broken meter is not\n * memoised either, so a provider that finishes wiring its meter later can\n * still recover.\n *\n * The receipt label is `host` so the number is never mistaken for a provider\n * measurement; the only other label would be a fabricated `chars/4` fallback,\n * which this assembly deliberately does not implement.\n *\n * Memoisation covers the *binding*, not the answer. `kind()` probes the\n * memoised estimator on every call, because a meter that answered once is not\n * a meter forever: after it starts returning `NaN`, projection receipts already\n * record `estimate:'unknown'` for that assembly, and a cached `host` label\n * would contradict them in the same `boost status` output.\n */\nconst METER_PROBE = 'dsh-boost meter probe'\n\nfunction meterSeamOf(ctx: PluginContext): {\n estimate(): ((text: string) => number) | undefined\n kind(): 'host' | 'unknown'\n} {\n let estimator: ((text: string) => number) | undefined\n /** One probe through a raw host estimator; a throw or non-number is failure. */\n const probe = (estimate: (message: unknown) => number): boolean => {\n try {\n const value = estimate({\n role: 'user',\n content: [{ type: 'text', text: METER_PROBE }],\n })\n return typeof value === 'number' && Number.isFinite(value)\n } catch {\n return false\n }\n }\n const resolve = (): ((text: string) => number) | undefined => {\n if (estimator !== undefined) return estimator\n const meter = serviceOf<{ estimateMessage?: (message: unknown) => number }>(ctx, 'tokenMeter')\n if (meter === undefined || typeof meter.estimateMessage !== 'function') return undefined\n const estimate = meter.estimateMessage.bind(meter)\n if (!probe(estimate)) return undefined\n estimator = (text: string): number => {\n try {\n const value = estimate({ role: 'user', content: [{ type: 'text', text }] })\n return typeof value === 'number' && Number.isFinite(value) ? value : Number.NaN\n } catch {\n return Number.NaN\n }\n }\n return estimator\n }\n return {\n estimate: resolve,\n kind: () => {\n const estimate = resolve()\n if (estimate === undefined) return 'unknown'\n // Probe through the memoised wrapper, so the label prices the same\n // pipeline every receipt uses. `resolve()` alone cannot answer: it\n // returns a cached binding even after the meter stopped answering.\n return Number.isFinite(estimate(METER_PROBE)) ? 'host' : 'unknown'\n },\n }\n}\n\n/** How many disposed session ids the runtime facade remembers (FIFO). */\nconst MAX_DISPOSED_RUNTIME_SESSIONS = 256\n\n/**\n * `SessionRuntime` that refuses to recreate state for a disposed session.\n *\n * `clearSession` drops a session's runtime entry, but a `post-execute` that was\n * already in flight (a selector call can take 20 s) lands after disposal and\n * calls `clockFor`/`budgetFor`/`usageFor` again; the base class would create a\n * fresh entry nothing ever clears. The facade returns throwaway primitives for\n * disposed ids instead: the late hook records nothing, and the map cannot grow\n * after session end. The id set is FIFO-bounded so a long process cannot grow\n * it without limit.\n */\nclass DisposalAwareSessionRuntime extends SessionRuntime {\n private readonly disposed = new Set<string>()\n private readonly disposedOrder: string[] = []\n\n /** Mark a session disposed and drop whatever the base class still holds. */\n markDisposed(sessionId: string): void {\n this.clear(sessionId)\n if (this.disposed.has(sessionId)) return\n this.disposed.add(sessionId)\n this.disposedOrder.push(sessionId)\n while (this.disposedOrder.length > MAX_DISPOSED_RUNTIME_SESSIONS) {\n const oldest = this.disposedOrder.shift()\n if (oldest !== undefined) this.disposed.delete(oldest)\n }\n }\n\n override clockFor(sessionId: string): TurnClock {\n return this.disposed.has(sessionId) ? new TurnClock() : super.clockFor(sessionId)\n }\n\n override budgetFor(sessionId: string): StepBudget {\n return this.disposed.has(sessionId) ? new StepBudget(0) : super.budgetFor(sessionId)\n }\n\n override usageFor(sessionId: string): UsageLedger {\n return this.disposed.has(sessionId) ? new UsageLedger() : super.usageFor(sessionId)\n }\n\n override onModelRequest(sessionId: string, turn: number, step?: number): void {\n if (!this.disposed.has(sessionId)) super.onModelRequest(sessionId, turn, step)\n }\n}\n\n/** The `agent/request` payload fields this assembly reads. */\ntype RequestPayload = {\n agent?: unknown\n turn?: unknown\n step?: unknown\n /** Captured step route on `agent/pre-step` (also the selector's inheritance source). */\n modelSelection?: unknown\n}\n\n/**\n * Warm the synchronous visibility cache and remember the canonical workspace.\n *\n * `resolveWorkspace` is the async answer and also writes `scope.judgement(key)`;\n * it prefers the registry's `resolveByPath`, so a symlinked or trailing-slash\n * cwd resolves to the same id the judgement used. The workspace id is kept even\n * when the answer is \"invisible\", so the resolver must consult the live\n * judgement rather than treating the map as the answer. A workspace disabled\n * after a commit therefore stops resolving before the next synthesized turn.\n */\nasync function warmVisibility(\n scope: ScopeStore,\n registry: () => WorkspaceRegistry | undefined,\n agent: unknown,\n sessionId: string,\n workspaces: Map<string, string>,\n): Promise<boolean> {\n try {\n const result = await resolveWorkspace(scope, agent, registry())\n // The map carries identity, `scope.judgement` carries visibility: cache the\n // id even when the answer is \"invisible\", and let the resolver combine the\n // two. A stale id therefore cannot outlive a visibility change.\n if (typeof result.workspaceId === 'string') workspaces.set(sessionId, result.workspaceId)\n else workspaces.delete(sessionId)\n return result.visible\n } catch {\n // `resolveWorkspace` is total; this contains a foreign registry.\n return false\n }\n}\n\n/** Remember the effective route the selector call must inherit. */\nfunction rememberRoute(\n routes: Map<string, SelectorRoute>,\n sessionId: string,\n config: unknown,\n): void {\n const resolved = config as\n | { provider?: unknown; model?: unknown; reasoningEffort?: unknown }\n | undefined\n if (resolved == null) return\n if (typeof resolved.provider !== 'string' || typeof resolved.model !== 'string') return\n const route: SelectorRoute = { provider: resolved.provider, model: resolved.model }\n if (typeof resolved.reasoningEffort === 'string') route.reasoningEffort = resolved.reasoningEffort\n routes.set(sessionId, route)\n}\n\n/**\n * Replace the protocol section's already-resolved text with the fresh answer.\n *\n * This runs *after* the assemble waterfall, so it rewrites text a section\n * provider already produced. That is deliberate and does not contradict D4\n * (\"persistent, stable content\"): every agent has its own prompt prefix and\n * its own context window, so changing this section cannot invalidate another\n * agent's cached prefix. Within one agent the answer changes only when its\n * resolved visibility changes (a workspace edit/`scope-set`), which is exactly\n * the point at which the prefix must change; every other assembly reproduces\n * the same bytes. The alternative — a section whose text is fixed at\n * registration — would either leak one agent's visibility to every other or\n * require a second provider to read a cache this listener has not warmed yet.\n */\nfunction patchProtocolSection(assembly: unknown, visible: boolean): unknown {\n const value = assembly as { sections?: unknown } | undefined\n if (value === undefined || value === null || !Array.isArray(value.sections)) return assembly\n const sections = value.sections.map((section) => {\n const entry = section as { name?: unknown } | null\n return entry?.name === PROTOCOL_NAME\n ? { ...(entry as Record<string, unknown>), text: visible ? PROTOCOL_TEXT : '' }\n : section\n })\n return { ...(value as Record<string, unknown>), sections }\n}\n\n/** The marker every protocol text carries; a system prompt without it lost the section. */\nconst PROTOCOL_PROBE = '<CHISEL_PLAN>'\n\n/**\n * The system-role text of one model request, or `undefined` when the request\n * carries no system prompt at all.\n *\n * Loop-built requests put the rendered prompt in the leading system-role\n * message (``GenerateOptions.messages``); one-shot callers use `system`. A\n * request with neither is a diagnostic that cannot tell us whether the section\n * landed, so it is not evidence of a complete-section swallow.\n */\nfunction systemTextOf(options: unknown): string | undefined {\n const source = options as { messages?: unknown; system?: unknown } | null | undefined\n if (typeof source?.system === 'string' && source.system.length > 0) return source.system\n const messages = source?.messages\n if (!Array.isArray(messages)) return undefined\n let seen = false\n let text = ''\n for (const message of messages) {\n const entry = message as { role?: unknown; content?: unknown } | null\n if (entry?.role !== 'system') continue\n seen = true\n if (typeof entry.content === 'string') {\n text += entry.content\n continue\n }\n if (!Array.isArray(entry.content)) continue\n for (const block of entry.content) {\n const part = block as { type?: unknown; text?: unknown } | null\n if (part?.type === 'text' && typeof part.text === 'string') text += part.text\n }\n }\n return seen ? text : undefined\n}\n\n/**\n * Mount the host events the assembly owns.\n *\n * ## Why `system-prompt/assemble` owns the warm\n *\n * The host's preStep is `tools.resolve` -> `systemPrompt.assemble` ->\n * `agent/pre-step`; section text resolves inside `assemble`, and\n * `agent/request` fires only later in `step()`. A warm driven from\n * `agent/request` therefore misses request 1 (the gate can never act on step\n * 1) and then flips the system prompt on request 2, invalidating the whole\n * cached prefix (design D4). This listener runs inside the awaited assemble\n * waterfall, after sections resolve, with `context.scope` being the agent: it\n * warms the judgement and then rewrites our section's text from that fresh\n * answer. Request 1 is correct and request 2 reproduces the same bytes.\n *\n * The tool-level `when` was the alternative early seam; it is worse here\n * because it never runs when `tools.resolve` is unavailable or the boost tool\n * is filtered out, and it cannot await `resolveByPath` without making a\n * synchronous visibility predicate asynchronous. The assemble listener also\n * costs nothing on tool-listing paths.\n *\n * `agent/pre-step` is the non-deprecated clock seam (`agent/request` is\n * marked `@deprecated`); it fires once per proposed step with the host\n * `turn`/`step`. `agent/request` is kept for the selector route, which only\n * its resolved config carries, and as a clock/visibility fallback. A model\n * request that reaches `llm/stream` without any observed `agent/request` is\n * reported once with `ERR_HOST_NO_AGENT_REQUEST` instead of silently losing\n * the route.\n *\n * `session/event` (`turn/end`), `session/flush` and `session/disposed` call\n * `ReceiptStore.flush()` so the turn-end durability the design promises is\n * real. `session/disposed` also drops every per-session map the assembly owns\n * and tells the stores to evict their state.\n */\nfunction wireSessionEvents(\n ctx: PluginContext,\n deps: HookDeps,\n scope: ScopeStore,\n registry: () => WorkspaceRegistry | undefined,\n sessions: DisposalAwareSessionRuntime,\n horizon: RuntimeStepHorizon,\n workspaces: Map<string, string>,\n routes: Map<string, SelectorRoute>,\n counters: ProjectionCounters,\n): void {\n /** Session ids seen at `agent/pre-step`; a `llm/stream` without a request is drift. */\n const preStepSeen = new Set<string>()\n /** Session ids observed on `agent/request`. */\n const requestSeen = new Set<string>()\n let warnedMissingRequest = false\n /** Warn once per process about a prompt that swallowed the protocol section. */\n let warnedCompleteSection = false\n\n ctx.on('system-prompt/assemble', async (_assembly: unknown, context: unknown, next: () => unknown) => {\n const resolved = await next()\n try {\n // `dsh-agent` augments `AssembleContext` with the real `Agent`; `scope`\n // is an opaque `ScopeKey` and is never read as an Agent (review row 11).\n // A diagnostic assembly has no agent: the documented no-scope view, so\n // the section is suppressed and counted rather than keyed on a guess.\n const carrier = (context ?? {}) as { agent?: unknown }\n const agent = carrier.agent\n const sessionId = sessionIdOf(agent)\n if (sessionId === undefined) {\n // The provider has nothing to key the judgement on and returns '';\n // clear the section explicitly so a stale provider answer cannot leak\n // into an assembly with no agent. Count the decision, not the\n // section's presence — design §5.5:378 asks for every assembly to be\n // judged.\n counters.protocolSuppressed()\n return patchProtocolSection(resolved, false)\n }\n const visible = await warmVisibility(scope, registry, agent, sessionId, workspaces)\n // Same rule for an invisible workspace: the section is suppressed for\n // this assembly, so the operator gets a live signal in `boost status`.\n // A visible one never increments, so the count stays a failure count.\n if (!visible) counters.protocolSuppressed()\n return patchProtocolSection(resolved, visible)\n } catch {\n return resolved\n }\n })\n\n ctx.on('agent/pre-step', async (payload: unknown, next: () => unknown) => {\n const request = (payload ?? {}) as RequestPayload\n const sessionId = sessionIdOf(request.agent)\n if (sessionId !== undefined) {\n preStepSeen.add(sessionId)\n try {\n sessions.onModelRequest(\n sessionId,\n typeof request.turn === 'number' ? request.turn : Number(request.turn),\n typeof request.step === 'number' ? request.step : undefined,\n )\n } catch {\n // A clock that cannot be driven must not break the step.\n }\n try {\n horizon.observe(\n sessionId,\n typeof request.turn === 'number' ? request.turn : Number(request.turn),\n typeof request.step === 'number' ? request.step : Number(request.step),\n )\n } catch {\n // History is an estimate; a bad observation is not a step failure.\n }\n // `agent/pre-step` already carries the captured step selection. It is\n // the non-deprecated source for the selector route; `agent/request`'s\n // resolved config remains a fallback for hosts that only populate it\n // there (review row 37). A later request overwrites with the same route.\n rememberRoute(routes, sessionId, request.modelSelection)\n }\n return next()\n })\n\n ctx.on('agent/request', async (payload: unknown, next: () => unknown) => {\n const request = (payload ?? {}) as RequestPayload\n const sessionId = sessionIdOf(request.agent)\n if (sessionId !== undefined) {\n requestSeen.add(sessionId)\n try {\n sessions.onModelRequest(\n sessionId,\n typeof request.turn === 'number' ? request.turn : Number(request.turn),\n typeof request.step === 'number' ? request.step : undefined,\n )\n } catch {\n // A clock that cannot be driven must not break the model request.\n }\n try {\n horizon.observe(\n sessionId,\n typeof request.turn === 'number' ? request.turn : Number(request.turn),\n typeof request.step === 'number' ? request.step : Number(request.step),\n )\n } catch {\n // Same as the pre-step observation: history is an estimate.\n }\n await warmVisibility(scope, registry, request.agent, sessionId, workspaces)\n }\n const config = await next()\n if (sessionId !== undefined) rememberRoute(routes, sessionId, config)\n return config\n })\n\n // The deprecated event's disappearance would otherwise disable the selector\n // route silently. A session that reached `llm/stream` after a pre-step but\n // never saw `agent/request` is proof enough; the model request itself is\n // passed through untouched.\n //\n // This listener is also the complete-section detector, and it MUST be\n // outermost: the synthesizer mounted by `registerHooks` consumes a queued\n // entry synchronously, so a detector registered after it would only mark the\n // session unsubstitutable *after* the first affected request had already been\n // substituted. Cordis runs the first-registered listener outermost\n // (`events.ts` unshifts on `prepend`), so `prepend: true` is what puts the\n // detector before the synthesizer regardless of mount order (finding 4).\n ctx.on(\n 'llm/stream',\n (options: unknown, next: () => unknown) => {\n try {\n const request = (options ?? {}) as { sessionId?: unknown; purpose?: unknown }\n const sessionId = request.sessionId\n if (\n !warnedMissingRequest &&\n typeof sessionId === 'string' &&\n preStepSeen.has(sessionId) &&\n !requestSeen.has(sessionId)\n ) {\n warnedMissingRequest = true\n ctx.logger?.warn?.(\n 'ERR_HOST_NO_AGENT_REQUEST: agent/request was not observed before llm/stream; the selector route cannot be captured (the event is deprecated and may have been removed)',\n )\n }\n\n // A `complete: true` prompt section replaces every other section after\n // the assembly waterfall, so the protocol text\n // `system-prompt/assemble` patched in is gone from the request the\n // model actually receives. The host exposes no code or flag for that\n // restoration; the outgoing system prompt is the first place it is\n // observable. Detect it, count it, and fail closed: without the\n // protocol there is nothing to teach the plan grammar, so substitution\n // (and the projection that shares the same visibility gate) must not\n // act for this request (review row 12).\n if (\n typeof sessionId === 'string' &&\n request.purpose !== SELECTOR_PURPOSE &&\n scope.judgement(sessionId)\n ) {\n const systemText = systemTextOf(options)\n if (systemText !== undefined && !systemText.includes(PROTOCOL_PROBE)) {\n counters.protocolSuppressed()\n counters.protocolMissing()\n scope.remember(sessionId, false)\n if (!warnedCompleteSection) {\n warnedCompleteSection = true\n ctx.logger?.warn?.(\n 'ERR_HOST_COMPLETE_SECTION: the final system prompt does not carry the dsh-boost protocol section (a complete prompt section replaced the assembly); substitution is disabled for affected requests',\n )\n }\n }\n }\n } catch {\n // Detection must never break the model request.\n }\n return next()\n },\n { prepend: true },\n )\n\n // `session/event` carries a plain `type` string, so `turn/end` is matched by\n // value, not by a stable code. That match is a convenience: it flushes early\n // on the common path, but it is not the durability boundary. The host does\n // not await this listener, so a process exit immediately after `turn/end`\n // can drop the flush; the awaited `session/flush` below is what the\n // persistence contract rests on, and `session/disposed` flushes again after\n // the last hook for the id. Receipts are evidence, so an early flush that\n // does not happen costs latency, never correctness.\n ctx.on('session/event', (_session: unknown, event: unknown) => {\n const type = (event as { type?: unknown } | undefined)?.type\n if (type === 'turn/end') {\n // Fire-and-forget on the real host; `flush()` never rejects.\n return deps.receipts.flush()\n }\n return undefined\n })\n\n ctx.on('session/flush', () => deps.receipts.flush())\n\n ctx.on('session/disposed', async (session: unknown) => {\n const sessionId = sessionIdOf(session)\n if (sessionId === undefined) return\n try {\n clearSession(deps, sessionId)\n } catch {\n // Session end owns no tool result; a failed clear must not throw here.\n }\n sessions.markDisposed(sessionId)\n workspaces.delete(sessionId)\n routes.delete(sessionId)\n requestSeen.delete(sessionId)\n preStepSeen.delete(sessionId)\n horizon.clear(sessionId)\n scope.forget(sessionId)\n // Flush this session's buffered lines before evicting its state, then make\n // every later hook for the id a no-op.\n try {\n await deps.receipts.flush()\n } catch {\n // Flush is total; a foreign store must not break session end.\n }\n deps.receipts.disposeSession(sessionId)\n })\n}\n\n/**\n * Register the `boost` tool family.\n *\n * After T19 the family is just this one tool. The tool itself is scope-exempt\n * (`when: () => true`) because it is the only way a user can enable a workspace\n * that is not enabled yet — gating it on the scope document would make\n * `selected + []` impossible to leave. The protocol section is not exempt; T17\n * already handles it.\n *\n * No step-`when` capability probe is needed: the condition is constant-true, so\n * a host that ignored the registration options would register it\n * unconditionally — exactly the behaviour this build wants. The old probe only\n * tested `typeof tools.register === 'function'`, which every host since\n * 0.2.2-rc.1 satisfies, so the branch it fed could never run; it was removed\n * rather than left as a claim that can never be false.\n */\nfunction registerBoostTool(ctx: PluginContext, deps: BoostDeps): void {\n // Annotating with the host's ToolDefinition makes a host-side tightening a\n // build error instead of a runtime registration failure. The tool is\n // scope-exempt by design (`when: () => true`), so it needs no registry: the\n // registry is only the visibility warm's input, wired above.\n const definition: ToolDefinition = boostTool(deps)\n\n ctx.tools.register(definition, { when: () => true })\n}\n\nexport function apply(ctx: PluginContext, config: unknown): void {\n const repairs: string[] = []\n const cfg = resolveConfig(config, message => {\n repairs.push(message)\n ctx.logger?.warn?.(message)\n })\n // The effective-config line serialises `resolveConfig`'s output, which never\n // carries `dshHome` (that override is resolved by `resolveBoostRoot`). Log\n // the resolved root with it, once, so the operator can see the state root in\n // use — including the `$DSH_HOME`/`~/.dsh` fallback and the cwd resolution of\n // a relative override.\n let root: string\n try {\n root = resolveBoostRoot(config)\n } catch (error) {\n ctx.logger?.warn?.(`dsh-boost: cannot resolve the state root: ${messageOf(error)}`)\n return\n }\n // One line with the effective values (not only the keys this module happens\n // to use): an operator can see every clamp and fallback instead of guessing.\n ctx.logger?.info?.(\n `dsh-boost loaded (stepsPerTurn=${cfg.stepsPerTurn}, horizonSteps=${cfg.horizonSteps}); effective config=${JSON.stringify(cfg)}; root=${root}`,\n )\n if (repairs.length > 0) {\n ctx.logger?.info?.(`dsh-boost: ${repairs.length} configuration value(s) repaired`)\n }\n // The only version guard outside the managed-install preflight. Advisory:\n // an unverified host is a warning, never a refusal to load.\n reportHostVersion(ctx)\n\n if (!canRegister(ctx)) {\n ctx.logger?.warn?.('dsh-boost: host hook services unavailable; registration skipped')\n return\n }\n\n try {\n // The root was resolved above (D4) so the log can show it; both stores use\n // the same value. `resolveBoostRoot` is the only root rule (design §10), so\n // `apply` and the hook stores cannot diverge.\n const scope = new ScopeStore(root, { warn: (message: string) => ctx.logger?.warn?.(message) })\n const receipts = new ReceiptStore(root)\n const anchors = new AnchorStore()\n const queue = new PendingQueue()\n const plans = new Map<string, Plan>()\n const sessions = new DisposalAwareSessionRuntime(cfg.stepsPerTurn)\n const horizon = new RuntimeStepHorizon(cfg.horizonSteps, cfg.historyTurns)\n const retrievals = new RetrievalLedger()\n /** Session id → workspace id, populated by the visibility warm. */\n const workspaces = new Map<string, string>()\n /** Session id → the route the selector call inherits. */\n const routes = new Map<string, SelectorRoute>()\n\n // Soft host services. Cordis activates sibling providers concurrently, so\n // these getters retry until the provider fiber is ACTIVE; an absence is\n // never memoised. The workspace registry is the `resolveByPath`/`list()`\n // seam; the spill store is the projection backend; the token meter prices\n // projections and admission.\n const registry = lazyService<WorkspaceRegistry>(ctx, 'workspaceRegistry')\n const spill = lazyService<SpillBackend>(ctx, 'spillStore')\n // `llm` is soft (see `inject`): projection and admission never need it, and\n // the selector checks it at call time. A getter keeps a provider that\n // becomes active after `apply` reachable on the next decision.\n const llm = lazyService<LlmLike>(ctx, 'llm')\n const meter = meterSeamOf(ctx)\n const projectionCounters = new ProjectionCounters()\n\n // Host capabilities `status` renders as stable codes. Getters keep them\n // facts about the host *now*: a service that appears after `apply` must not\n // leave a permanent `ERR_HOST_NO_*`. The fixed-cost probe starts here\n // (startup time) and is awaited only by `status` — it is deliberately not\n // on any request path.\n const hostFacts: BoostHostFacts = {\n get hasTokenMeter() {\n return meter.kind() === 'host'\n },\n get hasSpill() {\n return spill() !== undefined\n },\n get hasWorkspaceRegistry() {\n return registry() !== undefined\n },\n }\n const fixedOverhead = measureBoostFixedOverhead()\n\n // The hook reads this synchronously, so it only ever returns the warmed\n // answer. The map alone is not the answer: a workspace disabled between\n // commit and synthesis leaves the id behind but flips `judgement` to false.\n const resolveSession = (sessionId: string): string | undefined => {\n try {\n if (!scope.judgement(sessionId)) return undefined\n return workspaces.get(sessionId)\n } catch {\n return undefined\n }\n }\n\n // `deps` MUST stay the same object `registerHooks` receives: it publishes\n // the created `ReceiptSessionState` onto `deps.sessionState`, and\n // `clearSession(deps, id)` can only reach it through that reference.\n const deps: HookDeps = {\n config: cfg,\n scope,\n receipts,\n anchors,\n resolveSession,\n queue,\n plans,\n sessions,\n // Getters, not snapshots: the hook reads them per decision, so a service\n // that becomes active after `apply` is picked up on the next call.\n get spill() {\n return spill()\n },\n retrievals,\n get estimateText() {\n return meter.estimate()\n },\n get estimateKind() {\n return meter.kind()\n },\n projectionCounters,\n // The live horizon, so a projection receipt pins the value its own\n // decision was made under instead of whatever the cross-session minimum\n // happens to be when an operator runs `boost status` (design §5.3).\n horizonFor: (sessionId) => horizon.remainingFor(sessionId),\n get llm() {\n return llm()\n },\n selectorRoute: (sessionId) => routes.get(sessionId),\n }\n // The section mount is the first thing `registerHooks` touches. Only the\n // host's genuine duplicate error means a previous apply already owns the\n // mounts; every other throw is a wiring failure that must be named and must\n // not take the control tool down with it (finding 8).\n try {\n registerHooks(ctx, deps)\n } catch (error) {\n if (isDuplicateSectionError(error)) {\n duplicateMountAttempts += 1\n ctx.logger?.warn?.(\n `dsh-boost: ERR_BOOST_ALREADY_MOUNTED: duplicate apply #${duplicateMountAttempts} found an existing mount; registration skipped (${messageOf(error)})`,\n )\n return\n }\n ctx.logger?.warn?.(\n `dsh-boost: ERR_BOOST_SECTION_REGISTER_FAILED: prompt section registration failed; continuing with the remaining mounts (${messageOf(error)})`,\n )\n }\n\n // The clock/visibility warm and the session-end cleanup. Wired separately\n // so a host that cannot accept these events still gets the tool below.\n try {\n wireSessionEvents(ctx, deps, scope, registry, sessions, horizon, workspaces, routes, projectionCounters)\n } catch (error) {\n ctx.logger?.warn?.(`dsh-boost: session wiring failed: ${messageOf(error)}`)\n }\n\n // After the hooks: a genuine duplicate aborts above before it can register\n // the tool twice. A different section failure still reaches here, and so\n // does a tool registration failure of its own — neither may be swallowed\n // behind the other's diagnosis.\n try {\n registerBoostTool(ctx, {\n scope,\n receipts,\n host: hostFacts,\n fixedOverhead: () => fixedOverhead,\n get estimateKind() {\n return meter.kind()\n },\n // Design §5.3's runtime horizon: min(config horizon, mean of the last\n // `historyTurns` completed turns) over live sessions. `runBoost` spreads\n // the deps when it is called, so this getter is read at status time.\n get horizonSteps() {\n return horizon.remaining()\n },\n locatorEvictions: () => retrievals.evictions(),\n receiptReadErrors: () => receipts.readErrors(),\n receiptsTruncated: () => receipts.scanTruncated(),\n unknownFamilies: () => projectionCounters.unknownFamilies(),\n unknownTools: () => projectionCounters.unknownToolCounts(),\n protocolSuppressed: () => projectionCounters.protocolSuppressions(),\n completeSectionSuppressions: () => projectionCounters.protocolMissings(),\n })\n } catch (error) {\n // The tool is the user's only control surface; its failure is reported\n // on its own, never as a hook failure.\n ctx.logger?.warn?.(\n `dsh-boost: boost tool registration failed (ERR_BOOST_TOOL_REGISTER_FAILED): ${messageOf(error)}`,\n )\n }\n } catch (error) {\n ctx.logger?.warn?.(`dsh-boost: hook registration skipped: ${messageOf(error)}`)\n }\n}\n"]}
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Projection execution: the shadow accounting and the real replacement.
3
+ *
4
+ * `projectShadow` is the half of projection that never changes what the model
5
+ * sees: it decides whether a receipt *would* be cut, composes the replacement
6
+ * string `projectApply` would produce, and prices both sides in tokens through
7
+ * the caller's `estimate`. It writes nothing and reads no host service, so the
8
+ * caller alone decides which mode to invoke (design §5.4).
9
+ *
10
+ * `projectApply` is the half that replaces, and it only replaces what is still
11
+ * recoverable: the canonical receipt is persisted through the injected spill
12
+ * backend first, then head line, head, spill footer and tail are composed. All
13
+ * guards run before the write, a failed write or footer is a skip rather than
14
+ * an exception, and a footer that would grow the receipt sends the original
15
+ * back unchanged — a projection that grows a receipt defeats the plugin's
16
+ * premise.
17
+ *
18
+ * The projected size is composed here, not read off `Truncation.after`:
19
+ * `after` is the head line plus the two windows *without* the omission note, so
20
+ * it is only a lower bound on the final replacement. Shadow mode prices
21
+ * `renderHeadLine + head + omission note + tail`; the note's locator part is
22
+ * unknown before the spill write, so only the standardized omission clause is
23
+ * included.
24
+ *
25
+ * Skip reasons are stable codes, never prose: `error-receipt` (an error receipt
26
+ * is evidence and is never projected), `family-not-configured` (the family has
27
+ * no window), `not-worth-it` (`truncate`'s guard said no, or the footer left no
28
+ * net gain), `empty` (shadow's empty receipt), and on the apply half
29
+ * `no-spill`, `no-owner`, `projection-skipped:no-footer`, `spill-failed`, and
30
+ * `footer-failed`.
31
+ *
32
+ * @module dsh-boost/projection/apply
33
+ */
34
+ import type { BoostConfig, ToolFamily } from '../types.js';
35
+ /** Which projection behaviour the caller is running. */
36
+ export type ProjectionMode = 'off' | 'shadow' | 'on';
37
+ /** What projection did, or would have done, to one receipt. */
38
+ export interface ProjectionOutcome {
39
+ kind: 'skipped' | 'shadow' | 'applied';
40
+ /** Stable skip code; present only when `kind === 'skipped'`. */
41
+ reason?: string;
42
+ /**
43
+ * Tokens in the original receipt.
44
+ *
45
+ * Present only when `kind === 'shadow'` and the estimator priced both
46
+ * sides; absent (with `estimate: 'unknown'` on the receipt) when it did not.
47
+ */
48
+ before?: number;
49
+ /** Tokens in the replacement shadow mode would have produced. */
50
+ after?: number;
51
+ /** `before - after`. */
52
+ saved?: number;
53
+ /**
54
+ * UTF-8 bytes the replacement omits; present only when `kind === 'applied'`.
55
+ *
56
+ * Apply mode has no token estimator: the caller (T23b) prices both texts
57
+ * itself, and these two fields are the projection's own accounting.
58
+ */
59
+ omittedBytes?: number;
60
+ /** Unicode code points the replacement omits; applied outcomes only. */
61
+ omittedCodePoints?: number;
62
+ /**
63
+ * The persisted artifact's locator; applied outcomes only.
64
+ *
65
+ * It is the path the footer tells the model to read, and the retrieval ledger
66
+ * matches later `read`/`grep` arguments against it (Task 25).
67
+ */
68
+ locator?: string;
69
+ }
70
+ /** A persisted spill artifact's model-facing handle. */
71
+ export interface SpillHandle {
72
+ /** Opaque locator the model can `read` or `grep`; never parsed here. */
73
+ locator: string;
74
+ /** How to retrieve the artifact, as guidance for the model. */
75
+ retrievalHint: string;
76
+ }
77
+ /**
78
+ * The host spill store, narrowed to the one method projection needs.
79
+ *
80
+ * `callId` and `label` are required because the host's `SaveTextSpill` requires
81
+ * them; `projectApply` fills them in before calling. `saveText` rejects on a
82
+ * real storage failure, and that rejection is handled as a skip.
83
+ */
84
+ export interface SpillBackend {
85
+ saveText(input: {
86
+ owner: {
87
+ sessionId: string;
88
+ };
89
+ source: {
90
+ kind: 'tool';
91
+ toolName: string;
92
+ callId: string;
93
+ label: string;
94
+ };
95
+ suggestedName: string;
96
+ content: string;
97
+ }): Promise<SpillHandle>;
98
+ }
99
+ /**
100
+ * Render the footer that names what was omitted and where the original lives.
101
+ *
102
+ * Injected by the caller, which dynamically imports the host's
103
+ * `formatSpillNotice`; this module must never statically import
104
+ * `@deepseek-ai/dsh-spill-policy` — it is not declared as a dependency, and a static import
105
+ * would make the degradation path unreachable (design §5.4).
106
+ */
107
+ export type FormatFooter = (omitted: {
108
+ kind: 'exact';
109
+ count: number;
110
+ }, ref: SpillHandle) => string;
111
+ /** Everything one apply decision reads; every host service arrives pre-bound. */
112
+ export interface ProjectApplyInput {
113
+ /** Canonical receipt text, byte for byte as it would enter history. */
114
+ text: string;
115
+ /** Whether the host marked the receipt as an error. */
116
+ isError: boolean;
117
+ /** Projection family, which selects the window from `cfg`. */
118
+ family: ToolFamily;
119
+ /** Resolved plugin configuration. */
120
+ cfg: BoostConfig;
121
+ /** Owning session; without one the spill has no owner and projection stops. */
122
+ sessionId: string | undefined;
123
+ /** Tool name, recorded on the spill source and used for its file name. */
124
+ toolName: string;
125
+ /** Model-issued call id; defaults to `toolName`. */
126
+ callId?: string;
127
+ /** Human label for the artifact; defaults to `family`. */
128
+ label?: string;
129
+ /** Spill backend, absent when the host has none (projection then stops). */
130
+ spill: SpillBackend | undefined;
131
+ /** Footer renderer, absent when the host spill policy package is not installed. */
132
+ formatFooter: FormatFooter | undefined;
133
+ }
134
+ /**
135
+ * Report what projection would save, without touching the receipt.
136
+ *
137
+ * Guards run in a fixed order: an error receipt is skipped before anything
138
+ * else, so even an empty or oversized error keeps its evidence (design §5.4
139
+ * contract 4); then empty text; then a family with no configured window; then
140
+ * `truncate`'s own decision (trigger, 256 KiB cap, net-gain guard).
141
+ */
142
+ export declare function projectShadow(input: {
143
+ /** Canonical receipt text, byte for byte as it would enter history. */
144
+ text: string;
145
+ /** Whether the host marked the receipt as an error. */
146
+ isError: boolean;
147
+ /** Projection family, which selects the window from `cfg`. */
148
+ family: ToolFamily;
149
+ /** Resolved plugin configuration. */
150
+ cfg: BoostConfig;
151
+ /** Token estimator injected by the caller (never imported from the host). */
152
+ estimate: (s: string) => number;
153
+ }): Promise<ProjectionOutcome>;
154
+ /**
155
+ * Replace an oversized receipt with its head, tail, and a way back to the rest.
156
+ *
157
+ * The canonical original is spilled *before* anything is replaced — never the
158
+ * projection, which would make the footer point at an artifact that does not
159
+ * contain what it promises. The footer sits on its own line between the two
160
+ * windows, and the composed replacement is re-checked against the original:
161
+ * at the trigger boundary a long locator can make the "projection" longer than
162
+ * the receipt it replaces, and a projection that grows a receipt is worse than
163
+ * none.
164
+ *
165
+ * A spill or footer failure is swallowed and reported as `spill-failed` /
166
+ * `footer-failed`; the caller's `post-execute` hook must never see an exception
167
+ * from here. The footer must be guarded too: the host turns a throwing
168
+ * `post-execute` listener into an `isError` result, which would lose the very
169
+ * output this module exists to preserve.
170
+ */
171
+ export declare function projectApply(input: ProjectApplyInput): Promise<{
172
+ content: string;
173
+ outcome: ProjectionOutcome;
174
+ }>;
@@ -0,0 +1,137 @@
1
+ import { renderHeadLine, truncate } from './truncate.js';
2
+ /** The omission clause of the spill footer; the locator is unknown here. */
3
+ function omissionNote(omittedBytes) {
4
+ return `(Omitted ${omittedBytes} bytes.)`;
5
+ }
6
+ /**
7
+ * The replacement shadow mode prices: head line, head, omission note, tail.
8
+ *
9
+ * `projectApply` replaces the note with the persisted spill footer; because the
10
+ * locator text is not known before that write, this is a lower bound.
11
+ */
12
+ function projectedText(truncation) {
13
+ return `${renderHeadLine(truncation)}\n${truncation.head}\n${omissionNote(truncation.omittedBytes)}\n${truncation.tail}`;
14
+ }
15
+ /** Price the original and the replacement together, so the pair always agrees. */
16
+ function measure(original, replacement, estimate) {
17
+ const before = estimate(original);
18
+ const after = estimate(replacement);
19
+ // A non-finite estimate is an unknown, never a number to serialise: JSON
20
+ // would turn NaN into `null`, which looks like a measured zero in the
21
+ // shadow account. The caller writes `estimate: 'unknown'` instead.
22
+ if (!Number.isFinite(before) || !Number.isFinite(after))
23
+ return undefined;
24
+ return { before, after, saved: before - after };
25
+ }
26
+ /**
27
+ * Report what projection would save, without touching the receipt.
28
+ *
29
+ * Guards run in a fixed order: an error receipt is skipped before anything
30
+ * else, so even an empty or oversized error keeps its evidence (design §5.4
31
+ * contract 4); then empty text; then a family with no configured window; then
32
+ * `truncate`'s own decision (trigger, 256 KiB cap, net-gain guard).
33
+ */
34
+ export async function projectShadow(input) {
35
+ const { text, isError, family, cfg, estimate } = input;
36
+ if (isError)
37
+ return { kind: 'skipped', reason: 'error-receipt' };
38
+ if (text === '')
39
+ return { kind: 'skipped', reason: 'empty' };
40
+ const params = cfg.projection[family];
41
+ if (!params)
42
+ return { kind: 'skipped', reason: 'family-not-configured' };
43
+ const truncation = truncate(text, params);
44
+ if (truncation === null)
45
+ return { kind: 'skipped', reason: 'not-worth-it' };
46
+ const measured = measure(text, projectedText(truncation), estimate);
47
+ return measured === undefined ? { kind: 'shadow' } : { kind: 'shadow', ...measured };
48
+ }
49
+ /**
50
+ * Decide whether the receipt may be replaced, in the plan's fixed order.
51
+ *
52
+ * Every guard returns the intact receipt and a stable code: an error receipt
53
+ * first (it is evidence, design §5.4 contract 4); then a family with no window;
54
+ * then `truncate`'s decision — calling it once is the same decision
55
+ * `shouldTruncate` exposes, without cutting twice; then the host pieces that
56
+ * would make the footer a lie: no backend, no owner, no footer renderer. None
57
+ * of these writes anything.
58
+ */
59
+ function precheck(input) {
60
+ const { text, isError, family, cfg, sessionId, spill, formatFooter } = input;
61
+ if (isError)
62
+ return { skip: { kind: 'skipped', reason: 'error-receipt' } };
63
+ const params = cfg.projection[family];
64
+ if (!params)
65
+ return { skip: { kind: 'skipped', reason: 'family-not-configured' } };
66
+ const truncation = truncate(text, params);
67
+ if (truncation === null)
68
+ return { skip: { kind: 'skipped', reason: 'not-worth-it' } };
69
+ if (!spill)
70
+ return { skip: { kind: 'skipped', reason: 'no-spill' } };
71
+ if (!sessionId)
72
+ return { skip: { kind: 'skipped', reason: 'no-owner' } };
73
+ if (!formatFooter)
74
+ return { skip: { kind: 'skipped', reason: 'projection-skipped:no-footer' } };
75
+ return { truncation, owner: { sessionId }, spill, formatFooter };
76
+ }
77
+ /**
78
+ * Replace an oversized receipt with its head, tail, and a way back to the rest.
79
+ *
80
+ * The canonical original is spilled *before* anything is replaced — never the
81
+ * projection, which would make the footer point at an artifact that does not
82
+ * contain what it promises. The footer sits on its own line between the two
83
+ * windows, and the composed replacement is re-checked against the original:
84
+ * at the trigger boundary a long locator can make the "projection" longer than
85
+ * the receipt it replaces, and a projection that grows a receipt is worse than
86
+ * none.
87
+ *
88
+ * A spill or footer failure is swallowed and reported as `spill-failed` /
89
+ * `footer-failed`; the caller's `post-execute` hook must never see an exception
90
+ * from here. The footer must be guarded too: the host turns a throwing
91
+ * `post-execute` listener into an `isError` result, which would lose the very
92
+ * output this module exists to preserve.
93
+ */
94
+ export async function projectApply(input) {
95
+ const ready = precheck(input);
96
+ if ('skip' in ready)
97
+ return { content: input.text, outcome: ready.skip };
98
+ const { text, family, toolName, callId, label } = input;
99
+ const { truncation, owner, spill, formatFooter } = ready;
100
+ // One guard covers both host calls: `saveText` and the footer renderer. The
101
+ // marker tells the two failures apart, because status counts distinguish
102
+ // them — and neither may reach the caller as an exception.
103
+ let phase = 'spill';
104
+ try {
105
+ const ref = await spill.saveText({
106
+ owner,
107
+ source: { kind: 'tool', toolName, callId: callId ?? toolName, label: label ?? family },
108
+ suggestedName: `${toolName}.txt`,
109
+ content: text,
110
+ });
111
+ phase = 'footer';
112
+ const footer = formatFooter({ kind: 'exact', count: truncation.omittedBytes }, ref);
113
+ const assembled = `${renderHeadLine(truncation)}\n${truncation.head}\n${footer}\n${truncation.tail}`;
114
+ // The footer is only known after the write, so this check can only run now.
115
+ // The backend exposes no delete: a spill that reaches this point stays in
116
+ // the store, unreferenced, while the model gets the original content back.
117
+ if (assembled.length >= text.length) {
118
+ return { content: text, outcome: { kind: 'skipped', reason: 'not-worth-it' } };
119
+ }
120
+ return {
121
+ content: assembled,
122
+ outcome: {
123
+ kind: 'applied',
124
+ omittedBytes: truncation.omittedBytes,
125
+ omittedCodePoints: truncation.omittedCodePoints,
126
+ locator: ref.locator,
127
+ },
128
+ };
129
+ }
130
+ catch {
131
+ return {
132
+ content: text,
133
+ outcome: { kind: 'skipped', reason: phase === 'spill' ? 'spill-failed' : 'footer-failed' },
134
+ };
135
+ }
136
+ }
137
+ //# sourceMappingURL=apply.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply.js","sourceRoot":"","sources":["../../src/projection/apply.ts"],"names":[],"mappings":"AAkCA,OAAO,EAAE,cAAc,EAAE,QAA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d,CAAC,CAAA;QACF,KAAK,GAAG,QAAQ,CAAA;QAEhB,MAAM,MAAM,GAAG,YAAY,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,YAAY,EAAE,EAAE,GAAG,CAAC,CAAA;QACnF,MAAM,SAAS,GAAG,GAAG,cAAc,CAAC,UAAU,CAAC,KAAK,UAAU,CAAC,IAAI,KAAK,MAAM,KAAK,UAAU,CAAC,IAAI,EAAE,CAAA;QAEpG,4EAA4E;QAC5E,0EAA0E;QAC1E,2EAA2E;QAC3E,IAAI,SAAS,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,cAAc,EAAE,EAAE,CAAA;QAChF,CAAC;QAED,OAAO;YACL,OAAO,EAAE,SAAS;YAClB,OAAO,EAAE;gBACP,IAAI,EAAE,SAAS;gBACf,YAAY,EAAE,UAAU,CAAC,YAAY;gBACrC,iBAAiB,EAAE,UAAU,CAAC,iBAAiB;gBAC/C,OAAO,EAAE,GAAG,CAAC,OAAO;aACrB;SACF,CAAA;IACH,CAAC;IAAC,MAAM,CAAC;QACP,OAAO;YACL,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,eAAe,EAAE;SAC3F,CAAA;IACH,CAAC;AACH,CAAC","sourcesContent":["/**\n * Projection execution: the shadow accounting and the real replacement.\n *\n * `projectShadow` is the half of projection that never changes what the model\n * sees: it decides whether a receipt *would* be cut, composes the replacement\n * string `projectApply` would produce, and prices both sides in tokens through\n * the caller's `estimate`. It writes nothing and reads no host service, so the\n * caller alone decides which mode to invoke (design §5.4).\n *\n * `projectApply` is the half that replaces, and it only replaces what is still\n * recoverable: the canonical receipt is persisted through the injected spill\n * backend first, then head line, head, spill footer and tail are composed. All\n * guards run before the write, a failed write or footer is a skip rather than\n * an exception, and a footer that would grow the receipt sends the original\n * back unchanged — a projection that grows a receipt defeats the plugin's\n * premise.\n *\n * The projected size is composed here, not read off `Truncation.after`:\n * `after` is the head line plus the two windows *without* the omission note, so\n * it is only a lower bound on the final replacement. Shadow mode prices\n * `renderHeadLine + head + omission note + tail`; the note's locator part is\n * unknown before the spill write, so only the standardized omission clause is\n * included.\n *\n * Skip reasons are stable codes, never prose: `error-receipt` (an error receipt\n * is evidence and is never projected), `family-not-configured` (the family has\n * no window), `not-worth-it` (`truncate`'s guard said no, or the footer left no\n * net gain), `empty` (shadow's empty receipt), and on the apply half\n * `no-spill`, `no-owner`, `projection-skipped:no-footer`, `spill-failed`, and\n * `footer-failed`.\n *\n * @module dsh-boost/projection/apply\n */\nimport type { BoostConfig, ProjectionParams, ToolFamily } from '../types.js'\nimport { renderHeadLine, truncate } from './truncate.js'\nimport type { Truncation } from './truncate.js'\n\n/** Which projection behaviour the caller is running. */\nexport type ProjectionMode = 'off' | 'shadow' | 'on'\n\n/** What projection did, or would have done, to one receipt. */\nexport interface ProjectionOutcome {\n kind: 'skipped' | 'shadow' | 'applied'\n /** Stable skip code; present only when `kind === 'skipped'`. */\n reason?: string\n /**\n * Tokens in the original receipt.\n *\n * Present only when `kind === 'shadow'` and the estimator priced both\n * sides; absent (with `estimate: 'unknown'` on the receipt) when it did not.\n */\n before?: number\n /** Tokens in the replacement shadow mode would have produced. */\n after?: number\n /** `before - after`. */\n saved?: number\n /**\n * UTF-8 bytes the replacement omits; present only when `kind === 'applied'`.\n *\n * Apply mode has no token estimator: the caller (T23b) prices both texts\n * itself, and these two fields are the projection's own accounting.\n */\n omittedBytes?: number\n /** Unicode code points the replacement omits; applied outcomes only. */\n omittedCodePoints?: number\n /**\n * The persisted artifact's locator; applied outcomes only.\n *\n * It is the path the footer tells the model to read, and the retrieval ledger\n * matches later `read`/`grep` arguments against it (Task 25).\n */\n locator?: string\n}\n\n/** A persisted spill artifact's model-facing handle. */\nexport interface SpillHandle {\n /** Opaque locator the model can `read` or `grep`; never parsed here. */\n locator: string\n /** How to retrieve the artifact, as guidance for the model. */\n retrievalHint: string\n}\n\n/**\n * The host spill store, narrowed to the one method projection needs.\n *\n * `callId` and `label` are required because the host's `SaveTextSpill` requires\n * them; `projectApply` fills them in before calling. `saveText` rejects on a\n * real storage failure, and that rejection is handled as a skip.\n */\nexport interface SpillBackend {\n saveText(input: {\n owner: { sessionId: string }\n source: { kind: 'tool'; toolName: string; callId: string; label: string }\n suggestedName: string\n content: string\n }): Promise<SpillHandle>\n}\n\n/**\n * Render the footer that names what was omitted and where the original lives.\n *\n * Injected by the caller, which dynamically imports the host's\n * `formatSpillNotice`; this module must never statically import\n * `@deepseek-ai/dsh-spill-policy` — it is not declared as a dependency, and a static import\n * would make the degradation path unreachable (design §5.4).\n */\nexport type FormatFooter = (omitted: { kind: 'exact'; count: number }, ref: SpillHandle) => string\n\n/** Everything one apply decision reads; every host service arrives pre-bound. */\nexport interface ProjectApplyInput {\n /** Canonical receipt text, byte for byte as it would enter history. */\n text: string\n /** Whether the host marked the receipt as an error. */\n isError: boolean\n /** Projection family, which selects the window from `cfg`. */\n family: ToolFamily\n /** Resolved plugin configuration. */\n cfg: BoostConfig\n /** Owning session; without one the spill has no owner and projection stops. */\n sessionId: string | undefined\n /** Tool name, recorded on the spill source and used for its file name. */\n toolName: string\n /** Model-issued call id; defaults to `toolName`. */\n callId?: string\n /** Human label for the artifact; defaults to `family`. */\n label?: string\n /** Spill backend, absent when the host has none (projection then stops). */\n spill: SpillBackend | undefined\n /** Footer renderer, absent when the host spill policy package is not installed. */\n formatFooter: FormatFooter | undefined\n}\n\n/** The omission clause of the spill footer; the locator is unknown here. */\nfunction omissionNote(omittedBytes: number): string {\n return `(Omitted ${omittedBytes} bytes.)`\n}\n\n/**\n * The replacement shadow mode prices: head line, head, omission note, tail.\n *\n * `projectApply` replaces the note with the persisted spill footer; because the\n * locator text is not known before that write, this is a lower bound.\n */\nfunction projectedText(truncation: Truncation): string {\n return `${renderHeadLine(truncation)}\\n${truncation.head}\\n${omissionNote(truncation.omittedBytes)}\\n${truncation.tail}`\n}\n\n/** Price the original and the replacement together, so the pair always agrees. */\nfunction measure(\n original: string,\n replacement: string,\n estimate: (s: string) => number,\n): Pick<ProjectionOutcome, 'before' | 'after' | 'saved'> | undefined {\n const before = estimate(original)\n const after = estimate(replacement)\n // A non-finite estimate is an unknown, never a number to serialise: JSON\n // would turn NaN into `null`, which looks like a measured zero in the\n // shadow account. The caller writes `estimate: 'unknown'` instead.\n if (!Number.isFinite(before) || !Number.isFinite(after)) return undefined\n return { before, after, saved: before - after }\n}\n\n/**\n * Report what projection would save, without touching the receipt.\n *\n * Guards run in a fixed order: an error receipt is skipped before anything\n * else, so even an empty or oversized error keeps its evidence (design §5.4\n * contract 4); then empty text; then a family with no configured window; then\n * `truncate`'s own decision (trigger, 256 KiB cap, net-gain guard).\n */\nexport async function projectShadow(input: {\n /** Canonical receipt text, byte for byte as it would enter history. */\n text: string\n /** Whether the host marked the receipt as an error. */\n isError: boolean\n /** Projection family, which selects the window from `cfg`. */\n family: ToolFamily\n /** Resolved plugin configuration. */\n cfg: BoostConfig\n /** Token estimator injected by the caller (never imported from the host). */\n estimate: (s: string) => number\n}): Promise<ProjectionOutcome> {\n const { text, isError, family, cfg, estimate } = input\n\n if (isError) return { kind: 'skipped', reason: 'error-receipt' }\n if (text === '') return { kind: 'skipped', reason: 'empty' }\n\n const params: ProjectionParams | undefined = cfg.projection[family]\n if (!params) return { kind: 'skipped', reason: 'family-not-configured' }\n\n const truncation = truncate(text, params)\n if (truncation === null) return { kind: 'skipped', reason: 'not-worth-it' }\n\n const measured = measure(text, projectedText(truncation), estimate)\n return measured === undefined ? { kind: 'shadow' } : { kind: 'shadow', ...measured }\n}\n\n/** The prechecks that passed, with the host pieces narrowed to their present values. */\ninterface Ready {\n truncation: Truncation\n owner: { sessionId: string }\n spill: SpillBackend\n formatFooter: FormatFooter\n}\n\n/**\n * Decide whether the receipt may be replaced, in the plan's fixed order.\n *\n * Every guard returns the intact receipt and a stable code: an error receipt\n * first (it is evidence, design §5.4 contract 4); then a family with no window;\n * then `truncate`'s decision — calling it once is the same decision\n * `shouldTruncate` exposes, without cutting twice; then the host pieces that\n * would make the footer a lie: no backend, no owner, no footer renderer. None\n * of these writes anything.\n */\nfunction precheck(input: ProjectApplyInput): { skip: ProjectionOutcome } | Ready {\n const { text, isError, family, cfg, sessionId, spill, formatFooter } = input\n\n if (isError) return { skip: { kind: 'skipped', reason: 'error-receipt' } }\n\n const params: ProjectionParams | undefined = cfg.projection[family]\n if (!params) return { skip: { kind: 'skipped', reason: 'family-not-configured' } }\n\n const truncation = truncate(text, params)\n if (truncation === null) return { skip: { kind: 'skipped', reason: 'not-worth-it' } }\n\n if (!spill) return { skip: { kind: 'skipped', reason: 'no-spill' } }\n if (!sessionId) return { skip: { kind: 'skipped', reason: 'no-owner' } }\n if (!formatFooter) return { skip: { kind: 'skipped', reason: 'projection-skipped:no-footer' } }\n\n return { truncation, owner: { sessionId }, spill, formatFooter }\n}\n\n/**\n * Replace an oversized receipt with its head, tail, and a way back to the rest.\n *\n * The canonical original is spilled *before* anything is replaced — never the\n * projection, which would make the footer point at an artifact that does not\n * contain what it promises. The footer sits on its own line between the two\n * windows, and the composed replacement is re-checked against the original:\n * at the trigger boundary a long locator can make the \"projection\" longer than\n * the receipt it replaces, and a projection that grows a receipt is worse than\n * none.\n *\n * A spill or footer failure is swallowed and reported as `spill-failed` /\n * `footer-failed`; the caller's `post-execute` hook must never see an exception\n * from here. The footer must be guarded too: the host turns a throwing\n * `post-execute` listener into an `isError` result, which would lose the very\n * output this module exists to preserve.\n */\nexport async function projectApply(\n input: ProjectApplyInput,\n): Promise<{ content: string; outcome: ProjectionOutcome }> {\n const ready = precheck(input)\n if ('skip' in ready) return { content: input.text, outcome: ready.skip }\n\n const { text, family, toolName, callId, label } = input\n const { truncation, owner, spill, formatFooter } = ready\n\n // One guard covers both host calls: `saveText` and the footer renderer. The\n // marker tells the two failures apart, because status counts distinguish\n // them — and neither may reach the caller as an exception.\n let phase: 'spill' | 'footer' = 'spill'\n try {\n const ref = await spill.saveText({\n owner,\n source: { kind: 'tool', toolName, callId: callId ?? toolName, label: label ?? family },\n suggestedName: `${toolName}.txt`,\n content: text,\n })\n phase = 'footer'\n\n const footer = formatFooter({ kind: 'exact', count: truncation.omittedBytes }, ref)\n const assembled = `${renderHeadLine(truncation)}\\n${truncation.head}\\n${footer}\\n${truncation.tail}`\n\n // The footer is only known after the write, so this check can only run now.\n // The backend exposes no delete: a spill that reaches this point stays in\n // the store, unreferenced, while the model gets the original content back.\n if (assembled.length >= text.length) {\n return { content: text, outcome: { kind: 'skipped', reason: 'not-worth-it' } }\n }\n\n return {\n content: assembled,\n outcome: {\n kind: 'applied',\n omittedBytes: truncation.omittedBytes,\n omittedCodePoints: truncation.omittedCodePoints,\n locator: ref.locator,\n },\n }\n } catch {\n return {\n content: text,\n outcome: { kind: 'skipped', reason: phase === 'spill' ? 'spill-failed' : 'footer-failed' },\n }\n }\n}\n"]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Receipt canonicalisation.
3
+ *
4
+ * The host hands a tool result's content to the plugin as an array of content
5
+ * blocks; every later stage (binding, guards, projection, hashing) reasons
6
+ * about one string. This module is the only place that array becomes that
7
+ * string.
8
+ *
9
+ * Only `type === 'text'` blocks contribute, in input order, byte-faithfully:
10
+ * no trim, no line-ending normalisation, no reordering, no separator. Text
11
+ * blocks without a `text` value contribute nothing and are not counted in
12
+ * `textBlocks`; other block kinds (image, file, …) are skipped entirely.
13
+ *
14
+ * The block array is untrusted at this boundary even though the host declares
15
+ * `ContentBlock[]`: the host validates lossless JSON, not block shape, so a
16
+ * third-party tool's renderer can hand over `null` or a non-object. Such a
17
+ * block is skipped, never dereferenced, and a content value that is not an
18
+ * array is an empty receipt. Throwing here would make the host replace the
19
+ * tool's real output with a tool error — the exact evidence loss this module
20
+ * exists to prevent.
21
+ *
22
+ * `empty` means "no text content" — it is true for an empty array and for
23
+ * text blocks whose concatenation is the empty string, and it is independent
24
+ * of `isError`.
25
+ *
26
+ * @module dsh-boost/projection/canonicalise
27
+ */
28
+ /** The single string later stages consume, plus the facts they branch on. */
29
+ export interface CanonicalReceipt {
30
+ /** Text blocks concatenated in order, byte-for-byte as received. */
31
+ text: string;
32
+ /** Whether the host marked the tool result as an error. */
33
+ isError: boolean;
34
+ /** `text.length === 0`; means "no text content", not "no blocks". */
35
+ empty: boolean;
36
+ /** Number of text blocks that contributed to `text`, not `blocks.length`. */
37
+ textBlocks: number;
38
+ }
39
+ /** Project a tool result's content blocks onto one canonical string. */
40
+ export declare function canonicalise(blocks: ReadonlyArray<{
41
+ type: string;
42
+ text?: string;
43
+ }>, isError: boolean): CanonicalReceipt;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Receipt canonicalisation.
3
+ *
4
+ * The host hands a tool result's content to the plugin as an array of content
5
+ * blocks; every later stage (binding, guards, projection, hashing) reasons
6
+ * about one string. This module is the only place that array becomes that
7
+ * string.
8
+ *
9
+ * Only `type === 'text'` blocks contribute, in input order, byte-faithfully:
10
+ * no trim, no line-ending normalisation, no reordering, no separator. Text
11
+ * blocks without a `text` value contribute nothing and are not counted in
12
+ * `textBlocks`; other block kinds (image, file, …) are skipped entirely.
13
+ *
14
+ * The block array is untrusted at this boundary even though the host declares
15
+ * `ContentBlock[]`: the host validates lossless JSON, not block shape, so a
16
+ * third-party tool's renderer can hand over `null` or a non-object. Such a
17
+ * block is skipped, never dereferenced, and a content value that is not an
18
+ * array is an empty receipt. Throwing here would make the host replace the
19
+ * tool's real output with a tool error — the exact evidence loss this module
20
+ * exists to prevent.
21
+ *
22
+ * `empty` means "no text content" — it is true for an empty array and for
23
+ * text blocks whose concatenation is the empty string, and it is independent
24
+ * of `isError`.
25
+ *
26
+ * @module dsh-boost/projection/canonicalise
27
+ */
28
+ /** Project a tool result's content blocks onto one canonical string. */
29
+ export function canonicalise(blocks, isError) {
30
+ // A malformed renderer can hand over a non-array; that is an empty receipt,
31
+ // not a crash on the way into history.
32
+ const list = Array.isArray(blocks) ? blocks : [];
33
+ const textBlocks = list.filter((block) => typeof block === 'object' &&
34
+ block !== null &&
35
+ block.type === 'text' &&
36
+ // `text` must actually be a string. `join` would silently coerce `null`
37
+ // to '' and `42` to '42', so a malformed renderer could inject content
38
+ // no text block declared (review row 64).
39
+ typeof block.text === 'string');
40
+ const text = textBlocks.map((block) => block.text).join('');
41
+ return { text, isError, empty: text.length === 0, textBlocks: textBlocks.length };
42
+ }
43
+ //# sourceMappingURL=canonicalise.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonicalise.js","sourceRoot":"","sources":["../../src/projection/canonicalise.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAcH,wEAAwE;AACxE,MAAM,UAAU,YAAY,CAC1B,MAAsD,EACtD,OAAgB;IAEhB,4EAA4E;IAC5E,uCAAuC;IACvC,MAAM,IAAI,GAA2B,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAA;IACxE,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAC5B,CAAC,KAAK,EAA2C,EAAE,CACjD,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACb,KAA4B,CAAC,IAAI,KAAK,MAAM;QAC7C,wEAAwE;QACxE,uEAAuE;QACvE,0CAA0C;QAC1C,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ,CACzD,CAAA;IACD,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,UAAU,EAAE,UAAU,CAAC,MAAM,EAAE,CAAA;AACnF,CAAC","sourcesContent":["/**\n * Receipt canonicalisation.\n *\n * The host hands a tool result's content to the plugin as an array of content\n * blocks; every later stage (binding, guards, projection, hashing) reasons\n * about one string. This module is the only place that array becomes that\n * string.\n *\n * Only `type === 'text'` blocks contribute, in input order, byte-faithfully:\n * no trim, no line-ending normalisation, no reordering, no separator. Text\n * blocks without a `text` value contribute nothing and are not counted in\n * `textBlocks`; other block kinds (image, file, …) are skipped entirely.\n *\n * The block array is untrusted at this boundary even though the host declares\n * `ContentBlock[]`: the host validates lossless JSON, not block shape, so a\n * third-party tool's renderer can hand over `null` or a non-object. Such a\n * block is skipped, never dereferenced, and a content value that is not an\n * array is an empty receipt. Throwing here would make the host replace the\n * tool's real output with a tool error — the exact evidence loss this module\n * exists to prevent.\n *\n * `empty` means \"no text content\" — it is true for an empty array and for\n * text blocks whose concatenation is the empty string, and it is independent\n * of `isError`.\n *\n * @module dsh-boost/projection/canonicalise\n */\n\n/** The single string later stages consume, plus the facts they branch on. */\nexport interface CanonicalReceipt {\n /** Text blocks concatenated in order, byte-for-byte as received. */\n text: string\n /** Whether the host marked the tool result as an error. */\n isError: boolean\n /** `text.length === 0`; means \"no text content\", not \"no blocks\". */\n empty: boolean\n /** Number of text blocks that contributed to `text`, not `blocks.length`. */\n textBlocks: number\n}\n\n/** Project a tool result's content blocks onto one canonical string. */\nexport function canonicalise(\n blocks: ReadonlyArray<{ type: string; text?: string }>,\n isError: boolean,\n): CanonicalReceipt {\n // A malformed renderer can hand over a non-array; that is an empty receipt,\n // not a crash on the way into history.\n const list: ReadonlyArray<unknown> = Array.isArray(blocks) ? blocks : []\n const textBlocks = list.filter(\n (block): block is { type: 'text'; text: string } =>\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n // `text` must actually be a string. `join` would silently coerce `null`\n // to '' and `42` to '42', so a malformed renderer could inject content\n // no text block declared (review row 64).\n typeof (block as { text?: unknown }).text === 'string',\n )\n const text = textBlocks.map((block) => block.text).join('')\n return { text, isError, empty: text.length === 0, textBlocks: textBlocks.length }\n}"]}