@jwitmann/operator-deepseek 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -2
- package/cordis.patch.yml +5 -0
- package/dist/client.js +40 -0
- package/dist/index.js +218667 -0
- package/dist/index.js.map +132 -0
- package/dist/tool.js +708 -0
- package/dist/tool.js.map +15 -0
- package/package.json +96 -4
package/dist/tool.js.map
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../core/src/utils.ts", "../../core/src/context/compiler.ts", "../../core/src/context/session-compat.ts", "../../core/src/context/recall.ts", "../../core/src/context/search.ts", "../src/tool.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"export type Result<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\nexport function success<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\nexport function failure<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\nexport function hasNodeErrorCode(error: unknown, code: string): boolean {\n return error instanceof Error && \"code\" in error && error.code === code;\n}\n\nexport function getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function readString(value: Record<string, unknown>, key: string): string | null {\n const field = value[key];\n return typeof field === \"string\" ? field : null;\n}\n",
|
|
6
|
+
"// Deterministic tokenizer and token-budget primitives for the instant\n// compaction compiler. Faithful logic port of dsh-compaction-vcc@0.7.4\n// `src/compiler.js` via the opencode-vcc-port stage 1 (`compiler/tokenize.mjs`):\n// fixed-density word-class tokens (letter runs, digit runs, single\n// punctuation, whitespace runs), character-density estimation (0.3 per\n// non-CJK character, 0.6 per CJK character), and dual-enforced truncation\n// (token count AND a `limit * 4` character ceiling, floor 32). Everything\n// here is total and offline: same input text always yields the same tokens,\n// counts, and slices. Oracle vectors live in `compiler.test.ts`, captured\n// from the original (port selftest run 2026-11-19).\n\nimport { isRecord } from \"../utils.ts\";\n\nconst TOKEN_RE = /[a-zA-Z]+|[0-9]+|[^\\sa-zA-Z0-9]|\\s+/g;\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: sanitizer intentionally matches the ESC byte class.\nconst ANSI_RE = /\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g;\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: sanitizer intentionally matches the C0/C1 byte classes.\nconst CONTROL_RE = /[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f]/g;\n\nfunction isHighSurrogate(code: number): boolean {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isLowSurrogate(code: number): boolean {\n return code >= 0xdc00 && code <= 0xdfff;\n}\n\n// Move the end of a slice to a code-point boundary: a cut must never leave\n// a high surrogate without its low half.\nfunction completeCodePointAtEnd(text: string): string {\n return isHighSurrogate(text.charCodeAt(text.length - 1)) ? text.slice(0, -1) : text;\n}\n\n// Move the start of a slice to a code-point boundary (a tail excerpt must\n// never begin inside a surrogate pair).\nfunction completeCodePointAtStart(text: string): string {\n return isLowSurrogate(text.charCodeAt(0)) ? text.slice(1) : text;\n}\n\n// Split text into fixed-density tokens: letter runs, digit runs, single\n// punctuation chars, and whitespace runs. Whitespace tokens are included in\n// the list but never counted by `countTokens`.\nexport function tokenize(text: string): string[] {\n return text.match(TOKEN_RE) ?? [];\n}\n\n// True when the character carries the 0.6 CJK weight. Name kept for API\n// stability; it means \"CJK-density character\" (kana, hangul, Thai, Lao,\n// Indic scripts included — same density class, not ideographs only).\nexport function isCjkChar(char: string): boolean {\n const code = char.codePointAt(0) ?? -1;\n return (\n (code >= 0x3400 && code <= 0x4dbf)\n || (code >= 0x4e00 && code <= 0x9fff)\n || (code >= 0xf900 && code <= 0xfaff)\n || (code >= 0x3000 && code <= 0x303f)\n || (code >= 0xff00 && code <= 0xffef)\n || (code >= 0x3040 && code <= 0x30ff)\n || (code >= 0x31f0 && code <= 0x31ff)\n || (code >= 0xac00 && code <= 0xd7af)\n || (code >= 0x1100 && code <= 0x11ff)\n || (code >= 0x0e00 && code <= 0x0e7f)\n || (code >= 0x0e80 && code <= 0x0eff)\n || (code >= 0x0900 && code <= 0x097f)\n || (code >= 0x0980 && code <= 0x09ff)\n || (code >= 0x0a00 && code <= 0x0a7f)\n || (code >= 0x0a80 && code <= 0x0aff)\n || (code >= 0x0b00 && code <= 0x0b7f)\n || (code >= 0x0b80 && code <= 0x0bff)\n || (code >= 0x0c00 && code <= 0x0c7f)\n || (code >= 0x0c80 && code <= 0x0cff)\n || (code >= 0x0d00 && code <= 0x0d7f)\n || (code >= 0x0d80 && code <= 0x0dff)\n || (code >= 0x1000 && code <= 0x109f)\n || (code >= 0x1780 && code <= 0x17ff)\n );\n}\n\n// Estimate tokens under the character-density conversion (0.3 per non-CJK\n// character, 0.6 per CJK character). Integer tenths, exact under ceil for\n// long inputs.\nexport function estimateDeepSeekTokens(text: string): number {\n let nonCjk = 0;\n let cjk = 0;\n for (const char of text) {\n if (isCjkChar(char)) cjk += 1;\n else nonCjk += 1;\n }\n return (nonCjk * 3 + cjk * 6) / 10;\n}\n\n// Count the non-whitespace tokens of a text under `tokenize`.\nexport function countTokens(text: string): number {\n let count = 0;\n for (const token of tokenize(text)) if (token.trim().length > 0) count += 1;\n return count;\n}\n\n// Size one emitted entry the way every budget in this module is enforced:\n// the word-class token count, floored at the character-density equivalent so\n// the total cap also sees pathological long runs.\nexport function estimateEntryTokens(text: string): number {\n return Math.max(countTokens(text), Math.ceil(estimateDeepSeekTokens(text)));\n}\n\n// Strip carriage returns, ANSI escapes, and control bytes — deterministic\n// cleanup, never token-changing rewrites.\nexport function sanitize(text: string): string {\n let out = text;\n if (out.includes(\"\\r\")) out = out.replaceAll(\"\\r\", \"\");\n if (out.includes(\"\\x1b\")) out = out.replace(ANSI_RE, \"\");\n return out.replace(CONTROL_RE, \"\");\n}\n\nexport type TruncatedText = {\n readonly text: string;\n readonly truncated: boolean;\n};\n\n// Truncate text to a non-whitespace-token budget, preserving exact original\n// tokens and appending a provenance note on a cut. Every budget is enforced\n// twice — by token count AND by a `limit * 4` character ceiling (floor 32),\n// so pathological unbroken runs (base64 blobs, minified files) cannot pass.\nexport function truncateTokens(text: string, limit: number, ref: string | null): TruncatedText {\n const tokens = tokenize(text);\n let count = 0;\n let cut = tokens.length;\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index] ?? \"\";\n if (token.trim().length === 0) continue;\n count += 1;\n if (count > limit) {\n cut = index;\n break;\n }\n }\n let out = cut >= tokens.length ? text : tokens.slice(0, cut).join(\"\");\n let truncated = cut < tokens.length;\n const maxChars = Math.max(32, limit * 4);\n if (out.length > maxChars) {\n out = completeCodePointAtEnd(out.slice(0, maxChars));\n truncated = true;\n } else if (truncated) {\n out = completeCodePointAtEnd(out);\n }\n if (!truncated) return { text, truncated: false };\n out = out.replace(/\\s+$/u, \"\");\n const note = ref === null ? \"...(truncated)\" : `...(truncated from ${ref})`;\n return { text: out + note, truncated: true };\n}\n\n// Keep the LAST `limit` non-whitespace tokens of a text, additionally capped\n// at `limit * 4` characters. The end of the text is always preserved.\nexport function tailTokens(text: string, limit: number, ref: string | null): TruncatedText {\n const tokens = tokenize(text);\n let count = 0;\n let startIndex = tokens.length;\n for (let index = tokens.length - 1; index >= 0; index -= 1) {\n if ((tokens[index] ?? \"\").trim().length > 0) {\n count += 1;\n if (count > limit) break;\n }\n startIndex = index;\n }\n let out = startIndex === 0 ? text : tokens.slice(startIndex).join(\"\");\n let truncated = startIndex > 0;\n const maxChars = Math.max(32, limit * 4);\n if (out.length > maxChars) {\n out = completeCodePointAtStart(out.slice(out.length - maxChars));\n truncated = true;\n } else if (truncated) {\n out = completeCodePointAtStart(out);\n }\n if (!truncated) return { text, truncated: false };\n const tailNote = ref === null ? \"...(elided before)\" : `...(elided before ${ref})`;\n return { text: tailNote + out, truncated: true };\n}\n\n// ── region compiler (stage 2) ─────────────────────────────────────────────\n// Faithful logic port of the port repo's `compile.mjs` (itself ported from\n// dsh-compaction-vcc@0.7.4 `src/compiler.js`): noise stripping, tool-call\n// one-liners, content projection, the ordered-region compiler with budget\n// rescaling and cap elision, and checkpoint framing. Deliberate deviations\n// from the port source are marked below; everything else reproduces it.\n// Oracle vectors live in `compiler.test.ts`, captured from the original.\n\n// ── noise stripping ──\n\nconst NOISE_UNWRAP_RE = /<\\/?(?:command-name|command-args)>/g;\n\n// The VCC brief-mode noise XML patterns, adapted to harness markup. Applied\n// with the `s` flag; the replacement set is configurable via\n// `CompilerConfig.noisePatterns`.\nexport const DEFAULT_NOISE_PATTERNS: readonly string[] = [\n \"<ide_opened_file>.*?</ide_opened_file>\",\n \"<ide_selection>.*?</ide_selection>\",\n \"<system-reminder>.*?</system-reminder>\",\n \"<command-message>.*?</command-message>\",\n \"<task-notification>.*?</task-notification>\",\n];\n\n// Compile untrusted noise-pattern sources, throwing on invalid regex.\nexport function compileNoisePatterns(sources: readonly string[]): RegExp[] {\n return sources.map((source, index) => {\n try {\n return new RegExp(source, \"s\");\n } catch (error) {\n throw new Error(\n `noisePatterns[${index}] (${JSON.stringify(source)}) is not a valid regular expression: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n });\n}\n\n// Strip configured noise XML blocks from user text and unwrap command-name /\n// command-args tags.\nexport function stripNoiseXml(text: string, patterns: readonly RegExp[]): string {\n let out = text;\n for (const pattern of patterns) out = out.replace(pattern, \"\");\n out = out.replace(NOISE_UNWRAP_RE, \"\");\n return out.trim();\n}\n\n// ── tool-call one-liner ──\n\n// VCC's `_TOOL_SUMMARY_FIELDS`, extended for the DSH tool catalog. The\n// OpenCode mapping lives in adapter config (`toolKeyFields`); these defaults\n// are carried verbatim so behavior without config matches the original.\nexport const DEFAULT_TOOL_KEY_FIELDS: Readonly<Record<string, string>> = {\n read: \"file_path\",\n edit: \"file_path\",\n write: \"file_path\",\n glob: \"pattern\",\n grep: \"pattern\",\n bash: \"command\",\n web_search: \"query\",\n skill: \"name\",\n ralph: \"objective\",\n subagent: \"description\",\n subagent_fork: \"description\",\n create_goal: \"objective\",\n update_goal: \"objective\",\n workflow: \"name\",\n interrupt_agent: \"agent_id\",\n job_kill: \"job_id\",\n job_output: \"job_id\",\n send_message: \"message\",\n};\n\n// Tools whose key argument is kept in the one-liner. Everything else renders\n// name-only — bookkeeping tools carry no semantic payload worth the tokens.\nexport const DEFAULT_ARG_TOOLS: readonly string[] = [\n \"read\",\n \"write\",\n \"edit\",\n \"glob\",\n \"grep\",\n \"bash\",\n \"shell\",\n \"web_search\",\n \"skill\",\n \"subagent\",\n \"subagent_fork\",\n \"ralph\",\n \"workflow\",\n];\n\n// First-line projection for a tool-call one-liner: multiline arguments\n// collapse to the first physical line plus a `[+ N lines]` marker.\nexport function oneLineArg(value: string): string {\n const lines = value.split(/\\r?\\n/u);\n if (lines.length === 1) return value;\n const firstLine = lines[0] ?? \"\";\n if (firstLine !== \"\" || lines.every(line => line.trim() === \"\")) return firstLine;\n return `${lines.find(line => line.trim() !== \"\") ?? \"\"} [+ ${lines.length - 1} lines]`;\n}\n\n// Pick the key argument for a tool-call one-liner: the tool-specific field\n// first, then the first string-valued argument, else nothing.\nexport function pickToolKeyArg(\n name: string,\n input: unknown,\n keyFields: Readonly<Record<string, string>>,\n): string | undefined {\n if (!isRecord(input)) return undefined;\n const preferred = keyFields[name];\n if (preferred !== undefined) {\n const value = input[preferred];\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n for (const value of Object.values(input)) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return undefined;\n}\n\n// Safely parse a tool-call's raw JSON arguments. Non-string inputs yield\n// null exactly where the original's throwing parse does: every downstream\n// use only distinguishes parsed-object from not-parsed.\nexport function parseToolArguments(args: unknown): unknown {\n if (typeof args !== \"string\") return null;\n try {\n return JSON.parse(args) as unknown;\n } catch {\n return null;\n }\n}\n\n// ── content projection helpers ──\n\nexport type CompileContentBlock = {\n readonly type?: string;\n readonly text?: string;\n readonly name?: string;\n readonly arguments?: unknown;\n readonly id?: string;\n readonly toolCallId?: string;\n};\n\nexport type CompileMessage = {\n readonly role: string;\n readonly content: readonly (CompileContentBlock | null)[] | null;\n readonly toolCallId?: string;\n readonly source?: { readonly kind?: unknown } | null;\n};\n\nexport type CompileNode = {\n readonly seq: number;\n readonly message: CompileMessage | null;\n};\n\n// Project nested tool-result blocks into one plain-text string: text blocks\n// are joined, images and documents render as VCC-style labels.\nexport function projectToolResultText(blocks: unknown): string {\n const parts: string[] = [];\n if (!Array.isArray(blocks)) return \"\";\n for (const block of blocks) {\n if (block === null || block === undefined) continue;\n if (!isRecord(block)) continue;\n if (block.type === \"text\") {\n const raw = block.text;\n const text = sanitize(typeof raw === \"string\" ? raw : \"\");\n if (text.length > 0) parts.push(text);\n } else if (block.type === \"image\") parts.push(\"[image]\");\n else if (block.type === \"document\") parts.push(\"[document]\");\n else parts.push(`[${String(block.type)}]`);\n }\n return parts.join(\"\\n\");\n}\n\nexport type MessageSource =\n | {\n readonly kind?: unknown;\n readonly [key: string]: unknown;\n }\n | null\n | undefined;\n\n// Whether a message source identifies a landed compaction checkpoint node.\n// Host 0.2.x builds the marker with `compactCheckpointSource()`, which yields\n// `{ kind: \"compact-checkpoint\", compactionId, sourceCommandId? }`. The legacy\n// `{ kind: \"plugin\", plugin: \"compact\" }` shape from earlier hosts is still\n// accepted so checkpoints written by an older host stay recallable.\nexport function isCheckpointSource(source: MessageSource): boolean {\n if (!isRecord(source)) return false;\n if (source.kind === \"compact-checkpoint\") return true;\n return source.kind === \"plugin\" && source.plugin === \"compact\";\n}\n\n// Whether a message source is one of the harness-injected instruction blocks\n// the caller asked to elide (see `elideSourceKinds`). Matching is on the\n// structured `source.kind` field the harness records, never on message text.\nexport function isElidableSource(source: MessageSource, kinds: readonly string[]): boolean {\n if (kinds === undefined || kinds.length === 0) return false;\n const kind = source?.kind;\n return typeof kind === \"string\" && kinds.includes(kind);\n}\n\n// Display labels for elidable instruction sources. Anything not listed falls\n// back to its raw `source.kind`, so a new host source still gets a readable\n// pointer without a code change. Carried as the default; the adapter supplies\n// its own table through `CompilerConfig.elideSourceLabels`.\nexport const DEFAULT_ELIDABLE_SOURCE_LABELS: Readonly<Record<string, string>> = {\n \"dsh-mnemon\": \"记忆快照\",\n \"agent-instructions\": \"规则与冷库索引\",\n \"skill-catalog\": \"技能清单\",\n \"runtime-context\": \"运行时上下文\",\n \"time-context\": \"时间上下文\",\n};\n\n// Markers that open a hot-memory snapshot as the sibling memory plugin\n// renders it. Carried as the default; the adapter supplies its own markers\n// through `CompilerConfig.memorySnapshotMarkers`. Inert unless\n// checkpoint-body elision runs.\nexport const DEFAULT_MEMORY_SNAPSHOT_MARKERS: readonly string[] = [\n \"MNEMON RUNTIME MEMORY SNAPSHOT\",\n \"[MNEMON]\",\n];\n// Closing tag of one memory file block inside a snapshot.\nexport const DEFAULT_MEMORY_FILE_CLOSE = \"</runtime-memory-file>\";\n// Text that may separate two consecutive memory file blocks of ONE snapshot,\n// so the two are treated as a single span.\nexport const DEFAULT_MEMORY_BLOCK_JOINER: RegExp =\n /^\\s*(?:MEMORY\\.md \\(working reference\\)|USER\\.md \\(user profile\\)|<runtime-memory-file )/;\n// One role header line of this compiler's own checkpoint format. Memory\n// snapshots never contain one, so finding it between a file block's opening\n// and its close means the close belongs to a LATER block (truncation case)\n// and the span must stop before this.\nexport const DEFAULT_MEMORY_ROLE_HEAD: RegExp = /\\n\\[(?:user|assistant|tool)\\]\\s*\\n/;\n\n// Marker text the host puts inside a REAL rules/index wrapper. Prose that\n// only mentions `<system-reminder>` as a string must not qualify.\nexport const DEFAULT_SYSTEM_REMINDER_BODY_MARKERS: readonly string[] = [\n \"The following workspace instructions may be relevant\",\n \"Instructions from:\",\n];\n// How far into a candidate wrapper the proof phrase must appear.\nexport const DEFAULT_SYSTEM_REMINDER_PROOF_WINDOW = 600;\n// How close a memory marker must sit to the first file block to count.\nexport const DEFAULT_MEMORY_MARKER_WINDOW = 800;\n\n// Default copy for the pointer standing in for an elided instruction block.\n// Carries the seq so the agent can `recall` the original, plus what it was\n// and how big it was. The adapter supplies its own wording through\n// `CompilerConfig.elidedSourceNote`.\nexport const DEFAULT_ELIDED_SOURCE_NOTE = (label: string, seq: number, length: number): string =>\n `[${label} 已压缩为指针(seq ${seq},原文 ${length} 字符)— 原文可用 recall 调回,且下一次压缩后会重新注入]`;\n\n// Default copy for a collapsed harness-injected body inside a prior\n// checkpoint. The adapter supplies its own wording through\n// `CompilerConfig.elidedBodyNote`.\nexport const DEFAULT_ELIDED_BODY_NOTE = (length: number): string =>\n `[注入内容已压缩为指针(原文 ${length} 字符)— 压缩后会重新注入,原文可用 recall 调回]`;\n\n// Locate injected memory snapshots embedded in a PRIOR checkpoint body.\n// Returns `[start, end)` character spans, left to right.\nfunction findMemorySnapshotSpans(\n text: string,\n markers: readonly string[],\n fileClose: string,\n blockJoiner: RegExp,\n roleHead: RegExp,\n markerWindow: number,\n): [number, number][] {\n const spans: [number, number][] = [];\n let searchFrom = 0;\n while (searchFrom < text.length) {\n let markerAt: number | undefined;\n for (const marker of markers) {\n const index = text.indexOf(marker, searchFrom);\n if (index !== -1 && (markerAt === undefined || index < markerAt)) markerAt = index;\n }\n if (markerAt === undefined) break;\n const firstFile = text.indexOf(\"<runtime-memory-file \", markerAt);\n if (firstFile === -1) break;\n if (firstFile - markerAt > markerWindow) {\n // Just prose quoting the marker — skip past it and keep looking.\n searchFrom = markerAt + 1;\n continue;\n }\n let end: number | undefined;\n let cursor = firstFile;\n for (;;) {\n const close = text.indexOf(fileClose, cursor);\n if (close === -1) break;\n // A memory block whose closing tag was truncated away has no close of\n // its own, so the search below would run on to the NEXT block's close\n // and swallow every real turn in between. Role headers are this\n // compiler's own output and never appear inside a memory snapshot, so\n // a role header before the close proves the span has left the block.\n const head = roleHead.exec(text.slice(cursor, close));\n if (head !== null) {\n end = cursor + head.index;\n break;\n }\n const after = close + fileClose.length;\n end = after;\n cursor = after;\n if (!blockJoiner.test(text.slice(after, after + 240))) break;\n }\n if (end === undefined) break;\n spans.push([markerAt, end]);\n searchFrom = end;\n }\n return spans;\n}\n\n// Locate `<system-reminder>…</system-reminder>` wrappers that really frame\n// workspace rules, the cold-store index or runtime context.\nfunction findSystemReminderSpans(\n text: string,\n bodyMarkers: readonly string[],\n proofWindow: number,\n): [number, number][] {\n const spans: [number, number][] = [];\n const pattern = /(?:^|\\n)<system-reminder>\\n/g;\n let match = pattern.exec(text);\n while (match !== null) {\n const open = text.indexOf(\"<system-reminder>\", match.index);\n const head = text.slice(open, open + proofWindow);\n if (bodyMarkers.some(marker => head.includes(marker))) {\n const close = text.indexOf(\"</system-reminder>\", open);\n if (close !== -1) spans.push([open, close + \"</system-reminder>\".length]);\n }\n match = pattern.exec(text);\n }\n return spans;\n}\n\nexport type ElideResult = {\n readonly text: string;\n readonly spans: number;\n readonly chars: number;\n};\n\n// Collapse harness-injected bodies embedded in a PRIOR checkpoint to\n// one-line pointers. Only checkpoint prose is touched; live conversation\n// text is never scanned. Marker lists and pointer copy come from config.\nexport function elideCheckpointInjectedBodies(text: string, config: CompilerConfig): ElideResult {\n const spans = [\n ...findMemorySnapshotSpans(\n text,\n config.memorySnapshotMarkers,\n config.memoryFileClose,\n config.memoryBlockJoiner,\n config.memoryRoleHead,\n config.memoryMarkerWindow,\n ),\n ...findSystemReminderSpans(\n text,\n config.systemReminderBodyMarkers,\n config.systemReminderProofWindow,\n ),\n ].sort((left, right) => left[0] - right[0]);\n if (spans.length === 0) return { text, spans: 0, chars: 0 };\n let out = \"\";\n let cursor = 0;\n let chars = 0;\n let removed = 0;\n for (const span of spans) {\n const start = span[0];\n const end = span[1];\n // Overlapping spans would otherwise duplicate text; keep the outer one.\n if (start < cursor) continue;\n out += text.slice(cursor, start);\n const length = end - start;\n chars += length;\n removed += 1;\n out += config.elidedBodyNote(length);\n cursor = end;\n }\n out += text.slice(cursor);\n return { text: out, spans: removed, chars };\n}\n\n// Head/tail excerpt of a tool result under one shared token budget. The tail\n// is anchored to the end of the text at character granularity, so a result\n// whose tail matters more than its head (file listings, logs) keeps its end.\nexport function excerptToolResult(text: string, budget: number, ref: string): string {\n const overBudget = countTokens(text) > budget || text.length > budget * 4;\n if (budget <= 0 || !overBudget) return text;\n const half = Math.floor(budget / 2);\n const headLimit = Math.max(8, half);\n const tailLimit = Math.max(8, budget - headLimit);\n const head = truncateTokens(text, headLimit, ref);\n const tail = tailTokens(text, tailLimit, ref);\n return `${head.text}\\n...(elided from ${ref})\\n${tail.text}`;\n}\n\n// ── the region compiler ──\n\nexport const CHECKPOINT_PREAMBLE =\n \"This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.\";\nexport const CHECKPOINT_OPEN_TAG = \"<compacted-checkpoint>\";\nexport const CHECKPOINT_CLOSE_TAG = \"</compacted-checkpoint>\";\n\n// Checkpoint framing copy: the recall guide plus the preamble and tags that\n// wrap the compiled body. Part of the checkpoint wire format (bumped with\n// COMPILER_REV); carried as config so the adapter owns its wording.\nexport type CheckpointFraming = {\n readonly recallGuide: string;\n readonly preamble: string;\n readonly openTag: string;\n readonly closeTag: string;\n};\n\n// Model-facing guide framed into the head of every checkpoint: tells the\n// agent how to recover content the compiler elided or truncated, using the\n// two recall tools that read the append-only durable log.\nexport const RECALL_GUIDE =\n 'RECALL: append-only log — nothing is lost. `recall` restores original content: type \"seq\", id \"3-7\"; \"result\", id \"3\"; \"checkpoint\", id \"1\" (`[checkpoint N]` = dropped). `search` finds by keyword.';\n\n// Per-node reference marker: the durable seq is the lossless pointer.\nfunction seqRef(seq: number): string {\n return `seq ${seq}`;\n}\n\n// Build marker for this compiler revision. Bumped whenever the compiled\n// output format changes, so debug logs can prove which code version ran.\nexport const COMPILER_REV = \"vcc-compiler-debug-2\";\n\nexport const DEFAULT_CHECKPOINT_FRAMING: CheckpointFraming = {\n recallGuide: RECALL_GUIDE,\n preamble: CHECKPOINT_PREAMBLE,\n openTag: CHECKPOINT_OPEN_TAG,\n closeTag: CHECKPOINT_CLOSE_TAG,\n};\n\nexport type CompilerConfig = {\n readonly textTokens: number;\n readonly userTextTokens: number;\n readonly toolCallTokens: number;\n readonly toolResultExcerptTokens: number;\n readonly maxTokens: number;\n readonly includeReasoning: boolean;\n readonly stripNoiseXml: boolean;\n readonly noisePatterns: readonly RegExp[];\n readonly toolKeyFields: Readonly<Record<string, string>>;\n readonly toolArgTools: readonly string[];\n readonly hideTools: readonly string[];\n readonly elideCheckpointInjectedBodies: boolean;\n readonly elideSourceKinds: readonly string[];\n readonly elideSourceLabels: Readonly<Record<string, string>>;\n readonly memorySnapshotMarkers: readonly string[];\n readonly memoryFileClose: string;\n readonly memoryBlockJoiner: RegExp;\n readonly memoryRoleHead: RegExp;\n readonly memoryMarkerWindow: number;\n readonly systemReminderBodyMarkers: readonly string[];\n readonly systemReminderProofWindow: number;\n readonly elidedSourceNote: (label: string, seq: number, length: number) => string;\n readonly elidedBodyNote: (length: number) => string;\n readonly framing: CheckpointFraming;\n readonly checkpointOrdinals: ReadonlyMap<number, number | string> | null;\n readonly debug: boolean;\n readonly debugSink: ((text: string) => void) | null;\n};\n\nexport type CompileBudgets = {\n readonly textTokens: number;\n readonly userTextTokens: number;\n readonly toolCallTokens: number;\n readonly toolResultExcerptTokens: number;\n};\n\nexport type CompileEntryKind =\n | \"text\"\n | \"reasoning\"\n | \"tool\"\n | \"media\"\n | \"result\"\n | \"checkpoint\"\n | \"note\";\n\nexport type CompileEntry = {\n readonly seq: number;\n readonly text: string;\n readonly kind: CompileEntryKind;\n};\n\nexport type CompileStats = {\n readonly nodes: number;\n readonly entries: number;\n readonly toolCalls: number;\n readonly toolResults: number;\n readonly images: number;\n readonly documents: number;\n readonly reasoningElided: number;\n readonly noiseElided: number;\n readonly elidedSourceRows: number;\n readonly elidedSourceChars: number;\n readonly elidedCheckpointSpans: number;\n readonly elidedCheckpointChars: number;\n readonly checkpoints: number;\n readonly tokens: number;\n readonly elidedToolRows: number;\n readonly elidedRows: number;\n};\n\n// Emit one debug line through the configured sink when `debug` is enabled.\n// Deviation from the port: no `console.error` fallback — runtime code never\n// writes to the console; observability flows through the caller's channels.\nfunction debugLog(config: CompilerConfig, tag: string, line: string): void {\n if (!config.debug) return;\n const text = `[dsh-compaction-vcc] ${tag}: ${line}`;\n try {\n config.debugSink?.(text);\n } catch {\n // A failing debug sink must never break a compaction.\n }\n}\n\n// Compile one ordered region into compact entries. `message` may be null\n// (non-projecting node); `budgets` selects the per-block budgets, defaulting\n// to the config values (the budget-cap loop passes scaled budgets on retry).\nexport function compileNodes(\n nodes: readonly CompileNode[],\n config: CompilerConfig,\n budgets: CompileBudgets | null,\n): { readonly entries: CompileEntry[]; readonly stats: CompileStats } {\n const effective: CompileBudgets = budgets ?? {\n textTokens: config.textTokens,\n userTextTokens: config.userTextTokens,\n toolCallTokens: config.toolCallTokens,\n toolResultExcerptTokens: config.toolResultExcerptTokens,\n };\n const keyFields = { ...DEFAULT_TOOL_KEY_FIELDS, ...config.toolKeyFields };\n const patterns = config.noisePatterns;\n // Empty lists mean \"unset\": the config pipeline injects `[]` for absent\n // array keys, so fall back to the defaults instead of rendering every\n // tool call name-only.\n const argTools = config.toolArgTools.length > 0 ? config.toolArgTools : DEFAULT_ARG_TOOLS;\n const hiddenTools = new Set(config.hideTools);\n debugLog(\n config,\n \"compile\",\n `rev=${COMPILER_REV} nodes=${nodes.length} argTools=[${argTools.join(\",\")}] hideTools={${[...hiddenTools].join(\",\")}} budgets=${JSON.stringify(effective)}`,\n );\n const entries: CompileEntry[] = [];\n const stats = {\n nodes: nodes.length,\n entries: 0,\n toolCalls: 0,\n toolResults: 0,\n images: 0,\n documents: 0,\n reasoningElided: 0,\n noiseElided: 0,\n elidedSourceRows: 0,\n elidedSourceChars: 0,\n elidedCheckpointSpans: 0,\n elidedCheckpointChars: 0,\n checkpoints: 0,\n tokens: 0,\n elidedToolRows: 0,\n elidedRows: 0,\n };\n // Pre-pass over the ordered nodes: map each tool-call id to the seq of its\n // result node, so every call one-liner can carry a VCC-style result pointer\n // even though results no longer occupy entries. Reads the message-level\n // `toolCallId` first with the legacy first-block shape as fallback.\n const resultSeqByCallId = new Map<string, number>();\n for (const node of nodes) {\n const message = node.message;\n if (message === null || message === undefined) continue;\n const first = message.content?.[0];\n const toolResultBlock =\n first !== undefined && first !== null && first.type === \"tool-result\" ? first : undefined;\n const callId =\n typeof message.toolCallId === \"string\"\n ? message.toolCallId\n : typeof toolResultBlock?.toolCallId === \"string\"\n ? toolResultBlock.toolCallId\n : undefined;\n if (callId !== undefined) resultSeqByCallId.set(callId, node.seq);\n }\n let lastRole: string | undefined;\n let open = false;\n\n // Append one compiled entry carrying a deletion-priority kind. Kinds order\n // the cap-elision passes in compileRegion: `result`/`tool`/`media`/`note`\n // rows are dropped before `text`/`reasoning`/`checkpoint` rows, so when a\n // checkpoint must shrink, the conversation's words survive its logs.\n const pushEntry = (seq: number, text: string, kind: CompileEntryKind): void => {\n entries.push({ seq, text, kind });\n stats.entries += 1;\n stats.tokens += estimateEntryTokens(text);\n };\n const roleHeader = (role: string): string => {\n if (!open || lastRole !== role) {\n open = true;\n lastRole = role;\n return `[${role}]\\n`;\n }\n return \"\";\n };\n\n for (const node of nodes) {\n const message = node.message;\n // A null/absent `content` used to fall through and throw, aborting the\n // whole compile. Skip the node instead so the rest still compiles.\n if (message === null || message === undefined) continue;\n if (!Array.isArray(message.content)) continue;\n if (message.role === \"assistant\") {\n let header = \"\";\n for (const block of message.content) {\n // A null block in the array used to throw on `block.type` and abort\n // the whole compile. Skip it.\n if (block === null || block === undefined) continue;\n if (block.type === \"text\") {\n const text = sanitize(block.text ?? \"\");\n if (text.trim().length === 0) continue;\n header = roleHeader(\"assistant\");\n const kept = truncateTokens(text, effective.textTokens, seqRef(node.seq));\n pushEntry(node.seq, `${header}${kept.text}`, \"text\");\n continue;\n }\n if (block.type === \"reasoning\") {\n if (!config.includeReasoning) {\n stats.reasoningElided += 1;\n continue;\n }\n const text = sanitize(block.text ?? \"\");\n if (text.trim().length === 0) continue;\n header = roleHeader(\"assistant\");\n const kept = truncateTokens(text, effective.textTokens, seqRef(node.seq));\n pushEntry(node.seq, `${header}${kept.text}`, \"reasoning\");\n continue;\n }\n if (block.type === \"tool-call\") {\n const name = block.name ?? \"unknown\";\n stats.toolCalls += 1;\n if (hiddenTools.has(name)) {\n debugLog(config, \"tool\", `seq=${node.seq} name=${name} HIDDEN (hideTools)`);\n continue;\n }\n header = roleHeader(\"assistant\");\n // One line, always: key argument only for whitelisted tools, and a\n // pointer to the result node so the dropped result stays one recall\n // away.\n let oneLine: string;\n let diag: string;\n if (argTools.includes(name)) {\n const parsed = parseToolArguments(block.arguments);\n const arg = pickToolKeyArg(name, parsed, keyFields);\n oneLine = arg === undefined ? `* ${name}` : `* ${name} \"${oneLineArg(arg)}\"`;\n diag = `whitelist=yes argsType=${typeof block.arguments} argsLen=${\n block.arguments === null || block.arguments === undefined\n ? 0\n : String(block.arguments).length\n } argsHead=${JSON.stringify(String(block.arguments).slice(0, 60))} parse=${\n parsed === null ? \"FAIL\" : \"ok\"\n } key=${keyFields[name] ?? \"(fallback)\"} arg=${\n arg === undefined ? \"(none)\" : JSON.stringify(String(arg).slice(0, 60))\n }`;\n } else {\n oneLine = `* ${name}`;\n diag = `whitelist=no argsType=${typeof block.arguments} argsLen=${\n block.arguments === null || block.arguments === undefined\n ? 0\n : String(block.arguments).length\n } argsHead=${JSON.stringify(String(block.arguments).slice(0, 60))}`;\n }\n const callId = typeof block.id === \"string\" ? block.id : undefined;\n const resultSeq = callId === undefined ? undefined : resultSeqByCallId.get(callId);\n const ref =\n resultSeq === undefined\n ? seqRef(node.seq)\n : `${seqRef(node.seq)} -> result ${resultSeq}`;\n const kept = truncateTokens(oneLine, effective.toolCallTokens, seqRef(node.seq));\n debugLog(\n config,\n \"tool\",\n `seq=${node.seq} name=${name} ${diag} line=${JSON.stringify(oneLine.slice(0, 80))} truncated=${kept.truncated} ref=${ref}`,\n );\n pushEntry(node.seq, `${header}${kept.text} (${ref})`, \"tool\");\n continue;\n }\n if (block.type === \"image\") {\n stats.images += 1;\n header = roleHeader(\"assistant\");\n pushEntry(node.seq, `${header}[image] (${seqRef(node.seq)})`, \"media\");\n continue;\n }\n if (block.type === \"document\") {\n stats.documents += 1;\n header = roleHeader(\"assistant\");\n pushEntry(node.seq, `${header}[document] (${seqRef(node.seq)})`, \"media\");\n continue;\n }\n // Unknown merge-extensible block types render as labels.\n header = roleHeader(\"assistant\");\n pushEntry(node.seq, `${header}[${String(block.type)}] (${seqRef(node.seq)})`, \"media\");\n }\n // Reasoning-only and empty assistant messages produce no entry.\n continue;\n }\n if (message.role === \"tool\") {\n stats.toolResults += 1;\n const body = projectToolResultText(message.content);\n if (body.length > 0) {\n const header = roleHeader(\"tool\");\n // Excerpt to the configured budget: tool output is the bulk of a long\n // session, and the full text stays one recall away via the call\n // line's `-> result N` pointer.\n const kept = excerptToolResult(body, effective.toolResultExcerptTokens, seqRef(node.seq));\n pushEntry(node.seq, `${header}${kept}`, \"result\");\n }\n continue;\n }\n if (message.role === \"user\") {\n const first = message.content[0];\n if (first !== undefined && first !== null && first.type === \"tool-result\") {\n // Tool results never occupy an entry: the content is either absorbed\n // into the following assistant text or one recall away via the call\n // line's `-> result N` pointer.\n stats.toolResults += 1;\n continue;\n }\n if (isCheckpointSource(message.source)) {\n stats.checkpoints += 1;\n let text = projectToolResultText(message.content);\n if (text.length > 0 && config.elideCheckpointInjectedBodies) {\n // A prior checkpoint body still carries every memory snapshot and\n // rules block that was live when it was compiled. Those are re-sent\n // in full after this compaction, so keeping them here is a\n // duplicate. Opt-in (default off) because it rewrites previously\n // compiled prose.\n const collapsed = elideCheckpointInjectedBodies(text, config);\n if (collapsed.spans > 0) {\n text = collapsed.text;\n stats.elidedCheckpointSpans += collapsed.spans;\n stats.elidedCheckpointChars += collapsed.chars;\n }\n }\n if (text.length > 0) {\n // The checkpoint node is harness-generated framing — display it as\n // [system].\n const header = roleHeader(\"system\");\n pushEntry(node.seq, `${header}${text}`, \"checkpoint\");\n }\n continue;\n }\n if (isElidableSource(message.source, config.elideSourceKinds)) {\n // Harness-injected instruction blocks are re-injected in full after\n // every compaction, so keeping their body here duplicates them.\n // Collapse to a recall pointer.\n const text = projectToolResultText(message.content);\n if (text.length === 0) continue;\n const kind = message.source?.kind;\n const label =\n typeof kind === \"string\" ? (config.elideSourceLabels[kind] ?? kind) : \"(unknown)\";\n stats.elidedSourceRows += 1;\n stats.elidedSourceChars += text.length;\n pushEntry(\n node.seq,\n `${roleHeader(\"user\")}* ${config.elidedSourceNote(label, node.seq, text.length)}`,\n \"note\",\n );\n continue;\n }\n let surviving = 0;\n let header = \"\";\n for (const block of message.content) {\n // A null block in the array used to throw on `block.type` and abort\n // the whole compile. Skip it.\n if (block === null || block === undefined) continue;\n if (block.type === \"text\") {\n let text = sanitize(block.text ?? \"\");\n if (config.stripNoiseXml) text = stripNoiseXml(text, patterns);\n if (text.length === 0) continue;\n surviving += 1;\n header = roleHeader(\"user\");\n const kept = truncateTokens(text, effective.userTextTokens, seqRef(node.seq));\n pushEntry(node.seq, `${header}${kept.text}`, \"text\");\n } else if (block.type === \"image\") {\n stats.images += 1;\n surviving += 1;\n header = roleHeader(\"user\");\n pushEntry(node.seq, `${header}[image] (${seqRef(node.seq)})`, \"media\");\n } else if (block.type === \"document\") {\n stats.documents += 1;\n surviving += 1;\n header = roleHeader(\"user\");\n pushEntry(node.seq, `${header}[document] (${seqRef(node.seq)})`, \"media\");\n } else {\n const text = sanitize(block.text ?? \"\");\n if (text.length === 0) continue;\n surviving += 1;\n header = roleHeader(\"user\");\n const kept = truncateTokens(text, effective.userTextTokens, seqRef(node.seq));\n pushEntry(node.seq, `${header}${kept.text}`, \"text\");\n }\n }\n if (surviving === 0) {\n stats.noiseElided += 1;\n pushEntry(\n node.seq,\n `${roleHeader(\"user\")}* [user message elided: noise-only] (${seqRef(node.seq)})`,\n \"note\",\n );\n }\n }\n }\n return { entries, stats };\n}\n\n// Per-budget elision floors: conversation text keeps a meaningful minimum\n// even when the total cap forces heavy rescaling, while tool one-liners and\n// result excerpts may collapse to near-nothing first.\nconst BUDGET_FLOORS = {\n textTokens: 32,\n userTextTokens: 32,\n toolCallTokens: 8,\n toolResultExcerptTokens: 8,\n} as const;\n\n// Entry kinds dropped by the first (low-value) elision pass.\nconst LOW_VALUE_KINDS: ReadonlySet<CompileEntryKind> = new Set([\"result\", \"tool\", \"media\", \"note\"]);\n\n// Scale ONLY the conversation-text budgets toward a total cap, never below\n// the per-key floor. Tool-call rows stay one-liners at their configured\n// budget: conversation shrinks first, tool rows are sacrificed whole by the\n// elision pass, so tool calls can never squeeze the dialogue out.\nfunction scaleBudgets(budgets: CompileBudgets, factor: number): CompileBudgets {\n return {\n ...budgets,\n textTokens: Math.max(BUDGET_FLOORS.textTokens, Math.floor(budgets.textTokens * factor)),\n userTextTokens: Math.max(\n BUDGET_FLOORS.userTextTokens,\n Math.floor(budgets.userTextTokens * factor),\n ),\n };\n}\n\n// Render the provenance range of one dropped-entry list. The list is never\n// empty at the call sites; the fallback only satisfies the type checker.\nfunction seqRangeOf(dropped: readonly CompileEntry[]): string {\n const first = dropped[0];\n const last = dropped[dropped.length - 1];\n if (first === undefined || last === undefined) return \"seq ?\";\n return first.seq === last.seq ? `seq ${first.seq}` : `seqs ${first.seq}-${last.seq}`;\n}\n\n// Mutable working copy of the counters: `CompileStats` is readonly for\n// callers, but the cap pass adjusts totals as it elides.\ntype MutableStats = { -readonly [Key in keyof CompileStats]: CompileStats[Key] };\n\nexport type CompileRegionResult = {\n readonly entries: CompileEntry[];\n readonly stats: CompileStats;\n readonly capped: boolean;\n};\n\n// Compile a region to completion under the total checkpoint cap: budgets are\n// rescaled toward `config.maxTokens` up to four attempts, then the oldest\n// low-value rows (tool/result/media/note) are front-elided first, and only\n// then the oldest remaining entries — so the conversation's words survive\n// elision before its logs do. The newest entries always survive.\nexport function compileRegion(\n nodes: readonly CompileNode[],\n config: CompilerConfig,\n): CompileRegionResult {\n const baseBudgets: CompileBudgets = {\n textTokens: config.textTokens,\n userTextTokens: config.userTextTokens,\n toolCallTokens: config.toolCallTokens,\n toolResultExcerptTokens: config.toolResultExcerptTokens,\n };\n let budgets: CompileBudgets = baseBudgets;\n let compiled = compileNodes(nodes, config, budgets);\n let attempts = 0;\n const maxAttempts = 4;\n while (compiled.stats.tokens > config.maxTokens && attempts < maxAttempts) {\n budgets = scaleBudgets(budgets, (config.maxTokens / compiled.stats.tokens) * 0.95);\n compiled = compileNodes(nodes, config, budgets);\n attempts += 1;\n }\n const entries = [...compiled.entries];\n const stats: MutableStats = { ...compiled.stats };\n let capped = false;\n if (stats.tokens > config.maxTokens) {\n // Phase A: drop the oldest low-value rows (tool/result/media/note)\n // anywhere in the list first, so conversation text and prior-checkpoint\n // knowledge survive elision before the logs do.\n const toolRows: CompileEntry[] = [];\n while (entries.length > 1 && stats.tokens > config.maxTokens) {\n const index = entries.findIndex(\n (entry, position) => position < entries.length - 1 && LOW_VALUE_KINDS.has(entry.kind),\n );\n if (index === -1) break;\n const dropped = entries.splice(index, 1)[0];\n if (dropped === undefined) break;\n stats.tokens -= estimateEntryTokens(dropped.text);\n toolRows.push(dropped);\n }\n if (toolRows.length > 0) {\n capped = true;\n stats.elidedToolRows += toolRows.length;\n const firstToolRow = toolRows[0];\n const marker: CompileEntry = {\n seq: firstToolRow?.seq ?? 0,\n text: `[${toolRows.length} tool/result entries elided: ${seqRangeOf(toolRows)}]`,\n kind: \"note\",\n };\n entries.unshift(marker);\n stats.tokens += estimateEntryTokens(marker.text);\n }\n const elided: CompileEntry[] = [];\n const droppedCheckpoints: CompileEntry[] = [];\n while (entries.length > 1 && stats.tokens > config.maxTokens) {\n const dropped = entries.shift();\n if (dropped === undefined) break;\n stats.tokens -= estimateEntryTokens(dropped.text);\n elided.push(dropped);\n if (dropped.kind === \"checkpoint\") droppedCheckpoints.push(dropped);\n }\n if (elided.length > 0) {\n capped = true;\n stats.elidedRows += elided.length;\n // Dropped prior checkpoints never vanish silently: each leaves a\n // single `[checkpoint N]` line the agent can restore in full via\n // recall(type:\"checkpoint\", id:\"N\").\n const firstElided = elided[0];\n const markerLines = [`[${elided.length} earlier entries elided: ${seqRangeOf(elided)}]`];\n for (const dropped of droppedCheckpoints) {\n const ordinal = config.checkpointOrdinals?.get(dropped.seq);\n const ref = ordinal === undefined ? `@ seq ${dropped.seq}` : String(ordinal);\n markerLines.push(`[checkpoint ${ref}]`);\n }\n const marker: CompileEntry = {\n seq: firstElided?.seq ?? 0,\n text: markerLines.join(\"\\n\"),\n kind: \"note\",\n };\n entries.unshift(marker);\n stats.tokens += estimateEntryTokens(marker.text);\n }\n if (stats.tokens > config.maxTokens && entries.length === 1) {\n capped = true;\n const only = entries[0];\n if (only !== undefined) {\n const hard = truncateTokens(only.text, Math.max(8, config.maxTokens - 4), \"total cap\");\n entries[0] = { seq: only.seq, text: hard.text, kind: only.kind };\n stats.tokens = estimateEntryTokens(hard.text);\n }\n }\n }\n return { entries, stats, capped };\n}\n\n// Normalize one compiled entry to its text: entries are `{ seq, text }`\n// pairs, but a custom compile hook may supply plain strings.\nexport function entryText(entry: string | { readonly text: string }): string {\n return typeof entry === \"string\" ? entry : entry.text;\n}\n\n// Join compiled entries with separators that keep tool runs compact:\n// consecutive `tool` rows join with a single newline (no blank line), while\n// every other boundary keeps the blank line that separates entry groups.\n// Strings (guide, header, elision markers) behave like `text` entries.\nexport function joinCompiledEntries(entries: readonly (string | CompileEntry)[]): string {\n let out = \"\";\n let previousKind: CompileEntryKind | undefined;\n for (const entry of entries) {\n const kind: CompileEntryKind = typeof entry === \"string\" ? \"text\" : entry.kind;\n if (out.length > 0) out += previousKind === \"tool\" && kind === \"tool\" ? \"\\n\" : \"\\n\\n\";\n out += typeof entry === \"string\" ? entry : entry.text;\n previousKind = kind;\n }\n return out;\n}\n\n// Frame compiled entries as the durable replacement checkpoint content:\n// the shared preamble, the recall guide, then one tagged block (guide first,\n// then the optional intro line, the optional header line, the entries, and\n// the optional retention footer). Prior-checkpoint text copied verbatim\n// nests inside harmlessly.\nexport function frameCheckpoint(\n entries: readonly (string | CompileEntry)[],\n headerLine: string | null,\n introLine: string | null,\n footerLine: string | readonly string[] | null,\n framing: CheckpointFraming,\n): { readonly type: \"text\"; readonly text: string }[] {\n const body: (string | CompileEntry)[] = [framing.recallGuide];\n if (introLine !== null) body.push(introLine);\n if (headerLine !== null) body.push(headerLine);\n for (const entry of entries) body.push(entry);\n // `footerLine` accepts one line or an ordered list, so callers can append\n // several trailing notes without concatenating them into one paragraph.\n if (footerLine !== null) {\n if (typeof footerLine === \"string\") body.push(footerLine);\n else {\n for (const line of footerLine) body.push(line);\n }\n }\n return [\n { type: \"text\", text: `${framing.preamble}\\n\\n${framing.openTag}` },\n { type: \"text\", text: joinCompiledEntries(body) },\n { type: \"text\", text: framing.closeTag },\n ];\n}\n",
|
|
7
|
+
"// Cross-version session-log access for the recall/search stages. Faithful\n// logic port of the port repo's `session-compat.mjs` (itself ported from\n// dsh-compaction-vcc@0.7.4 `src/session-compat.js`): duck-typed accessors\n// (`eventAt`/`snapshotEvents`) with the legacy `events`-array fallback — no\n// DSH imports, so any session-shaped value works. Oracle vectors live in\n// `recall.test.ts`, captured from the original (port selftest run 2026-11-19).\n//\n// Deliberate deviation: the original warns through `console.warn`. Runtime\n// code never writes to the console; missed-capability reports flow through an\n// optional module sink (no-op by default, set by the caller for observability\n// or tests). Return values are unaffected.\n\nexport type CompatSessionEvent = {\n readonly seq: number;\n readonly type: string;\n readonly data?: unknown;\n};\n\nexport type CompatSession = {\n readonly snapshotEvents?: (() => readonly CompatSessionEvent[] | null | undefined) | unknown;\n readonly eventAt?: ((seq: number) => CompatSessionEvent | null | undefined) | unknown;\n readonly events?: readonly CompatSessionEvent[] | null | undefined;\n};\n\ntype WarnSink = (text: string) => void;\n\nlet warnSink: WarnSink | null = null;\n\n// Capability gaps already reported, so the log stays readable.\nconst warned = new Set<string>();\n\n// Install the sink for missed-capability reports, or null to silence them.\n// Module-level (not per-call) so the oracle-identical call shapes\n// `sessionEvents(session)` / `sessionEventAt(session, seq)` are preserved.\nexport function setSessionCompatWarnSink(sink: WarnSink | null): void {\n warnSink = sink;\n}\n\nfunction warnOnce(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n try {\n warnSink?.(`[dsh-compaction-vcc] ${message}`);\n } catch {\n // A failing warn sink must never break recall or search.\n }\n}\n\n// Whether a session-shaped value exposes any readable event log.\nexport function hasSessionEventAccess(session: unknown): boolean {\n if (session === null || session === undefined) return false;\n if (typeof session !== \"object\") return false;\n const candidate = session as CompatSession;\n if (typeof candidate.snapshotEvents === \"function\") return true;\n if (typeof candidate.eventAt === \"function\") return true;\n return candidate.events !== null && candidate.events !== undefined;\n}\n\n// A frozen snapshot of every event in the durable log. Empty only when the\n// session genuinely has no log access, reported once through the warn sink.\nexport function sessionEvents(session: unknown): readonly CompatSessionEvent[] {\n if (session === null || session === undefined) return [];\n if (typeof session !== \"object\") return [];\n const candidate = session as CompatSession;\n if (typeof candidate.snapshotEvents === \"function\") {\n const events = candidate.snapshotEvents();\n if (events === null || events === undefined) {\n warnOnce(\"snapshotEvents() returned no array; treating the log as empty\");\n return [];\n }\n return events;\n }\n if (candidate.events !== null && candidate.events !== undefined) return candidate.events;\n warnOnce(\n \"session exposes neither snapshotEvents() nor events; the durable log is unreadable on this host — compaction will not run\",\n );\n return [];\n}\n\n// The immutable event stored at one exact sequence number, or undefined when\n// the log does not contain it.\nexport function sessionEventAt(session: unknown, seq: number): CompatSessionEvent | undefined {\n if (session === null || session === undefined) return undefined;\n if (typeof session !== \"object\") return undefined;\n const candidate = session as CompatSession;\n if (typeof candidate.eventAt === \"function\") {\n const event = candidate.eventAt(seq);\n return event === null || event === undefined ? undefined : event;\n }\n const events = candidate.events;\n if (events === null || events === undefined) return undefined;\n // The legacy array is indexed by POSITION, not by seq: the durable log\n // numbers events from 1 while array indices start at 0, so `events[seq]`\n // is off by one. Every call site re-checks `event.seq === seq` and treats\n // a mismatch as \"not found\", so this is a safe failure rather than wrong\n // data — but it means the legacy path only works for a 0-based array.\n // Prefer the accessor pair; this branch exists for old unit fixtures.\n const positional = events[seq];\n if (positional !== undefined && positional?.seq === seq) return positional;\n for (const event of events) {\n if (event?.seq === seq) return event;\n }\n return positional;\n}\n",
|
|
8
|
+
"// Same-session recall core, the lossless counterpart of the compiler:\n// checkpoint `(seq N)` pointers expand back into exact original content from\n// the append-only log. Faithful logic port of the port repo's `recall.mjs`\n// (itself ported from dsh-compaction-vcc@0.7.4 `src/recall.js`). Oracle\n// vectors live in `recall.test.ts`, captured from the original (port selftest\n// run 2026-11-19).\n//\n// Deliberate deviation: `deriveEventMessage` access is guarded with `isRecord`\n// instead of bare property reads, so non-object sessions return the log-only\n// rendering instead of throwing. The deriver is invoked receiver-preserving\n// (Reflect.apply): the host exposes it as a prototype method over instance\n// state, so a detached call throws on `this`.\n\nimport {\n estimateEntryTokens,\n isCheckpointSource,\n projectToolResultText,\n sanitize,\n truncateTokens,\n type MessageSource,\n} from \"./compiler.ts\";\nimport { isRecord } from \"../utils.ts\";\nimport { sessionEventAt, sessionEvents } from \"./session-compat.ts\";\n\n// Total budget for one recall operation, in density-aware tokens.\nexport const DEFAULT_MAX_RECALL_TOKENS = 16000;\n// Widest single range accepted from one selection, bounding expansion work.\nexport const MAX_RECALL_SPAN = 1000;\n\nexport type SeqSelection = {\n readonly start: number;\n readonly end: number;\n};\n\nexport type SeqParseResult = {\n readonly selections: SeqSelection[];\n readonly errors: string[];\n};\n\n// One block of a recall-projected message. Recall is the lossless layer, so\n// blocks carry full text, reasoning, raw tool-call arguments, and nested\n// tool-result content; only media renders as labels.\nexport type RecallBlock = {\n readonly type?: string;\n readonly text?: string;\n readonly name?: string;\n readonly arguments?: string;\n readonly content?: readonly unknown[];\n};\n\nexport type RecallMessage = {\n readonly role: string;\n readonly content: readonly (RecallBlock | null)[] | null;\n};\n\nexport type RecallEntry = {\n readonly seq: number;\n readonly text: string;\n readonly truncated?: boolean;\n};\n\nexport type RecallConfig = {\n readonly maxRecallTokens: number;\n};\n\nexport type RecallResult = {\n readonly text: string;\n readonly entries: RecallEntry[];\n readonly seqs: number[];\n readonly recalled: number;\n readonly missing: number;\n readonly skipped: number;\n readonly truncated: boolean;\n readonly tokens: number;\n};\n\n// Parse one seq selection string into ordered inclusive ranges. Accepted\n// forms per comma-separated part: `12`, `3-7`, `seq 12`, `seqs 3-7`, with\n// optional surrounding parentheses — so a model or human can paste a\n// checkpoint marker verbatim.\nexport function parseSeqSpec(input: unknown): SeqParseResult {\n const selections: SeqSelection[] = [];\n const errors: string[] = [];\n const raw = String(input ?? \"\").trim();\n if (raw.length === 0) return { selections, errors: [\"missing seq selection\"] };\n for (const part of raw.split(\",\")) {\n let token = part.trim();\n if (token.length === 0) continue;\n token = token.replace(/^\\((.*)\\)$/u, \"$1\").trim();\n const match = /^(?:seqs?\\s+)?(\\d+)(?:\\s*-\\s*(\\d+))?$/iu.exec(token);\n if (match === null) {\n errors.push(`invalid seq selection \"${part}\"`);\n continue;\n }\n const start = Number(match[1]);\n const end = match[2] === undefined ? start : Number(match[2]);\n // Rejects anything outside the safe-integer range BEFORE any arithmetic:\n // a seq at or above 2^53 makes `seq += 1` a no-op in IEEE-754, so the\n // expansion loop below never terminates and freezes the host\n // synchronously. Both bounds are checked because an out-of-range `end`\n // only needs the loop guard to be true.\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {\n errors.push(`seq selection \"${part}\" is outside the safe integer range`);\n continue;\n }\n if (start < 1) {\n errors.push(`invalid seq selection \"${part}\" (seq starts at 1)`);\n continue;\n }\n if (end < start) {\n errors.push(`invalid seq range \"${part}\" (end before start)`);\n continue;\n }\n if (end - start + 1 > MAX_RECALL_SPAN) {\n errors.push(`seq range \"${part}\" is wider than the ${MAX_RECALL_SPAN}-seq limit`);\n continue;\n }\n selections.push({ start, end });\n }\n return { selections, errors };\n}\n\n// Project one derived message into plain text, keeping everything: text,\n// reasoning, raw tool-call arguments, and nested tool-result content. Media\n// renders as labels (their bytes live in the attachment service).\nexport function projectMessageText(message: RecallMessage): string {\n const parts: string[] = [];\n const content = message.content ?? [];\n for (const block of content) {\n if (block === null || block === undefined) continue;\n switch (block.type) {\n case \"text\":\n if (block.text !== undefined && block.text.length > 0) parts.push(sanitize(block.text));\n break;\n case \"reasoning\":\n if (block.text !== undefined && block.text.length > 0) {\n parts.push(`[reasoning]\\n${sanitize(block.text)}`);\n }\n break;\n case \"tool-call\":\n parts.push(`[tool-call ${block.name ?? \"unknown\"}]\\n${sanitize(block.arguments ?? \"\")}`);\n break;\n case \"tool-result\":\n parts.push(`[tool-result]\\n${projectToolResultText(block.content ?? [])}`);\n break;\n case \"image\":\n parts.push(\"[image]\");\n break;\n case \"document\":\n parts.push(\"[document]\");\n break;\n default:\n parts.push(`[${String(block.type)}]`);\n }\n }\n return parts.join(\"\\n\");\n}\n\n// Expand ordered selections into a deduplicated ordered seq list.\nexport function expandSelections(selections: readonly SeqSelection[]): number[] {\n const seqs: number[] = [];\n const seen = new Set<number>();\n for (const selection of selections) {\n const start = selection?.start;\n const end = selection?.end;\n // Defensive guard: `parseSeqSpec` already rejects unsafe integers, but\n // this function is exported and reachable with a hand-built selection\n // array. Without the guard, `seq += 1` at 2^53 is a no-op and the loop\n // below never terminates (synchronous host freeze). Skipping the range\n // is the only safe failure mode.\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) continue;\n if (start === undefined || end === undefined) continue;\n for (let seq = start; seq <= end; seq += 1) {\n if (seen.has(seq)) continue;\n seen.add(seq);\n seqs.push(seq);\n }\n }\n return seqs;\n}\n\n// The structured `source` of a session event's data, or undefined when the\n// event carries none. Guards through isRecord so foreign sessions cannot\n// throw the lookup.\nfunction eventSource(event: { readonly data?: unknown }): MessageSource {\n if (!isRecord(event.data)) return undefined;\n const source = event.data.source;\n return isRecord(source) ? source : undefined;\n}\n\n// Collect the durable seqs of every landed compaction checkpoint node in one\n// session, oldest first. Each compaction replaces its span with exactly one\n// checkpoint node, so the ordinal (`1` = oldest) counts compactions.\nexport function findCheckpointSeqs(session: unknown): number[] {\n const seqs: number[] = [];\n for (const event of sessionEvents(session)) {\n if (event.type === \"user/message\" && isCheckpointSource(eventSource(event))) {\n seqs.push(event.seq);\n }\n }\n return seqs;\n}\n\n// Derive the display message for one session event through the host's own\n// accessor, validating the result shape. Shared by recall and search so both\n// read the log the same way. Sessions without the accessor yield null, and\n// the caller falls back to the raw data payload.\nexport function deriveSessionMessage(\n session: unknown,\n event: { readonly seq: number; readonly type: string; readonly data?: unknown },\n): RecallMessage | null {\n if (!isRecord(session)) return null;\n const derive = session.deriveEventMessage;\n if (typeof derive !== \"function\") return null;\n // Receiver-preserving call: the host exposes this as a prototype method\n // over instance state, so a detached call throws on `this`.\n const message = Reflect.apply(derive as (event: unknown) => unknown, session, [event]);\n if (!isRecord(message)) return null;\n const role = message.role;\n const content = message.content;\n if (typeof role !== \"string\" || !Array.isArray(content)) return null;\n return { role, content: content as readonly (RecallBlock | null)[] };\n}\n\n// Resolve one typed recall reference into inclusive seq ranges:\n// `seq` takes a seq selection; `result` names a tool result via the\n// `result N` pointer on a tool-call one-liner; `checkpoint` takes an ordinal\n// (`1` = oldest, as in the `[checkpoint N]` elision marker) or a `seq N`\n// pointer to a checkpoint node.\nexport function resolveRecallReference(\n session: unknown,\n type: string,\n id: unknown,\n): SeqParseResult {\n const raw = String(id ?? \"\").trim();\n if (type === \"seq\") return parseSeqSpec(raw);\n if (type === \"result\") {\n const token = raw\n .replace(/^\\((.*)\\)$/u, \"$1\")\n .trim()\n .replace(/^result\\s+/iu, \"\");\n const match = /^(\\d+)$/u.exec(token);\n if (match === null) {\n return {\n selections: [],\n errors: [`invalid result reference \"${id}\" (expected a seq like \"3\" or \"result 3\")`],\n };\n }\n const seq = Number(match[1]);\n const event = sessionEventAt(session, seq);\n if (event === undefined || event.seq !== seq) {\n return { selections: [], errors: [`result seq ${seq} not found in this session`] };\n }\n if (event.type !== \"tool/result\") {\n return { selections: [], errors: [`seq ${seq} is not a tool result (it is ${event.type})`] };\n }\n return { selections: [{ start: seq, end: seq }], errors: [] };\n }\n if (type === \"checkpoint\") {\n const token = raw.replace(/^\\((.*)\\)$/u, \"$1\").trim();\n const bySeq = /^seqs?\\s+(\\d+)$/iu.exec(token);\n if (bySeq !== null) {\n const seq = Number(bySeq[1]);\n const event = sessionEventAt(session, seq);\n if (event === undefined || event.seq !== seq) {\n return { selections: [], errors: [`checkpoint seq ${seq} not found in this session`] };\n }\n if (!isCheckpointSource(eventSource(event))) {\n return { selections: [], errors: [`seq ${seq} is not a checkpoint node`] };\n }\n return { selections: [{ start: seq, end: seq }], errors: [] };\n }\n const ordinal = token.replace(/^checkpoint\\s+/iu, \"\");\n const match = /^(\\d+)$/u.exec(ordinal);\n if (match === null) {\n return {\n selections: [],\n errors: [\n `invalid checkpoint reference \"${id}\" (expected an ordinal like \"1\" or \"checkpoint 1\", or a \"seq N\" pointer)`,\n ],\n };\n }\n const index = Number(match[1]);\n if (!Number.isSafeInteger(index) || index < 1) {\n return { selections: [], errors: [`invalid checkpoint ordinal \"${id}\"`] };\n }\n const checkpointSeqs = findCheckpointSeqs(session);\n const seq = checkpointSeqs[index - 1];\n if (seq === undefined) {\n return {\n selections: [],\n errors: [\n `checkpoint ${index} not found (this session has ${checkpointSeqs.length} checkpoint(s))`,\n ],\n };\n }\n return { selections: [{ start: seq, end: seq }], errors: [] };\n }\n return {\n selections: [],\n errors: [`invalid recall type \"${String(type)}\" (expected \"seq\", \"result\", or \"checkpoint\")`],\n };\n}\n\n// Recall the full original content of the requested seqs from one session's\n// durable log. Message events project through `deriveEventMessage`; log-only\n// events render as a labeled data dump. The total output is bounded by\n// `maxRecallTokens`; a cut appends a provenance marker and remaining\n// requested seqs are accounted in `skipped`.\nexport function recallSession(\n session: unknown,\n selections: readonly SeqSelection[],\n config: RecallConfig,\n): RecallResult {\n const maxRecallTokens = config.maxRecallTokens;\n const requested = expandSelections(selections);\n const entries: RecallEntry[] = [];\n const seqs: number[] = [];\n let budget = maxRecallTokens;\n let truncated = false;\n let missing = 0;\n let skipped = 0;\n for (let index = 0; index < requested.length; index += 1) {\n const seq = requested[index];\n if (seq === undefined) continue;\n if (budget <= 0) {\n skipped = requested.length - index;\n truncated = true;\n break;\n }\n const event = sessionEventAt(session, seq);\n if (event === undefined || event.seq !== seq) {\n missing += 1;\n entries.push({ seq, text: `[seq ${seq}: not found in this session]` });\n continue;\n }\n const message = deriveSessionMessage(session, event);\n const body =\n message !== null\n ? `[seq ${seq}: ${message.role}]\\n${projectMessageText(message)}`\n : `[seq ${seq}: ${event.type}]\\n${JSON.stringify(event.data ?? null).slice(0, maxRecallTokens * 4)}`;\n const kept = truncateTokens(body, budget, \"recall budget\");\n budget -= estimateEntryTokens(kept.text);\n if (kept.truncated) truncated = true;\n entries.push({ seq, text: kept.text, truncated: kept.truncated });\n seqs.push(seq);\n }\n if (skipped > 0) {\n const firstSkipped = requested[requested.length - skipped];\n entries.push({\n seq: firstSkipped ?? 0,\n text: `[recall budget exhausted: ${skipped} further requested seq(s) not included]`,\n });\n }\n return {\n text: entries.map(entry => entry.text).join(\"\\n\\n\"),\n entries,\n seqs,\n recalled: seqs.length,\n missing,\n skipped,\n truncated,\n tokens: entries.reduce((total, entry) => total + estimateEntryTokens(entry.text), 0),\n };\n}\n",
|
|
9
|
+
"// Keyword/regex search over the durable session log, the retrieval\n// counterpart of the compiler: scans every event's projected content and\n// returns matching events with `(seq N)` pointers that recall restores in\n// full. Faithful logic port of the port repo's `search.mjs` (itself ported\n// from dsh-compaction-vcc@0.7.4 `src/search.js`). Oracle vectors live in\n// `search.test.ts`, captured from the original (port selftest run 2026-11-19).\n//\n// Deliberate deviations: `deriveEventMessage` access is guarded with\n// `isRecord` instead of bare property reads; `sessionEventAt` is not imported\n// (the original imports it but never calls it — carrying a dead import would\n// trip the linter).\n\nimport { estimateEntryTokens, sanitize, truncateTokens } from \"./compiler.ts\";\nimport { deriveSessionMessage, projectMessageText } from \"./recall.ts\";\nimport { sessionEvents } from \"./session-compat.ts\";\n\n// Cap on the number of matching events shown in one result.\nexport const DEFAULT_MAX_SEARCH_HITS = 50;\n// Cap on shown matching lines per hit event.\nexport const MAX_LINES_PER_HIT = 10;\n\n// A search pattern that cannot be compiled into a regular expression.\nexport class InvalidSearchPatternError extends Error {\n readonly source: string;\n\n constructor(source: unknown, reason: string) {\n super(`invalid search pattern ${JSON.stringify(String(source))}: ${reason}`);\n this.name = \"InvalidSearchPatternError\";\n this.source = String(source);\n }\n}\n\n// Compile one search pattern: case-insensitive, Unicode-aware, treated as a\n// regular expression (VCC `--grep` semantics) so keywords work as-is and\n// regexes work when escaped. Throws InvalidSearchPatternError when empty or\n// not compilable.\nexport function compileSearchPattern(source: unknown): RegExp {\n const trimmed = String(source ?? \"\").trim();\n if (trimmed.length === 0) throw new InvalidSearchPatternError(source, \"pattern is empty\");\n try {\n return new RegExp(trimmed, \"iu\");\n } catch (error) {\n throw new InvalidSearchPatternError(\n source,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\nexport type SearchHit = {\n readonly seq: number;\n readonly kind: string;\n readonly text: string;\n};\n\nexport type SearchConfig = {\n readonly maxSearchHits: number;\n readonly maxRecallTokens: number;\n};\n\nexport type SearchResult = {\n readonly pattern: string;\n readonly totalMatches: number;\n readonly hits: SearchHit[];\n readonly omitted: number;\n readonly truncated: boolean;\n readonly tokens: number;\n readonly text: string;\n};\n\n// One search hit: the durable seq, its kind, and the rendered matched lines.\nexport function searchSession(\n session: unknown,\n patternSource: unknown,\n config: SearchConfig,\n): SearchResult {\n const pattern = compileSearchPattern(patternSource);\n const maxHits = config.maxSearchHits;\n const maxTokens = config.maxRecallTokens;\n const events = sessionEvents(session);\n const hits: SearchHit[] = [];\n let totalMatches = 0;\n let budget = maxTokens;\n let truncated = false;\n // Known upstream quirk carried verbatim: the scan is positional\n // (`events[seq]` with `event.seq === seq`, so a 1-based log in a 0-based\n // array matches nothing). The adapter's snapshot pads a dummy seq-0 entry\n // so this contract holds; not papered over here.\n for (let seq = 0; seq < events.length; seq += 1) {\n const event = events[seq];\n if (event === undefined || event.seq !== seq) continue;\n const message = deriveSessionMessage(session, event);\n const body =\n message !== null\n ? projectMessageText(message)\n : `[${event.type}]\\n${JSON.stringify(event.data ?? null)}`;\n const lines = body.split(\"\\n\");\n const matched: { readonly line: number; readonly text: string }[] = [];\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index] ?? \"\";\n if (pattern.test(line)) matched.push({ line: index + 1, text: sanitize(line) });\n }\n if (matched.length === 0) continue;\n totalMatches += 1;\n if (hits.length >= maxHits || budget <= 0) {\n truncated = true;\n continue;\n }\n const header = `[seq ${seq}: ${message !== null ? message.role : event.type}]`;\n const shown = matched.slice(0, MAX_LINES_PER_HIT);\n const more = matched.length - shown.length;\n const block = [\n header,\n ...shown.map(match => ` ${match.line}: ${match.text}`),\n ...(more > 0 ? [` ...(${more} more matching lines in this event)`] : []),\n ].join(\"\\n\");\n const kept = truncateTokens(block, budget, \"search budget\");\n budget -= estimateEntryTokens(kept.text);\n if (kept.truncated) truncated = true;\n hits.push({ seq, kind: message !== null ? message.role : event.type, text: kept.text });\n }\n const omitted = totalMatches - hits.length;\n const lines = [\n `[search \"${pattern.source}\": ${totalMatches} matching event(s)]`,\n ...hits.map(hit => hit.text),\n ...(omitted > 0\n ? [`[${omitted} more matching event(s) omitted — narrow the pattern or use recall]`]\n : []),\n ...(truncated ? [\"[search budget exhausted; some hits were cut]\"] : []),\n ];\n if (hits.length > 0)\n lines.push(\"[use recall with a (seq N) pointer to restore any hit's full original content]\");\n const text = lines.join(\"\\n\\n\");\n return {\n pattern: pattern.source,\n totalMatches,\n hits,\n omitted,\n truncated,\n tokens: hits.reduce((total, hit) => total + estimateEntryTokens(hit.text), 0),\n text,\n };\n}\n",
|
|
10
|
+
"// Model-facing recall/search over the durable DSH session log.\n//\n// Two complementary entry points over the same log the compaction backend\n// compacts, so recovery needs no snapshot file (unlike the opencode adapter,\n// whose request view is transient): the log is append-only, and the core\n// recall/search modules read it directly through the host's own\n// `events`/`deriveEventMessage` accessors.\n//\n// - `operator-recall` — restore exact original content by a typed\n// reference: `seq` for `(seq N)` / `(seqs A-B)` markers, `result` for\n// the `result N` pointer, `checkpoint` for a `[checkpoint N]` ordinal.\n// - `operator-search` — keyword/regex search returning `(seq N)` pointers\n// that `operator-recall` restores in full.\n//\n// Faithful destructure of the reference `dsh-compaction-vcc/tool` module:\n// same tool semantics against the same log shape, same core functions.\n// Deliberate deviations, matching the opencode adapter's tool contract:\n// hyphenated `operator-` names (colons break OpenAI-protocol gateways, so\n// both adapters register flat hyphenated names; the brain-update counter\n// excludes exactly this prefix, so recovery calls never nudge the\n// documentation threshold),\n// text replies instead of thrown harness errors (defineTool validates the\n// argument shapes; semantic failures resolve to a valid canonical value\n// carrying the message), core-default budgets with no config keys, and no\n// `console` output anywhere.\n\nimport {\n DEFAULT_MAX_RECALL_TOKENS,\n recallSession,\n resolveRecallReference,\n} from \"@jwitmann/operator-core/context/recall\";\nimport {\n DEFAULT_MAX_SEARCH_HITS,\n InvalidSearchPatternError,\n searchSession,\n} from \"@jwitmann/operator-core/context/search\";\nimport { isRecord } from \"@jwitmann/operator-core/utils\";\nimport type { Context } from \"@deepseek-ai/cordis\";\nimport { defineTool } from \"@deepseek-ai/dsh-tools\";\n\n/** Stable Loader identity for the bundle row. */\nexport const name = \"tool-recall\";\n\n/** Services used by the recall tools: agent-scoped tool registry. */\nexport const inject = [\"tools\"];\n\ntype ToolScopedContext = {\n readonly effect: (register: () => () => void) => void;\n readonly tools: {\n readonly register: (definition: object) => () => void;\n };\n};\n\n/** Register the recall tools (`operator-recall` + `operator-search`). */\nexport function apply(context: Context): void {\n const scoped = context as unknown as ToolScopedContext;\n scoped.effect(() => {\n const disposers = [\n scoped.tools.register(defineRecallTool()),\n scoped.tools.register(defineSearchTool()),\n ];\n return () => {\n for (const dispose of disposers) dispose();\n };\n });\n}\n\nconst RECALL_DESCRIPTION =\n \"Restore the exact original content of earlier events in THIS conversation by a typed reference. \"\n + 'type \"seq\" with a seq selection like \"3-7\" restores those events; type \"result\" with the \"result N\" '\n + 'pointer from a tool-call one-liner restores that tool result; type \"checkpoint\" with an ordinal like \"1\" '\n + '(1 = oldest, as in a \"[checkpoint N]\" elision line) restores that whole checkpoint. '\n + \"The durable log is append-only, so recalled content is always the original tokens, including content \"\n + \"elided by compaction checkpoints. To find events by keyword or regex instead, use operator-search.\";\n\nconst SEARCH_DESCRIPTION =\n \"Search THIS conversation's durable event log by keyword or regular expression (case-insensitive). \"\n + \"Every recorded event is searchable, including content elided by compaction checkpoints. \"\n + \"Returns the matching events with their (seq N) numbers and the matching lines. \"\n + \"Then call operator-recall with a (seq N) pointer to restore any hit's full exact original content.\";\n\ntype RecallResult = {\n readonly text: string;\n readonly recalled: number;\n readonly missing: number;\n readonly skipped: number;\n readonly truncated: boolean;\n readonly tokens: number;\n};\n\ntype SearchResult = {\n readonly text: string;\n readonly pattern: string;\n readonly totalMatches: number;\n readonly omitted: number;\n readonly truncated: boolean;\n readonly tokens: number;\n};\n\nfunction emptyRecall(text: string): RecallResult {\n return { text, recalled: 0, missing: 0, skipped: 0, truncated: false, tokens: 0 };\n}\n\nfunction emptySearch(pattern: string, text: string): SearchResult {\n return { text, pattern, totalMatches: 0, omitted: 0, truncated: false, tokens: 0 };\n}\n\nfunction formatRecallReply(type: string, id: string, recalled: RecallResult): string {\n // Local copy of the opencode adapter's snapshot formatter (not shared:\n // core RecallResult differs from the snapshot result type, only the\n // count accessor varies). Header wording stays identical so agents see\n // one surface.\n const label =\n `**operator-recall ${type} ${id}** (${recalled.recalled} event(s), ${recalled.tokens} tokens`\n + `${recalled.missing > 0 ? `, ${recalled.missing} missing` : \"\"}`\n + `${recalled.truncated ? \", budget-truncated\" : \"\"})`;\n return `${label}\\n\\n${recalled.text}`;\n}\n\nfunction formatSearchReply(pattern: string, found: SearchResult): string {\n return `**operator-search ${pattern}** (${found.totalMatches} matching event(s))\\n\\n${found.text}`;\n}\n\nfunction readSession(agent: unknown): unknown {\n if (!isRecord(agent)) return null;\n return agent.session ?? null;\n}\n\n/** Build the typed `operator-recall` tool definition. Exported for tests. */\nexport function defineRecallTool() {\n return defineTool({\n name: \"operator-recall\",\n description: RECALL_DESCRIPTION,\n parameters: {\n type: {\n type: \"string\",\n required: true,\n enum: [\"seq\", \"result\", \"checkpoint\"],\n description:\n 'Reference type: \"seq\" for events by sequence number, \"result\" for a tool result by its `result N` pointer, \"checkpoint\" for a whole checkpoint by ordinal or seq.',\n },\n id: {\n type: \"string\",\n required: true,\n description:\n 'Type-dependent reference: \"3-7\" / \"seq 12\" for seq; \"result 3\" or \"3\" for result; \"1\" / \"checkpoint 1\" or \"seq 12345\" for checkpoint.',\n },\n },\n output: {\n schema: {\n type: \"object\",\n additionalProperties: false,\n properties: {\n text: { type: \"string\", required: true },\n recalled: { type: \"integer\", required: true },\n missing: { type: \"integer\", required: true },\n skipped: { type: \"integer\", required: true },\n truncated: { type: \"boolean\", required: true },\n tokens: { type: \"integer\", required: true },\n },\n },\n render: (_args, value) => [{ type: \"text\", text: value.text }],\n },\n async execute(args, exec) {\n if (args.type !== \"seq\" && args.type !== \"result\" && args.type !== \"checkpoint\") {\n return emptyRecall(\n \"Missing or invalid input: type must be one of seq, result, checkpoint.\",\n );\n }\n if (typeof args.id !== \"string\" || args.id.trim() === \"\") {\n return emptyRecall(\"Missing required input: id.\");\n }\n const session = readSession(exec.agent);\n if (session === null) {\n return emptyRecall(\"recall requires a calling agent with a session.\");\n }\n try {\n const resolved = resolveRecallReference(session, args.type, args.id);\n if (resolved.errors.length > 0 || resolved.selections.length === 0) {\n return emptyRecall(\n resolved.errors.length > 0 ? resolved.errors.join(\"; \") : \"Nothing to recall.\",\n );\n }\n const recalled = recallSession(session, resolved.selections, {\n maxRecallTokens: DEFAULT_MAX_RECALL_TOKENS,\n });\n return {\n text: formatRecallReply(args.type, args.id, recalled),\n recalled: recalled.recalled,\n missing: recalled.missing,\n skipped: recalled.skipped,\n truncated: recalled.truncated,\n tokens: recalled.tokens,\n };\n } catch {\n // The durable log is host-written: a poisoned event (or deriver)\n // must degrade to text, never to a harness error.\n return emptyRecall(\"Could not read the session log.\");\n }\n },\n presentCall: args => ({\n card: \"generic\",\n title: \"Recall events\",\n kind: \"read\",\n rawInput: `${args.type} ${args.id}`,\n }),\n });\n}\n\n/** Build the `operator-search` (grep) tool definition. Exported for tests. */\nexport function defineSearchTool() {\n return defineTool({\n name: \"operator-search\",\n description: SEARCH_DESCRIPTION,\n parameters: {\n pattern: {\n type: \"string\",\n required: true,\n description:\n \"Keyword or regular expression to search for (case-insensitive). Escape regex special characters.\",\n },\n },\n output: {\n schema: {\n type: \"object\",\n additionalProperties: false,\n properties: {\n text: { type: \"string\", required: true },\n pattern: { type: \"string\", required: true },\n totalMatches: { type: \"integer\", required: true },\n omitted: { type: \"integer\", required: true },\n truncated: { type: \"boolean\", required: true },\n tokens: { type: \"integer\", required: true },\n },\n },\n render: (_args, value) => [{ type: \"text\", text: value.text }],\n },\n async execute(args, exec) {\n if (typeof args.pattern !== \"string\" || args.pattern.trim() === \"\") {\n return emptySearch(\"\", \"Missing required input: pattern.\");\n }\n const session = readSession(exec.agent);\n if (session === null) {\n return emptySearch(args.pattern, \"search requires a calling agent with a session.\");\n }\n try {\n const found = searchSession(session, args.pattern, {\n maxSearchHits: DEFAULT_MAX_SEARCH_HITS,\n maxRecallTokens: DEFAULT_MAX_RECALL_TOKENS,\n });\n return {\n text: formatSearchReply(args.pattern, found),\n pattern: found.pattern,\n totalMatches: found.totalMatches,\n omitted: found.omitted,\n truncated: found.truncated,\n tokens: found.tokens,\n };\n } catch (error) {\n // Same reply shape as the opencode adapter: only the pattern\n // source, not the core's full reason string.\n if (error instanceof InvalidSearchPatternError) {\n return emptySearch(args.pattern, `Invalid search pattern: ${error.source}.`);\n }\n // The durable log is host-written: a poisoned event (or deriver)\n // must degrade to text, never to a harness error.\n return emptySearch(args.pattern, \"Could not read the session log.\");\n }\n },\n presentCall: args => ({\n card: \"generic\",\n title: \"Search history\",\n kind: \"read\",\n rawInput: args.pattern,\n }),\n });\n}\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";AAIO,SAAS,OAAU,CAAC,OAA4B;AAAA,EACrD,OAAO,EAAE,IAAI,MAAM,MAAM;AAAA;AAGpB,SAAS,OAAU,CAAC,OAA4B;AAAA,EACrD,OAAO,EAAE,IAAI,OAAO,MAAM;AAAA;AAGrB,SAAS,gBAAgB,CAAC,OAAgB,MAAuB;AAAA,EACtE,OAAO,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS;AAAA;AAG9D,SAAS,eAAe,CAAC,OAAwB;AAAA,EACtD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA;AAGvD,SAAS,QAAQ,CAAC,OAAkD;AAAA,EACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAAA;AAGrE,SAAS,UAAU,CAAC,OAAgC,KAA4B;AAAA,EACrF,MAAM,QAAQ,MAAM;AAAA,EACpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAAA;;;ACb7C,IAAM,WAAW;AAGjB,IAAM,UAAU;AAGhB,IAAM,aAAa;AAEnB,SAAS,eAAe,CAAC,MAAuB;AAAA,EAC9C,OAAO,QAAQ,SAAU,QAAQ;AAAA;AASnC,SAAS,sBAAsB,CAAC,MAAsB;AAAA,EACpD,OAAO,gBAAgB,KAAK,WAAW,KAAK,SAAS,CAAC,CAAC,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AAAA;AAY1E,SAAS,QAAQ,CAAC,MAAwB;AAAA,EAC/C,OAAO,KAAK,MAAM,QAAQ,KAAK,CAAC;AAAA;AAM3B,SAAS,SAAS,CAAC,MAAuB;AAAA,EAC/C,MAAM,OAAO,KAA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AAC;AAAA,QACD,OAAO;AAAA,UACL,MAAM,kBAAkB,KAAK,SAAS,KAAK;AAAA,UAC3C,SAAS,MAAM;AAAA,UACf,cAAc,MAAM;AAAA,UACpB,SAAS,MAAM;AAAA,UACf,WAAW,MAAM;AAAA,UACjB,QAAQ,MAAM;AAAA,QAChB;AAAA,QACA,OAAO,OAAO;AAAA,QAGd,IAAI,iBAAiB,2BAA2B;AAAA,UAC9C,OAAO,YAAY,KAAK,SAAS,2BAA2B,MAAM,SAAS;AAAA,QAC7E;AAAA,QAGA,OAAO,YAAY,KAAK,SAAS,iCAAiC;AAAA;AAAA;AAAA,IAGtE,aAAa,WAAS;AAAA,MACpB,MAAM;AAAA,MACN,OAAO;AAAA,MACP,MAAM;AAAA,MACN,UAAU,KAAK;AAAA,IACjB;AAAA,EACF,CAAC;AAAA;",
|
|
13
|
+
"debugId": "DC9EC42D892DC67264756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,98 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jwitmann/operator-deepseek",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Operator Memory adapter for DeepSeek Harness.",
|
|
5
|
+
"license": "BSD-3-Clause",
|
|
6
|
+
"author": "jwitmann",
|
|
7
|
+
"homepage": "https://github.com/jwitmann/operator-memory#readme",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/jwitmann/operator-memory/issues"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "dist/index.js",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./dist/index.js",
|
|
15
|
+
"./client": "./dist/client.js",
|
|
16
|
+
"./tool": "./dist/tool.js",
|
|
17
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
18
|
+
"./package.json": "./package.json"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"cordis.patch.yml"
|
|
23
|
+
],
|
|
24
|
+
"keywords": [
|
|
25
|
+
"deepseek",
|
|
26
|
+
"deepseek-harness",
|
|
27
|
+
"memory",
|
|
28
|
+
"plugin"
|
|
29
|
+
],
|
|
30
|
+
"dsh": {
|
|
31
|
+
"bundle": {
|
|
32
|
+
"patch": "./cordis.patch.yml"
|
|
33
|
+
},
|
|
34
|
+
"client": {
|
|
35
|
+
"platform": "web",
|
|
36
|
+
"inject": [
|
|
37
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/jwitmann/operator-memory.git",
|
|
44
|
+
"directory": "packages/deepseek"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=22.19"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "bun ./scripts/build.ts",
|
|
54
|
+
"prepack": "bun run build"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@deepseek-ai/cordis": "~4.0.4",
|
|
58
|
+
"@deepseek-ai/dsh": ">=0.2.0-rc.2 <0.3.0",
|
|
59
|
+
"@deepseek-ai/dsh-agent": ">=0.2.0-rc.2 <0.3.0",
|
|
60
|
+
"@deepseek-ai/dsh-commands": ">=0.2.0-rc.2 <0.3.0",
|
|
61
|
+
"@deepseek-ai/dsh-llm": ">=0.2.0-rc.2 <0.3.0",
|
|
62
|
+
"@deepseek-ai/dsh-system-prompt": ">=0.2.0-rc.2 <0.3.0",
|
|
63
|
+
"@deepseek-ai/dsh-tools": ">=0.2.0-rc.2 <0.3.0"
|
|
64
|
+
},
|
|
65
|
+
"peerDependenciesMeta": {
|
|
66
|
+
"@deepseek-ai/cordis": {
|
|
67
|
+
"optional": true
|
|
68
|
+
},
|
|
69
|
+
"@deepseek-ai/dsh": {
|
|
70
|
+
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"@deepseek-ai/dsh-agent": {
|
|
73
|
+
"optional": true
|
|
74
|
+
},
|
|
75
|
+
"@deepseek-ai/dsh-commands": {
|
|
76
|
+
"optional": true
|
|
77
|
+
},
|
|
78
|
+
"@deepseek-ai/dsh-llm": {
|
|
79
|
+
"optional": true
|
|
80
|
+
},
|
|
81
|
+
"@deepseek-ai/dsh-system-prompt": {
|
|
82
|
+
"optional": true
|
|
83
|
+
},
|
|
84
|
+
"@deepseek-ai/dsh-tools": {
|
|
85
|
+
"optional": true
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
"devDependencies": {
|
|
89
|
+
"@jwitmann/operator-core": "workspace:*",
|
|
90
|
+
"@deepseek-ai/cordis": "4.0.4",
|
|
91
|
+
"@deepseek-ai/dsh": "0.2.0-rc.2",
|
|
92
|
+
"@deepseek-ai/dsh-agent": "0.2.0-rc.2",
|
|
93
|
+
"@deepseek-ai/dsh-commands": "0.2.0-rc.2",
|
|
94
|
+
"@deepseek-ai/dsh-llm": "0.2.0-rc.2",
|
|
95
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
|
|
96
|
+
"@deepseek-ai/dsh-tools": "0.2.0-rc.2"
|
|
97
|
+
}
|
|
98
|
+
}
|