dsh-compaction-studio 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-compaction-studio
2
2
 
3
- > **Version:** `0.1.0` — part of **[The Ivory Tower](https://github.com/janpauldahlke/the-ivory-tower)** Studio suite for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness).
3
+ > **Version:** `0.1.1` — part of **[The Ivory Tower](https://github.com/janpauldahlke/the-ivory-tower)** Studio suite for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness).
4
4
 
5
5
  Zero-fork, language-preserving editorial, research, and curriculum conversation compaction overlay for DeepSeek Harness (`dsh`).
6
6
 
package/lib/client.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/client/index.ts", "../src/shared/types.ts"],
4
- "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 browser client face (ModuleLoader CJS entry).\n */\nimport { PLUGIN } from '../shared/types.ts'\n\nexport const name = PLUGIN\nexport const inject: string[] = []\n\nexport function apply(): void {\n // Populated by client-facing milestones; no-op for host-only bricks.\n}\n", "/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.0' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n"],
4
+ "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 browser client face (ModuleLoader CJS entry).\n */\nimport { PLUGIN } from '../shared/types.ts'\n\nexport const name = PLUGIN\nexport const inject: string[] = []\n\nexport function apply(): void {\n // Populated by client-facing milestones; no-op for host-only bricks.\n}\n", "/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.1' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,SAAS;;;ADCf,IAAM,OAAO;AACb,IAAM,SAAmB,CAAC;AAE1B,SAAS,QAAc;AAE9B;",
6
6
  "names": []
7
7
  }
package/lib/core.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/shared/types.ts
2
2
  var PLUGIN = "dsh-compaction-studio";
3
- var VERSION = "0.1.0";
3
+ var VERSION = "0.1.1";
4
4
 
5
5
  // src/core/config.ts
