dsh-compaction-studio 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +77 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +6 -0
- package/lib/client.js +40 -0
- package/lib/client.js.map +7 -0
- package/lib/core.mjs +280 -0
- package/lib/core.mjs.map +7 -0
- package/lib/index.js +309 -0
- package/lib/index.js.map +7 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/package.json +75 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jan (HagbardCeline) / janpauldahlke
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-compaction-studio
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
5
|
+
Zero-fork, language-preserving editorial, research, and curriculum conversation compaction overlay for DeepSeek Harness (`dsh`).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Architectural Seam: Zero-Fork `llm/stream` Compaction Overlay
|
|
10
|
+
|
|
11
|
+
DeepSeek Harness ships `@deepseek-ai/dsh-compaction-basic` to manage token-pressure accounting, balanced tool-call/result slicing, durable `compaction/start → compaction/summary → compaction/end` checkpoints, shadow-pricing replacement `user/message` events, `/compact` maintenance serialization, and `CONTEXT_WINDOW_EXCEEDED` overflow recovery.
|
|
12
|
+
|
|
13
|
+
When summarizing, `compaction-basic` replays the warm conversation prefix (`[...messages]` + `tools`), appends **one trailing `UserMessage`** carrying a software-engineering prompt (`## Files and Code`, `## Errors and Fixes`), and calls `ctx.llm.stream(options)` with `options.purpose === 'compaction'`.
|
|
14
|
+
|
|
15
|
+
`dsh-compaction-studio` mounts alongside `compaction-basic` and registers a global `llm/stream` listener (`{ global: true }`, observing isolated `cordis:group` compaction scopes):
|
|
16
|
+
|
|
17
|
+
1. **Zero-allocation fast path:** Any call with `enabled === false`, `options.purpose !== 'compaction'`, or already recorded in the `WeakSet` recursion guard passes straight through `next()`.
|
|
18
|
+
2. **Fail-open verification:** Confirms `options.messages` ends with a `user` message whose text blocks contain `<compacted-summary>`. If an unexpected caller ever uses `purpose: 'compaction'` without that shape, `dsh-compaction-studio` logs a guarded warning and passes through `next()` untouched.
|
|
19
|
+
3. **Warm KV-cache prefix guarantee:** Never mutates `options` in place. Constructs a detached `rewrittenOptions` where `messages.slice(0, -1)` and `tools` keep exact `===` object references, keeping local `llama.cpp` and cloud KV-caches 100% warm while replacing **only** `messages[messages.length - 1]` with a deep-frozen Studio Editorial Compaction instruction.
|
|
20
|
+
4. **`AbortSignal` & re-dispatch safety:** Never recursively freezes `options.signal` (`AbortSignal` EventTarget internals stay live) and re-invokes `runtime.stream(rewrittenOptions)` guarded by `WeakSet<object>` so `@deepseek-ai/dsh-llm`'s outer-bound terminal waterfall closure receives the rewritten prompt.
|
|
21
|
+
5. **Hermetic runtime:** Zero `@deepseek-ai/*` runtime value imports on both `./core` and `.` entrypoints.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 7-Section Editorial Checkpoint Schema
|
|
26
|
+
|
|
27
|
+
Checkpoints always keep fixed English `##` headings so downstream studio tools can parse them deterministically while bullet content follows the configured language policy:
|
|
28
|
+
|
|
29
|
+
1. `## Editorial & Authoring Goal` — original and evolving document, research, or unit-planning intent.
|
|
30
|
+
2. `## Active Workbenches & Unit Spine` — active `galley` `packetId`s, `templateId`s, `blockId`s, review mode (`Auto` vs `Review`), `almanac` unit/lesson slots, and active gear or lens.
|
|
31
|
+
3. `## Vetted Sources, Quotes & Media` — exact `fundusId`s, `quoteSha256` hashes, citations/locators, vetted URLs, `mission_id`s, media asset IDs, and verbatim primary-source quotes.
|
|
32
|
+
4. `## Craft, Didactic & House-Style Constraints` — audience/grade targets, rubric/operator rules, page/layout budgets, tone rules, and explicit user corrections.
|
|
33
|
+
5. `## Open Reviews & Diagnostics` — unresolved margin annotations, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals.
|
|
34
|
+
6. `## Pending Work` — requested work not yet completed, respecting staged-draft boundaries.
|
|
35
|
+
7. `## Next Step` — the single immediate next action aligned with the user's latest request, or `(none)`.
|
|
36
|
+
|
|
37
|
+
When a prior `<compacted-summary>` block is already present in the replayed prefix, the instruction directs the model to consolidate still-valid facts and newer developments rather than copying the old checkpoint verbatim.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Configuration (`StudioCompactionConfig`)
|
|
42
|
+
|
|
43
|
+
```yaml
|
|
44
|
+
# Optional configuration under plugins in cordis.yml / cordis.patch.yml:
|
|
45
|
+
dsh-compaction-studio:
|
|
46
|
+
enabled: true
|
|
47
|
+
languagePolicy: preserve-conversation # 'preserve-conversation' | 'en' | 'de'
|
|
48
|
+
extraPreserveRules:
|
|
49
|
+
- Preserve exact AFB I-III operator annotations verbatim.
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
| Field | Type | Default | Description |
|
|
53
|
+
| :--- | :--- | :--- | :--- |
|
|
54
|
+
| `enabled` | `boolean` | `true` | Enable or disable the compaction prompt overlay. |
|
|
55
|
+
| `languagePolicy` | `'preserve-conversation' \| 'en' \| 'de'` | `'preserve-conversation'` | Bullet language policy (`##` headings always remain English). |
|
|
56
|
+
| `extraPreserveRules` | `readonly string[]` | `[]` | Up to `5` single-line rules (`≤ 200` chars each, `≤ 600` chars total) appended to `Rules:`. |
|
|
57
|
+
|
|
58
|
+
Unknown top-level keys, non-boolean `enabled`, unsupported `languagePolicy` values, CR/LF newlines, or over-cap `extraPreserveRules` fail fast at plugin load with a descriptive `StudioCompactionConfig: ...` error.
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Package Entrypoints & Development
|
|
63
|
+
|
|
64
|
+
- `dsh-compaction-studio` (`./lib/index.js`) — Cordis host plugin (`inject: ['llm']`) + re-exported core API.
|
|
65
|
+
- `dsh-compaction-studio/core` (`./lib/core.mjs`) — Hermetic pure-Node core for standalone testing.
|
|
66
|
+
- `dsh-compaction-studio/client` (`./lib/client.js`) — No-op web `__ModuleLoader__` face.
|
|
67
|
+
- `dsh-compaction-studio/locale/*.json` & `dsh-compaction-studio/icon` — Plugin Manager display metadata (`en`, `de`, SVG icon).
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
npm install
|
|
71
|
+
npm run build # node build.mjs && tsc --noEmit
|
|
72
|
+
npm test # node build.mjs && node --test "test/**/*.test.mjs"
|
|
73
|
+
npm run prepublishOnly # full build + typecheck + test suite
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
MIT — see [`LICENSE`](./LICENSE).
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="Studio compaction">
|
|
2
|
+
<path d="M6 3h12a1 1 0 0 1 1 1v17l-7-4-7 4V4a1 1 0 0 1 1-1z" />
|
|
3
|
+
<path d="M9.5 8h5" />
|
|
4
|
+
<path d="M9.5 11.5h5" />
|
|
5
|
+
<path d="M12 14.5v-1" />
|
|
6
|
+
</svg>
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({ id: "dsh-compaction-studio", factory: (require) => {
|
|
2
|
+
var module = { exports: {} }; var exports = module.exports;
|
|
3
|
+
"use strict";
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name2 in all)
|
|
10
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
|
|
22
|
+
// src/client/index.ts
|
|
23
|
+
var index_exports = {};
|
|
24
|
+
__export(index_exports, {
|
|
25
|
+
apply: () => apply,
|
|
26
|
+
inject: () => inject,
|
|
27
|
+
name: () => name
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(index_exports);
|
|
30
|
+
|
|
31
|
+
// src/shared/types.ts
|
|
32
|
+
var PLUGIN = "dsh-compaction-studio";
|
|
33
|
+
|
|
34
|
+
// src/client/index.ts
|
|
35
|
+
var name = PLUGIN;
|
|
36
|
+
var inject = [];
|
|
37
|
+
function apply() {
|
|
38
|
+
}
|
|
39
|
+
return module.exports; } });
|
|
40
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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.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
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,SAAS;;;ADCf,IAAM,OAAO;AACb,IAAM,SAAmB,CAAC;AAE1B,SAAS,QAAc;AAE9B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/lib/core.mjs
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// src/shared/types.ts
|
|
2
|
+
var PLUGIN = "dsh-compaction-studio";
|
|
3
|
+
var VERSION = "0.1.1";
|
|
4
|
+
|
|
5
|
+
// src/core/config.ts
|
|
6
|
+
var VALID_LANGUAGE_POLICIES = Object.freeze([
|
|
7
|
+
"preserve-conversation",
|
|
8
|
+
"en",
|
|
9
|
+
"de"
|
|
10
|
+
]);
|
|
11
|
+
var MAX_EXTRA_PRESERVE_RULES = 5;
|
|
12
|
+
var MAX_EXTRA_RULE_LENGTH = 200;
|
|
13
|
+
var MAX_EXTRA_RULES_TOTAL_LENGTH = 600;
|
|
14
|
+
var ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "languagePolicy", "extraPreserveRules"]);
|
|
15
|
+
var EMPTY_RULES = Object.freeze([]);
|
|
16
|
+
var DEFAULT_STUDIO_CONFIG = Object.freeze({
|
|
17
|
+
enabled: true,
|
|
18
|
+
languagePolicy: "preserve-conversation",
|
|
19
|
+
extraPreserveRules: EMPTY_RULES
|
|
20
|
+
});
|
|
21
|
+
function resolveStudioConfig(rawConfig) {
|
|
22
|
+
if (rawConfig === void 0) {
|
|
23
|
+
return DEFAULT_STUDIO_CONFIG;
|
|
24
|
+
}
|
|
25
|
+
if (rawConfig === null || typeof rawConfig !== "object" || Array.isArray(rawConfig)) {
|
|
26
|
+
throw new Error("StudioCompactionConfig: expected a configuration object");
|
|
27
|
+
}
|
|
28
|
+
const record = rawConfig;
|
|
29
|
+
for (const key of Object.keys(record)) {
|
|
30
|
+
if (!ALLOWED_KEYS.has(key)) {
|
|
31
|
+
throw new Error(`StudioCompactionConfig: unknown key "${key}"`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let enabled = true;
|
|
35
|
+
if (record.enabled !== void 0) {
|
|
36
|
+
if (typeof record.enabled !== "boolean") {
|
|
37
|
+
throw new Error('StudioCompactionConfig: "enabled" must be a boolean');
|
|
38
|
+
}
|
|
39
|
+
enabled = record.enabled;
|
|
40
|
+
}
|
|
41
|
+
let languagePolicy = "preserve-conversation";
|
|
42
|
+
if (record.languagePolicy !== void 0) {
|
|
43
|
+
if (typeof record.languagePolicy !== "string" || !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy)) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`StudioCompactionConfig: invalid "languagePolicy" "${String(record.languagePolicy)}" (expected "preserve-conversation", "en", or "de")`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
languagePolicy = record.languagePolicy;
|
|
49
|
+
}
|
|
50
|
+
let extraPreserveRules = EMPTY_RULES;
|
|
51
|
+
if (record.extraPreserveRules !== void 0) {
|
|
52
|
+
if (!Array.isArray(record.extraPreserveRules)) {
|
|
53
|
+
throw new Error('StudioCompactionConfig: "extraPreserveRules" must be an array of strings');
|
|
54
|
+
}
|
|
55
|
+
if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`StudioCompactionConfig: "extraPreserveRules" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const normalized = [];
|
|
61
|
+
let totalChars = 0;
|
|
62
|
+
for (let i = 0; i < record.extraPreserveRules.length; i++) {
|
|
63
|
+
const item = record.extraPreserveRules[i];
|
|
64
|
+
if (typeof item !== "string") {
|
|
65
|
+
throw new Error(`StudioCompactionConfig: "extraPreserveRules[${i}]" must be a string`);
|
|
66
|
+
}
|
|
67
|
+
if (item.includes("\r") || item.includes("\n")) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" must be single-line (no CR/LF)`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const trimmed = item.trim();
|
|
73
|
+
if (trimmed.length === 0) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" must not be empty`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
totalChars += trimmed.length;
|
|
84
|
+
if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`StudioCompactionConfig: "extraPreserveRules" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
normalized.push(trimmed);
|
|
90
|
+
}
|
|
91
|
+
extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized);
|
|
92
|
+
}
|
|
93
|
+
return Object.freeze({
|
|
94
|
+
enabled,
|
|
95
|
+
languagePolicy,
|
|
96
|
+
extraPreserveRules
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/core/prompt.ts
|
|
101
|
+
var SECTION_HEADINGS = Object.freeze([
|
|
102
|
+
"## Editorial & Authoring Goal",
|
|
103
|
+
"## Active Workbenches & Unit Spine",
|
|
104
|
+
"## Vetted Sources, Quotes & Media",
|
|
105
|
+
"## Craft, Didactic & House-Style Constraints",
|
|
106
|
+
"## Open Reviews & Diagnostics",
|
|
107
|
+
"## Pending Work",
|
|
108
|
+
"## Next Step"
|
|
109
|
+
]);
|
|
110
|
+
var LANGUAGE_RULE_LINES = Object.freeze({
|
|
111
|
+
"preserve-conversation": "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.",
|
|
112
|
+
en: "Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.",
|
|
113
|
+
de: "Write concise German bullet content (pr\xE4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim."
|
|
114
|
+
});
|
|
115
|
+
function buildStudioCompactionInstruction(config) {
|
|
116
|
+
const resolved = resolveStudioConfig(config);
|
|
117
|
+
const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy];
|
|
118
|
+
const lines = [
|
|
119
|
+
"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.",
|
|
120
|
+
"",
|
|
121
|
+
"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.",
|
|
122
|
+
"",
|
|
123
|
+
"## Editorial & Authoring Goal",
|
|
124
|
+
"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]",
|
|
125
|
+
"",
|
|
126
|
+
"## Active Workbenches & Unit Spine",
|
|
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
|
+
"",
|
|
129
|
+
"## Vetted Sources, Quotes & Media",
|
|
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
|
+
"",
|
|
132
|
+
"## Craft, Didactic & House-Style Constraints",
|
|
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]',
|
|
134
|
+
"",
|
|
135
|
+
"## Open Reviews & Diagnostics",
|
|
136
|
+
"- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]",
|
|
137
|
+
"",
|
|
138
|
+
"## Pending Work",
|
|
139
|
+
"- [explicitly requested work not yet completed, respecting staged-draft boundaries]",
|
|
140
|
+
"",
|
|
141
|
+
"## Next Step",
|
|
142
|
+
"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]",
|
|
143
|
+
"",
|
|
144
|
+
"Rules:",
|
|
145
|
+
`- ${languageRule}`,
|
|
146
|
+
"- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.",
|
|
147
|
+
"- 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.",
|
|
148
|
+
"- Capture user feedback, rejections, and explicit corrections faithfully.",
|
|
149
|
+
"- Do NOT mention this summarization request or acknowledge that context was compacted.",
|
|
150
|
+
"- 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.",
|
|
151
|
+
"- 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."
|
|
152
|
+
];
|
|
153
|
+
for (const extraRule of resolved.extraPreserveRules) {
|
|
154
|
+
lines.push(`- ${extraRule}`);
|
|
155
|
+
}
|
|
156
|
+
return lines.join("\n");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/core/interceptor.ts
|
|
160
|
+
var COMPACTION_SUMMARY_MARKER = "<compacted-summary>";
|
|
161
|
+
function buildFrozenCompactionUserMessage(instructionText) {
|
|
162
|
+
const textPart = Object.freeze({
|
|
163
|
+
type: "text",
|
|
164
|
+
text: instructionText
|
|
165
|
+
});
|
|
166
|
+
const content = Object.freeze([textPart]);
|
|
167
|
+
return Object.freeze({
|
|
168
|
+
role: "user",
|
|
169
|
+
content
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
function isCompactionInstructionMessage(message) {
|
|
173
|
+
if (!message || typeof message !== "object") {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
const msg = message;
|
|
177
|
+
if (msg.role !== "user" || !Array.isArray(msg.content)) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
let concatenatedText = "";
|
|
181
|
+
for (const part of msg.content) {
|
|
182
|
+
if (part && typeof part === "object" && part.type === "text" && typeof part.text === "string") {
|
|
183
|
+
concatenatedText += part.text;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return concatenatedText.includes(COMPACTION_SUMMARY_MARKER);
|
|
187
|
+
}
|
|
188
|
+
function isFrozenCompactionMessage(value) {
|
|
189
|
+
return Boolean(value) && typeof value === "object" && value.role === "user" && Array.isArray(value.content);
|
|
190
|
+
}
|
|
191
|
+
function rewriteCompactionOptions(options, replacement) {
|
|
192
|
+
if (!options || typeof options !== "object" || !Array.isArray(options.messages)) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const len = options.messages.length;
|
|
196
|
+
if (len < 1) {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
const lastMessage = options.messages[len - 1];
|
|
200
|
+
if (!isCompactionInstructionMessage(lastMessage)) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
let trailingMessage;
|
|
204
|
+
if (typeof replacement === "string") {
|
|
205
|
+
trailingMessage = buildFrozenCompactionUserMessage(replacement);
|
|
206
|
+
} else if (isFrozenCompactionMessage(replacement)) {
|
|
207
|
+
trailingMessage = replacement;
|
|
208
|
+
} else {
|
|
209
|
+
trailingMessage = buildFrozenCompactionUserMessage(
|
|
210
|
+
buildStudioCompactionInstruction(replacement)
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage]);
|
|
214
|
+
return Object.freeze({
|
|
215
|
+
...options,
|
|
216
|
+
messages: nextMessages
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
function safeWarn(onWarn, message) {
|
|
220
|
+
if (!onWarn) return;
|
|
221
|
+
try {
|
|
222
|
+
onWarn(message);
|
|
223
|
+
} catch {
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function createCompactionStreamHandler(init = {}) {
|
|
227
|
+
const resolvedConfig = resolveStudioConfig(init.config);
|
|
228
|
+
const instructionText = buildStudioCompactionInstruction(resolvedConfig);
|
|
229
|
+
const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText);
|
|
230
|
+
const rewritten = /* @__PURE__ */ new WeakSet();
|
|
231
|
+
return function compactionStreamListener(options, next) {
|
|
232
|
+
if (!resolvedConfig.enabled || !options || typeof options !== "object" || options.purpose !== "compaction" || rewritten.has(options)) {
|
|
233
|
+
return next();
|
|
234
|
+
}
|
|
235
|
+
const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage);
|
|
236
|
+
if (!rewrittenOptions) {
|
|
237
|
+
safeWarn(
|
|
238
|
+
init.onWarn,
|
|
239
|
+
'purpose="compaction" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite'
|
|
240
|
+
);
|
|
241
|
+
return next();
|
|
242
|
+
}
|
|
243
|
+
const selfRuntime = this && typeof this.stream === "function" ? this : void 0;
|
|
244
|
+
const runtime = selfRuntime ?? init.getRuntime?.();
|
|
245
|
+
if (!runtime || typeof runtime.stream !== "function") {
|
|
246
|
+
safeWarn(
|
|
247
|
+
init.onWarn,
|
|
248
|
+
'purpose="compaction" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite'
|
|
249
|
+
);
|
|
250
|
+
return next();
|
|
251
|
+
}
|
|
252
|
+
rewritten.add(rewrittenOptions);
|
|
253
|
+
return runtime.stream(rewrittenOptions);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/core/index.ts
|
|
258
|
+
function probeHealth() {
|
|
259
|
+
return { ok: true, plugin: PLUGIN, version: VERSION };
|
|
260
|
+
}
|
|
261
|
+
export {
|
|
262
|
+
COMPACTION_SUMMARY_MARKER,
|
|
263
|
+
DEFAULT_STUDIO_CONFIG,
|
|
264
|
+
LANGUAGE_RULE_LINES,
|
|
265
|
+
MAX_EXTRA_PRESERVE_RULES,
|
|
266
|
+
MAX_EXTRA_RULES_TOTAL_LENGTH,
|
|
267
|
+
MAX_EXTRA_RULE_LENGTH,
|
|
268
|
+
PLUGIN,
|
|
269
|
+
SECTION_HEADINGS,
|
|
270
|
+
VALID_LANGUAGE_POLICIES,
|
|
271
|
+
VERSION,
|
|
272
|
+
buildFrozenCompactionUserMessage,
|
|
273
|
+
buildStudioCompactionInstruction,
|
|
274
|
+
createCompactionStreamHandler,
|
|
275
|
+
isCompactionInstructionMessage,
|
|
276
|
+
probeHealth,
|
|
277
|
+
resolveStudioConfig,
|
|
278
|
+
rewriteCompactionOptions
|
|
279
|
+
};
|
|
280
|
+
//# sourceMappingURL=core.mjs.map
|
package/lib/core.mjs.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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.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
|
+
"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,cA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K,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
|
+
"names": []
|
|
7
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// src/shared/types.ts
|
|
2
|
+
var PLUGIN = "dsh-compaction-studio";
|
|
3
|
+
var VERSION = "0.1.1";
|
|
4
|
+
|
|
5
|
+
// src/core/config.ts
|
|
6
|
+
var VALID_LANGUAGE_POLICIES = Object.freeze([
|
|
7
|
+
"preserve-conversation",
|
|
8
|
+
"en",
|
|
9
|
+
"de"
|
|
10
|
+
]);
|
|
11
|
+
var MAX_EXTRA_PRESERVE_RULES = 5;
|
|
12
|
+
var MAX_EXTRA_RULE_LENGTH = 200;
|
|
13
|
+
var MAX_EXTRA_RULES_TOTAL_LENGTH = 600;
|
|
14
|
+
var ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "languagePolicy", "extraPreserveRules"]);
|
|
15
|
+
var EMPTY_RULES = Object.freeze([]);
|
|
16
|
+
var DEFAULT_STUDIO_CONFIG = Object.freeze({
|
|
17
|
+
enabled: true,
|
|
18
|
+
languagePolicy: "preserve-conversation",
|
|
19
|
+
extraPreserveRules: EMPTY_RULES
|
|
20
|
+
});
|
|
21
|
+
function resolveStudioConfig(rawConfig) {
|
|
22
|
+
if (rawConfig === void 0) {
|
|
23
|
+
return DEFAULT_STUDIO_CONFIG;
|
|
24
|
+
}
|
|
25
|
+
if (rawConfig === null || typeof rawConfig !== "object" || Array.isArray(rawConfig)) {
|
|
26
|
+
throw new Error("StudioCompactionConfig: expected a configuration object");
|
|
27
|
+
}
|
|
28
|
+
const record = rawConfig;
|
|
29
|
+
for (const key of Object.keys(record)) {
|
|
30
|
+
if (!ALLOWED_KEYS.has(key)) {
|
|
31
|
+
throw new Error(`StudioCompactionConfig: unknown key "${key}"`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let enabled = true;
|
|
35
|
+
if (record.enabled !== void 0) {
|
|
36
|
+
if (typeof record.enabled !== "boolean") {
|
|
37
|
+
throw new Error('StudioCompactionConfig: "enabled" must be a boolean');
|
|
38
|
+
}
|
|
39
|
+
enabled = record.enabled;
|
|
40
|
+
}
|
|
41
|
+
let languagePolicy = "preserve-conversation";
|
|
42
|
+
if (record.languagePolicy !== void 0) {
|
|
43
|
+
if (typeof record.languagePolicy !== "string" || !VALID_LANGUAGE_POLICIES.includes(record.languagePolicy)) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`StudioCompactionConfig: invalid "languagePolicy" "${String(record.languagePolicy)}" (expected "preserve-conversation", "en", or "de")`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
languagePolicy = record.languagePolicy;
|
|
49
|
+
}
|
|
50
|
+
let extraPreserveRules = EMPTY_RULES;
|
|
51
|
+
if (record.extraPreserveRules !== void 0) {
|
|
52
|
+
if (!Array.isArray(record.extraPreserveRules)) {
|
|
53
|
+
throw new Error('StudioCompactionConfig: "extraPreserveRules" must be an array of strings');
|
|
54
|
+
}
|
|
55
|
+
if (record.extraPreserveRules.length > MAX_EXTRA_PRESERVE_RULES) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`StudioCompactionConfig: "extraPreserveRules" exceeds max ${MAX_EXTRA_PRESERVE_RULES} items (received ${record.extraPreserveRules.length})`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const normalized = [];
|
|
61
|
+
let totalChars = 0;
|
|
62
|
+
for (let i = 0; i < record.extraPreserveRules.length; i++) {
|
|
63
|
+
const item = record.extraPreserveRules[i];
|
|
64
|
+
if (typeof item !== "string") {
|
|
65
|
+
throw new Error(`StudioCompactionConfig: "extraPreserveRules[${i}]" must be a string`);
|
|
66
|
+
}
|
|
67
|
+
if (item.includes("\r") || item.includes("\n")) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" must be single-line (no CR/LF)`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const trimmed = item.trim();
|
|
73
|
+
if (trimmed.length === 0) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" must not be empty`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
if (trimmed.length > MAX_EXTRA_RULE_LENGTH) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`StudioCompactionConfig: "extraPreserveRules[${i}]" exceeds max ${MAX_EXTRA_RULE_LENGTH} chars (received ${trimmed.length})`
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
totalChars += trimmed.length;
|
|
84
|
+
if (totalChars > MAX_EXTRA_RULES_TOTAL_LENGTH) {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`StudioCompactionConfig: "extraPreserveRules" total length exceeds max ${MAX_EXTRA_RULES_TOTAL_LENGTH} chars (received ${totalChars})`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
normalized.push(trimmed);
|
|
90
|
+
}
|
|
91
|
+
extraPreserveRules = normalized.length === 0 ? EMPTY_RULES : Object.freeze(normalized);
|
|
92
|
+
}
|
|
93
|
+
return Object.freeze({
|
|
94
|
+
enabled,
|
|
95
|
+
languagePolicy,
|
|
96
|
+
extraPreserveRules
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/core/prompt.ts
|
|
101
|
+
var SECTION_HEADINGS = Object.freeze([
|
|
102
|
+
"## Editorial & Authoring Goal",
|
|
103
|
+
"## Active Workbenches & Unit Spine",
|
|
104
|
+
"## Vetted Sources, Quotes & Media",
|
|
105
|
+
"## Craft, Didactic & House-Style Constraints",
|
|
106
|
+
"## Open Reviews & Diagnostics",
|
|
107
|
+
"## Pending Work",
|
|
108
|
+
"## Next Step"
|
|
109
|
+
]);
|
|
110
|
+
var LANGUAGE_RULE_LINES = Object.freeze({
|
|
111
|
+
"preserve-conversation": "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.",
|
|
112
|
+
en: "Write concise English bullet content; preserve non-English primary-source quotes and proper terms verbatim where relevant.",
|
|
113
|
+
de: "Write concise German bullet content (pr\xE4zise Stichpunkte auf Deutsch); preserve non-German primary-source quotes and technical identifiers verbatim."
|
|
114
|
+
});
|
|
115
|
+
function buildStudioCompactionInstruction(config) {
|
|
116
|
+
const resolved = resolveStudioConfig(config);
|
|
117
|
+
const languageRule = LANGUAGE_RULE_LINES[resolved.languagePolicy];
|
|
118
|
+
const lines = [
|
|
119
|
+
"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.",
|
|
120
|
+
"",
|
|
121
|
+
"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.",
|
|
122
|
+
"",
|
|
123
|
+
"## Editorial & Authoring Goal",
|
|
124
|
+
"- [the user's original and evolving document, research, or unit-planning intent; quote key user phrasing verbatim where wording matters]",
|
|
125
|
+
"",
|
|
126
|
+
"## Active Workbenches & Unit Spine",
|
|
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
|
+
"",
|
|
129
|
+
"## Vetted Sources, Quotes & Media",
|
|
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
|
+
"",
|
|
132
|
+
"## Craft, Didactic & House-Style Constraints",
|
|
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]',
|
|
134
|
+
"",
|
|
135
|
+
"## Open Reviews & Diagnostics",
|
|
136
|
+
"- [unresolved annotations/Randnotizen, stale `dependsOn` blocks, preflight/quote-hash warnings, or rejected proposals]",
|
|
137
|
+
"",
|
|
138
|
+
"## Pending Work",
|
|
139
|
+
"- [explicitly requested work not yet completed, respecting staged-draft boundaries]",
|
|
140
|
+
"",
|
|
141
|
+
"## Next Step",
|
|
142
|
+
"- [the single immediate next action directly aligned with the user's most recent request, or `(none)`]",
|
|
143
|
+
"",
|
|
144
|
+
"Rules:",
|
|
145
|
+
`- ${languageRule}`,
|
|
146
|
+
"- Keep the exact English `##` headings above unchanged regardless of bullet language so tools can parse checkpoints deterministically.",
|
|
147
|
+
"- 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.",
|
|
148
|
+
"- Capture user feedback, rejections, and explicit corrections faithfully.",
|
|
149
|
+
"- Do NOT mention this summarization request or acknowledge that context was compacted.",
|
|
150
|
+
"- 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.",
|
|
151
|
+
"- 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."
|
|
152
|
+
];
|
|
153
|
+
for (const extraRule of resolved.extraPreserveRules) {
|
|
154
|
+
lines.push(`- ${extraRule}`);
|
|
155
|
+
}
|
|
156
|
+
return lines.join("\n");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/core/interceptor.ts
|
|
160
|
+
var COMPACTION_SUMMARY_MARKER = "<compacted-summary>";
|
|
161
|
+
function buildFrozenCompactionUserMessage(instructionText) {
|
|
162
|
+
const textPart = Object.freeze({
|
|
163
|
+
type: "text",
|
|
164
|
+
text: instructionText
|
|
165
|
+
});
|
|
166
|
+
const content = Object.freeze([textPart]);
|
|
167
|
+
return Object.freeze({
|
|
168
|
+
role: "user",
|
|
169
|
+
content
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
function isCompactionInstructionMessage(message) {
|
|
173
|
+
if (!message || typeof message !== "object") {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
const msg = message;
|
|
177
|
+
if (msg.role !== "user" || !Array.isArray(msg.content)) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
let concatenatedText = "";
|
|
181
|
+
for (const part of msg.content) {
|
|
182
|
+
if (part && typeof part === "object" && part.type === "text" && typeof part.text === "string") {
|
|
183
|
+
concatenatedText += part.text;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return concatenatedText.includes(COMPACTION_SUMMARY_MARKER);
|
|
187
|
+
}
|
|
188
|
+
function isFrozenCompactionMessage(value) {
|
|
189
|
+
return Boolean(value) && typeof value === "object" && value.role === "user" && Array.isArray(value.content);
|
|
190
|
+
}
|
|
191
|
+
function rewriteCompactionOptions(options, replacement) {
|
|
192
|
+
if (!options || typeof options !== "object" || !Array.isArray(options.messages)) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const len = options.messages.length;
|
|
196
|
+
if (len < 1) {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
const lastMessage = options.messages[len - 1];
|
|
200
|
+
if (!isCompactionInstructionMessage(lastMessage)) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
let trailingMessage;
|
|
204
|
+
if (typeof replacement === "string") {
|
|
205
|
+
trailingMessage = buildFrozenCompactionUserMessage(replacement);
|
|
206
|
+
} else if (isFrozenCompactionMessage(replacement)) {
|
|
207
|
+
trailingMessage = replacement;
|
|
208
|
+
} else {
|
|
209
|
+
trailingMessage = buildFrozenCompactionUserMessage(
|
|
210
|
+
buildStudioCompactionInstruction(replacement)
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
const nextMessages = Object.freeze([...options.messages.slice(0, -1), trailingMessage]);
|
|
214
|
+
return Object.freeze({
|
|
215
|
+
...options,
|
|
216
|
+
messages: nextMessages
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
function safeWarn(onWarn, message) {
|
|
220
|
+
if (!onWarn) return;
|
|
221
|
+
try {
|
|
222
|
+
onWarn(message);
|
|
223
|
+
} catch {
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function createCompactionStreamHandler(init = {}) {
|
|
227
|
+
const resolvedConfig = resolveStudioConfig(init.config);
|
|
228
|
+
const instructionText = buildStudioCompactionInstruction(resolvedConfig);
|
|
229
|
+
const frozenTrailingMessage = buildFrozenCompactionUserMessage(instructionText);
|
|
230
|
+
const rewritten = /* @__PURE__ */ new WeakSet();
|
|
231
|
+
return function compactionStreamListener(options, next) {
|
|
232
|
+
if (!resolvedConfig.enabled || !options || typeof options !== "object" || options.purpose !== "compaction" || rewritten.has(options)) {
|
|
233
|
+
return next();
|
|
234
|
+
}
|
|
235
|
+
const rewrittenOptions = rewriteCompactionOptions(options, frozenTrailingMessage);
|
|
236
|
+
if (!rewrittenOptions) {
|
|
237
|
+
safeWarn(
|
|
238
|
+
init.onWarn,
|
|
239
|
+
'purpose="compaction" stream did not match expected trailing <compacted-summary> user instruction; failing open without rewrite'
|
|
240
|
+
);
|
|
241
|
+
return next();
|
|
242
|
+
}
|
|
243
|
+
const selfRuntime = this && typeof this.stream === "function" ? this : void 0;
|
|
244
|
+
const runtime = selfRuntime ?? init.getRuntime?.();
|
|
245
|
+
if (!runtime || typeof runtime.stream !== "function") {
|
|
246
|
+
safeWarn(
|
|
247
|
+
init.onWarn,
|
|
248
|
+
'purpose="compaction" stream lacked an active LlmRuntime.stream receiver; failing open without rewrite'
|
|
249
|
+
);
|
|
250
|
+
return next();
|
|
251
|
+
}
|
|
252
|
+
rewritten.add(rewrittenOptions);
|
|
253
|
+
return runtime.stream(rewrittenOptions);
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/core/index.ts
|
|
258
|
+
function probeHealth() {
|
|
259
|
+
return { ok: true, plugin: PLUGIN, version: VERSION };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/host/index.ts
|
|
263
|
+
var name = PLUGIN;
|
|
264
|
+
var inject = ["llm"];
|
|
265
|
+
function apply(ctx, rawConfig) {
|
|
266
|
+
const config = resolveStudioConfig(rawConfig);
|
|
267
|
+
const handler = createCompactionStreamHandler({
|
|
268
|
+
config,
|
|
269
|
+
getRuntime: () => ctx.llm && typeof ctx.llm.stream === "function" ? ctx.llm : void 0,
|
|
270
|
+
onWarn: (message) => {
|
|
271
|
+
try {
|
|
272
|
+
ctx.logger?.(PLUGIN)?.warn?.("[%s] %s", PLUGIN, message);
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
const dispose = ctx.on("llm/stream", handler, { global: true });
|
|
278
|
+
ctx.effect(() => dispose, "dsh-compaction-studio: llm/stream");
|
|
279
|
+
try {
|
|
280
|
+
ctx.logger?.(PLUGIN)?.debug?.(
|
|
281
|
+
"%s@%s mounted (enabled=%s, languagePolicy=%s, extraRules=%d)",
|
|
282
|
+
PLUGIN,
|
|
283
|
+
VERSION,
|
|
284
|
+
config.enabled,
|
|
285
|
+
config.languagePolicy,
|
|
286
|
+
config.extraPreserveRules.length
|
|
287
|
+
);
|
|
288
|
+
} catch {
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
export {
|
|
292
|
+
COMPACTION_SUMMARY_MARKER,
|
|
293
|
+
DEFAULT_STUDIO_CONFIG,
|
|
294
|
+
LANGUAGE_RULE_LINES,
|
|
295
|
+
PLUGIN,
|
|
296
|
+
SECTION_HEADINGS,
|
|
297
|
+
VERSION,
|
|
298
|
+
apply,
|
|
299
|
+
buildFrozenCompactionUserMessage,
|
|
300
|
+
buildStudioCompactionInstruction,
|
|
301
|
+
createCompactionStreamHandler,
|
|
302
|
+
inject,
|
|
303
|
+
isCompactionInstructionMessage,
|
|
304
|
+
name,
|
|
305
|
+
probeHealth,
|
|
306
|
+
resolveStudioConfig,
|
|
307
|
+
rewriteCompactionOptions
|
|
308
|
+
};
|
|
309
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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.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
|
+
"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,MAA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AEA,cAAU,IAAI,gBAAgB;AAC9B,WAAO,QAAQ,OAAO,gBAAgB;AAAA,EACxC;AACF;;;AC7HO,SAAS,cAA2B;AACzC,SAAO,EAAE,IAAI,MAAM,QAAQ,QAAQ,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
|
+
"names": []
|
|
7
|
+
}
|
package/locale/de.json
ADDED
package/locale/en.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-compaction-studio",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Language-preserving editorial, research, and curriculum conversation compaction backend for DeepSeek Harness.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "lib/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./lib/index.js",
|
|
9
|
+
"./core": "./lib/core.mjs",
|
|
10
|
+
"./client": "./lib/client.js",
|
|
11
|
+
"./locale/*.json": "./locale/*.json",
|
|
12
|
+
"./icon": "./icon.svg",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"lib",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"locale/*.json",
|
|
19
|
+
"icon.svg",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/janpauldahlke/dsh-compaction-studio.git"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://github.com/janpauldahlke/dsh-compaction-studio#readme",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/janpauldahlke/dsh-compaction-studio/issues"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "node build.mjs && tsc --noEmit",
|
|
36
|
+
"prepare": "node build.mjs",
|
|
37
|
+
"prepublishOnly": "npm run build && npm test",
|
|
38
|
+
"test": "node build.mjs && node --test \"test/**/*.test.mjs\""
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"dsh-plugin",
|
|
42
|
+
"deepseek-harness",
|
|
43
|
+
"deepseek-harness-plugin",
|
|
44
|
+
"dsh",
|
|
45
|
+
"cordis",
|
|
46
|
+
"cordis-plugin",
|
|
47
|
+
"ivory-tower",
|
|
48
|
+
"compaction",
|
|
49
|
+
"summarization",
|
|
50
|
+
"editorial",
|
|
51
|
+
"memory",
|
|
52
|
+
"kv-cache"
|
|
53
|
+
],
|
|
54
|
+
"dsh": {
|
|
55
|
+
"bundle": {
|
|
56
|
+
"patch": "./cordis.patch.yml"
|
|
57
|
+
},
|
|
58
|
+
"client": {
|
|
59
|
+
"platform": "web",
|
|
60
|
+
"inject": []
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"devDependencies": {
|
|
64
|
+
"@types/node": "^22.0.0",
|
|
65
|
+
"dsh-build-tools": "^0.2.0",
|
|
66
|
+
"esbuild": "^0.25.0",
|
|
67
|
+
"typescript": "^5.6.0"
|
|
68
|
+
},
|
|
69
|
+
"author": {
|
|
70
|
+
"name": "Jan (HagbardCeline)",
|
|
71
|
+
"email": "janpauldahlke@gmail.com"
|
|
72
|
+
},
|
|
73
|
+
"license": "MIT",
|
|
74
|
+
"engines": {
|
|
75
|
+
"node": ">=20"
|
|
76
|
+
}
|
|
77
|
+
}
|