6
6
  var VALID_LANGUAGE_POLICIES = Object.freeze([
@@ -124,10 +124,10 @@ function buildStudioCompactionInstruction(config) {
124
124
  "- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]",
125
125
  "",
126
126
  "## Active Workbenches & Unit Spine",
127
- "- [active galley packetIds, templateIds, blockIds (e.g. h1, q1, t1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]",
127
+ "- [active galley packetIds (e.g. p-\u2026), templateIds, blockIds (e.g. b1, b2), sheetIds (e.g. s1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]",
128
128
  "",
129
129
  "## Vetted Sources, Quotes & Media",
130
- "- [exact fundusIds, quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs, and key verbatim quotes or data points in play]",
130
+ "- [exact fundusIds (e.g. pas-\u2026, src-\u2026), quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs (e.g. a1), plateIds (e.g. plt-\u2026), and key verbatim quotes or data points in play]",
131
131
  "",
132
132
  "## Craft, Didactic & House-Style Constraints",
133
133
  '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or "do not" instructions]',
package/lib/core.mjs.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/shared/types.ts", "../src/core/config.ts", "../src/core/prompt.ts", "../src/core/interceptor.ts", "../src/core/index.ts"],
4
- "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.0' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n", "/**\n * dsh-compaction-studio \u2014 strict configuration validation & normalization.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\n\nexport const VALID_LANGUAGE_POLICIES: readonly LanguagePolicy[] = Object.freeze([\n 'preserve-conversation',\n 'en',\n 'de',\n])\n\nexport const MAX_EXTRA_PRESERVE_RULES = 5\nexport const MAX_EXTRA_RULE_LENGTH = 200\nexport const MAX_EXTRA_RULES_TOTAL_LENGTH = 600\n\nconst ALLOWED_KEYS = new Set<string>(['enabled', 'languagePolicy', 'extraPreserveRules'])\n\nconst EMPTY_RULES: readonly string[] = Object.freeze([])\n\nexport const DEFAULT_STUDIO_CONFIG: ResolvedStudioCompactionConfig = Object.freeze({\n enabled: true,\n languagePolicy: 'preserve-conversation',\n extraPreserveRules: EMPTY_RULES,\n})\n\n/**\n * Validate and normalize `StudioCompactionConfig` into a frozen `ResolvedStudioCompactionConfig`.\n * Throws descriptive `Error` instances on unknown keys, invalid types/enums, or rule cap violations.\n */\nexport function resolveStudioConfig(rawConfig?: unknown): ResolvedStudioCompactionConfig {\n if (rawConfig === undefined) {\n return DEFAULT_STUDIO_CONFIG\n }\n if (rawConfig === null || typeof rawConfig !== 'object' || Array.isArray(rawConfig)) {\n throw new Error('StudioCompactionConfig: expected a configuration object')\n }\n\n const record = rawConfig as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (!ALLOWED_KEYS.has(key)) {\n throw new Error(`StudioCompactionConfig: unknown key \"${key}\"`)\n }\n }\n\n let enabled = true\n if (record.enabled !== undefined) {\n if (typeof record.enabled !== 'boolean') {\n throw new Error('StudioCompactionConfig: \"enabled\" must be a boolean')\n }\n enabled = record.enabled\n }\n\n let languagePolicy: LanguagePolicy = 'preserve-conversation'\n if (record.languagePolicy !== undefined) {\n if (\n typeof record.languagePolicy !== 'string' ||\n !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy as LanguagePolicy)\n ) {\n throw new Error(\n `StudioCompactionConfig: invalid \"languagePolicy\" \"${String(record.languagePolicy)}\" (expected \"preserve-conversation\", \"en\", or \"de\")`,\n )\n }\n languagePolicy = record.languagePolicy as LanguagePolicy\n }\n\n let extraPreserveRules: readonly string[] = EMPTY_RULES\n if (record.extraPreserveRules !== undefined) {\n if (!Array.isArray(record.extraPreserveRules)) {\n throw new Error('StudioCompactionConfig: \"extraPreserveRules\" must be an array of strings')\n }\n if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`,\n )\n }\n\n const normalized: string[] = []\n let totalChars = 0\n\n for (let i = 0; i < record.extraPreserveRules.length; i++) {\n const item = record.extraPreserveRules[i]\n if (typeof item !== 'string') {\n throw new Error(`StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be a string`)\n }\n if (item.includes('\\r') || item.includes('\\n')) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be single-line (no CR/LF)`,\n )\n }\n const trimmed = item.trim()\n if (trimmed.length === 0) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must not be empty`,\n )\n }\n if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`,\n )\n }\n totalChars += trimmed.length\n if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`,\n )\n }\n normalized.push(trimmed)\n }\n\n extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized)\n }\n\n return Object.freeze({\n enabled,\n languagePolicy,\n extraPreserveRules,\n })\n}\n", "/**\n * dsh-compaction-studio \u2014 domain-neutral, language-preserving editorial compaction prompt builder.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\n\nexport const SECTION_HEADINGS = Object.freeze([\n '## Editorial & Authoring Goal',\n '## Active Workbenches & Unit Spine',\n '## Vetted Sources, Quotes & Media',\n '## Craft, Didactic & House-Style Constraints',\n '## Open Reviews & Diagnostics',\n '## Pending Work',\n '## Next Step',\n] as const)\n\nexport const LANGUAGE_RULE_LINES: Readonly<Record<LanguagePolicy, string>> = Object.freeze({\n 'preserve-conversation':\n 'Write bullet content in the dominant human language used by the user in the conversation (for example, German if the user writes in German, English if in English); preserve original-language source quotes verbatim.',\n en: 'Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.',\n de: 'Write concise German bullet content (pr\u00E4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim.',\n})\n\n/**\n * Build the exact Studio Editorial Compaction instruction text with deterministic 7-section\n * Markdown headings, language policy rule, `<compacted-summary>` prior-checkpoint merge rule,\n * and optional validated `extraPreserveRules` bullets.\n */\nexport function buildStudioCompactionInstruction(\n config?: StudioCompactionConfig | ResolvedStudioCompactionConfig,\n): string {\n const resolved = resolveStudioConfig(config)\n const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy]\n\n const lines: string[] = [\n 'You are now acting as the context compaction engine for a document, research, and curriculum co-authoring studio. Condense the conversation ABOVE into a structured editorial checkpoint so work can resume seamlessly with zero loss of essential context, provenance, or constraints.',\n '',\n 'Output EXACTLY the Markdown structure below: keep every `##` section heading verbatim and in this exact order. Use concise, information-dense bullets rather than prose paragraphs. Write `(none)` for any empty section \u2014 never omit or rename a section.',\n '',\n '## Editorial & Authoring Goal',\n \"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]\",\n '',\n '## Active Workbenches & Unit Spine',\n '- [active galley packetIds, templateIds, blockIds (e.g. h1, q1, t1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]',\n '',\n '## Vetted Sources, Quotes & Media',\n '- [exact fundusIds, quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs, and key verbatim quotes or data points in play]',\n '',\n '## Craft, Didactic & House-Style Constraints',\n '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or \"do not\" instructions]',\n '',\n '## Open Reviews & Diagnostics',\n '- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]',\n '',\n '## Pending Work',\n '- [explicitly requested work not yet completed, respecting staged-draft boundaries]',\n '',\n '## Next Step',\n \"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]\",\n '',\n 'Rules:',\n `- ${languageRule}`,\n '- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.',\n '- Preserve ALL exact identifiers verbatim: `packetId`s, `blockId`s, `fundusId`s, `quoteSha256` hashes, `mission_id`s, file paths, URLs, dates, numbers, citations, and quoted primary-source fragments. Never paraphrase away an ID or hash.',\n '- Capture user feedback, rejections, and explicit corrections faithfully.',\n '- Do NOT mention this summarization request or acknowledge that context was compacted.',\n '- Output ONLY the Markdown checkpoint text: do NOT call any tools, do NOT emit images, and do NOT wrap the output in outer XML/code fences.',\n '- If the conversation above already contains a <compacted-summary> block, it is a PRIOR checkpoint: do not copy it verbatim \u2014 keep still-valid facts, drop superseded ones, and merge newer developments into one consolidated checkpoint under the same headings.',\n ]\n\n for (const extraRule of resolved.extraPreserveRules) {\n lines.push(`- ${extraRule}`)\n }\n\n return lines.join('\\n')\n}\n", "/**\n * dsh-compaction-studio \u2014 zero-fork `llm/stream` compaction prompt interceptor.\n */\nimport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\nimport { buildStudioCompactionInstruction } from './prompt.ts'\n\nexport const COMPACTION_SUMMARY_MARKER = '<compacted-summary>'\n\n/**\n * Create a deep-frozen replacement trailing `UserMessage` carrying the Studio compaction prompt.\n * Only freezes the message itself, its single-element `content` tuple, and its `{ type: 'text', text }` block.\n */\nexport function buildFrozenCompactionUserMessage(instructionText: string): CompactionUserMessage {\n const textPart: TextContentPartLike = Object.freeze({\n type: 'text',\n text: instructionText,\n })\n const content = Object.freeze([textPart] as const)\n return Object.freeze({\n role: 'user',\n content,\n })\n}\n\n/**\n * Verify that `message` matches `compaction-basic`'s trailing instruction `UserMessage`\n * (`role === 'user'`, `Array.isArray(content)`, concatenated text blocks contain `<compacted-summary>`).\n */\nexport function isCompactionInstructionMessage(message: unknown): message is RequestMessageLike {\n if (!message || typeof message !== 'object') {\n return false\n }\n const msg = message as RequestMessageLike\n if (msg.role !== 'user' || !Array.isArray(msg.content)) {\n return false\n }\n\n let concatenatedText = ''\n for (const part of msg.content) {\n if (\n part &&\n typeof part === 'object' &&\n (part as ContentPartLike).type === 'text' &&\n typeof (part as ContentPartLike).text === 'string'\n ) {\n concatenatedText += (part as ContentPartLike).text as string\n }\n }\n\n return concatenatedText.includes(COMPACTION_SUMMARY_MARKER)\n}\n\nfunction isFrozenCompactionMessage(value: unknown): value is CompactionUserMessage {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n (value as RequestMessageLike).role === 'user' &&\n Array.isArray((value as RequestMessageLike).content)\n )\n}\n\n/**\n * Construct a detached `GenerateOptionsLike` replacing ONLY `messages[messages.length - 1]`\n * with a deep-frozen Studio compaction `UserMessage`.\n *\n * Invariants:\n * - Returns `null` (fail-open) if `options.messages` is empty or the trailing message fails `isCompactionInstructionMessage`.\n * - Never mutates `options` or `options.messages`.\n * - Preserves `messages.slice(0, -1)` element references (`===`) and all top-level keys (`tools`, `signal`, etc.).\n * - Never recursively freezes `AbortSignal` or prefix messages (only shallow-freezes `rewrittenOptions` and `rewrittenOptions.messages`, plus deep-freezes the new trailing `UserMessage`).\n */\nexport function rewriteCompactionOptions(\n options: GenerateOptionsLike,\n replacement?:\n | string\n | CompactionUserMessage\n | StudioCompactionConfig\n | ResolvedStudioCompactionConfig,\n): GenerateOptionsLike | null {\n if (!options || typeof options !== 'object' || !Array.isArray(options.messages)) {\n return null\n }\n const len = options.messages.length\n if (len < 1) {\n return null\n }\n\n const lastMessage = options.messages[len - 1]\n if (!isCompactionInstructionMessage(lastMessage)) {\n return null\n }\n\n let trailingMessage: CompactionUserMessage\n if (typeof replacement === 'string') {\n trailingMessage = buildFrozenCompactionUserMessage(replacement)\n } else if (isFrozenCompactionMessage(replacement)) {\n trailingMessage = replacement\n } else {\n trailingMessage = buildFrozenCompactionUserMessage(\n buildStudioCompactionInstruction(replacement),\n )\n }\n\n const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage])\n return Object.freeze({\n ...options,\n messages: nextMessages,\n })\n}\n\nfunction safeWarn(onWarn: ((message: string) => void) | undefined, message: string): void {\n if (!onWarn) return\n try {\n onWarn(message)\n } catch {\n /* logging must never throw or abort an LLM stream */\n }\n}\n\n/**\n * Create a `llm/stream` Cordis waterfall listener that intercepts strictly `options.purpose === 'compaction'`,\n * guards against infinite recursion with a `WeakSet<object>`, fails open on unexpected shapes,\n * and re-dispatches `runtime.stream(rewrittenOptions)`.\n */\nexport function createCompactionStreamHandler(\n init: CompactionStreamHandlerInit = {},\n): CompactionStreamListener {\n const resolvedConfig = resolveStudioConfig(init.config)\n const instructionText = buildStudioCompactionInstruction(resolvedConfig)\n const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText)\n const rewritten = new WeakSet<object>()\n\n return function compactionStreamListener(\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n ): AsyncIterable<StreamChunkLike> {\n // Fast path: 0 allocations for disabled overlay, non-compaction traffic, or WeakSet re-entry.\n if (\n !resolvedConfig.enabled ||\n !options ||\n typeof options !== 'object' ||\n options.purpose !== 'compaction' ||\n rewritten.has(options)\n ) {\n return next()\n }\n\n // Fail-open shape check on compaction-basic's trailing instruction message.\n const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage)\n if (!rewrittenOptions) {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite',\n )\n return next()\n }\n\n const selfRuntime =\n this && typeof (this as LlmRuntimeLike).stream === 'function'\n ? (this as LlmRuntimeLike)\n : undefined\n const runtime = selfRuntime ?? init.getRuntime?.()\n if (!runtime || typeof runtime.stream !== 'function') {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite',\n )\n return next()\n }\n\n rewritten.add(rewrittenOptions)\n return runtime.stream(rewrittenOptions)\n }\n}\n", "/**\n * dsh-compaction-studio \u2014 hermetic core module (zero @deepseek-ai/* imports; testable via node --test).\n */\nimport {\n PLUGIN,\n VERSION,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type ContentPartLike,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StreamChunkLike,\n type StreamNextFn,\n type StudioCompactionConfig,\n type TextContentPartLike,\n} from '../shared/types.ts'\n\nexport { PLUGIN, VERSION }\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n}\n\nexport {\n DEFAULT_STUDIO_CONFIG,\n MAX_EXTRA_PRESERVE_RULES,\n MAX_EXTRA_RULE_LENGTH,\n MAX_EXTRA_RULES_TOTAL_LENGTH,\n VALID_LANGUAGE_POLICIES,\n resolveStudioConfig,\n} from './config.ts'\n\nexport {\n LANGUAGE_RULE_LINES,\n SECTION_HEADINGS,\n buildStudioCompactionInstruction,\n} from './prompt.ts'\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n buildFrozenCompactionUserMessage,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n rewriteCompactionOptions,\n} from './interceptor.ts'\n\nexport function probeHealth(): HealthProbe {\n return { ok: true, plugin: PLUGIN, version: VERSION }\n}\n"],
4
+ "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.1' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n", "/**\n * dsh-compaction-studio \u2014 strict configuration validation & normalization.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\n\nexport const VALID_LANGUAGE_POLICIES: readonly LanguagePolicy[] = Object.freeze([\n 'preserve-conversation',\n 'en',\n 'de',\n])\n\nexport const MAX_EXTRA_PRESERVE_RULES = 5\nexport const MAX_EXTRA_RULE_LENGTH = 200\nexport const MAX_EXTRA_RULES_TOTAL_LENGTH = 600\n\nconst ALLOWED_KEYS = new Set<string>(['enabled', 'languagePolicy', 'extraPreserveRules'])\n\nconst EMPTY_RULES: readonly string[] = Object.freeze([])\n\nexport const DEFAULT_STUDIO_CONFIG: ResolvedStudioCompactionConfig = Object.freeze({\n enabled: true,\n languagePolicy: 'preserve-conversation',\n extraPreserveRules: EMPTY_RULES,\n})\n\n/**\n * Validate and normalize `StudioCompactionConfig` into a frozen `ResolvedStudioCompactionConfig`.\n * Throws descriptive `Error` instances on unknown keys, invalid types/enums, or rule cap violations.\n */\nexport function resolveStudioConfig(rawConfig?: unknown): ResolvedStudioCompactionConfig {\n if (rawConfig === undefined) {\n return DEFAULT_STUDIO_CONFIG\n }\n if (rawConfig === null || typeof rawConfig !== 'object' || Array.isArray(rawConfig)) {\n throw new Error('StudioCompactionConfig: expected a configuration object')\n }\n\n const record = rawConfig as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (!ALLOWED_KEYS.has(key)) {\n throw new Error(`StudioCompactionConfig: unknown key \"${key}\"`)\n }\n }\n\n let enabled = true\n if (record.enabled !== undefined) {\n if (typeof record.enabled !== 'boolean') {\n throw new Error('StudioCompactionConfig: \"enabled\" must be a boolean')\n }\n enabled = record.enabled\n }\n\n let languagePolicy: LanguagePolicy = 'preserve-conversation'\n if (record.languagePolicy !== undefined) {\n if (\n typeof record.languagePolicy !== 'string' ||\n !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy as LanguagePolicy)\n ) {\n throw new Error(\n `StudioCompactionConfig: invalid \"languagePolicy\" \"${String(record.languagePolicy)}\" (expected \"preserve-conversation\", \"en\", or \"de\")`,\n )\n }\n languagePolicy = record.languagePolicy as LanguagePolicy\n }\n\n let extraPreserveRules: readonly string[] = EMPTY_RULES\n if (record.extraPreserveRules !== undefined) {\n if (!Array.isArray(record.extraPreserveRules)) {\n throw new Error('StudioCompactionConfig: \"extraPreserveRules\" must be an array of strings')\n }\n if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`,\n )\n }\n\n const normalized: string[] = []\n let totalChars = 0\n\n for (let i = 0; i < record.extraPreserveRules.length; i++) {\n const item = record.extraPreserveRules[i]\n if (typeof item !== 'string') {\n throw new Error(`StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be a string`)\n }\n if (item.includes('\\r') || item.includes('\\n')) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be single-line (no CR/LF)`,\n )\n }\n const trimmed = item.trim()\n if (trimmed.length === 0) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must not be empty`,\n )\n }\n if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`,\n )\n }\n totalChars += trimmed.length\n if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`,\n )\n }\n normalized.push(trimmed)\n }\n\n extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized)\n }\n\n return Object.freeze({\n enabled,\n languagePolicy,\n extraPreserveRules,\n })\n}\n", "/**\n * dsh-compaction-studio \u2014 domain-neutral, language-preserving editorial compaction prompt builder.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\n\nexport const SECTION_HEADINGS = Object.freeze([\n '## Editorial & Authoring Goal',\n '## Active Workbenches & Unit Spine',\n '## Vetted Sources, Quotes & Media',\n '## Craft, Didactic & House-Style Constraints',\n '## Open Reviews & Diagnostics',\n '## Pending Work',\n '## Next Step',\n] as const)\n\nexport const LANGUAGE_RULE_LINES: Readonly<Record<LanguagePolicy, string>> = Object.freeze({\n 'preserve-conversation':\n 'Write bullet content in the dominant human language used by the user in the conversation (for example, German if the user writes in German, English if in English); preserve original-language source quotes verbatim.',\n en: 'Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.',\n de: 'Write concise German bullet content (pr\u00E4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim.',\n})\n\n/**\n * Build the exact Studio Editorial Compaction instruction text with deterministic 7-section\n * Markdown headings, language policy rule, `<compacted-summary>` prior-checkpoint merge rule,\n * and optional validated `extraPreserveRules` bullets.\n */\nexport function buildStudioCompactionInstruction(\n config?: StudioCompactionConfig | ResolvedStudioCompactionConfig,\n): string {\n const resolved = resolveStudioConfig(config)\n const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy]\n\n const lines: string[] = [\n 'You are now acting as the context compaction engine for a document, research, and curriculum co-authoring studio. Condense the conversation ABOVE into a structured editorial checkpoint so work can resume seamlessly with zero loss of essential context, provenance, or constraints.',\n '',\n 'Output EXACTLY the Markdown structure below: keep every `##` section heading verbatim and in this exact order. Use concise, information-dense bullets rather than prose paragraphs. Write `(none)` for any empty section \u2014 never omit or rename a section.',\n '',\n '## Editorial & Authoring Goal',\n \"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]\",\n '',\n '## Active Workbenches & Unit Spine',\n '- [active galley packetIds (e.g. p-\u2026), templateIds, blockIds (e.g. b1, b2), sheetIds (e.g. s1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]',\n '',\n '## Vetted Sources, Quotes & Media',\n '- [exact fundusIds (e.g. pas-\u2026, src-\u2026), quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs (e.g. a1), plateIds (e.g. plt-\u2026), and key verbatim quotes or data points in play]',\n '',\n '## Craft, Didactic & House-Style Constraints',\n '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or \"do not\" instructions]',\n '',\n '## Open Reviews & Diagnostics',\n '- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]',\n '',\n '## Pending Work',\n '- [explicitly requested work not yet completed, respecting staged-draft boundaries]',\n '',\n '## Next Step',\n \"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]\",\n '',\n 'Rules:',\n `- ${languageRule}`,\n '- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.',\n '- Preserve ALL exact identifiers verbatim: `packetId`s, `blockId`s, `fundusId`s, `quoteSha256` hashes, `mission_id`s, file paths, URLs, dates, numbers, citations, and quoted primary-source fragments. Never paraphrase away an ID or hash.',\n '- Capture user feedback, rejections, and explicit corrections faithfully.',\n '- Do NOT mention this summarization request or acknowledge that context was compacted.',\n '- Output ONLY the Markdown checkpoint text: do NOT call any tools, do NOT emit images, and do NOT wrap the output in outer XML/code fences.',\n '- If the conversation above already contains a <compacted-summary> block, it is a PRIOR checkpoint: do not copy it verbatim \u2014 keep still-valid facts, drop superseded ones, and merge newer developments into one consolidated checkpoint under the same headings.',\n ]\n\n for (const extraRule of resolved.extraPreserveRules) {\n lines.push(`- ${extraRule}`)\n }\n\n return lines.join('\\n')\n}\n", "/**\n * dsh-compaction-studio \u2014 zero-fork `llm/stream` compaction prompt interceptor.\n */\nimport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\nimport { buildStudioCompactionInstruction } from './prompt.ts'\n\nexport const COMPACTION_SUMMARY_MARKER = '<compacted-summary>'\n\n/**\n * Create a deep-frozen replacement trailing `UserMessage` carrying the Studio compaction prompt.\n * Only freezes the message itself, its single-element `content` tuple, and its `{ type: 'text', text }` block.\n */\nexport function buildFrozenCompactionUserMessage(instructionText: string): CompactionUserMessage {\n const textPart: TextContentPartLike = Object.freeze({\n type: 'text',\n text: instructionText,\n })\n const content = Object.freeze([textPart] as const)\n return Object.freeze({\n role: 'user',\n content,\n })\n}\n\n/**\n * Verify that `message` matches `compaction-basic`'s trailing instruction `UserMessage`\n * (`role === 'user'`, `Array.isArray(content)`, concatenated text blocks contain `<compacted-summary>`).\n */\nexport function isCompactionInstructionMessage(message: unknown): message is RequestMessageLike {\n if (!message || typeof message !== 'object') {\n return false\n }\n const msg = message as RequestMessageLike\n if (msg.role !== 'user' || !Array.isArray(msg.content)) {\n return false\n }\n\n let concatenatedText = ''\n for (const part of msg.content) {\n if (\n part &&\n typeof part === 'object' &&\n (part as ContentPartLike).type === 'text' &&\n typeof (part as ContentPartLike).text === 'string'\n ) {\n concatenatedText += (part as ContentPartLike).text as string\n }\n }\n\n return concatenatedText.includes(COMPACTION_SUMMARY_MARKER)\n}\n\nfunction isFrozenCompactionMessage(value: unknown): value is CompactionUserMessage {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n (value as RequestMessageLike).role === 'user' &&\n Array.isArray((value as RequestMessageLike).content)\n )\n}\n\n/**\n * Construct a detached `GenerateOptionsLike` replacing ONLY `messages[messages.length - 1]`\n * with a deep-frozen Studio compaction `UserMessage`.\n *\n * Invariants:\n * - Returns `null` (fail-open) if `options.messages` is empty or the trailing message fails `isCompactionInstructionMessage`.\n * - Never mutates `options` or `options.messages`.\n * - Preserves `messages.slice(0, -1)` element references (`===`) and all top-level keys (`tools`, `signal`, etc.).\n * - Never recursively freezes `AbortSignal` or prefix messages (only shallow-freezes `rewrittenOptions` and `rewrittenOptions.messages`, plus deep-freezes the new trailing `UserMessage`).\n */\nexport function rewriteCompactionOptions(\n options: GenerateOptionsLike,\n replacement?:\n | string\n | CompactionUserMessage\n | StudioCompactionConfig\n | ResolvedStudioCompactionConfig,\n): GenerateOptionsLike | null {\n if (!options || typeof options !== 'object' || !Array.isArray(options.messages)) {\n return null\n }\n const len = options.messages.length\n if (len < 1) {\n return null\n }\n\n const lastMessage = options.messages[len - 1]\n if (!isCompactionInstructionMessage(lastMessage)) {\n return null\n }\n\n let trailingMessage: CompactionUserMessage\n if (typeof replacement === 'string') {\n trailingMessage = buildFrozenCompactionUserMessage(replacement)\n } else if (isFrozenCompactionMessage(replacement)) {\n trailingMessage = replacement\n } else {\n trailingMessage = buildFrozenCompactionUserMessage(\n buildStudioCompactionInstruction(replacement),\n )\n }\n\n const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage])\n return Object.freeze({\n ...options,\n messages: nextMessages,\n })\n}\n\nfunction safeWarn(onWarn: ((message: string) => void) | undefined, message: string): void {\n if (!onWarn) return\n try {\n onWarn(message)\n } catch {\n /* logging must never throw or abort an LLM stream */\n }\n}\n\n/**\n * Create a `llm/stream` Cordis waterfall listener that intercepts strictly `options.purpose === 'compaction'`,\n * guards against infinite recursion with a `WeakSet<object>`, fails open on unexpected shapes,\n * and re-dispatches `runtime.stream(rewrittenOptions)`.\n */\nexport function createCompactionStreamHandler(\n init: CompactionStreamHandlerInit = {},\n): CompactionStreamListener {\n const resolvedConfig = resolveStudioConfig(init.config)\n const instructionText = buildStudioCompactionInstruction(resolvedConfig)\n const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText)\n const rewritten = new WeakSet<object>()\n\n return function compactionStreamListener(\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n ): AsyncIterable<StreamChunkLike> {\n // Fast path: 0 allocations for disabled overlay, non-compaction traffic, or WeakSet re-entry.\n if (\n !resolvedConfig.enabled ||\n !options ||\n typeof options !== 'object' ||\n options.purpose !== 'compaction' ||\n rewritten.has(options)\n ) {\n return next()\n }\n\n // Fail-open shape check on compaction-basic's trailing instruction message.\n const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage)\n if (!rewrittenOptions) {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite',\n )\n return next()\n }\n\n const selfRuntime =\n this && typeof (this as LlmRuntimeLike).stream === 'function'\n ? (this as LlmRuntimeLike)\n : undefined\n const runtime = selfRuntime ?? init.getRuntime?.()\n if (!runtime || typeof runtime.stream !== 'function') {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite',\n )\n return next()\n }\n\n rewritten.add(rewrittenOptions)\n return runtime.stream(rewrittenOptions)\n }\n}\n", "/**\n * dsh-compaction-studio \u2014 hermetic core module (zero @deepseek-ai/* imports; testable via node --test).\n */\nimport {\n PLUGIN,\n VERSION,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type ContentPartLike,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StreamChunkLike,\n type StreamNextFn,\n type StudioCompactionConfig,\n type TextContentPartLike,\n} from '../shared/types.ts'\n\nexport { PLUGIN, VERSION }\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n}\n\nexport {\n DEFAULT_STUDIO_CONFIG,\n MAX_EXTRA_PRESERVE_RULES,\n MAX_EXTRA_RULE_LENGTH,\n MAX_EXTRA_RULES_TOTAL_LENGTH,\n VALID_LANGUAGE_POLICIES,\n resolveStudioConfig,\n} from './config.ts'\n\nexport {\n LANGUAGE_RULE_LINES,\n SECTION_HEADINGS,\n buildStudioCompactionInstruction,\n} from './prompt.ts'\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n buildFrozenCompactionUserMessage,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n rewriteCompactionOptions,\n} from './interceptor.ts'\n\nexport function probeHealth(): HealthProbe {\n return { ok: true, plugin: PLUGIN, version: VERSION }\n}\n"],
5
5
  "mappings": ";AAIO,IAAM,SAAS;AACf,IAAM,UAAU;;;ACIhB,IAAM,0BAAqD,OAAO,OAAO;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,2BAA2B;AACjC,IAA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EhC,QACE,CAAC,eAAe,WAChB,CAAC,WACD,OAAO,YAAY,YACnB,QAAQ,YAAY,gBACpB,UAAU,IAAI,OAAO,GACrB;AACA,aAAO,KAAK;AAAA,IACd;AAGA,UAAM,mBAAmB,yBAAyB,SAAS,qBAAqB;AAChF,QAAI,CAAC,kBAAkB;AACrB;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AACA,aAAO,KAAK;AAAA,IACd;AAEA,UAAM,cACJ,QAAQ,OAAQ,KAAwB,WAAW,aAC9C,OACD;AACN,UAAM,UAAU,eAAe,KAAK,aAAa;AACjD,QAAI,CAAC,WAAW,OAAO,QAAQ,WAAW,YAAY;AACpD;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AACA,aAAO,KAAK;AAAA,IACd;AAEA,cAAU,IAAI,gBAAgB;AAC9B,WAAO,QAAQ,OAAO,gBAAgB;AAAA,EACxC;AACF;;;AC7HO,SAAS,cAA2B;AACzC,SAAO,EAAE,IAAI,MAAM,QAAQ,QAAQ,SAAS,QAAQ;AACtD;",
6
6
  "names": []
7
7
  }
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/shared/types.ts
2
2
  var PLUGIN = "dsh-compaction-studio";
3
- var VERSION = "0.1.0";
3
+ var VERSION = "0.1.1";
4
4
 
5
5
  // src/core/config.ts
6
6
  var VALID_LANGUAGE_POLICIES = Object.freeze([
@@ -124,10 +124,10 @@ function buildStudioCompactionInstruction(config) {
124
124
  "- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]",
125
125
  "",
126
126
  "## Active Workbenches & Unit Spine",
127
- "- [active galley packetIds, templateIds, blockIds (e.g. h1, q1, t1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]",
127
+ "- [active galley packetIds (e.g. p-\u2026), templateIds, blockIds (e.g. b1, b2), sheetIds (e.g. s1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]",
128
128
  "",
129
129
  "## Vetted Sources, Quotes & Media",
130
- "- [exact fundusIds, quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs, and key verbatim quotes or data points in play]",
130
+ "- [exact fundusIds (e.g. pas-\u2026, src-\u2026), quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs (e.g. a1), plateIds (e.g. plt-\u2026), and key verbatim quotes or data points in play]",
131
131
  "",
132
132
  "## Craft, Didactic & House-Style Constraints",
133
133
  '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or "do not" instructions]',
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/shared/types.ts", "../src/core/config.ts", "../src/core/prompt.ts", "../src/core/interceptor.ts", "../src/core/index.ts", "../src/host/index.ts"],
4
- "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.0' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n", "/**\n * dsh-compaction-studio \u2014 strict configuration validation & normalization.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\n\nexport const VALID_LANGUAGE_POLICIES: readonly LanguagePolicy[] = Object.freeze([\n 'preserve-conversation',\n 'en',\n 'de',\n])\n\nexport const MAX_EXTRA_PRESERVE_RULES = 5\nexport const MAX_EXTRA_RULE_LENGTH = 200\nexport const MAX_EXTRA_RULES_TOTAL_LENGTH = 600\n\nconst ALLOWED_KEYS = new Set<string>(['enabled', 'languagePolicy', 'extraPreserveRules'])\n\nconst EMPTY_RULES: readonly string[] = Object.freeze([])\n\nexport const DEFAULT_STUDIO_CONFIG: ResolvedStudioCompactionConfig = Object.freeze({\n enabled: true,\n languagePolicy: 'preserve-conversation',\n extraPreserveRules: EMPTY_RULES,\n})\n\n/**\n * Validate and normalize `StudioCompactionConfig` into a frozen `ResolvedStudioCompactionConfig`.\n * Throws descriptive `Error` instances on unknown keys, invalid types/enums, or rule cap violations.\n */\nexport function resolveStudioConfig(rawConfig?: unknown): ResolvedStudioCompactionConfig {\n if (rawConfig === undefined) {\n return DEFAULT_STUDIO_CONFIG\n }\n if (rawConfig === null || typeof rawConfig !== 'object' || Array.isArray(rawConfig)) {\n throw new Error('StudioCompactionConfig: expected a configuration object')\n }\n\n const record = rawConfig as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (!ALLOWED_KEYS.has(key)) {\n throw new Error(`StudioCompactionConfig: unknown key \"${key}\"`)\n }\n }\n\n let enabled = true\n if (record.enabled !== undefined) {\n if (typeof record.enabled !== 'boolean') {\n throw new Error('StudioCompactionConfig: \"enabled\" must be a boolean')\n }\n enabled = record.enabled\n }\n\n let languagePolicy: LanguagePolicy = 'preserve-conversation'\n if (record.languagePolicy !== undefined) {\n if (\n typeof record.languagePolicy !== 'string' ||\n !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy as LanguagePolicy)\n ) {\n throw new Error(\n `StudioCompactionConfig: invalid \"languagePolicy\" \"${String(record.languagePolicy)}\" (expected \"preserve-conversation\", \"en\", or \"de\")`,\n )\n }\n languagePolicy = record.languagePolicy as LanguagePolicy\n }\n\n let extraPreserveRules: readonly string[] = EMPTY_RULES\n if (record.extraPreserveRules !== undefined) {\n if (!Array.isArray(record.extraPreserveRules)) {\n throw new Error('StudioCompactionConfig: \"extraPreserveRules\" must be an array of strings')\n }\n if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`,\n )\n }\n\n const normalized: string[] = []\n let totalChars = 0\n\n for (let i = 0; i < record.extraPreserveRules.length; i++) {\n const item = record.extraPreserveRules[i]\n if (typeof item !== 'string') {\n throw new Error(`StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be a string`)\n }\n if (item.includes('\\r') || item.includes('\\n')) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be single-line (no CR/LF)`,\n )\n }\n const trimmed = item.trim()\n if (trimmed.length === 0) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must not be empty`,\n )\n }\n if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`,\n )\n }\n totalChars += trimmed.length\n if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`,\n )\n }\n normalized.push(trimmed)\n }\n\n extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized)\n }\n\n return Object.freeze({\n enabled,\n languagePolicy,\n extraPreserveRules,\n })\n}\n", "/**\n * dsh-compaction-studio \u2014 domain-neutral, language-preserving editorial compaction prompt builder.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\n\nexport const SECTION_HEADINGS = Object.freeze([\n '## Editorial & Authoring Goal',\n '## Active Workbenches & Unit Spine',\n '## Vetted Sources, Quotes & Media',\n '## Craft, Didactic & House-Style Constraints',\n '## Open Reviews & Diagnostics',\n '## Pending Work',\n '## Next Step',\n] as const)\n\nexport const LANGUAGE_RULE_LINES: Readonly<Record<LanguagePolicy, string>> = Object.freeze({\n 'preserve-conversation':\n 'Write bullet content in the dominant human language used by the user in the conversation (for example, German if the user writes in German, English if in English); preserve original-language source quotes verbatim.',\n en: 'Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.',\n de: 'Write concise German bullet content (pr\u00E4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim.',\n})\n\n/**\n * Build the exact Studio Editorial Compaction instruction text with deterministic 7-section\n * Markdown headings, language policy rule, `<compacted-summary>` prior-checkpoint merge rule,\n * and optional validated `extraPreserveRules` bullets.\n */\nexport function buildStudioCompactionInstruction(\n config?: StudioCompactionConfig | ResolvedStudioCompactionConfig,\n): string {\n const resolved = resolveStudioConfig(config)\n const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy]\n\n const lines: string[] = [\n 'You are now acting as the context compaction engine for a document, research, and curriculum co-authoring studio. Condense the conversation ABOVE into a structured editorial checkpoint so work can resume seamlessly with zero loss of essential context, provenance, or constraints.',\n '',\n 'Output EXACTLY the Markdown structure below: keep every `##` section heading verbatim and in this exact order. Use concise, information-dense bullets rather than prose paragraphs. Write `(none)` for any empty section \u2014 never omit or rename a section.',\n '',\n '## Editorial & Authoring Goal',\n \"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]\",\n '',\n '## Active Workbenches & Unit Spine',\n '- [active galley packetIds, templateIds, blockIds (e.g. h1, q1, t1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]',\n '',\n '## Vetted Sources, Quotes & Media',\n '- [exact fundusIds, quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs, and key verbatim quotes or data points in play]',\n '',\n '## Craft, Didactic & House-Style Constraints',\n '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or \"do not\" instructions]',\n '',\n '## Open Reviews & Diagnostics',\n '- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]',\n '',\n '## Pending Work',\n '- [explicitly requested work not yet completed, respecting staged-draft boundaries]',\n '',\n '## Next Step',\n \"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]\",\n '',\n 'Rules:',\n `- ${languageRule}`,\n '- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.',\n '- Preserve ALL exact identifiers verbatim: `packetId`s, `blockId`s, `fundusId`s, `quoteSha256` hashes, `mission_id`s, file paths, URLs, dates, numbers, citations, and quoted primary-source fragments. Never paraphrase away an ID or hash.',\n '- Capture user feedback, rejections, and explicit corrections faithfully.',\n '- Do NOT mention this summarization request or acknowledge that context was compacted.',\n '- Output ONLY the Markdown checkpoint text: do NOT call any tools, do NOT emit images, and do NOT wrap the output in outer XML/code fences.',\n '- If the conversation above already contains a <compacted-summary> block, it is a PRIOR checkpoint: do not copy it verbatim \u2014 keep still-valid facts, drop superseded ones, and merge newer developments into one consolidated checkpoint under the same headings.',\n ]\n\n for (const extraRule of resolved.extraPreserveRules) {\n lines.push(`- ${extraRule}`)\n }\n\n return lines.join('\\n')\n}\n", "/**\n * dsh-compaction-studio \u2014 zero-fork `llm/stream` compaction prompt interceptor.\n */\nimport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\nimport { buildStudioCompactionInstruction } from './prompt.ts'\n\nexport const COMPACTION_SUMMARY_MARKER = '<compacted-summary>'\n\n/**\n * Create a deep-frozen replacement trailing `UserMessage` carrying the Studio compaction prompt.\n * Only freezes the message itself, its single-element `content` tuple, and its `{ type: 'text', text }` block.\n */\nexport function buildFrozenCompactionUserMessage(instructionText: string): CompactionUserMessage {\n const textPart: TextContentPartLike = Object.freeze({\n type: 'text',\n text: instructionText,\n })\n const content = Object.freeze([textPart] as const)\n return Object.freeze({\n role: 'user',\n content,\n })\n}\n\n/**\n * Verify that `message` matches `compaction-basic`'s trailing instruction `UserMessage`\n * (`role === 'user'`, `Array.isArray(content)`, concatenated text blocks contain `<compacted-summary>`).\n */\nexport function isCompactionInstructionMessage(message: unknown): message is RequestMessageLike {\n if (!message || typeof message !== 'object') {\n return false\n }\n const msg = message as RequestMessageLike\n if (msg.role !== 'user' || !Array.isArray(msg.content)) {\n return false\n }\n\n let concatenatedText = ''\n for (const part of msg.content) {\n if (\n part &&\n typeof part === 'object' &&\n (part as ContentPartLike).type === 'text' &&\n typeof (part as ContentPartLike).text === 'string'\n ) {\n concatenatedText += (part as ContentPartLike).text as string\n }\n }\n\n return concatenatedText.includes(COMPACTION_SUMMARY_MARKER)\n}\n\nfunction isFrozenCompactionMessage(value: unknown): value is CompactionUserMessage {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n (value as RequestMessageLike).role === 'user' &&\n Array.isArray((value as RequestMessageLike).content)\n )\n}\n\n/**\n * Construct a detached `GenerateOptionsLike` replacing ONLY `messages[messages.length - 1]`\n * with a deep-frozen Studio compaction `UserMessage`.\n *\n * Invariants:\n * - Returns `null` (fail-open) if `options.messages` is empty or the trailing message fails `isCompactionInstructionMessage`.\n * - Never mutates `options` or `options.messages`.\n * - Preserves `messages.slice(0, -1)` element references (`===`) and all top-level keys (`tools`, `signal`, etc.).\n * - Never recursively freezes `AbortSignal` or prefix messages (only shallow-freezes `rewrittenOptions` and `rewrittenOptions.messages`, plus deep-freezes the new trailing `UserMessage`).\n */\nexport function rewriteCompactionOptions(\n options: GenerateOptionsLike,\n replacement?:\n | string\n | CompactionUserMessage\n | StudioCompactionConfig\n | ResolvedStudioCompactionConfig,\n): GenerateOptionsLike | null {\n if (!options || typeof options !== 'object' || !Array.isArray(options.messages)) {\n return null\n }\n const len = options.messages.length\n if (len < 1) {\n return null\n }\n\n const lastMessage = options.messages[len - 1]\n if (!isCompactionInstructionMessage(lastMessage)) {\n return null\n }\n\n let trailingMessage: CompactionUserMessage\n if (typeof replacement === 'string') {\n trailingMessage = buildFrozenCompactionUserMessage(replacement)\n } else if (isFrozenCompactionMessage(replacement)) {\n trailingMessage = replacement\n } else {\n trailingMessage = buildFrozenCompactionUserMessage(\n buildStudioCompactionInstruction(replacement),\n )\n }\n\n const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage])\n return Object.freeze({\n ...options,\n messages: nextMessages,\n })\n}\n\nfunction safeWarn(onWarn: ((message: string) => void) | undefined, message: string): void {\n if (!onWarn) return\n try {\n onWarn(message)\n } catch {\n /* logging must never throw or abort an LLM stream */\n }\n}\n\n/**\n * Create a `llm/stream` Cordis waterfall listener that intercepts strictly `options.purpose === 'compaction'`,\n * guards against infinite recursion with a `WeakSet<object>`, fails open on unexpected shapes,\n * and re-dispatches `runtime.stream(rewrittenOptions)`.\n */\nexport function createCompactionStreamHandler(\n init: CompactionStreamHandlerInit = {},\n): CompactionStreamListener {\n const resolvedConfig = resolveStudioConfig(init.config)\n const instructionText = buildStudioCompactionInstruction(resolvedConfig)\n const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText)\n const rewritten = new WeakSet<object>()\n\n return function compactionStreamListener(\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n ): AsyncIterable<StreamChunkLike> {\n // Fast path: 0 allocations for disabled overlay, non-compaction traffic, or WeakSet re-entry.\n if (\n !resolvedConfig.enabled ||\n !options ||\n typeof options !== 'object' ||\n options.purpose !== 'compaction' ||\n rewritten.has(options)\n ) {\n return next()\n }\n\n // Fail-open shape check on compaction-basic's trailing instruction message.\n const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage)\n if (!rewrittenOptions) {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite',\n )\n return next()\n }\n\n const selfRuntime =\n this && typeof (this as LlmRuntimeLike).stream === 'function'\n ? (this as LlmRuntimeLike)\n : undefined\n const runtime = selfRuntime ?? init.getRuntime?.()\n if (!runtime || typeof runtime.stream !== 'function') {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite',\n )\n return next()\n }\n\n rewritten.add(rewrittenOptions)\n return runtime.stream(rewrittenOptions)\n }\n}\n", "/**\n * dsh-compaction-studio \u2014 hermetic core module (zero @deepseek-ai/* imports; testable via node --test).\n */\nimport {\n PLUGIN,\n VERSION,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type ContentPartLike,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StreamChunkLike,\n type StreamNextFn,\n type StudioCompactionConfig,\n type TextContentPartLike,\n} from '../shared/types.ts'\n\nexport { PLUGIN, VERSION }\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n}\n\nexport {\n DEFAULT_STUDIO_CONFIG,\n MAX_EXTRA_PRESERVE_RULES,\n MAX_EXTRA_RULE_LENGTH,\n MAX_EXTRA_RULES_TOTAL_LENGTH,\n VALID_LANGUAGE_POLICIES,\n resolveStudioConfig,\n} from './config.ts'\n\nexport {\n LANGUAGE_RULE_LINES,\n SECTION_HEADINGS,\n buildStudioCompactionInstruction,\n} from './prompt.ts'\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n buildFrozenCompactionUserMessage,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n rewriteCompactionOptions,\n} from './interceptor.ts'\n\nexport function probeHealth(): HealthProbe {\n return { ok: true, plugin: PLUGIN, version: VERSION }\n}\n", "/**\n * dsh-compaction-studio \u2014 Cordis host face.\n *\n * Mounts alongside `@deepseek-ai/dsh-compaction-basic` and intercepts `llm/stream`\n * globally (`{ global: true }`) strictly when `options.purpose === 'compaction'`.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n COMPACTION_SUMMARY_MARKER,\n DEFAULT_STUDIO_CONFIG,\n LANGUAGE_RULE_LINES,\n PLUGIN,\n SECTION_HEADINGS,\n VERSION,\n buildFrozenCompactionUserMessage,\n buildStudioCompactionInstruction,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n probeHealth,\n resolveStudioConfig,\n rewriteCompactionOptions,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StudioCompactionConfig,\n} from '../core/index.ts'\n\nexport const name = PLUGIN\nexport const inject: string[] = ['llm']\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n DEFAULT_STUDIO_CONFIG,\n LANGUAGE_RULE_LINES,\n PLUGIN,\n SECTION_HEADINGS,\n VERSION,\n buildFrozenCompactionUserMessage,\n buildStudioCompactionInstruction,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n probeHealth,\n resolveStudioConfig,\n rewriteCompactionOptions,\n}\n\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n}\n\nexport function apply(ctx: Context, rawConfig?: StudioCompactionConfig): void {\n const config = resolveStudioConfig(rawConfig)\n\n const handler = createCompactionStreamHandler({\n config,\n getRuntime: () =>\n ctx.llm && typeof ctx.llm.stream === 'function'\n ? (ctx.llm as LlmRuntimeLike)\n : undefined,\n onWarn: (message: string) => {\n try {\n ctx.logger?.(PLUGIN)?.warn?.('[%s] %s', PLUGIN, message)\n } catch {\n /* logging must never throw */\n }\n },\n })\n\n const dispose = ctx.on('llm/stream', handler, { global: true })\n ctx.effect(() => dispose, 'dsh-compaction-studio: llm/stream')\n\n try {\n ctx.logger?.(PLUGIN)?.debug?.(\n '%s@%s mounted (enabled=%s, languagePolicy=%s, extraRules=%d)',\n PLUGIN,\n VERSION,\n config.enabled,\n config.languagePolicy,\n config.extraPreserveRules.length,\n )\n } catch {\n /* never throw from logger */\n }\n}\n"],
4
+ "sourcesContent": ["/**\n * dsh-compaction-studio \u2014 shared type definitions (zero runtime dependencies).\n */\n\nexport const PLUGIN = 'dsh-compaction-studio' as const\nexport const VERSION = '0.1.1' as const\n\nexport interface HealthProbe {\n readonly ok: true\n readonly plugin: typeof PLUGIN\n readonly version: string\n}\n\nexport type LanguagePolicy = 'preserve-conversation' | 'en' | 'de'\n\nexport interface StudioCompactionConfig {\n /** Enable the studio compaction prompt overlay. Defaults to `true`. */\n readonly enabled?: boolean\n /**\n * Output language policy for checkpoint bullet text (headings always remain fixed English Markdown).\n * - `'preserve-conversation'` (default): match the dominant human language of the conversation (e.g. German -> German, English -> English).\n * - `'en'`: write checkpoint bullet content in English.\n * - `'de'`: write checkpoint bullet content in German.\n */\n readonly languagePolicy?: LanguagePolicy\n /**\n * Optional extra 1-line preservation bullets appended to the Rules list (e.g. from a domain profile).\n * Max 5 items; each item trimmed, non-empty, single-line (no `\\r`/`\\n`), max 200 chars each (total \u2264 600 chars).\n */\n readonly extraPreserveRules?: readonly string[]\n}\n\nexport interface ResolvedStudioCompactionConfig {\n readonly enabled: boolean\n readonly languagePolicy: LanguagePolicy\n readonly extraPreserveRules: readonly string[]\n}\n\nexport interface TextContentPartLike {\n readonly type: 'text'\n readonly text: string\n readonly [key: string]: unknown\n}\n\nexport interface ContentPartLike {\n readonly type: string\n readonly text?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface RequestMessageLike {\n readonly role: string\n readonly content?: unknown\n readonly [key: string]: unknown\n}\n\nexport interface CompactionUserMessage extends RequestMessageLike {\n readonly role: 'user'\n readonly content: readonly [TextContentPartLike]\n}\n\nexport interface GenerateOptionsLike {\n readonly provider: string\n readonly model: string\n readonly messages: readonly RequestMessageLike[]\n readonly tools?: readonly unknown[]\n readonly toolHistory?: unknown\n readonly maxTokens?: number\n readonly sessionId?: string\n readonly purpose?: string\n readonly signal?: AbortSignal\n readonly [key: string]: unknown\n}\n\nexport type StreamChunkLike = unknown\n\nexport interface LlmRuntimeLike {\n stream(options: GenerateOptionsLike): AsyncIterable<StreamChunkLike>\n}\n\nexport type StreamNextFn = () => AsyncIterable<StreamChunkLike>\n\nexport type CompactionStreamListener = (\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n) => AsyncIterable<StreamChunkLike>\n\nexport interface CompactionStreamHandlerInit {\n /** Studio compaction config (raw or already resolved). */\n readonly config?: StudioCompactionConfig | ResolvedStudioCompactionConfig\n /** Fallback LlmRuntime accessor when `this` does not directly expose `.stream()`. */\n readonly getRuntime?: () => LlmRuntimeLike | undefined\n /** Optional warning sink invoked on fail-open conditions; guarded so logging never throws. */\n readonly onWarn?: (message: string) => void\n}\n", "/**\n * dsh-compaction-studio \u2014 strict configuration validation & normalization.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\n\nexport const VALID_LANGUAGE_POLICIES: readonly LanguagePolicy[] = Object.freeze([\n 'preserve-conversation',\n 'en',\n 'de',\n])\n\nexport const MAX_EXTRA_PRESERVE_RULES = 5\nexport const MAX_EXTRA_RULE_LENGTH = 200\nexport const MAX_EXTRA_RULES_TOTAL_LENGTH = 600\n\nconst ALLOWED_KEYS = new Set<string>(['enabled', 'languagePolicy', 'extraPreserveRules'])\n\nconst EMPTY_RULES: readonly string[] = Object.freeze([])\n\nexport const DEFAULT_STUDIO_CONFIG: ResolvedStudioCompactionConfig = Object.freeze({\n enabled: true,\n languagePolicy: 'preserve-conversation',\n extraPreserveRules: EMPTY_RULES,\n})\n\n/**\n * Validate and normalize `StudioCompactionConfig` into a frozen `ResolvedStudioCompactionConfig`.\n * Throws descriptive `Error` instances on unknown keys, invalid types/enums, or rule cap violations.\n */\nexport function resolveStudioConfig(rawConfig?: unknown): ResolvedStudioCompactionConfig {\n if (rawConfig === undefined) {\n return DEFAULT_STUDIO_CONFIG\n }\n if (rawConfig === null || typeof rawConfig !== 'object' || Array.isArray(rawConfig)) {\n throw new Error('StudioCompactionConfig: expected a configuration object')\n }\n\n const record = rawConfig as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (!ALLOWED_KEYS.has(key)) {\n throw new Error(`StudioCompactionConfig: unknown key \"${key}\"`)\n }\n }\n\n let enabled = true\n if (record.enabled !== undefined) {\n if (typeof record.enabled !== 'boolean') {\n throw new Error('StudioCompactionConfig: \"enabled\" must be a boolean')\n }\n enabled = record.enabled\n }\n\n let languagePolicy: LanguagePolicy = 'preserve-conversation'\n if (record.languagePolicy !== undefined) {\n if (\n typeof record.languagePolicy !== 'string' ||\n !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy as LanguagePolicy)\n ) {\n throw new Error(\n `StudioCompactionConfig: invalid \"languagePolicy\" \"${String(record.languagePolicy)}\" (expected \"preserve-conversation\", \"en\", or \"de\")`,\n )\n }\n languagePolicy = record.languagePolicy as LanguagePolicy\n }\n\n let extraPreserveRules: readonly string[] = EMPTY_RULES\n if (record.extraPreserveRules !== undefined) {\n if (!Array.isArray(record.extraPreserveRules)) {\n throw new Error('StudioCompactionConfig: \"extraPreserveRules\" must be an array of strings')\n }\n if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`,\n )\n }\n\n const normalized: string[] = []\n let totalChars = 0\n\n for (let i = 0; i < record.extraPreserveRules.length; i++) {\n const item = record.extraPreserveRules[i]\n if (typeof item !== 'string') {\n throw new Error(`StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be a string`)\n }\n if (item.includes('\\r') || item.includes('\\n')) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must be single-line (no CR/LF)`,\n )\n }\n const trimmed = item.trim()\n if (trimmed.length === 0) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" must not be empty`,\n )\n }\n if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules[${i}]\" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`,\n )\n }\n totalChars += trimmed.length\n if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {\n throw new Error(\n `StudioCompactionConfig: \"extraPreserveRules\" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`,\n )\n }\n normalized.push(trimmed)\n }\n\n extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized)\n }\n\n return Object.freeze({\n enabled,\n languagePolicy,\n extraPreserveRules,\n })\n}\n", "/**\n * dsh-compaction-studio \u2014 domain-neutral, language-preserving editorial compaction prompt builder.\n */\nimport type {\n LanguagePolicy,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\n\nexport const SECTION_HEADINGS = Object.freeze([\n '## Editorial & Authoring Goal',\n '## Active Workbenches & Unit Spine',\n '## Vetted Sources, Quotes & Media',\n '## Craft, Didactic & House-Style Constraints',\n '## Open Reviews & Diagnostics',\n '## Pending Work',\n '## Next Step',\n] as const)\n\nexport const LANGUAGE_RULE_LINES: Readonly<Record<LanguagePolicy, string>> = Object.freeze({\n 'preserve-conversation':\n 'Write bullet content in the dominant human language used by the user in the conversation (for example, German if the user writes in German, English if in English); preserve original-language source quotes verbatim.',\n en: 'Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.',\n de: 'Write concise German bullet content (pr\u00E4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim.',\n})\n\n/**\n * Build the exact Studio Editorial Compaction instruction text with deterministic 7-section\n * Markdown headings, language policy rule, `<compacted-summary>` prior-checkpoint merge rule,\n * and optional validated `extraPreserveRules` bullets.\n */\nexport function buildStudioCompactionInstruction(\n config?: StudioCompactionConfig | ResolvedStudioCompactionConfig,\n): string {\n const resolved = resolveStudioConfig(config)\n const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy]\n\n const lines: string[] = [\n 'You are now acting as the context compaction engine for a document, research, and curriculum co-authoring studio. Condense the conversation ABOVE into a structured editorial checkpoint so work can resume seamlessly with zero loss of essential context, provenance, or constraints.',\n '',\n 'Output EXACTLY the Markdown structure below: keep every `##` section heading verbatim and in this exact order. Use concise, information-dense bullets rather than prose paragraphs. Write `(none)` for any empty section \u2014 never omit or rename a section.',\n '',\n '## Editorial & Authoring Goal',\n \"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]\",\n '',\n '## Active Workbenches & Unit Spine',\n '- [active galley packetIds (e.g. p-\u2026), templateIds, blockIds (e.g. b1, b2), sheetIds (e.g. s1), review mode (`Auto` vs `Review`), almanac unit/lesson slots, and active functional gear or subject lens]',\n '',\n '## Vetted Sources, Quotes & Media',\n '- [exact fundusIds (e.g. pas-\u2026, src-\u2026), quoteSha256 hashes, bibliographic citations/locators, vetted URLs, web-mission IDs, media asset IDs (e.g. a1), plateIds (e.g. plt-\u2026), and key verbatim quotes or data points in play]',\n '',\n '## Craft, Didactic & House-Style Constraints',\n '- [audience/grade/reading-level targets, operator or rubric constraints, page/layout budgets (maxPages, overflow limits), tone rules, and explicit user corrections or \"do not\" instructions]',\n '',\n '## Open Reviews & Diagnostics',\n '- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]',\n '',\n '## Pending Work',\n '- [explicitly requested work not yet completed, respecting staged-draft boundaries]',\n '',\n '## Next Step',\n \"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]\",\n '',\n 'Rules:',\n `- ${languageRule}`,\n '- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.',\n '- Preserve ALL exact identifiers verbatim: `packetId`s, `blockId`s, `fundusId`s, `quoteSha256` hashes, `mission_id`s, file paths, URLs, dates, numbers, citations, and quoted primary-source fragments. Never paraphrase away an ID or hash.',\n '- Capture user feedback, rejections, and explicit corrections faithfully.',\n '- Do NOT mention this summarization request or acknowledge that context was compacted.',\n '- Output ONLY the Markdown checkpoint text: do NOT call any tools, do NOT emit images, and do NOT wrap the output in outer XML/code fences.',\n '- If the conversation above already contains a <compacted-summary> block, it is a PRIOR checkpoint: do not copy it verbatim \u2014 keep still-valid facts, drop superseded ones, and merge newer developments into one consolidated checkpoint under the same headings.',\n ]\n\n for (const extraRule of resolved.extraPreserveRules) {\n lines.push(`- ${extraRule}`)\n }\n\n return lines.join('\\n')\n}\n", "/**\n * dsh-compaction-studio \u2014 zero-fork `llm/stream` compaction prompt interceptor.\n */\nimport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n} from '../shared/types.ts'\nimport { resolveStudioConfig } from './config.ts'\nimport { buildStudioCompactionInstruction } from './prompt.ts'\n\nexport const COMPACTION_SUMMARY_MARKER = '<compacted-summary>'\n\n/**\n * Create a deep-frozen replacement trailing `UserMessage` carrying the Studio compaction prompt.\n * Only freezes the message itself, its single-element `content` tuple, and its `{ type: 'text', text }` block.\n */\nexport function buildFrozenCompactionUserMessage(instructionText: string): CompactionUserMessage {\n const textPart: TextContentPartLike = Object.freeze({\n type: 'text',\n text: instructionText,\n })\n const content = Object.freeze([textPart] as const)\n return Object.freeze({\n role: 'user',\n content,\n })\n}\n\n/**\n * Verify that `message` matches `compaction-basic`'s trailing instruction `UserMessage`\n * (`role === 'user'`, `Array.isArray(content)`, concatenated text blocks contain `<compacted-summary>`).\n */\nexport function isCompactionInstructionMessage(message: unknown): message is RequestMessageLike {\n if (!message || typeof message !== 'object') {\n return false\n }\n const msg = message as RequestMessageLike\n if (msg.role !== 'user' || !Array.isArray(msg.content)) {\n return false\n }\n\n let concatenatedText = ''\n for (const part of msg.content) {\n if (\n part &&\n typeof part === 'object' &&\n (part as ContentPartLike).type === 'text' &&\n typeof (part as ContentPartLike).text === 'string'\n ) {\n concatenatedText += (part as ContentPartLike).text as string\n }\n }\n\n return concatenatedText.includes(COMPACTION_SUMMARY_MARKER)\n}\n\nfunction isFrozenCompactionMessage(value: unknown): value is CompactionUserMessage {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n (value as RequestMessageLike).role === 'user' &&\n Array.isArray((value as RequestMessageLike).content)\n )\n}\n\n/**\n * Construct a detached `GenerateOptionsLike` replacing ONLY `messages[messages.length - 1]`\n * with a deep-frozen Studio compaction `UserMessage`.\n *\n * Invariants:\n * - Returns `null` (fail-open) if `options.messages` is empty or the trailing message fails `isCompactionInstructionMessage`.\n * - Never mutates `options` or `options.messages`.\n * - Preserves `messages.slice(0, -1)` element references (`===`) and all top-level keys (`tools`, `signal`, etc.).\n * - Never recursively freezes `AbortSignal` or prefix messages (only shallow-freezes `rewrittenOptions` and `rewrittenOptions.messages`, plus deep-freezes the new trailing `UserMessage`).\n */\nexport function rewriteCompactionOptions(\n options: GenerateOptionsLike,\n replacement?:\n | string\n | CompactionUserMessage\n | StudioCompactionConfig\n | ResolvedStudioCompactionConfig,\n): GenerateOptionsLike | null {\n if (!options || typeof options !== 'object' || !Array.isArray(options.messages)) {\n return null\n }\n const len = options.messages.length\n if (len < 1) {\n return null\n }\n\n const lastMessage = options.messages[len - 1]\n if (!isCompactionInstructionMessage(lastMessage)) {\n return null\n }\n\n let trailingMessage: CompactionUserMessage\n if (typeof replacement === 'string') {\n trailingMessage = buildFrozenCompactionUserMessage(replacement)\n } else if (isFrozenCompactionMessage(replacement)) {\n trailingMessage = replacement\n } else {\n trailingMessage = buildFrozenCompactionUserMessage(\n buildStudioCompactionInstruction(replacement),\n )\n }\n\n const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage])\n return Object.freeze({\n ...options,\n messages: nextMessages,\n })\n}\n\nfunction safeWarn(onWarn: ((message: string) => void) | undefined, message: string): void {\n if (!onWarn) return\n try {\n onWarn(message)\n } catch {\n /* logging must never throw or abort an LLM stream */\n }\n}\n\n/**\n * Create a `llm/stream` Cordis waterfall listener that intercepts strictly `options.purpose === 'compaction'`,\n * guards against infinite recursion with a `WeakSet<object>`, fails open on unexpected shapes,\n * and re-dispatches `runtime.stream(rewrittenOptions)`.\n */\nexport function createCompactionStreamHandler(\n init: CompactionStreamHandlerInit = {},\n): CompactionStreamListener {\n const resolvedConfig = resolveStudioConfig(init.config)\n const instructionText = buildStudioCompactionInstruction(resolvedConfig)\n const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText)\n const rewritten = new WeakSet<object>()\n\n return function compactionStreamListener(\n this: unknown,\n options: GenerateOptionsLike,\n next: StreamNextFn,\n ): AsyncIterable<StreamChunkLike> {\n // Fast path: 0 allocations for disabled overlay, non-compaction traffic, or WeakSet re-entry.\n if (\n !resolvedConfig.enabled ||\n !options ||\n typeof options !== 'object' ||\n options.purpose !== 'compaction' ||\n rewritten.has(options)\n ) {\n return next()\n }\n\n // Fail-open shape check on compaction-basic's trailing instruction message.\n const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage)\n if (!rewrittenOptions) {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite',\n )\n return next()\n }\n\n const selfRuntime =\n this && typeof (this as LlmRuntimeLike).stream === 'function'\n ? (this as LlmRuntimeLike)\n : undefined\n const runtime = selfRuntime ?? init.getRuntime?.()\n if (!runtime || typeof runtime.stream !== 'function') {\n safeWarn(\n init.onWarn,\n 'purpose=\"compaction\" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite',\n )\n return next()\n }\n\n rewritten.add(rewrittenOptions)\n return runtime.stream(rewrittenOptions)\n }\n}\n", "/**\n * dsh-compaction-studio \u2014 hermetic core module (zero @deepseek-ai/* imports; testable via node --test).\n */\nimport {\n PLUGIN,\n VERSION,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type ContentPartLike,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StreamChunkLike,\n type StreamNextFn,\n type StudioCompactionConfig,\n type TextContentPartLike,\n} from '../shared/types.ts'\n\nexport { PLUGIN, VERSION }\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n ContentPartLike,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StreamChunkLike,\n StreamNextFn,\n StudioCompactionConfig,\n TextContentPartLike,\n}\n\nexport {\n DEFAULT_STUDIO_CONFIG,\n MAX_EXTRA_PRESERVE_RULES,\n MAX_EXTRA_RULE_LENGTH,\n MAX_EXTRA_RULES_TOTAL_LENGTH,\n VALID_LANGUAGE_POLICIES,\n resolveStudioConfig,\n} from './config.ts'\n\nexport {\n LANGUAGE_RULE_LINES,\n SECTION_HEADINGS,\n buildStudioCompactionInstruction,\n} from './prompt.ts'\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n buildFrozenCompactionUserMessage,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n rewriteCompactionOptions,\n} from './interceptor.ts'\n\nexport function probeHealth(): HealthProbe {\n return { ok: true, plugin: PLUGIN, version: VERSION }\n}\n", "/**\n * dsh-compaction-studio \u2014 Cordis host face.\n *\n * Mounts alongside `@deepseek-ai/dsh-compaction-basic` and intercepts `llm/stream`\n * globally (`{ global: true }`) strictly when `options.purpose === 'compaction'`.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n COMPACTION_SUMMARY_MARKER,\n DEFAULT_STUDIO_CONFIG,\n LANGUAGE_RULE_LINES,\n PLUGIN,\n SECTION_HEADINGS,\n VERSION,\n buildFrozenCompactionUserMessage,\n buildStudioCompactionInstruction,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n probeHealth,\n resolveStudioConfig,\n rewriteCompactionOptions,\n type CompactionStreamHandlerInit,\n type CompactionStreamListener,\n type CompactionUserMessage,\n type GenerateOptionsLike,\n type HealthProbe,\n type LanguagePolicy,\n type LlmRuntimeLike,\n type RequestMessageLike,\n type ResolvedStudioCompactionConfig,\n type StudioCompactionConfig,\n} from '../core/index.ts'\n\nexport const name = PLUGIN\nexport const inject: string[] = ['llm']\n\nexport {\n COMPACTION_SUMMARY_MARKER,\n DEFAULT_STUDIO_CONFIG,\n LANGUAGE_RULE_LINES,\n PLUGIN,\n SECTION_HEADINGS,\n VERSION,\n buildFrozenCompactionUserMessage,\n buildStudioCompactionInstruction,\n createCompactionStreamHandler,\n isCompactionInstructionMessage,\n probeHealth,\n resolveStudioConfig,\n rewriteCompactionOptions,\n}\n\nexport type {\n CompactionStreamHandlerInit,\n CompactionStreamListener,\n CompactionUserMessage,\n GenerateOptionsLike,\n HealthProbe,\n LanguagePolicy,\n LlmRuntimeLike,\n RequestMessageLike,\n ResolvedStudioCompactionConfig,\n StudioCompactionConfig,\n}\n\nexport function apply(ctx: Context, rawConfig?: StudioCompactionConfig): void {\n const config = resolveStudioConfig(rawConfig)\n\n const handler = createCompactionStreamHandler({\n config,\n getRuntime: () =>\n ctx.llm && typeof ctx.llm.stream === 'function'\n ? (ctx.llm as LlmRuntimeLike)\n : undefined,\n onWarn: (message: string) => {\n try {\n ctx.logger?.(PLUGIN)?.warn?.('[%s] %s', PLUGIN, message)\n } catch {\n /* logging must never throw */\n }\n },\n })\n\n const dispose = ctx.on('llm/stream', handler, { global: true })\n ctx.effect(() => dispose, 'dsh-compaction-studio: llm/stream')\n\n try {\n ctx.logger?.(PLUGIN)?.debug?.(\n '%s@%s mounted (enabled=%s, languagePolicy=%s, extraRules=%d)',\n PLUGIN,\n VERSION,\n config.enabled,\n config.languagePolicy,\n config.extraPreserveRules.length,\n )\n } catch {\n /* never throw from logger */\n }\n}\n"],
5
5
  "mappings": ";AAIO,IAAM,SAAS;AACf,IAAM,UAAU;;;ACIhB,IAAM,0BAAqD,OAAO,OAAO;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,2BAA2B;AACjC,IAAM,wBAAwB;AAC9B,IAAM,+BAA+B;AAE5C,IAAM,eAAe,oBAAI,IAAY,CAAC,WAAW,kBAAkB,oBAAoB,CAAC;AAExF,IAAM,cAAiC,OAAO,OAAO,CAAC,CAAC;AAEhD,IAAM,wBAAwD,OAAO,OAAO;AAAA,EACjF,SAAS;AAAA,EACT,gBAAgB;AAAA,EAChB,oBAAoB;AACtB,CAAC;AAMM,SAAS,oBAAoB,WAAqD;AACvF,MAAI,cAAc,QAAW;AAC3B,WAAO;AAAA,EACT;AACA,MAAI,cAAc,QAAQ,OAAO,cAAc,YAAY,MAAM,QAAQ,SAAS,GAAG;AACnF,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AAEA,QAAM,SAAS;AACf,aAAW,OAAO,OAAO,KAAK,MAAM,GAAG;AACrC,QAAI,CAAC,aAAa,IAAI,GAAG,GAAG;AAC1B,YAAM,IAAI,MAAM,wCAAwC,GAAG,GAAG;AAAA,IAChE;AAAA,EACF;AAEA,MAAI,UAAU;AACd,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,SAAS,QAAQ;AACtD;;;AChCO,IAAM,OAAO;AACb,IAAM,SAAmB,CAAC,KAAK;AA+B/B,SAAS,MAAM,KAAc,WAA0C;AAC5E,QAAM,SAAS,oBAAoB,SAAS;AAE5C,QAAM,UAAU,8BAA8B;AAAA,IAC5C;AAAA,IACA,YAAY,MACV,IAAI,OAAO,OAAO,IAAI,IAAI,WAAW,aAChC,IAAI,MACL;AAAA,IACN,QAAQ,CAAC,YAAoB;AAC3B,UAAI;AACF,YAAI,SAAS,MAAM,GAAG,OAAO,WAAW,QAAQ,OAAO;AAAA,MACzD,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF,CAAC;AAED,QAAM,UAAU,IAAI,GAAG,cAAc,SAAS,EAAE,QAAQ,KAAK,CAAC;AAC9D,MAAI,OAAO,MAAM,SAAS,mCAAmC;AAE7D,MAAI;AACF,QAAI,SAAS,MAAM,GAAG;AAAA,MACpB;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,MACP,OAAO,mBAAmB;AAAA,IAC5B;AAAA,EACF,QAAQ;AAAA,EAER;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-compaction-studio",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Language-preserving editorial, research, and curriculum conversation compaction backend for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",