acp-kernel 0.0.49-pr.186.40 → 0.0.49-pr.189.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,6 @@
14
14
  * - the store never deletes files; cleanup is a downstream decision
15
15
  */
16
16
  export { StateStore, flatFileNameFor } from "./store.js";
17
- export type { LoadAllOptions, PersistedEnvelope, PersistLogger, StateStoreOptions } from "./store.js";
17
+ export type { PersistedEnvelope, PersistLogger, StateStoreOptions } from "./store.js";
18
18
  export { mergeCompressionState } from "./state-merge.js";
19
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/persist/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,YAAY,EAAE,cAAc,EAAE,iBAAiB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACtG,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/persist/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -161,17 +161,11 @@ var StateStore = class {
161
161
  /** Load every record under dir. Populates the discovery map (enables
162
162
  * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`
163
163
  * orphans, and records whose filename does not match their id — one
164
- * bad file never blocks boot; filesystem and record problems never
165
- * throw. An invalid `maxParseBytes` (non-finite or negative) throws
166
- * TypeError fail-fast instead.
167
- *
168
- * With `options.maxParseBytes`, parsing is budget-limited via a stat-only
169
- * preselection pass (see {@link LoadAllOptions.maxParseBytes}); skipped
170
- * records are not deleted and remain loadable via loadSync(id, hint). */
171
- async loadAll(options) {
164
+ * bad file never blocks boot. Never throws. */
165
+ async loadAll() {
172
166
  const out = /* @__PURE__ */ new Map();
173
167
  if (!this.enabled) return out;
174
- const files = options?.maxParseBytes == null ? await this.walkJsonFiles(this.dir) : await this.selectWithinBudget(options.maxParseBytes);
168
+ const files = await this.walkJsonFiles(this.dir);
175
169
  for (const file of files) {
176
170
  const envelope = this.readEnvelope(file);
177
171
  if (!envelope) continue;
@@ -419,60 +413,6 @@ var StateStore = class {
419
413
  }
420
414
  return out;
421
415
  }
422
- /** Stat-only preselection for budgeted loadAll: pairs each canonical
423
- * file with its `.fb.json` spill under a dir+stem key (identical stems
424
- * in different directories are different records), sums group sizes,
425
- * and fills the budget newest-mtime-first. Never reads file content. */
426
- async selectWithinBudget(budget) {
427
- if (!Number.isFinite(budget) || budget < 0) {
428
- throw new TypeError(
429
- `maxParseBytes must be a finite non-negative number, got ${String(budget)}`
430
- );
431
- }
432
- const entries = await Promise.all(
433
- (await this.walkJsonFiles(this.dir)).map(async (file) => {
434
- try {
435
- const st = await fsp.stat(file);
436
- return { file, size: st.size, mtimeMs: st.mtimeMs };
437
- } catch {
438
- return null;
439
- }
440
- })
441
- );
442
- const groups = /* @__PURE__ */ new Map();
443
- for (const e of entries) {
444
- if (!e) continue;
445
- const base = path.basename(e.file);
446
- const stem = base.endsWith(".fb.json") ? base.slice(0, -".fb.json".length) : base.slice(0, -".json".length);
447
- const key = `${path.dirname(e.file)}\0${stem}`;
448
- const g = groups.get(key) ?? { key, files: [], size: 0, mtimeMs: 0 };
449
- g.files.push(e.file);
450
- g.size += e.size;
451
- g.mtimeMs = Math.max(g.mtimeMs, e.mtimeMs);
452
- groups.set(key, g);
453
- }
454
- const ordered = [...groups.values()].sort(
455
- (a, b) => b.mtimeMs - a.mtimeMs || b.size - a.size || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
456
- );
457
- const selected = [];
458
- let used = 0;
459
- let skipped = 0;
460
- for (const g of ordered) {
461
- if (used + g.size > budget) {
462
- skipped++;
463
- continue;
464
- }
465
- selected.push(...g.files);
466
- used += g.size;
467
- }
468
- if (skipped > 0) {
469
- this.log(
470
- "warn",
471
- `[persist] loadAll budget ${budget} bytes: parsed ${ordered.length - skipped}/${ordered.length} record groups (skipped ${skipped})`
472
- );
473
- }
474
- return selected;
475
- }
476
416
  };
477
417
  function defaultValidate(envelope) {
478
418
  return typeof envelope.id === "string" && envelope.id.length > 0 && envelope.payload != null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/persist/store.ts","../../src/persist/state-merge.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Logger callback. Downstream routes it wherever it wants (file, stderr). */\nexport type PersistLogger = (level: \"info\" | \"warn\" | \"error\", msg: string) => void;\n\n/**\n * On-disk record shape. The store owns the envelope (version stamp, save\n * time, id) so atomicity and discovery can rely on it; the payload schema\n * is entirely downstream-owned. `payload` must be JSON-serializable.\n */\nexport interface PersistedEnvelope<T> {\n version: number;\n savedAt: number;\n id: string;\n payload: T;\n}\n\n/** A legacy (pre-envelope) record adopted on load. `version`/`savedAt`\n * preserve the source record's own stamps when present. */\nexport interface LegacyAdoption<T> {\n id: string;\n payload: T;\n version?: number;\n savedAt?: number;\n}\n\nexport interface StateStoreOptions<T> {\n /**\n * Storage root. The kernel deliberately has NO default location: the\n * downstream decides where state lives (CLI dir, XDG data dir, plugin\n * dir, temp dir in tests). All records live under this directory.\n */\n dir: string;\n /**\n * Schema version stamped into every envelope. Owned by the downstream;\n * bump it when the payload shape changes. The store itself never\n * rejects a record over its version — migration policy belongs to the\n * reader.\n */\n version: number;\n /** Debounce window for scheduleSave, ms. Default 500. */\n debounceMs?: number;\n /** Default true. When false, all writes are silent no-ops and loads\n * return empty results. */\n enabled?: boolean;\n log?: PersistLogger;\n /**\n * Relative path (under `dir`) for a record, possibly namespaced into\n * subdirectories (e.g. `openai/host-hash.json`). Default: flat\n * `<sha256(id)[:24]>.json`.\n *\n * Because the path may depend on payload fields the store only learns\n * at write time, single-record loads resolve namespaced files only\n * after loadAll() has discovered them (or the store itself wrote\n * them). The flat default name is always checked as a fallback, so\n * downstreams using a custom relPath should call loadAll() at boot.\n */\n relPath?: (id: string, payload: T) => string;\n /**\n * Adopt records written by an older, pre-envelope schema. Receives the\n * parsed JSON of any file that failed the envelope-shape check; return\n * an adoption to load it as an envelope, or null to skip it. Adopted\n * records are re-persisted in the current envelope format on the next\n * dirty write — files migrate organically, and old files keep loading\n * (same policy billion-context's proxy used for its v1→v3 migration).\n */\n legacy?: (parsed: unknown) => LegacyAdoption<T> | null;\n /**\n * Payload validation on load. Return false to skip a record (foreign\n * schema, corrupt content). Default: envelope-shape check only\n * (string id, non-null payload).\n */\n validate?: (envelope: PersistedEnvelope<T>) => boolean;\n /**\n * Rename-retry policy for Windows transient locks (EPERM/EBUSY/EACCES\n * from AV scan, search indexer, SMB). Exponential backoff: the delay\n * after attempt i is min(retryBaseMs * 2^i, retryMaxMs). Defaults\n * (6 attempts, 50ms base, 1600ms cap) give a ~1.5s window — long enough\n * for most AV locks to release, short enough not to stall a sync flush.\n * When the window is exhausted the write spills to a side file (see\n * spillPath) instead of dropping the data.\n */\n retryAttempts?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n}\n\n/** Options for {@link StateStore.loadAll}. */\nexport interface LoadAllOptions {\n /**\n * Cap on the total bytes of record files loadAll will read and parse.\n * When set, loadAll does a stat-only pass first (readdir + stat, no\n * content reads), groups each canonical file with its `.fb.json` spill\n * variant (same id ⇒ all-or-nothing, so the pair's freshest-wins\n * reconciliation always sees both sides), then includes groups\n * newest-mtime-first while the running total stays within the budget.\n * A group that does not fit is skipped individually and selection\n * continues with older groups — the byte cap is hard even when the\n * newest group alone exceeds it; only if NO group fits is the result\n * empty. Excluded groups are left on disk untouched (the store never deletes)\n * and stay individually reachable via loadSync(id, hint). If no group\n * fits, the result is an empty map (a warning is logged) — the budget\n * is a hard cap, so one oversized record can never blow past it. Group\n * freshness uses file mtime as a stat-level proxy for the in-envelope\n * savedAt; ordering among parsed records still comes from savedAt\n * reconciliation. Omitted ⇒ parse every record (default, unchanged).\n */\n maxParseBytes?: number;\n}\n\n/**\n * Crash-safe, debounce-coalescing JSON state store. Mechanism only — lifted\n * from billion-context's proxy SessionStore and generalized:\n *\n * - atomic writes: temp file + rename, so a crash mid-write never leaves a\n * truncated record (readers see either the old or the new file)\n * - rename retries with exponential backoff on Windows transient locks\n * (EPERM/EBUSY/EACCES); when the window is exhausted the record spills to\n * a side file (`<name>.fb.json`) instead of being dropped, so a lock held\n * by AV/indexer/SMB never silently loses session data\n * - per-id serialization so concurrent writeNow calls never interleave\n * temp-file names or reorders writes\n * - debounced scheduleSave coalesces bursts into one write; the record is\n * built at WRITE time from a builder, so late mutations are picked up\n * - loadAll skips `.tmp-*` orphans, corrupt JSON, and records whose\n * filename does not match their id — one bad file never blocks boot; it\n * reconciles a canonical record against its spill by savedAt (freshest wins)\n *\n * The store never deletes a record's data. On a successful canonical write it\n * removes a now-stale spill of the SAME id (a duplicate, not distinct data).\n * Session cleanup is a downstream policy decision (kernel position: persisted\n * state should not be deleted opportunistically).\n */\nexport class StateStore<T> {\n readonly enabled: boolean;\n private readonly dir: string;\n private readonly version: number;\n private readonly debounceMs: number;\n private readonly log: PersistLogger;\n private readonly legacyFn?: (parsed: unknown) => LegacyAdoption<T> | null;\n private readonly relPathFn?: (id: string, payload: T) => string;\n private readonly validateFn: (envelope: PersistedEnvelope<T>) => boolean;\n private readonly retryAttempts: number;\n private readonly retryBaseMs: number;\n private readonly retryMaxMs: number;\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly pending = new Map<string, () => T>();\n private readonly writeChains = new Map<string, Promise<void>>();\n /** id → absolute path, populated by writes and loadAll. */\n private readonly discovered = new Map<string, string>();\n /** id → cumulative write-failure count, for rate-limited alerting. */\n private readonly failCounts = new Map<string, number>();\n /** Monotonic counter for unique temp filenames within a process. */\n private tmpSeq = 0;\n\n constructor(opts: StateStoreOptions<T>) {\n this.dir = opts.dir;\n this.version = opts.version;\n this.debounceMs = opts.debounceMs ?? 500;\n this.enabled = opts.enabled ?? true;\n this.log = opts.log ?? ((_level, _msg) => {});\n this.relPathFn = opts.relPath;\n this.legacyFn = opts.legacy;\n this.validateFn = opts.validate ?? defaultValidate;\n this.retryAttempts = Math.max(1, opts.retryAttempts ?? 6);\n this.retryBaseMs = Math.max(1, opts.retryBaseMs ?? 50);\n this.retryMaxMs = Math.max(this.retryBaseMs, opts.retryMaxMs ?? 1600);\n }\n\n /** Debounced save. Coalesces bursts; the builder runs at write time, so\n * the freshest state is always persisted. Never throws. */\n scheduleSave(id: string, build: () => T): void {\n if (!this.enabled) return;\n this.pending.set(id, build);\n const existing = this.timers.get(id);\n if (existing) return;\n const timer = setTimeout(() => {\n this.timers.delete(id);\n const builder = this.pending.get(id);\n this.pending.delete(id);\n if (!builder) return;\n // Errors are logged inside writeInner; swallowing here keeps a\n // failed timer write from becoming an unhandledRejection.\n void this.writeNow(id, builder).catch(() => {});\n }, this.debounceMs);\n timer.unref?.();\n this.timers.set(id, timer);\n }\n\n /** Immediate save, serialized per id. Rejects on write failure; a\n * failing write never breaks the chain for the next one. */\n async writeNow(id: string, build: () => T): Promise<void> {\n if (!this.enabled) return;\n // The previous promise may reject (disk full, EPERM) — catch so our\n // chain doesn't break, then run our own write.\n const prev = this.writeChains.get(id) ?? Promise.resolve();\n const next = prev.catch(() => {}).then(() => this.writeInner(id, build));\n this.writeChains.set(id, next);\n // Clean up the chain entry once settled so the Map doesn't grow. The\n // .catch() is load-bearing: .finally() returns a derived promise that\n // nobody else holds — when the chain rejects it would surface as an\n // unhandledRejection and crash the host on default Node settings.\n next\n .finally(() => {\n if (this.writeChains.get(id) === next) this.writeChains.delete(id);\n })\n .catch(() => {});\n return next;\n }\n\n /** Synchronous flush for one id. Used where the caller cannot await\n * (memory eviction, sync shutdown paths). Cancels any pending debounce\n * timer. Returns true on success, false on failure — callers that use\n * the result to drop in-memory state must NOT drop it on failure. */\n flushSync(id: string, build: () => T): boolean {\n if (!this.enabled) return true;\n const timer = this.timers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(id);\n this.pending.delete(id);\n }\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n return false;\n }\n const file = this.resolvePath(id, payload);\n const data = JSON.stringify(this.envelope(id, payload));\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (e) {\n this.log(\"warn\", `[persist] could not create dir ${path.dirname(file)}: ${errText(e)}`);\n }\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name per attempt: on Windows a failed cleanup can\n // leave the previous name delete-pending, and creating over a\n // tombstoned name fails immediately — reusing it would burn every\n // remaining attempt before the write even happens.\n const tmp = this.tempPath(file);\n try {\n fs.writeFileSync(tmp, data, \"utf8\");\n fs.renameSync(tmp, file);\n lastErr = undefined;\n break;\n } catch (e) {\n lastErr = e;\n try {\n fs.unlinkSync(tmp);\n } catch {\n // temp never created or already gone\n }\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== \"EPERM\" && code !== \"EBUSY\" && code !== \"EACCES\") break;\n if (attempt === this.retryAttempts - 1) break;\n // sync sleep (Atomics.wait) — backoff grows per attempt\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (!lastErr) {\n this.discovered.set(id, file);\n this.clearFailure(id);\n this.removeSpillSync(file);\n return true;\n }\n // The canonical rename outlived the retry window (Windows lock held by\n // AV/indexer/SMB). Spill to a side file so the data still lands on\n // disk instead of being dropped — loadAll picks the freshest of the\n // canonical and the spill.\n let spillPath: string | null = null;\n try {\n const spill = this.spillPathFor(file);\n fs.writeFileSync(spill, data, \"utf8\");\n spillPath = spill;\n this.discovered.set(id, spill);\n } catch {\n // spillover also failed (dir read-only / disk full) — data at risk\n }\n this.recordFailure(id, lastErr, spillPath);\n return spillPath !== null;\n }\n\n /** Load one record. Checks the discovered path (from a prior\n * write/loadAll), an optional relative-path hint, and the flat default\n * name. Returns null when absent, disabled, corrupt, or rejected by\n * validate. The hint covers namespaced records the store has not\n * discovered (e.g. an evicted session re-requested with its meta,\n * where the path depends on data the store cannot reconstruct from\n * the id alone). */\n loadSync(id: string, hint?: string): PersistedEnvelope<T> | null {\n if (!this.enabled) return null;\n const candidates = [\n this.discovered.get(id),\n hint ? path.join(this.dir, hint) : undefined,\n path.join(this.dir, flatFileNameFor(id)),\n ];\n for (const file of candidates) {\n if (!file) continue;\n const envelope = this.readEnvelope(file);\n if (envelope && envelope.id === id) return envelope;\n }\n return null;\n }\n\n /** Load every record under dir. Populates the discovery map (enables\n * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`\n * orphans, and records whose filename does not match their id — one\n * bad file never blocks boot; filesystem and record problems never\n * throw. An invalid `maxParseBytes` (non-finite or negative) throws\n * TypeError fail-fast instead.\n *\n * With `options.maxParseBytes`, parsing is budget-limited via a stat-only\n * preselection pass (see {@link LoadAllOptions.maxParseBytes}); skipped\n * records are not deleted and remain loadable via loadSync(id, hint). */\n async loadAll(options?: LoadAllOptions): Promise<Map<string, PersistedEnvelope<T>>> {\n const out = new Map<string, PersistedEnvelope<T>>();\n if (!this.enabled) return out;\n const files =\n options?.maxParseBytes == null\n ? await this.walkJsonFiles(this.dir)\n : await this.selectWithinBudget(options.maxParseBytes);\n for (const file of files) {\n const envelope = this.readEnvelope(file);\n if (!envelope) continue;\n const base = path.basename(file);\n const relBase = path.basename(this.relPathOf(envelope.id, envelope.payload));\n const flatBase = flatFileNameFor(envelope.id);\n // A file is a valid record for its envelope id when its name is the\n // canonical name OR a spill (`.fb`) of the canonical name. This lets\n // a spilled record (written while the canonical was locked) be\n // discovered and reconciled against the canonical by savedAt.\n let owner: string | null = null;\n if (base === relBase || base === flatBase) {\n owner = envelope.id;\n } else if (base.endsWith(\".fb.json\")) {\n const canonicalBase = `${base.slice(0, -\".fb.json\".length)}.json`;\n if (canonicalBase === relBase || canonicalBase === flatBase) {\n owner = envelope.id;\n }\n }\n if (owner === null) {\n this.log(\"warn\", `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`);\n continue;\n }\n const existing = out.get(owner);\n if (!existing || envelope.savedAt >= existing.savedAt) {\n out.set(owner, envelope);\n this.discovered.set(owner, file);\n }\n }\n return out;\n }\n\n /** Whether a debounced write is pending for an id. */\n hasPending(id: string): boolean {\n return this.timers.has(id);\n }\n\n /** Ids with a pending debounced write. */\n pendingIds(): string[] {\n return [...this.timers.keys()];\n }\n\n /** Flush every pending debounced write immediately, then drain in-flight\n * writes. For graceful shutdown (SIGTERM/SIGINT). Never rejects. */\n async flushAll(): Promise<void> {\n const ids = this.pendingIds();\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n const builders = new Map<string, () => T>();\n for (const id of ids) {\n const build = this.pending.get(id);\n if (build) builders.set(id, build);\n this.pending.delete(id);\n }\n await Promise.all(\n [...builders.entries()].map(([id, build]) =>\n this.writeNow(id, build).catch((e) => {\n this.log(\"error\", `[persist] shutdown flush failed for ${id}: ${errText(e)}`);\n }),\n ),\n );\n // Drain writes whose timer fired earlier but are still mid-flight.\n await Promise.allSettled([...this.writeChains.values()]);\n }\n\n /** Cancel all pending debounced writes without flushing (tests). */\n cancelAll(): void {\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pending.clear();\n }\n\n private async writeInner(id: string, build: () => T): Promise<void> {\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n throw e;\n }\n const file = this.resolvePath(id, payload);\n try {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n } catch (e) {\n this.log(\"warn\", `[persist] could not create dir ${path.dirname(file)}: ${errText(e)}`);\n }\n const tmp = this.tempPath(file);\n const env = this.envelope(id, payload);\n try {\n await fsp.writeFile(tmp, JSON.stringify(env), \"utf8\");\n await this.renameWithRetry(tmp, file);\n this.discovered.set(id, file);\n this.clearFailure(id);\n await this.removeSpill(file);\n } catch (e) {\n // Clean up the .tmp orphan so the next write doesn't collide with it.\n await fsp.unlink(tmp).catch(() => {});\n // The canonical rename outlived the retry window (Windows lock held\n // by AV/indexer/SMB). Spill to a side file so the data still lands\n // on disk instead of being dropped — loadAll picks the freshest of\n // the canonical and the spill.\n let spillPath: string | null = null;\n try {\n const spill = this.spillPathFor(file);\n await fsp.writeFile(spill, JSON.stringify(env), \"utf8\");\n spillPath = spill;\n this.discovered.set(id, spill);\n } catch {\n // spillover also failed (dir read-only / disk full) — data at risk\n }\n this.recordFailure(id, e, spillPath);\n throw e;\n }\n }\n\n private envelope(id: string, payload: T): PersistedEnvelope<T> {\n return { version: this.version, savedAt: Date.now(), id, payload };\n }\n\n /** Absolute path for a record: custom relPath (guarded against path\n * escape) or the flat hash default. */\n private resolvePath(id: string, payload: T): string {\n return path.join(this.dir, this.relPathOf(id, payload));\n }\n\n private relPathOf(id: string, payload: T): string {\n const custom = this.relPathFn?.(id, payload);\n if (!custom) return flatFileNameFor(id);\n const rel = path.normalize(custom);\n if (path.isAbsolute(rel) || rel.split(/[\\\\/]+/).includes(\"..\")) {\n this.log(\"warn\", `[persist] relPath for ${id} escapes dir; using flat name`);\n return flatFileNameFor(id);\n }\n return rel;\n }\n\n /** Unique temp file next to the destination (same dir ⇒ same volume ⇒\n * rename is atomic). Prefixed `.tmp-` so loadAll skips orphans. */\n private tempPath(dest: string): string {\n const seq = this.tmpSeq++;\n return path.join(path.dirname(dest), `.tmp-${path.basename(dest, \".json\")}-${process.pid}-${seq}`);\n }\n\n private backoffMs(attempt: number): number {\n return Math.min(this.retryBaseMs * 2 ** attempt, this.retryMaxMs);\n }\n\n /** Side file for a record whose canonical write keeps failing: the\n * canonical name with a `.fb` (fallback) infix, e.g. `a.json` →\n * `a.fb.json`. One slot per id, overwritten on each spill, so a stuck\n * lock never accumulates files. Ends in `.json` so loadAll discovers it. */\n private spillPathFor(file: string): string {\n const base = path.basename(file);\n const dot = base.lastIndexOf(\".\");\n const stem = dot > 0 ? base.slice(0, dot) : base;\n const ext = dot > 0 ? base.slice(dot) : \".json\";\n return path.join(path.dirname(file), `${stem}.fb${ext}`);\n }\n\n /** Remove a stale spill after a successful canonical write (best-effort). */\n private async removeSpill(file: string): Promise<void> {\n await fsp.unlink(this.spillPathFor(file)).catch(() => {});\n }\n\n private removeSpillSync(file: string): void {\n try {\n fs.unlinkSync(this.spillPathFor(file));\n } catch {\n // no spill or still locked — loadAll reconciles by savedAt\n }\n }\n\n /** Rate-limited failure alerting: log on the first failure and at each\n * power-of-two count (1,2,4,8,…), so a long lock yields ~log2(N) lines\n * instead of one per write. Includes the spill path so the operator can\n * see where the data landed. */\n private recordFailure(id: string, err: unknown, spillPath: string | null): void {\n const count = (this.failCounts.get(id) ?? 0) + 1;\n this.failCounts.set(id, count);\n const alertAt = count === 1 || (count >= 2 && (count & (count - 1)) === 0);\n if (!alertAt) return;\n const where = spillPath\n ? `; data spilled to ${rel(spillPath, this.dir)}`\n : \"; SPILLOVER ALSO FAILED — data at risk\";\n this.log(count === 1 ? \"error\" : \"warn\", `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`);\n }\n\n private clearFailure(id: string): void {\n this.failCounts.delete(id);\n }\n\n /** fs.rename with exponential-backoff retries on Windows transient locks\n * (EPERM/EBUSY/EACCES from AV scan, search indexer, SMB). Other errors\n * are real and rethrown immediately. */\n private async renameWithRetry(src: string, dest: string): Promise<void> {\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n try {\n await fsp.rename(src, dest);\n return;\n } catch (e) {\n lastErr = e;\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== \"EPERM\" && code !== \"EBUSY\" && code !== \"EACCES\") throw e;\n if (attempt === this.retryAttempts - 1) throw e;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n throw lastErr;\n }\n\n /** Parse + validate one file. Corrupt or invalid records return null\n * (logged) instead of throwing — load paths must never block boot. */\n private readEnvelope(file: string): PersistedEnvelope<T> | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (e) {\n // A missing candidate path is an expected miss (loadSync probes);\n // only genuinely unreadable/corrupt files get logged.\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") {\n this.log(\"warn\", `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`);\n }\n return null;\n }\n if (isEnvelopeLike(parsed)) {\n if (!this.validateFn(parsed as PersistedEnvelope<T>)) {\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n return parsed as PersistedEnvelope<T>;\n }\n const adopted = this.adoptLegacy(parsed);\n if (adopted) return adopted;\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n\n /** Wrap a legacy (pre-envelope) record as an envelope via the `legacy`\n * hook, then validate the adopted payload like any other. */\n private adoptLegacy(parsed: unknown): PersistedEnvelope<T> | null {\n const adoption = this.legacyFn ? this.legacyFn(parsed) : null;\n if (!adoption || typeof adoption.id !== \"string\" || adoption.id.length === 0 || adoption.payload == null) {\n return null;\n }\n const source = parsed as Partial<PersistedEnvelope<T>>;\n const envelope: PersistedEnvelope<T> = {\n version: adoption.version ?? source.version ?? this.version,\n savedAt: adoption.savedAt ?? source.savedAt ?? 0,\n id: adoption.id,\n payload: adoption.payload,\n };\n if (!this.validateFn(envelope)) return null;\n return envelope;\n }\n\n /** Iterative recursive walk (no readdir-recursive dependency), skipping\n * `.tmp-*` names and non-.json files. */\n private async walkJsonFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n const queue: string[] = [root];\n while (queue.length > 0) {\n const dir = queue.pop()!;\n let dirents: fs.Dirent[];\n try {\n dirents = await fsp.readdir(dir, { withFileTypes: true });\n } catch {\n continue; // missing dir → no records yet\n }\n for (const d of dirents) {\n if (d.name.startsWith(\".tmp-\")) continue;\n const full = path.join(dir, d.name);\n if (d.isDirectory()) queue.push(full);\n else if (d.isFile() && d.name.endsWith(\".json\")) out.push(full);\n }\n }\n return out;\n }\n\n /** Stat-only preselection for budgeted loadAll: pairs each canonical\n * file with its `.fb.json` spill under a dir+stem key (identical stems\n * in different directories are different records), sums group sizes,\n * and fills the budget newest-mtime-first. Never reads file content. */\n private async selectWithinBudget(budget: number): Promise<string[]> {\n if (!Number.isFinite(budget) || budget < 0) {\n throw new TypeError(\n `maxParseBytes must be a finite non-negative number, got ${String(budget)}`,\n );\n }\n const entries = await Promise.all(\n (await this.walkJsonFiles(this.dir)).map(async (file) => {\n try {\n const st = await fsp.stat(file);\n return { file, size: st.size, mtimeMs: st.mtimeMs };\n } catch {\n return null; // vanished or unreadable between walk and stat\n }\n }),\n );\n const groups = new Map<string, { key: string; files: string[]; size: number; mtimeMs: number }>();\n for (const e of entries) {\n if (!e) continue;\n const base = path.basename(e.file);\n const stem = base.endsWith(\".fb.json\")\n ? base.slice(0, -\".fb.json\".length)\n : base.slice(0, -\".json\".length);\n const key = `${path.dirname(e.file)}\\u0000${stem}`;\n const g = groups.get(key) ?? { key, files: [], size: 0, mtimeMs: 0 };\n g.files.push(e.file);\n g.size += e.size;\n g.mtimeMs = Math.max(g.mtimeMs, e.mtimeMs);\n groups.set(key, g);\n }\n const ordered = [...groups.values()].sort(\n (a, b) => b.mtimeMs - a.mtimeMs || b.size - a.size || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0),\n );\n const selected: string[] = [];\n let used = 0;\n let skipped = 0;\n for (const g of ordered) {\n if (used + g.size > budget) {\n skipped++;\n continue;\n }\n selected.push(...g.files);\n used += g.size;\n }\n if (skipped > 0) {\n this.log(\n \"warn\",\n `[persist] loadAll budget ${budget} bytes: parsed ${ordered.length - skipped}/${ordered.length} record groups (skipped ${skipped})`,\n );\n }\n return selected;\n }\n}\n\nfunction defaultValidate<T>(envelope: PersistedEnvelope<T>): boolean {\n return typeof envelope.id === \"string\" && envelope.id.length > 0 && envelope.payload != null;\n}\n\nfunction isEnvelopeLike(value: unknown): value is PersistedEnvelope<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Partial<PersistedEnvelope<unknown>>;\n return typeof v.id === \"string\" && \"payload\" in v;\n}\n\n/** Deterministic flat filename: `<sha256(id)[:24]>.json`. Truncated hash —\n * 96 bits keeps collisions unreachable for realistic id counts, and short\n * names stay greppable. */\nexport function flatFileNameFor(id: string): string {\n return createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\").slice(0, 24) + \".json\";\n}\n\nfunction errText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n\nfunction rel(p: string, base: string): string {\n const r = path.relative(base, p);\n return r && !r.startsWith(\"..\") ? r : p;\n}\n","import type { CompressionState } from \"../types.js\";\nimport { createInitialState } from \"../state.js\";\n\n/**\n * Forward-compat: merge a parsed state with a fresh one so fields added in\n * later kernel versions get sane defaults instead of `undefined`. Nested\n * groups (nudge, stats) are shallow-merged per field so older snapshots\n * keep their values while newer counters default in.\n *\n * Lifted verbatim in behavior from billion-context's proxy mergeState.\n */\nexport function mergeCompressionState(parsed: CompressionState): CompressionState {\n const fresh = createInitialState();\n return {\n blocks: parsed.blocks ?? fresh.blocks,\n messageRefs: parsed.messageRefs ?? fresh.messageRefs,\n nudge: { ...fresh.nudge, ...(parsed.nudge ?? {}) },\n stats: { ...fresh.stats, ...(parsed.stats ?? {}) },\n nextBlockId: parsed.nextBlockId ?? fresh.nextBlockId,\n nextRunId: parsed.nextRunId ?? fresh.nextRunId,\n tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot,\n absorbed: parsed.absorbed ?? fresh.absorb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,QAAM,QAAQ,mBAAmB;AACjC,SAAO;AAAA,IACL,QAAQ,OAAO,UAAU,MAAM;AAAA,IAC/B,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,WAAW,OAAO,aAAa,MAAM;AAAA,IACrC,eAAe,OAAO,iBAAiB,MAAM;AAAA,IAC7C,UAAU,OAAO,YAAY,MAAM;AAAA,EACrC;AACF;","names":["rel"]}
1
+ {"version":3,"sources":["../../src/persist/store.ts","../../src/persist/state-merge.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Logger callback. Downstream routes it wherever it wants (file, stderr). */\nexport type PersistLogger = (level: \"info\" | \"warn\" | \"error\", msg: string) => void;\n\n/**\n * On-disk record shape. The store owns the envelope (version stamp, save\n * time, id) so atomicity and discovery can rely on it; the payload schema\n * is entirely downstream-owned. `payload` must be JSON-serializable.\n */\nexport interface PersistedEnvelope<T> {\n version: number;\n savedAt: number;\n id: string;\n payload: T;\n}\n\n/** A legacy (pre-envelope) record adopted on load. `version`/`savedAt`\n * preserve the source record's own stamps when present. */\nexport interface LegacyAdoption<T> {\n id: string;\n payload: T;\n version?: number;\n savedAt?: number;\n}\n\nexport interface StateStoreOptions<T> {\n /**\n * Storage root. The kernel deliberately has NO default location: the\n * downstream decides where state lives (CLI dir, XDG data dir, plugin\n * dir, temp dir in tests). All records live under this directory.\n */\n dir: string;\n /**\n * Schema version stamped into every envelope. Owned by the downstream;\n * bump it when the payload shape changes. The store itself never\n * rejects a record over its version — migration policy belongs to the\n * reader.\n */\n version: number;\n /** Debounce window for scheduleSave, ms. Default 500. */\n debounceMs?: number;\n /** Default true. When false, all writes are silent no-ops and loads\n * return empty results. */\n enabled?: boolean;\n log?: PersistLogger;\n /**\n * Relative path (under `dir`) for a record, possibly namespaced into\n * subdirectories (e.g. `openai/host-hash.json`). Default: flat\n * `<sha256(id)[:24]>.json`.\n *\n * Because the path may depend on payload fields the store only learns\n * at write time, single-record loads resolve namespaced files only\n * after loadAll() has discovered them (or the store itself wrote\n * them). The flat default name is always checked as a fallback, so\n * downstreams using a custom relPath should call loadAll() at boot.\n */\n relPath?: (id: string, payload: T) => string;\n /**\n * Adopt records written by an older, pre-envelope schema. Receives the\n * parsed JSON of any file that failed the envelope-shape check; return\n * an adoption to load it as an envelope, or null to skip it. Adopted\n * records are re-persisted in the current envelope format on the next\n * dirty write — files migrate organically, and old files keep loading\n * (same policy billion-context's proxy used for its v1→v3 migration).\n */\n legacy?: (parsed: unknown) => LegacyAdoption<T> | null;\n /**\n * Payload validation on load. Return false to skip a record (foreign\n * schema, corrupt content). Default: envelope-shape check only\n * (string id, non-null payload).\n */\n validate?: (envelope: PersistedEnvelope<T>) => boolean;\n /**\n * Rename-retry policy for Windows transient locks (EPERM/EBUSY/EACCES\n * from AV scan, search indexer, SMB). Exponential backoff: the delay\n * after attempt i is min(retryBaseMs * 2^i, retryMaxMs). Defaults\n * (6 attempts, 50ms base, 1600ms cap) give a ~1.5s window — long enough\n * for most AV locks to release, short enough not to stall a sync flush.\n * When the window is exhausted the write spills to a side file (see\n * spillPath) instead of dropping the data.\n */\n retryAttempts?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n}\n\n/**\n * Crash-safe, debounce-coalescing JSON state store. Mechanism only — lifted\n * from billion-context's proxy SessionStore and generalized:\n *\n * - atomic writes: temp file + rename, so a crash mid-write never leaves a\n * truncated record (readers see either the old or the new file)\n * - rename retries with exponential backoff on Windows transient locks\n * (EPERM/EBUSY/EACCES); when the window is exhausted the record spills to\n * a side file (`<name>.fb.json`) instead of being dropped, so a lock held\n * by AV/indexer/SMB never silently loses session data\n * - per-id serialization so concurrent writeNow calls never interleave\n * temp-file names or reorders writes\n * - debounced scheduleSave coalesces bursts into one write; the record is\n * built at WRITE time from a builder, so late mutations are picked up\n * - loadAll skips `.tmp-*` orphans, corrupt JSON, and records whose\n * filename does not match their id — one bad file never blocks boot; it\n * reconciles a canonical record against its spill by savedAt (freshest wins)\n *\n * The store never deletes a record's data. On a successful canonical write it\n * removes a now-stale spill of the SAME id (a duplicate, not distinct data).\n * Session cleanup is a downstream policy decision (kernel position: persisted\n * state should not be deleted opportunistically).\n */\nexport class StateStore<T> {\n readonly enabled: boolean;\n private readonly dir: string;\n private readonly version: number;\n private readonly debounceMs: number;\n private readonly log: PersistLogger;\n private readonly legacyFn?: (parsed: unknown) => LegacyAdoption<T> | null;\n private readonly relPathFn?: (id: string, payload: T) => string;\n private readonly validateFn: (envelope: PersistedEnvelope<T>) => boolean;\n private readonly retryAttempts: number;\n private readonly retryBaseMs: number;\n private readonly retryMaxMs: number;\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly pending = new Map<string, () => T>();\n private readonly writeChains = new Map<string, Promise<void>>();\n /** id → absolute path, populated by writes and loadAll. */\n private readonly discovered = new Map<string, string>();\n /** id → cumulative write-failure count, for rate-limited alerting. */\n private readonly failCounts = new Map<string, number>();\n /** Monotonic counter for unique temp filenames within a process. */\n private tmpSeq = 0;\n\n constructor(opts: StateStoreOptions<T>) {\n this.dir = opts.dir;\n this.version = opts.version;\n this.debounceMs = opts.debounceMs ?? 500;\n this.enabled = opts.enabled ?? true;\n this.log = opts.log ?? ((_level, _msg) => {});\n this.relPathFn = opts.relPath;\n this.legacyFn = opts.legacy;\n this.validateFn = opts.validate ?? defaultValidate;\n this.retryAttempts = Math.max(1, opts.retryAttempts ?? 6);\n this.retryBaseMs = Math.max(1, opts.retryBaseMs ?? 50);\n this.retryMaxMs = Math.max(this.retryBaseMs, opts.retryMaxMs ?? 1600);\n }\n\n /** Debounced save. Coalesces bursts; the builder runs at write time, so\n * the freshest state is always persisted. Never throws. */\n scheduleSave(id: string, build: () => T): void {\n if (!this.enabled) return;\n this.pending.set(id, build);\n const existing = this.timers.get(id);\n if (existing) return;\n const timer = setTimeout(() => {\n this.timers.delete(id);\n const builder = this.pending.get(id);\n this.pending.delete(id);\n if (!builder) return;\n // Errors are logged inside writeInner; swallowing here keeps a\n // failed timer write from becoming an unhandledRejection.\n void this.writeNow(id, builder).catch(() => {});\n }, this.debounceMs);\n timer.unref?.();\n this.timers.set(id, timer);\n }\n\n /** Immediate save, serialized per id. Rejects on write failure; a\n * failing write never breaks the chain for the next one. */\n async writeNow(id: string, build: () => T): Promise<void> {\n if (!this.enabled) return;\n // The previous promise may reject (disk full, EPERM) — catch so our\n // chain doesn't break, then run our own write.\n const prev = this.writeChains.get(id) ?? Promise.resolve();\n const next = prev.catch(() => {}).then(() => this.writeInner(id, build));\n this.writeChains.set(id, next);\n // Clean up the chain entry once settled so the Map doesn't grow. The\n // .catch() is load-bearing: .finally() returns a derived promise that\n // nobody else holds — when the chain rejects it would surface as an\n // unhandledRejection and crash the host on default Node settings.\n next\n .finally(() => {\n if (this.writeChains.get(id) === next) this.writeChains.delete(id);\n })\n .catch(() => {});\n return next;\n }\n\n /** Synchronous flush for one id. Used where the caller cannot await\n * (memory eviction, sync shutdown paths). Cancels any pending debounce\n * timer. Returns true on success, false on failure — callers that use\n * the result to drop in-memory state must NOT drop it on failure. */\n flushSync(id: string, build: () => T): boolean {\n if (!this.enabled) return true;\n const timer = this.timers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(id);\n this.pending.delete(id);\n }\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n return false;\n }\n const file = this.resolvePath(id, payload);\n const data = JSON.stringify(this.envelope(id, payload));\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n } catch (e) {\n this.log(\"warn\", `[persist] could not create dir ${path.dirname(file)}: ${errText(e)}`);\n }\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name per attempt: on Windows a failed cleanup can\n // leave the previous name delete-pending, and creating over a\n // tombstoned name fails immediately — reusing it would burn every\n // remaining attempt before the write even happens.\n const tmp = this.tempPath(file);\n try {\n fs.writeFileSync(tmp, data, \"utf8\");\n fs.renameSync(tmp, file);\n lastErr = undefined;\n break;\n } catch (e) {\n lastErr = e;\n try {\n fs.unlinkSync(tmp);\n } catch {\n // temp never created or already gone\n }\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== \"EPERM\" && code !== \"EBUSY\" && code !== \"EACCES\") break;\n if (attempt === this.retryAttempts - 1) break;\n // sync sleep (Atomics.wait) — backoff grows per attempt\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (!lastErr) {\n this.discovered.set(id, file);\n this.clearFailure(id);\n this.removeSpillSync(file);\n return true;\n }\n // The canonical rename outlived the retry window (Windows lock held by\n // AV/indexer/SMB). Spill to a side file so the data still lands on\n // disk instead of being dropped — loadAll picks the freshest of the\n // canonical and the spill.\n let spillPath: string | null = null;\n try {\n const spill = this.spillPathFor(file);\n fs.writeFileSync(spill, data, \"utf8\");\n spillPath = spill;\n this.discovered.set(id, spill);\n } catch {\n // spillover also failed (dir read-only / disk full) — data at risk\n }\n this.recordFailure(id, lastErr, spillPath);\n return spillPath !== null;\n }\n\n /** Load one record. Checks the discovered path (from a prior\n * write/loadAll), an optional relative-path hint, and the flat default\n * name. Returns null when absent, disabled, corrupt, or rejected by\n * validate. The hint covers namespaced records the store has not\n * discovered (e.g. an evicted session re-requested with its meta,\n * where the path depends on data the store cannot reconstruct from\n * the id alone). */\n loadSync(id: string, hint?: string): PersistedEnvelope<T> | null {\n if (!this.enabled) return null;\n const candidates = [\n this.discovered.get(id),\n hint ? path.join(this.dir, hint) : undefined,\n path.join(this.dir, flatFileNameFor(id)),\n ];\n for (const file of candidates) {\n if (!file) continue;\n const envelope = this.readEnvelope(file);\n if (envelope && envelope.id === id) return envelope;\n }\n return null;\n }\n\n /** Load every record under dir. Populates the discovery map (enables\n * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`\n * orphans, and records whose filename does not match their id — one\n * bad file never blocks boot. Never throws. */\n async loadAll(): Promise<Map<string, PersistedEnvelope<T>>> {\n const out = new Map<string, PersistedEnvelope<T>>();\n if (!this.enabled) return out;\n const files = await this.walkJsonFiles(this.dir);\n for (const file of files) {\n const envelope = this.readEnvelope(file);\n if (!envelope) continue;\n const base = path.basename(file);\n const relBase = path.basename(this.relPathOf(envelope.id, envelope.payload));\n const flatBase = flatFileNameFor(envelope.id);\n // A file is a valid record for its envelope id when its name is the\n // canonical name OR a spill (`.fb`) of the canonical name. This lets\n // a spilled record (written while the canonical was locked) be\n // discovered and reconciled against the canonical by savedAt.\n let owner: string | null = null;\n if (base === relBase || base === flatBase) {\n owner = envelope.id;\n } else if (base.endsWith(\".fb.json\")) {\n const canonicalBase = `${base.slice(0, -\".fb.json\".length)}.json`;\n if (canonicalBase === relBase || canonicalBase === flatBase) {\n owner = envelope.id;\n }\n }\n if (owner === null) {\n this.log(\"warn\", `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`);\n continue;\n }\n const existing = out.get(owner);\n if (!existing || envelope.savedAt >= existing.savedAt) {\n out.set(owner, envelope);\n this.discovered.set(owner, file);\n }\n }\n return out;\n }\n\n /** Whether a debounced write is pending for an id. */\n hasPending(id: string): boolean {\n return this.timers.has(id);\n }\n\n /** Ids with a pending debounced write. */\n pendingIds(): string[] {\n return [...this.timers.keys()];\n }\n\n /** Flush every pending debounced write immediately, then drain in-flight\n * writes. For graceful shutdown (SIGTERM/SIGINT). Never rejects. */\n async flushAll(): Promise<void> {\n const ids = this.pendingIds();\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n const builders = new Map<string, () => T>();\n for (const id of ids) {\n const build = this.pending.get(id);\n if (build) builders.set(id, build);\n this.pending.delete(id);\n }\n await Promise.all(\n [...builders.entries()].map(([id, build]) =>\n this.writeNow(id, build).catch((e) => {\n this.log(\"error\", `[persist] shutdown flush failed for ${id}: ${errText(e)}`);\n }),\n ),\n );\n // Drain writes whose timer fired earlier but are still mid-flight.\n await Promise.allSettled([...this.writeChains.values()]);\n }\n\n /** Cancel all pending debounced writes without flushing (tests). */\n cancelAll(): void {\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pending.clear();\n }\n\n private async writeInner(id: string, build: () => T): Promise<void> {\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n throw e;\n }\n const file = this.resolvePath(id, payload);\n try {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n } catch (e) {\n this.log(\"warn\", `[persist] could not create dir ${path.dirname(file)}: ${errText(e)}`);\n }\n const tmp = this.tempPath(file);\n const env = this.envelope(id, payload);\n try {\n await fsp.writeFile(tmp, JSON.stringify(env), \"utf8\");\n await this.renameWithRetry(tmp, file);\n this.discovered.set(id, file);\n this.clearFailure(id);\n await this.removeSpill(file);\n } catch (e) {\n // Clean up the .tmp orphan so the next write doesn't collide with it.\n await fsp.unlink(tmp).catch(() => {});\n // The canonical rename outlived the retry window (Windows lock held\n // by AV/indexer/SMB). Spill to a side file so the data still lands\n // on disk instead of being dropped — loadAll picks the freshest of\n // the canonical and the spill.\n let spillPath: string | null = null;\n try {\n const spill = this.spillPathFor(file);\n await fsp.writeFile(spill, JSON.stringify(env), \"utf8\");\n spillPath = spill;\n this.discovered.set(id, spill);\n } catch {\n // spillover also failed (dir read-only / disk full) — data at risk\n }\n this.recordFailure(id, e, spillPath);\n throw e;\n }\n }\n\n private envelope(id: string, payload: T): PersistedEnvelope<T> {\n return { version: this.version, savedAt: Date.now(), id, payload };\n }\n\n /** Absolute path for a record: custom relPath (guarded against path\n * escape) or the flat hash default. */\n private resolvePath(id: string, payload: T): string {\n return path.join(this.dir, this.relPathOf(id, payload));\n }\n\n private relPathOf(id: string, payload: T): string {\n const custom = this.relPathFn?.(id, payload);\n if (!custom) return flatFileNameFor(id);\n const rel = path.normalize(custom);\n if (path.isAbsolute(rel) || rel.split(/[\\\\/]+/).includes(\"..\")) {\n this.log(\"warn\", `[persist] relPath for ${id} escapes dir; using flat name`);\n return flatFileNameFor(id);\n }\n return rel;\n }\n\n /** Unique temp file next to the destination (same dir ⇒ same volume ⇒\n * rename is atomic). Prefixed `.tmp-` so loadAll skips orphans. */\n private tempPath(dest: string): string {\n const seq = this.tmpSeq++;\n return path.join(path.dirname(dest), `.tmp-${path.basename(dest, \".json\")}-${process.pid}-${seq}`);\n }\n\n private backoffMs(attempt: number): number {\n return Math.min(this.retryBaseMs * 2 ** attempt, this.retryMaxMs);\n }\n\n /** Side file for a record whose canonical write keeps failing: the\n * canonical name with a `.fb` (fallback) infix, e.g. `a.json` →\n * `a.fb.json`. One slot per id, overwritten on each spill, so a stuck\n * lock never accumulates files. Ends in `.json` so loadAll discovers it. */\n private spillPathFor(file: string): string {\n const base = path.basename(file);\n const dot = base.lastIndexOf(\".\");\n const stem = dot > 0 ? base.slice(0, dot) : base;\n const ext = dot > 0 ? base.slice(dot) : \".json\";\n return path.join(path.dirname(file), `${stem}.fb${ext}`);\n }\n\n /** Remove a stale spill after a successful canonical write (best-effort). */\n private async removeSpill(file: string): Promise<void> {\n await fsp.unlink(this.spillPathFor(file)).catch(() => {});\n }\n\n private removeSpillSync(file: string): void {\n try {\n fs.unlinkSync(this.spillPathFor(file));\n } catch {\n // no spill or still locked — loadAll reconciles by savedAt\n }\n }\n\n /** Rate-limited failure alerting: log on the first failure and at each\n * power-of-two count (1,2,4,8,…), so a long lock yields ~log2(N) lines\n * instead of one per write. Includes the spill path so the operator can\n * see where the data landed. */\n private recordFailure(id: string, err: unknown, spillPath: string | null): void {\n const count = (this.failCounts.get(id) ?? 0) + 1;\n this.failCounts.set(id, count);\n const alertAt = count === 1 || (count >= 2 && (count & (count - 1)) === 0);\n if (!alertAt) return;\n const where = spillPath\n ? `; data spilled to ${rel(spillPath, this.dir)}`\n : \"; SPILLOVER ALSO FAILED — data at risk\";\n this.log(count === 1 ? \"error\" : \"warn\", `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`);\n }\n\n private clearFailure(id: string): void {\n this.failCounts.delete(id);\n }\n\n /** fs.rename with exponential-backoff retries on Windows transient locks\n * (EPERM/EBUSY/EACCES from AV scan, search indexer, SMB). Other errors\n * are real and rethrown immediately. */\n private async renameWithRetry(src: string, dest: string): Promise<void> {\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n try {\n await fsp.rename(src, dest);\n return;\n } catch (e) {\n lastErr = e;\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== \"EPERM\" && code !== \"EBUSY\" && code !== \"EACCES\") throw e;\n if (attempt === this.retryAttempts - 1) throw e;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n throw lastErr;\n }\n\n /** Parse + validate one file. Corrupt or invalid records return null\n * (logged) instead of throwing — load paths must never block boot. */\n private readEnvelope(file: string): PersistedEnvelope<T> | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (e) {\n // A missing candidate path is an expected miss (loadSync probes);\n // only genuinely unreadable/corrupt files get logged.\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") {\n this.log(\"warn\", `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`);\n }\n return null;\n }\n if (isEnvelopeLike(parsed)) {\n if (!this.validateFn(parsed as PersistedEnvelope<T>)) {\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n return parsed as PersistedEnvelope<T>;\n }\n const adopted = this.adoptLegacy(parsed);\n if (adopted) return adopted;\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n\n /** Wrap a legacy (pre-envelope) record as an envelope via the `legacy`\n * hook, then validate the adopted payload like any other. */\n private adoptLegacy(parsed: unknown): PersistedEnvelope<T> | null {\n const adoption = this.legacyFn ? this.legacyFn(parsed) : null;\n if (!adoption || typeof adoption.id !== \"string\" || adoption.id.length === 0 || adoption.payload == null) {\n return null;\n }\n const source = parsed as Partial<PersistedEnvelope<T>>;\n const envelope: PersistedEnvelope<T> = {\n version: adoption.version ?? source.version ?? this.version,\n savedAt: adoption.savedAt ?? source.savedAt ?? 0,\n id: adoption.id,\n payload: adoption.payload,\n };\n if (!this.validateFn(envelope)) return null;\n return envelope;\n }\n\n /** Iterative recursive walk (no readdir-recursive dependency), skipping\n * `.tmp-*` names and non-.json files. */\n private async walkJsonFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n const queue: string[] = [root];\n while (queue.length > 0) {\n const dir = queue.pop()!;\n let dirents: fs.Dirent[];\n try {\n dirents = await fsp.readdir(dir, { withFileTypes: true });\n } catch {\n continue; // missing dir → no records yet\n }\n for (const d of dirents) {\n if (d.name.startsWith(\".tmp-\")) continue;\n const full = path.join(dir, d.name);\n if (d.isDirectory()) queue.push(full);\n else if (d.isFile() && d.name.endsWith(\".json\")) out.push(full);\n }\n }\n return out;\n }\n}\n\nfunction defaultValidate<T>(envelope: PersistedEnvelope<T>): boolean {\n return typeof envelope.id === \"string\" && envelope.id.length > 0 && envelope.payload != null;\n}\n\nfunction isEnvelopeLike(value: unknown): value is PersistedEnvelope<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Partial<PersistedEnvelope<unknown>>;\n return typeof v.id === \"string\" && \"payload\" in v;\n}\n\n/** Deterministic flat filename: `<sha256(id)[:24]>.json`. Truncated hash —\n * 96 bits keeps collisions unreachable for realistic id counts, and short\n * names stay greppable. */\nexport function flatFileNameFor(id: string): string {\n return createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\").slice(0, 24) + \".json\";\n}\n\nfunction errText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n\nfunction rel(p: string, base: string): string {\n const r = path.relative(base, p);\n return r && !r.startsWith(\"..\") ? r : p;\n}\n","import type { CompressionState } from \"../types.js\";\nimport { createInitialState } from \"../state.js\";\n\n/**\n * Forward-compat: merge a parsed state with a fresh one so fields added in\n * later kernel versions get sane defaults instead of `undefined`. Nested\n * groups (nudge, stats) are shallow-merged per field so older snapshots\n * keep their values while newer counters default in.\n *\n * Lifted verbatim in behavior from billion-context's proxy mergeState.\n */\nexport function mergeCompressionState(parsed: CompressionState): CompressionState {\n const fresh = createInitialState();\n return {\n blocks: parsed.blocks ?? fresh.blocks,\n messageRefs: parsed.messageRefs ?? fresh.messageRefs,\n nudge: { ...fresh.nudge, ...(parsed.nudge ?? {}) },\n stats: { ...fresh.stats, ...(parsed.stats ?? {}) },\n nextBlockId: parsed.nextBlockId ?? fresh.nextBlockId,\n nextRunId: parsed.nextRunId ?? fresh.nextRunId,\n tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot,\n absorbed: parsed.absorbed ?? fresh.absorbed,\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AA8GV,IAAM,aAAN,MAAoB;AAAA,EACd;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,oBAAI,IAA4B;AAAA,EACzC,UAAU,oBAAI,IAAqB;AAAA,EACnC,cAAc,oBAAI,IAA2B;AAAA;AAAA,EAE7C,aAAa,oBAAI,IAAoB;AAAA;AAAA,EAErC,aAAa,oBAAI,IAAoB;AAAA;AAAA,EAE9C,SAAS;AAAA,EAEjB,YAAY,MAA4B;AACpC,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,M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AM,IAAI,KAAK,SAAS,MAAM,CAAC;AAC/B,SAAO,KAAK,CAAC,EAAE,WAAW,IAAI,IAAI,IAAI;AAC1C;;;AC/kBO,SAAS,sBAAsB,QAA4C;AAChF,QAAM,QAAQ,mBAAmB;AACjC,SAAO;AAAA,IACL,QAAQ,OAAO,UAAU,MAAM;AAAA,IAC/B,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,WAAW,OAAO,aAAa,MAAM;AAAA,IACrC,eAAe,OAAO,iBAAiB,MAAM;AAAA,IAC7C,UAAU,OAAO,YAAY,MAAM;AAAA,EACrC;AACF;","names":["rel"]}
@@ -79,28 +79,6 @@ export interface StateStoreOptions<T> {
79
79
  retryBaseMs?: number;
80
80
  retryMaxMs?: number;
81
81
  }
82
- /** Options for {@link StateStore.loadAll}. */
83
- export interface LoadAllOptions {
84
- /**
85
- * Cap on the total bytes of record files loadAll will read and parse.
86
- * When set, loadAll does a stat-only pass first (readdir + stat, no
87
- * content reads), groups each canonical file with its `.fb.json` spill
88
- * variant (same id ⇒ all-or-nothing, so the pair's freshest-wins
89
- * reconciliation always sees both sides), then includes groups
90
- * newest-mtime-first while the running total stays within the budget.
91
- * A group that does not fit is skipped individually and selection
92
- * continues with older groups — the byte cap is hard even when the
93
- * newest group alone exceeds it; only if NO group fits is the result
94
- * empty. Excluded groups are left on disk untouched (the store never deletes)
95
- * and stay individually reachable via loadSync(id, hint). If no group
96
- * fits, the result is an empty map (a warning is logged) — the budget
97
- * is a hard cap, so one oversized record can never blow past it. Group
98
- * freshness uses file mtime as a stat-level proxy for the in-envelope
99
- * savedAt; ordering among parsed records still comes from savedAt
100
- * reconciliation. Omitted ⇒ parse every record (default, unchanged).
101
- */
102
- maxParseBytes?: number;
103
- }
104
82
  /**
105
83
  * Crash-safe, debounce-coalescing JSON state store. Mechanism only — lifted
106
84
  * from billion-context's proxy SessionStore and generalized:
@@ -168,14 +146,8 @@ export declare class StateStore<T> {
168
146
  /** Load every record under dir. Populates the discovery map (enables
169
147
  * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`
170
148
  * orphans, and records whose filename does not match their id — one
171
- * bad file never blocks boot; filesystem and record problems never
172
- * throw. An invalid `maxParseBytes` (non-finite or negative) throws
173
- * TypeError fail-fast instead.
174
- *
175
- * With `options.maxParseBytes`, parsing is budget-limited via a stat-only
176
- * preselection pass (see {@link LoadAllOptions.maxParseBytes}); skipped
177
- * records are not deleted and remain loadable via loadSync(id, hint). */
178
- loadAll(options?: LoadAllOptions): Promise<Map<string, PersistedEnvelope<T>>>;
149
+ * bad file never blocks boot. Never throws. */
150
+ loadAll(): Promise<Map<string, PersistedEnvelope<T>>>;
179
151
  /** Whether a debounced write is pending for an id. */
180
152
  hasPending(id: string): boolean;
181
153
  /** Ids with a pending debounced write. */
@@ -222,11 +194,6 @@ export declare class StateStore<T> {
222
194
  /** Iterative recursive walk (no readdir-recursive dependency), skipping
223
195
  * `.tmp-*` names and non-.json files. */
224
196
  private walkJsonFiles;
225
- /** Stat-only preselection for budgeted loadAll: pairs each canonical
226
- * file with its `.fb.json` spill under a dir+stem key (identical stems
227
- * in different directories are different records), sums group sizes,
228
- * and fills the budget newest-mtime-first. Never reads file content. */
229
- private selectWithinBudget;
230
197
  }
231
198
  /** Deterministic flat filename: `<sha256(id)[:24]>.json`. Truncated hash —
232
199
  * 96 bits keeps collisions unreachable for realistic id counts, and short
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/persist/store.ts"],"names":[],"mappings":"AAKA,8EAA8E;AAC9E,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,GAAG,EAAE,MAA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C,CAAC,CAAC,GAAG,IAAI;IAehE;;;oDAGgD;IAC1C,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;IAoC3D,sDAAsD;IACtD,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO;IAI/B,0CAA0C;IAC1C,UAAU,IAAI,MAAM,EAAE;IAItB;yEACqE;IAC/D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAqB/B,oEAAoE;IACpE,SAAS,IAAI,IAAI;YAMH,UAAU;IA2CxB,OAAO,CAAC,QAAQ;IAIhB;4CACwC;IACxC,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,SAAS;IAWjB;wEACoE;IACpE,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,SAAS;IAIjB;;;iFAG6E;IAC7E,OAAO,CAAC,YAAY;IAQpB,6EAA6E;YAC/D,WAAW;IAIzB,OAAO,CAAC,eAAe;IAQvB;;;qCAGiC;IACjC,OAAO,CAAC,aAAa;IAWrB,OAAO,CAAC,YAAY;IAIpB;;6CAEyC;YAC3B,eAAe;IAmB7B;2EACuE;IACvE,OAAO,CAAC,YAAY;IAyBpB;kEAC8D;IAC9D,OAAO,CAAC,WAAW;IAgBnB;8CAC0C;YAC5B,aAAa;CAoB9B;AAYD;;4BAE4B;AAC5B,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAElD"}
@@ -53,8 +53,8 @@ export interface BiliMessage extends CoreMessage {
53
53
  /** The base64 data of an image (without the data: prefix). Lets the
54
54
  * reverse conversion rebuild the full image payload. */
55
55
  imageBase64?: string;
56
- /** OpenAI chat: ALL original image_url content parts (each a data: URL
57
- * part) for a user message carrying more than one image, in wire order.
56
+ /** OpenAI chat: ALL original image_url content parts (data: or remote
57
+ * URL) for a user message carrying more than one image, in wire order.
58
58
  * coreToOpenai re-emits these verbatim (after the text part). The
59
59
  * singular `rawOpenaiContent` still covers the single-image case and
60
60
  * legacy persisted state. Typed as unknown[] (not OpenAIContentPart) to
@@ -253,7 +253,11 @@ function openaiToCore(body) {
253
253
  role: "user",
254
254
  contentType: "text",
255
255
  text,
256
- ...imgs.length === 1 && firstParsed ? { rawOpenaiContent: imgs[0], imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 } : imgs.length > 1 ? { rawOpenaiContentParts: imgs } : {}
256
+ ...imgs.length === 1 ? {
257
+ rawOpenaiContent: imgs[0],
258
+ // data: URLs only — remote URLs ride rawOpenaiContent verbatim (issue #187)
259
+ ...firstParsed ? { imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 } : {}
260
+ } : imgs.length > 1 ? { rawOpenaiContentParts: imgs } : {}
257
261
  });
258
262
  break;
259
263
  }
@@ -415,7 +419,7 @@ function allImageParts(content) {
415
419
  if (!("type" in p) || p.type !== "image_url" || !("image_url" in p)) continue;
416
420
  const imagePart = p;
417
421
  const url = imagePart.image_url.url;
418
- if (typeof url === "string" && parseDataUrl(url)) out.push(p);
422
+ if (typeof url === "string") out.push(p);
419
423
  }
420
424
  return out;
421
425
  }
@@ -440,6 +444,12 @@ function partText(part) {
440
444
  function messageContent(content) {
441
445
  return typeof content === "string" ? content : content.map(partText).join("\n");
442
446
  }
447
+ function canonicalUserText(message) {
448
+ const contentText = messageContent(message.content);
449
+ const hasImage = Array.isArray(message.content) && message.content.some((part) => part.type === "input_image");
450
+ const hasTextPart = typeof message.content !== "string" && message.content.some((part) => part.type === "input_text" || part.type === "output_text");
451
+ return !contentText || hasImage && !hasTextPart ? "[image]" : contentText;
452
+ }
443
453
  function reasoningText(item) {
444
454
  const fromParts = (parts, type) => {
445
455
  if (!Array.isArray(parts)) return "";
@@ -515,15 +525,18 @@ function responsesToCore(body) {
515
525
  effText = split.text;
516
526
  }
517
527
  }
518
- if (effText) {
519
- coreId = clusters.next(deriveMessageId(role, "text", effText));
528
+ const hasImage = Array.isArray(message.content) && message.content.some((part) => part.type === "input_image");
529
+ const hasTextPart = typeof message.content !== "string" && message.content.some((part) => part.type === "input_text" || part.type === "output_text");
530
+ if (effText || role === "user" && hasImage) {
531
+ const displayText = !effText || role === "user" && hasImage && !hasTextPart ? "[image]" : effText;
532
+ coreId = clusters.next(deriveMessageId(role, "text", displayText));
520
533
  const imageUrl = Array.isArray(message.content) ? message.content.find((part) => part.type === "input_image" && typeof part.image_url === "string")?.image_url : void 0;
521
534
  const image = typeof imageUrl === "string" ? parseDataUrl(imageUrl) : void 0;
522
535
  msgs.push({
523
536
  id: coreId,
524
537
  role,
525
538
  contentType: "text",
526
- text: effText,
539
+ text: displayText,
527
540
  rawResponsesItem: item,
528
541
  ...image ? { imageMediaType: image.mediaType, imageBase64: image.base64 } : {}
529
542
  });
@@ -679,7 +692,7 @@ function coreToResponses(messages, customToolCallIds = /* @__PURE__ */ new Set()
679
692
  if (message.role === "system") {
680
693
  out.push({ type: "message", role: "developer", content: message.text ?? "" });
681
694
  } else if (message.role === "user") {
682
- if (raw?.type === "message" && messageContent(raw.content) === (message.text ?? "")) out.push(raw);
695
+ if (raw?.type === "message" && canonicalUserText(raw) === (message.text ?? "")) out.push(raw);
683
696
  else out.push({ type: "message", role: "user", content: message.text ?? "" });
684
697
  } else if (message.role === "assistant") {
685
698
  if (message.contentType === "text") {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/wire/util.ts","../../src/wire/message-id.ts","../../src/wire/anthropic.ts","../../src/wire/demoted-thinking.ts","../../src/wire/bili-message.ts","../../src/wire/openai.ts","../../src/wire/responses.ts","../../src/wire/formats.ts","../../src/wire/mirror.ts","../../src/wire/compress-detect.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** SHA-256-derived short id — kept verbatim from the proxy so message ids\n * stay byte-identical across the extraction (re-keying would orphan every\n * downstream map keyed on these ids). */\nexport function hashId(s: string): string {\n return createHash(\"sha256\").update(s, \"utf8\").digest(\"hex\").slice(0, 16);\n}\n\n/** How a conversation's identity was derived (kept verbatim from the proxy's\n * session-id.ts — only the TYPE moves; session-key derivation stays in the\n * proxy, which owns multi-tenant state). */\nexport type ConversationIdentity = {\n value: string;\n source: \"header\" | \"body-session\" | \"metadata-session\" | \"previous-response\" | \"content-fingerprint\" | \"generated\";\n clientProvided: boolean;\n};\n","import { hashId } from \"./util.js\";\n\n/**\n * Derive a stable, content-based message id.\n *\n * PROBLEM: none of the three wire protocols (Anthropic Messages, OpenAI Chat\n * Completions, OpenAI Responses) attach a stable id to request-side message\n * items. Historically each converter used `raw-${idx}` — a *position* index,\n * not an identity. As soon as a client deletes/reorders messages (other plugins\n * summarizing away old turns, multi-agent setups, etc.) the index drifts:\n * downstream ids shift, so\n * - assignRefs reuses stale `byRaw` entries, hiding new messages, and\n * - compression `effectiveMessageIds` start pointing at the *wrong* messages,\n * silently swallowing live content under an unrelated summary.\n *\n * FIX: derive the id from a SHA-256 of the message identity:\n * role + contentType + toolCallId + toolName + text\n * Two messages with identical identity collide. To keep duplicates distinct\n * (and avoid `covered` sets collapsing unrelated turns onto one id) we append a\n * within-conversation *cluster index* `_N`: the Nth occurrence of the same\n * identity, counting from 0 in arrival order.\n *\n * Trade-off vs a real client id:\n * - deleting a duplicated message only disturbs the cluster of that identity\n * (local damage), never the whole downstream (global damage like position).\n * - fully distinct messages are completely immune to reordering/deletion.\n *\n * `idx` is passed purely to break ties *within a single conversion pass*; it is\n * not part of the identity, so two passes over the same content produce the\n * same cluster numbering (deterministic).\n */\nexport function deriveMessageId(\n role: string,\n contentType: string,\n text: string,\n options: {\n toolCallId?: string;\n toolName?: string;\n } = {},\n): string {\n const seed = `${role}|${contentType}|${options.toolCallId ?? \"\"}|${options.toolName ?? \"\"}|${text}`;\n return \"h_\" + hashId(seed);\n}\n\n/**\n * Stateful cluster counter. Each converter instantiates one per conversion\n * pass; it tracks how many times each base identity has been seen so that the\n * Nth duplicate gets a `_${N}` suffix.\n */\nexport class ClusterCounter {\n private counts = new Map<string, number>();\n\n next(baseId: string): string {\n const n = this.counts.get(baseId) ?? 0;\n this.counts.set(baseId, n + 1);\n return n === 0 ? baseId : `${baseId}_${n}`;\n }\n}\n","import type { BiliMessage } from \"./bili-message.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\n\nexport type AnthropicTextBlock = { type: \"text\"; text: string; cache_control?: unknown };\nexport type AnthropicToolUse = {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n cache_control?: unknown;\n};\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | AnthropicTextBlock[];\n is_error?: boolean;\n cache_control?: unknown;\n};\nexport type AnthropicImage = { type: \"image\"; source: unknown };\nexport type AnthropicThinking = { type: \"thinking\"; thinking: string; signature?: string };\nexport type AnthropicBlock =\n | AnthropicTextBlock\n | AnthropicToolUse\n | AnthropicToolResult\n | AnthropicImage\n | AnthropicThinking;\n\nexport type AnthropicMessage = {\n role: \"user\" | \"assistant\";\n content: string | AnthropicBlock[];\n};\n\nexport type AnthropicRequestBody = {\n model?: string;\n max_tokens?: number;\n system?: string | AnthropicTextBlock[];\n messages: AnthropicMessage[];\n tools?: unknown[];\n stream?: boolean;\n temperature?: number;\n [key: string]: unknown;\n};\n\n\nexport function extractSystem(system: AnthropicRequestBody[\"system\"]): string {\n if (!system) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\nexport function buildSystem(text: string, original: AnthropicRequestBody[\"system\"]): string | AnthropicTextBlock[] {\n if (Array.isArray(original) && original.length > 0) {\n const ccBlock = original.find((b) => b.cache_control);\n return [{ type: \"text\", text, ...(ccBlock ? { cache_control: ccBlock.cache_control } : {}) }];\n }\n return text;\n}\n\ntype Flat = { msgs: BiliMessage[]; cacheControls: Map<string, unknown> };\n\nexport function anthropicToCore(body: AnthropicRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const cacheControls = new Map<string, unknown>();\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n const blocks = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n for (const b of blocks) {\n switch (b.type) {\n case \"text\": {\n const base = deriveMessageId(m.role, \"text\", b.text);\n const id = clusters.next(base);\n msgs.push({ id, role: m.role, contentType: \"text\", text: b.text });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_use\": {\n const base = deriveMessageId(\"assistant\", \"tool-call\", safeStringify(b.input), {\n toolCallId: b.id,\n toolName: b.name,\n });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: b.name,\n toolCallId: b.id,\n text: safeStringify(b.input),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_result\": {\n const text = typeof b.content === \"string\" ? b.content : b.content.map((c) => c.text).join(\"\\n\");\n const base = deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: b.tool_use_id });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: b.tool_use_id,\n text,\n ...(b.is_error === true ? { toolIsError: true } : {}),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"thinking\": {\n const base = deriveMessageId(\"assistant\", \"reasoning\", b.thinking);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: b.thinking,\n ...(b.signature ? { thinkingSignature: b.signature } : {}),\n });\n break;\n }\n case \"image\": {\n const base = deriveMessageId(m.role, \"text\", \"[image]\");\n msgs.push({\n id: clusters.next(base),\n role: m.role,\n contentType: \"text\",\n text: \"[image]\",\n rawAnthropicBlock: b,\n });\n break;\n }\n }\n }\n }\n return { msgs, cacheControls };\n}\n\nexport function coreToAnthropic(messages: BiliMessage[], cacheControls?: Map<string, unknown>): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n let current: { role: \"user\" | \"assistant\"; blocks: AnthropicBlock[] } | null = null;\n const flush = () => {\n if (current && current.blocks.length > 0) {\n out.push({ role: current.role, content: current.blocks });\n }\n current = null;\n };\n const cc = (id: string): { cache_control?: unknown } => {\n const v = cacheControls?.get(id);\n return v ? { cache_control: v } : {};\n };\n for (const m of messages) {\n const target: \"user\" | \"assistant\" =\n m.role === \"assistant\" ? \"assistant\" : \"user\";\n if (!current || current.role !== target) {\n flush();\n current = { role: target, blocks: [] };\n }\n switch (m.contentType) {\n case \"text\": {\n if (m.rawAnthropicBlock) {\n current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);\n break;\n }\n current.blocks.push({ type: \"text\", text: m.text ?? \"\", ...cc(m.id) });\n break;\n }\n case \"tool-call\":\n current.blocks.push({\n type: \"tool_use\",\n id: m.toolCallId ?? `call_${m.id}`,\n name: m.toolName ?? \"unknown\",\n input: safeParse(m.text),\n ...cc(m.id),\n });\n break;\n case \"tool-result\":\n current.blocks.push({\n type: \"tool_result\",\n tool_use_id: m.toolCallId ?? \"\",\n content: m.text ?? \"\",\n ...(m.toolIsError ? { is_error: true } : {}),\n ...cc(m.id),\n });\n break;\n case \"reasoning\":\n current.blocks.push({\n type: \"thinking\",\n thinking: m.text ?? \"\",\n ...(m.thinkingSignature ? { signature: m.thinkingSignature } : {}),\n });\n break;\n }\n }\n flush();\n return out;\n}\n\n/** Extract the conversation dimension for Anthropic: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. The protocol+upstream+key dimensions are mixed in by the caller\n * (server.ts) via deriveSessionId() — this function contributes only the\n * conversation axis. */\nexport function conversationSignalAnthropic(body: AnthropicRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? JSON.stringify(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v ?? {});\n } catch {\n return \"{}\";\n }\n}\n\nfunction safeParse(s: string | undefined): unknown {\n if (!s) return {};\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n","/** Inline \"demoted thinking\" normalization.\n *\n * Hosts that cannot replay prior-turn reasoning as a structured block\n * (pi-ai transform-messages demotion on model switch, openai-completions\n * `requiresThinkingAsText` profiles, gateways that inline native\n * reasoning) fold it INTO the assistant content string wrapped in a\n * dialect tag:\n *\n * glm / deepseek / kimi / qwen3 / hermes : <think>\\n{text}\\n</think>\n * anthropic / minimax / xml : <thinking>\\n{text}\\n</thinking>\n * gemini : ```thinking\\n{text}\\n```\n *\n * followed by a single \"\\n\" glue before the next content block. The same\n * logical turn can therefore arrive as a `reasoning_content` field (or a\n * separate reasoning item on /v1/responses) OR as this inline form. If the\n * wire codecs kept both as one text blob, the two serializations of one\n * turn would land in DIFFERENT core-id/fingerprint spaces — exactly the\n * issue #64 \"restart loses blocks\" class, where the mirror produced one\n * form and the live wire the other.\n *\n * splitDemotedThinking() reverses the rendering byte-exactly so both\n * codecs can normalize before identity derivation (deriveMessageId). It\n * only fires when the tag opens at offset 0 of the content, which is the\n * only position the demotion renderer can produce it in.\n *\n * One form is intentionally NOT recoverable here: the pi-ai anthropic\n * dialect demotes to BARE text (no tag), which is indistinguishable from\n * ordinary assistant prose; that case must be aligned upstream (mirror\n * uses the same bare rendering), not parsed. */\n\nexport type DemotedSplit = {\n reasoning: string;\n text: string;\n};\n\ntype DelimitedForm = {\n open: string;\n close: string;\n};\n\n/** The three inline tag forms hosts actually emit (see file comment). */\nconst FORMS: readonly DelimitedForm[] = [\n { open: \"<think>\\n\", close: \"\\n</think>\" },\n { open: \"<thinking>\\n\", close: \"\\n</thinking>\" },\n { open: \"```thinking\\n\", close: \"\\n```\" },\n];\n\n/** If `content` starts with one or more inline demoted-thinking blocks,\n * split them out. Returns null when no tag opens the content (the common\n * case — including every user message and every assistant message whose\n * reasoning traveled as a field/item), in which case callers keep the\n * content as-is. Malformed (unterminated) or empty blocks do not match;\n * the content is then treated as plain text, never dropped. */\nexport function splitDemotedThinking(content: string): DemotedSplit | null {\n let rest = content;\n const parts: string[] = [];\n for (;;) {\n let matched = false;\n for (const form of FORMS) {\n if (!rest.startsWith(form.open)) continue;\n const end = rest.indexOf(form.close, form.open.length);\n if (end < 0) continue;\n const inner = rest.slice(form.open.length, end);\n if (inner.length === 0) continue;\n parts.push(inner);\n rest = rest.slice(end + form.close.length);\n // Glue the demotion renderer inserts between a demoted block\n // and the block that follows it.\n if (rest.startsWith(\"\\n\")) rest = rest.slice(1);\n matched = true;\n break;\n }\n if (!matched) break;\n }\n if (parts.length === 0) return null;\n return { reasoning: parts.join(\"\\n\"), text: rest };\n}\n","/**\n * Lossless message bridge between protocol-specific message formats and the\n * kernel's CoreMessage.\n *\n * Problem: `anthropicToCore` / `openaiToCore` / `responsesToCore` flatten\n * rich protocol blocks (images, thinking signatures, tool_result.is_error,\n * developer-role messages, image_url) into plain `{ text }` placeholders.\n * The reverse `coreToX` then can't reconstruct them — `is_error` is lost\n * (upstream can't tell a tool error from a result), `thinking.signature` is\n * lost (Anthropic rejects thinking blocks without a matching signature),\n * images become \"[image]\" (the model never sees the picture).\n *\n * Solution: `BiliMessage` extends CoreMessage with optional sidecar fields.\n * The kernel only reads `{ ...message }` (spread copy) and known fields, so\n * the extra fields survive the compression pipeline unchanged and arrive back\n * at `coreToX`, which prefers them over the flattened `text`. No `as any`\n * needed — TypeScript array covariance lets `BiliMessage[]` satisfy a\n * `CoreMessage[]` parameter.\n */\n\nimport type { CoreMessage } from \"acp-kernel\";\n\n/** A message that carries its original protocol block(s) verbatim, so the\n * reverse conversion can reconstruct losslessly. Every field is optional —\n * plain text messages (the common case) have none set. */\nexport interface BiliMessage extends CoreMessage {\n /** Anthropic: the original content block for an image or a structured\n * tool_result. Restored verbatim by coreToAnthropic. */\n rawAnthropicBlock?: unknown;\n /** OpenAI chat: the original content part for an image_url, or the\n * original message object for a developer-role message. */\n rawOpenaiContent?: unknown;\n /** Responses API: the original input item (for input_image, or a raw\n * function_call / function_call_output we pass through). */\n rawResponsesItem?: unknown;\n /** Anthropic thinking signature. Anthropic verifies thinking+signature\n * pairs; without it the request is rejected. Stored alongside the\n * reasoning text so coreToAnthropic can reattach it. */\n thinkingSignature?: string;\n /** OpenAI reasoning_content (chain-of-thought from DeepSeek-R1, GLM-4.6\n * thinking, Qwen-QwQ). These models require reasoning_content be echoed\n * back on subsequent requests or the API returns HTTP 400; stored so\n * coreToOpenai can reattach it. */\n reasoningContent?: string;\n /** Anthropic tool_result.is_error. Marks the tool result as an error so\n * the model knows the tool failed (not just returned an error string). */\n toolIsError?: boolean;\n /** OpenAI: original role was \"developer\" (reconstructed as \"system\" by\n * openaiToCore for the kernel; coreToOpenai restores \"developer\"). */\n originalRole?: \"system\" | \"developer\";\n /** The original media type for an image (image/png, image/jpeg, image/gif,\n * image/webp). Lets coreToOpenai/coreToResponses rebuild image_url /\n * input_image with the right data URL. */\n imageMediaType?: string;\n /** The base64 data of an image (without the data: prefix). Lets the\n * reverse conversion rebuild the full image payload. */\n imageBase64?: string;\n /** OpenAI chat: ALL original image_url content parts (each a data: URL\n * part) for a user message carrying more than one image, in wire order.\n * coreToOpenai re-emits these verbatim (after the text part). The\n * singular `rawOpenaiContent` still covers the single-image case and\n * legacy persisted state. Typed as unknown[] (not OpenAIContentPart) to\n * avoid a circular import with the openai codec. */\n rawOpenaiContentParts?: unknown[];\n}\n\n/** Narrow a BiliMessage[] to CoreMessage[] for the kernel. The sidecar fields\n * are transparently carried along — the kernel's `{ ...msg }` copies them. */\nexport function toCoreMessages(msgs: BiliMessage[]): CoreMessage[] {\n return msgs as CoreMessage[];\n}\n\n/** Re-decode a base64 data URL into media type + data. Returns undefined if\n * the input is not a recognized data URL. Used by openaiToCore/responsesToCore\n * to split image_url/input_image into the sidecar fields. */\nexport function parseDataUrl(url: string): { mediaType: string; base64: string } | undefined {\n const m = /^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);\n if (!m) return undefined;\n return { mediaType: m[1]!, base64: m[2]! };\n}\n","import { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type OpenAIContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } }\n | { type: string; [k: string]: unknown };\n\nexport type OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type OpenAIMessage = {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | null | OpenAIContentPart[];\n reasoning_content?: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n name?: string;\n};\n\nexport type OpenAITool = {\n type: \"function\";\n function: { name: string; description?: string; parameters?: unknown };\n};\n\nexport type OpenAIRequestBody = {\n model?: string;\n messages: OpenAIMessage[];\n tools?: OpenAITool[];\n stream?: boolean;\n [key: string]: unknown;\n};\n\ntype Flat = { msgs: BiliMessage[]; systemText: string };\n\n/** Hoist the contiguous leading system/developer prefix out of the fold\n * space (openai-chat variant of the responses codec's systemParts and the\n * anthropic codec's top-level `system` field). The system prompt is host\n * runtime state: its content varies across restarts (injected reminders,\n * host-composed instructions), so keeping it inside the id space made every\n * downstream fingerprint spanning it unstable, and a compress range that\n * covered it removed the model's system prompt from the rebuilt wire\n * entirely. Mid-conversation system messages (rare, host-synthetic) stay in\n * the fold space unchanged. */\nexport function openaiToCore(body: OpenAIRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n switch (m.role) {\n case \"system\":\n case \"developer\": {\n if (msgs.length === 0) {\n systemParts.push(stringContent(m.content));\n break;\n }\n const base = deriveMessageId(m.role, \"text\", stringContent(m.content));\n msgs.push({ id: clusters.next(base), role: \"system\", contentType: \"text\", text: stringContent(m.content), originalRole: m.role });\n break;\n }\n case \"user\": {\n const text = stringContent(m.content);\n const imgs = allImageParts(m.content);\n const firstImg = imgs[0];\n const firstUrl = firstImg ? firstImg.image_url.url : undefined;\n const firstParsed = firstUrl ? parseDataUrl(firstUrl) : undefined;\n const base = deriveMessageId(\"user\", \"text\", text);\n msgs.push({\n id: clusters.next(base),\n role: \"user\",\n contentType: \"text\",\n text,\n ...(imgs.length === 1 && firstParsed\n ? { rawOpenaiContent: imgs[0], imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 }\n : imgs.length > 1\n ? { rawOpenaiContentParts: imgs }\n : {}),\n });\n break;\n }\n case \"assistant\": {\n const fieldReasoning = typeof m.reasoning_content === \"string\" ? m.reasoning_content : \"\";\n let reasoning = fieldReasoning;\n let text = stringContent(m.content);\n if (!reasoning) {\n // Hosts that cannot replay prior-turn reasoning as a\n // structured field inline it into content wrapped in a\n // dialect tag (<think>, <thinking>, ```thinking). Split\n // it back out BEFORE identity derivation so the inline\n // form and the reasoning_content field form of one turn\n // land in a single core-id/fingerprint space (issue #64\n // demoted variant).\n const split = splitDemotedThinking(text);\n if (split) {\n reasoning = split.reasoning;\n text = split.text;\n }\n }\n if (reasoning) {\n const base = deriveMessageId(\"assistant\", \"reasoning\", reasoning);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: reasoning,\n reasoningContent: reasoning,\n });\n }\n if (text) {\n const base = deriveMessageId(\"assistant\", \"text\", text);\n msgs.push({ id: clusters.next(base), role: \"assistant\", contentType: \"text\", text });\n }\n if (Array.isArray(m.tool_calls)) {\n for (const tc of m.tool_calls) {\n const base = deriveMessageId(\"assistant\", \"tool-call\", tc.function.arguments ?? \"\", {\n toolCallId: tc.id,\n toolName: tc.function.name,\n });\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: tc.function.name,\n toolCallId: tc.id,\n text: tc.function.arguments ?? \"\",\n });\n }\n }\n break;\n }\n case \"tool\": {\n const base = deriveMessageId(\"tool\", \"tool-result\", stringContent(m.content), {\n toolCallId: m.tool_call_id ?? \"\",\n });\n msgs.push({\n id: clusters.next(base),\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: m.tool_call_id ?? \"\",\n text: stringContent(m.content),\n });\n break;\n }\n }\n }\n return { msgs, systemText: systemParts.join(\"\\n\\n\") };\n}\n\nexport function coreToOpenai(messages: BiliMessage[]): OpenAIMessage[] {\n const out: OpenAIMessage[] = [];\n let pending: { text: string | null; toolCalls: OpenAIToolCall[]; reasoning: string | null } | null = null;\n const flush = () => {\n if (!pending) return;\n const reasoning = pending.reasoning !== null && pending.reasoning.length > 0 ? pending.reasoning : undefined;\n if (pending.toolCalls.length > 0) {\n out.push({\n role: \"assistant\",\n content: pending.text ?? null,\n tool_calls: pending.toolCalls,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n });\n } else if (pending.text !== null) {\n out.push({ role: \"assistant\", content: pending.text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n } else if (reasoning) {\n out.push({ role: \"assistant\", content: null, reasoning_content: reasoning });\n }\n pending = null;\n };\n for (const m of messages) {\n if (m.role === \"assistant\") {\n if (!pending) pending = { text: null, toolCalls: [], reasoning: null };\n if (m.contentType === \"reasoning\") {\n pending.reasoning = (pending.reasoning ?? \"\") + (m.reasoningContent ?? m.text ?? \"\");\n } else if (m.contentType === \"text\") {\n pending.text = (pending.text ?? \"\") + (m.text ?? \"\");\n } else if (m.contentType === \"tool-call\") {\n pending.toolCalls.push({\n id: m.toolCallId ?? `call_${m.id}`,\n type: \"function\",\n function: { name: m.toolName ?? \"unknown\", arguments: m.text ?? \"\" },\n });\n }\n } else {\n flush();\n if (m.role === \"system\") {\n out.push({ role: m.originalRole === \"developer\" ? \"developer\" : \"system\", content: m.text ?? \"\" });\n } else if (m.role === \"user\") {\n if (m.rawOpenaiContent || m.imageBase64 || m.rawOpenaiContentParts) {\n const parts: OpenAIContentPart[] = [];\n if (m.text) parts.push({ type: \"text\", text: m.text });\n if (m.rawOpenaiContentParts && m.rawOpenaiContentParts.length > 0) {\n for (const part of m.rawOpenaiContentParts) parts.push(part as OpenAIContentPart);\n } else if (m.rawOpenaiContent) {\n parts.push(m.rawOpenaiContent as OpenAIContentPart);\n } else if (m.imageBase64 && m.imageMediaType) {\n parts.push({ type: \"image_url\", image_url: { url: `data:${m.imageMediaType};base64,${m.imageBase64}` } });\n }\n out.push({ role: \"user\", content: parts });\n } else {\n out.push({ role: \"user\", content: m.text ?? \"\" });\n }\n } else if (m.role === \"tool\") {\n out.push({ role: \"tool\", tool_call_id: m.toolCallId ?? \"\", content: m.text ?? \"\" });\n }\n }\n }\n flush();\n return out;\n}\n\nexport function injectOpenaiSystem(messages: OpenAIMessage[], parts: string[]): OpenAIMessage[] {\n if (parts.length === 0) return messages;\n const extra = parts.join(\"\\n\\n\");\n if (messages.length > 0 && (messages[0]?.role === \"system\" || messages[0]?.role === \"developer\")) {\n const head = messages[0] as OpenAIMessage;\n const base = stringContent(head.content);\n const merged = base ? `${base}\\n\\n---\\n\\n${extra}` : extra;\n return [{ ...head, content: merged }, ...messages.slice(1)];\n }\n return [{ role: \"system\", content: extra }, ...messages];\n}\n\n/** Extract the conversation dimension for OpenAI Chat: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. See conversationSignalAnthropic for the full rationale. */\nexport function conversationSignalOpenai(body: OpenAIRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? stringContent(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction stringContent(content: OpenAIMessage[\"content\"]): string {\n if (content == null) return \"\";\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((p) => (typeof p === \"string\" ? p : p.type === \"text\" ? (p as { text?: string }).text ?? \"\" : \"\"))\n .join(\"\\n\");\n }\n return \"\";\n}\n\ntype OpenAIImagePart = { type: \"image_url\"; image_url: { url: string } };\n\n/** Collect ALL data-URL image parts in a user content array, in wire order.\n * (firstImagePart only kept the first, which silently dropped images 2..N\n * on the coreToOpenai rebuild.) */\nfunction allImageParts(content: OpenAIMessage[\"content\"]): OpenAIImagePart[] {\n if (!Array.isArray(content)) return [];\n const out: OpenAIImagePart[] = [];\n for (const p of content) {\n if (typeof p !== \"object\" || p === null) continue;\n if (!(\"type\" in p) || p.type !== \"image_url\" || !(\"image_url\" in p)) continue;\n // The union's index-signature member leaves image_url as `unknown`, so\n // narrow via a named const before reading the url.\n const imagePart = p as { image_url: { url?: unknown } };\n const url = imagePart.image_url.url;\n if (typeof url === \"string\" && parseDataUrl(url)) out.push(p as OpenAIImagePart);\n }\n return out;\n}\n","import type { CoreMessage } from \"../types.js\";\nimport { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport type { ConversationIdentity } from \"./util.js\";\nimport { hashId } from \"./util.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type ResponseContentPart =\n | { type: \"input_text\"; text: string; [key: string]: unknown }\n | { type: \"output_text\"; text: string; [key: string]: unknown }\n | { type: \"input_image\"; image_url: string; [key: string]: unknown }\n | { type: string; [key: string]: unknown };\n\nexport type ResponseInputMessage = {\n type: \"message\";\n role: \"system\" | \"developer\" | \"user\" | \"assistant\";\n content: string | ResponseContentPart[];\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCall = {\n type: \"function_call\";\n id?: string;\n call_id: string;\n name: string;\n arguments: string;\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCallOutput = {\n type: \"function_call_output\";\n call_id: string;\n output: string;\n [key: string]: unknown;\n};\n\nexport type ResponseInputItem =\n | ResponseInputMessage\n | ResponseFunctionCall\n | ResponseFunctionCallOutput\n | { type: string; [key: string]: unknown };\n\nexport type ResponsesRequestBody = {\n model?: string;\n input: string | ResponseInputItem[];\n instructions?: string;\n tools?: unknown[];\n stream?: boolean;\n session_id?: string;\n previous_response_id?: string;\n prompt_cache_key?: string;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype ResponseLayoutSlot = {\n original: ResponseInputItem;\n coreId?: string;\n};\n\nexport type ResponsesProjection = {\n msgs: BiliMessage[];\n systemParts: string[];\n preamble: ResponseInputItem[];\n customToolCallIds: Set<string>;\n layout: ResponseLayoutSlot[];\n stringInput?: { original: string; coreId: string };\n /** Reasoning items dropped because ACP_REASONING_KEEP=none. 0 by default —\n * reasoning is normally routed through the compression pipeline so it is\n * hidden automatically once its turn is summarized. */\n droppedReasoning: number;\n};\n\n/** Item types that are host DIRECTIVES (tool/definition listings), not\n * conversation history: preserved verbatim and re-prepended at input[0..].\n * `additional_tools` carries the Codex code_mode exec/wait tool definitions\n * and MUST stay at input[0]. `mcp_list_tools` is a stable per-session listing.\n *\n * Only definitions belong here. Output/action items from a prior response\n * (reasoning, computer_call, function_call, mcp_call, ...) ARE conversation\n * history and are routed as tracked BiliMessages, so the compression pipeline\n * hides them once their turn is summarized — preserving them verbatim in the\n * preamble instead made them accumulate unbounded every turn and broke Codex's\n * prompt-cache prefix. */\nconst OPAQUE_ITEM_TYPES = new Set([\n \"additional_tools\",\n \"mcp_list_tools\",\n]);\n\nfunction isOpaqueItem(item: ResponseInputItem): boolean {\n return OPAQUE_ITEM_TYPES.has(item.type);\n}\n\nfunction shouldDropAllReasoning(): boolean {\n return (process.env.ACP_REASONING_KEEP ?? \"\").trim().toLowerCase() === \"none\";\n}\n\nfunction partText(part: ResponseContentPart): string {\n if (part.type === \"input_text\" || part.type === \"output_text\") {\n return typeof part.text === \"string\" ? part.text : \"\";\n }\n return \"\";\n}\n\nfunction messageContent(content: string | ResponseContentPart[]): string {\n return typeof content === \"string\" ? content : content.map(partText).join(\"\\n\");\n}\n\n/** Extract the reasoning text from a responses reasoning item. The host\n * carries it in `content` (reasoning_text parts); the primeFold mirror\n * carries it in `summary` (summary_text parts). Both must yield the same\n * text so the kernel derives the same core id (issue #64, responses). */\nfunction reasoningText(item: ResponseInputItem): string {\n const fromParts = (parts: unknown, type: string): string => {\n if (!Array.isArray(parts)) return \"\";\n const texts: string[] = [];\n for (const part of parts) {\n if (part && typeof part === \"object\" && \"type\" in part && \"text\" in part) {\n const rec = part as { type: unknown; text: unknown };\n if (rec.type === type && typeof rec.text === \"string\") texts.push(rec.text);\n }\n }\n return texts.join(\"\\n\");\n };\n const content = \"content\" in item ? item.content : undefined;\n const summary = \"summary\" in item ? item.summary : undefined;\n return fromParts(content, \"reasoning_text\") || fromParts(summary, \"summary_text\");\n}\n\nexport function responsesToCore(body: ResponsesRequestBody): ResponsesProjection {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const preamble: ResponseInputItem[] = [];\n const customToolCallIds = new Set<string>();\n const layout: ResponseLayoutSlot[] = [];\n let droppedReasoning = 0;\n const clusters = new ClusterCounter();\n let idx = 0;\n if (typeof body.instructions === \"string\" && body.instructions.trim()) systemParts.push(body.instructions);\n if (typeof body.input === \"string\") {\n const id = clusters.next(deriveMessageId(\"user\", \"text\", body.input));\n msgs.push({ id, role: \"user\", contentType: \"text\", text: body.input });\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning, stringInput: { original: body.input, coreId: id } };\n }\n for (const item of body.input) {\n let coreId: string | undefined;\n if (isOpaqueItem(item)) preamble.push(item);\n switch (item.type) {\n case \"reasoning\": {\n if (shouldDropAllReasoning()) {\n droppedReasoning++;\n continue;\n }\n // Key the reasoning piece on its TEXT (deterministic), consistent\n // with the anthropic/openai codecs. The host mints a per-request\n // item id that the primeFold mirror cannot reproduce; keying on it\n // put the mirror in a different ref/fingerprint space, so restart\n // replay rejected every in-stream compress call (issue #64,\n // responses variant).\n const text = reasoningText(item);\n const rid =\n text.length > 0\n ? text\n : \"id\" in item && typeof item.id === \"string\"\n ? item.id\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"reasoning\", rid));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"reasoning\",\n text: rid,\n rawResponsesItem: item,\n });\n break;\n }\n case \"message\": {\n const message = item as ResponseInputMessage;\n const text = messageContent(message.content);\n if (message.role === \"system\" || message.role === \"developer\") {\n systemParts.push(text);\n idx++;\n continue;\n } else if (message.role === \"user\" || (message.role === \"assistant\" && text)) {\n const role = message.role;\n let effText = text;\n if (role === \"assistant\") {\n // Same normalization as openaiToCore: hosts that demote\n // prior-turn reasoning inline it as a dialect tag at the\n // head of the message text. Split it out before identity\n // derivation so the inline form and the separate\n // reasoning-item form of one turn share a single\n // core-id/fingerprint space.\n const split = splitDemotedThinking(text);\n if (split) {\n msgs.push({\n id: clusters.next(deriveMessageId(\"assistant\", \"reasoning\", split.reasoning)),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: split.reasoning,\n rawResponsesItem: item,\n });\n effText = split.text;\n }\n }\n if (effText) {\n coreId = clusters.next(deriveMessageId(role, \"text\", effText));\n const imageUrl = Array.isArray(message.content)\n ? message.content.find((part) => part.type === \"input_image\" && typeof part.image_url === \"string\")?.image_url\n : undefined;\n const image = typeof imageUrl === \"string\" ? parseDataUrl(imageUrl) : undefined;\n msgs.push({\n id: coreId,\n role,\n contentType: \"text\",\n text: effText,\n rawResponsesItem: item,\n ...(image ? { imageMediaType: image.mediaType, imageBase64: image.base64 } : {}),\n });\n }\n }\n break;\n }\n case \"function_call\": {\n const call = item as ResponseFunctionCall;\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", call.arguments ?? \"\", {\n toolCallId: call.call_id,\n toolName: call.name,\n }));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: call.name,\n toolCallId: call.call_id,\n text: call.arguments ?? \"\",\n rawResponsesItem: item,\n });\n break;\n }\n case \"function_call_output\": {\n const output = item as ResponseFunctionCallOutput;\n const text = typeof output.output === \"string\" ? output.output : JSON.stringify(output.output);\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: output.call_id }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: output.call_id, text, rawResponsesItem: item });\n break;\n }\n case \"computer_call\":\n case \"computer_call_output\":\n case \"file_search_call\":\n case \"web_search_call\":\n case \"image_generation_call\":\n case \"code_interpreter_call\":\n case \"mcp_call\": {\n const rid =\n typeof (item as { id?: unknown }).id === \"string\"\n ? String((item as { id?: string }).id)\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"responses-call\", rid));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"reasoning\", text: rid, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call\": {\n const ctc = item as { call_id?: string; name?: string; input?: string; arguments?: string };\n const callId = ctc.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const argText = ctc.input ?? ctc.arguments ?? \"\";\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", argText, { toolCallId: callId, toolName: ctc.name ?? \"custom\" }));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"tool-call\", toolName: ctc.name ?? \"custom\", toolCallId: callId, text: argText, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call_output\": {\n const ctco = item as { call_id?: string; output?: string };\n const callId = ctco.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const outText = typeof ctco.output === \"string\" ? ctco.output : JSON.stringify(ctco.output ?? \"\");\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", outText, { toolCallId: callId }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: callId, text: outText, rawResponsesItem: item });\n break;\n }\n default:\n if (!isOpaqueItem(item)) preamble.push(item);\n break;\n }\n layout.push({ original: item, coreId });\n idx++;\n }\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning };\n}\n\nfunction patchTextParts(parts: ResponseContentPart[], text: string): ResponseContentPart[] {\n const textIndexes = parts.flatMap((part, index) =>\n part.type === \"input_text\" || part.type === \"output_text\" ? [index] : [],\n );\n if (textIndexes.length === 0) return [{ type: \"input_text\", text }, ...parts];\n const first = textIndexes[0];\n const remaining = new Set(textIndexes.slice(1));\n return parts.map((part, index) => {\n if (index === first) return { ...part, text };\n if (remaining.has(index)) return { ...part, text: \"\" };\n return part;\n });\n}\n\nfunction patchOriginalItem(original: ResponseInputItem, source: CoreMessage, next: CoreMessage): ResponseInputItem {\n if (\n source.text === next.text &&\n source.toolName === next.toolName &&\n source.toolCallId === next.toolCallId &&\n source.role === next.role &&\n source.contentType === next.contentType\n ) return original;\n if (original.type === \"message\") {\n const message = original as ResponseInputMessage;\n const content = typeof message.content === \"string\" ? next.text ?? \"\" : patchTextParts(message.content, next.text ?? \"\");\n return { ...message, content };\n }\n if (original.type === \"function_call\") {\n return {\n ...original,\n name: next.toolName ?? String(original.name ?? \"unknown\"),\n call_id: next.toolCallId ?? String(original.call_id ?? \"\"),\n arguments: next.text ?? \"\",\n };\n }\n if (original.type === \"function_call_output\") {\n return { ...original, call_id: next.toolCallId ?? String(original.call_id ?? \"\"), output: next.text ?? \"\" };\n }\n return original;\n}\n\nexport function patchResponsesInput(projection: ResponsesProjection, messages: CoreMessage[]): string | ResponseInputItem[] {\n if (projection.stringInput) {\n const original = projection.msgs.find((message) => message.id === projection.stringInput?.coreId);\n const next = messages.find((message) => message.id === projection.stringInput?.coreId);\n if (original && next && messages.length === 1 && next.role === \"user\" && next.contentType === \"text\") {\n return next.text === original.text ? projection.stringInput.original : next.text ?? \"\";\n }\n return coreToResponses(messages, projection.customToolCallIds);\n }\n const sourceById = new Map(projection.msgs.map((message) => [message.id, message]));\n const nextById = new Map(messages.map((message) => [message.id, message]));\n const slotById = new Map<string, number>();\n projection.layout.forEach((slot, index) => {\n if (slot.coreId) slotById.set(slot.coreId, index);\n });\n const insertions = new Map<number, ResponseInputItem[]>();\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (sourceById.has(message.id)) continue;\n let target = projection.layout.length;\n for (let nextIndex = index + 1; nextIndex < messages.length; nextIndex++) {\n const slot = slotById.get(messages[nextIndex]!.id);\n if (slot !== undefined) {\n target = slot;\n break;\n }\n }\n const generated = coreToResponses([message], projection.customToolCallIds);\n if (generated.length > 0) insertions.set(target, [...(insertions.get(target) ?? []), ...generated]);\n }\n const out: ResponseInputItem[] = [];\n projection.layout.forEach((slot, index) => {\n out.push(...(insertions.get(index) ?? []));\n if (!slot.coreId) {\n out.push(slot.original);\n return;\n }\n const source = sourceById.get(slot.coreId);\n const next = nextById.get(slot.coreId);\n if (source && next) out.push(patchOriginalItem(slot.original, source, next));\n });\n out.push(...(insertions.get(projection.layout.length) ?? []));\n return out;\n}\n\nexport function coreToResponses(\n messages: CoreMessage[],\n customToolCallIds: Set<string> = new Set(),\n): ResponseInputItem[] {\n const out: ResponseInputItem[] = [];\n for (const message of messages) {\n const biliMessage = message as BiliMessage;\n const raw = biliMessage.rawResponsesItem as ResponseInputItem | undefined;\n if (message.role === \"system\") {\n out.push({ type: \"message\", role: \"developer\", content: message.text ?? \"\" });\n } else if (message.role === \"user\") {\n if (raw?.type === \"message\" && messageContent((raw as ResponseInputMessage).content) === (message.text ?? \"\")) out.push(raw);\n else out.push({ type: \"message\", role: \"user\", content: message.text ?? \"\" });\n } else if (message.role === \"assistant\") {\n if (message.contentType === \"text\") {\n out.push({ type: \"message\", role: \"assistant\", content: message.text ?? \"\" });\n } else if (message.contentType === \"tool-call\") {\n const callId = message.toolCallId ?? `call_${message.id}`;\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call\", call_id: callId, name: message.toolName ?? \"unknown\", input: message.text ?? \"\", status: \"completed\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call\", call_id: callId, name: message.toolName ?? \"unknown\", arguments: message.text ?? \"\" });\n }\n } else if (message.contentType === \"reasoning\") {\n if (raw) out.push(raw);\n }\n } else if (message.role === \"tool\") {\n const callId = message.toolCallId ?? \"\";\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call_output\", call_id: callId, output: message.text ?? \"\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call_output\", call_id: callId, output: message.text ?? \"\" });\n }\n }\n }\n return out;\n}\n\nexport function injectResponsesDeveloperMessage(\n input: string | ResponseInputItem[],\n content: string,\n): ResponseInputItem[] {\n const items: ResponseInputItem[] = typeof input === \"string\"\n ? [{ type: \"message\", role: \"user\", content: input }]\n : [...input];\n let index = 0;\n while (items[index]?.type === \"additional_tools\") index++;\n items.splice(index, 0, { type: \"message\", role: \"developer\", content });\n return items;\n}\n\nexport function conversationIdentityResponses(\n body: ResponsesRequestBody,\n headerValue?: string,\n): ConversationIdentity {\n if (headerValue?.trim()) return { value: headerValue.trim(), source: \"header\", clientProvided: true };\n if (typeof body.session_id === \"string\" && body.session_id.trim()) {\n return { value: body.session_id.trim(), source: \"body-session\", clientProvided: true };\n }\n const metadataSession = body.metadata?.session_id;\n if (typeof metadataSession === \"string\" && metadataSession.trim()) {\n return { value: metadataSession.trim(), source: \"metadata-session\", clientProvided: true };\n }\n if (typeof body.previous_response_id === \"string\" && body.previous_response_id.trim()) {\n return { value: body.previous_response_id.trim(), source: \"previous-response\", clientProvided: false };\n }\n return { value: hashId(JSON.stringify(body.input ?? [])), source: \"content-fingerprint\", clientProvided: false };\n}\n\nexport function conversationSignalResponses(body: ResponsesRequestBody, headerValue?: string): string {\n return conversationIdentityResponses(body, headerValue).value;\n}\n\n// Codex subagents (guardian approval reviewer, etc.) reuse the main\n// conversation's body.session_id, so identity alone collapses their requests\n// onto the main session's compression state — a compressed subagent request\n// loses the verbatim user authorization it must read back (#150). Subagent\n// requests carry their own `instructions` (the agent's role prompt), so the\n// FIRST instructions seen for an identity anchor the main namespace (it never\n// changes for the conversation, even if the main prompt drifts), and any other\n// instructions value maps to a separate `|sub:` namespace with its own empty\n// compression state. Subagent requests are self-contained replays, so the\n// fresh namespace is lossless.\nexport interface SubagentNamespaces {\n /** Resolve the compression-state namespace for a request: the identity\n * itself for the anchored (main) instructions, `identity|sub:<fp>` for\n * any other instructions value. First-seen instructions anchor. */\n namespaceFor(identityValue: string, instructions: unknown): string;\n}\n\n/** Host-owned subagent-namespace store.\n *\n * The anchor map is per-conversation mutable state, so it belongs to the\n * host — NOT to a library module global. Create one instance and keep it for\n * the process lifetime (or persist it alongside your session store if you\n * need namespaces to survive restarts: a fresh instance re-anchors on the\n * first request it sees, which after a restart may be a subagent request,\n * orphaning the main conversation's stored compression state). */\nexport function createSubagentNamespaces(): SubagentNamespaces {\n const anchors = new Map<string, string>();\n return {\n namespaceFor(identityValue: string, instructions: unknown): string {\n if (typeof instructions !== \"string\" || instructions.trim().length === 0) return identityValue;\n const fp = hashId(instructions);\n const anchor = anchors.get(identityValue);\n if (anchor === undefined) {\n anchors.set(identityValue, fp);\n return identityValue;\n }\n return anchor === fp ? identityValue : `${identityValue}|sub:${fp}`;\n },\n };\n}\n\n// Convenience singleton for single-process proxies that don't manage\n// per-session state themselves. Hosts needing isolation between\n// conversations, deterministic namespaces across restarts, or a bound on\n// anchor memory should create their own instance via\n// createSubagentNamespaces() and own its lifecycle.\nconst defaultNamespaces = createSubagentNamespaces();\n\nexport function subagentNamespace(identityValue: string, instructions: unknown): string {\n return defaultNamespaces.namespaceFor(identityValue, instructions);\n}\n","export const WIRE_FORMATS = [\"anthropic\", \"openai\", \"responses\"] as const;\nexport type WireFormat = (typeof WIRE_FORMATS)[number];\n\nexport function isWireFormat(value: unknown): value is WireFormat {\n return (\n typeof value === \"string\" &&\n (WIRE_FORMATS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Classify a provider request body by the codec that can parse it.\n * Returns undefined when no codec handles the body — the caller must\n * pass such payloads through untransformed.\n */\nexport function detectWireFormat(payload: unknown): WireFormat | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const p = payload as Record<string, unknown>;\n if (Array.isArray(p.input)) return \"responses\";\n const messages = p.messages;\n if (!Array.isArray(messages)) return undefined;\n if (\"system\" in p || \"anthropic_version\" in p) return \"anthropic\";\n for (const m of messages as Array<Record<string, unknown>>) {\n if (m === null || typeof m !== \"object\") continue;\n const c = m.content;\n if (Array.isArray(c)) {\n for (const b of c as Array<Record<string, unknown>>) {\n if (b && typeof b === \"object\" && typeof b.type === \"string\") {\n if (\n b.type === \"tool_use\" ||\n b.type === \"tool_result\" ||\n b.type === \"thinking\"\n )\n return \"anthropic\";\n if (b.type === \"text\" && \"cache_control\" in b) return \"anthropic\";\n }\n }\n }\n if (Array.isArray(m.tool_calls)) return \"openai\";\n if (m.role === \"tool\" && typeof m.tool_call_id === \"string\")\n return \"openai\";\n if (m.role === \"system\" || m.role === \"developer\") return \"openai\";\n }\n // Both chat formats share role+messages; default to openai — the safer\n // guess for OpenAI-compatible endpoints (GLM, DeepSeek, vLLM).\n return \"openai\";\n}\n","import { anthropicToCore } from \"./anthropic.js\";\nimport { openaiToCore } from \"./openai.js\";\nimport { responsesToCore } from \"./responses.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/**\n * Mirror constructors: rebuild the WIRE-SHAPE projection of a persisted\n * conversation (the mirror of \"what the host will put on the wire after a\n * restart\") for each protocol family, then fold it through the matching\n * `*ToCore` codec so the projection lands in the same identity/fingerprint\n * space as the live request.\n *\n * This used to live as three hand-rolled builders in the omp plugin\n * (wire-fold.ts) — protocol knowledge scattered across consumers is exactly\n * how the issue-#64 class of restart divergences happened (one place fixed,\n * another broke). The wire layouts now live here, next to the codecs that\n * define their identity space.\n *\n * CONTRACT: the caller maps its own persisted message shape into\n * {@link MirrorMessage} FIRST and normalizes text there (e.g. ref-tag\n * stripping is a host-app concern, not a wire concern). Builders only apply\n * host-encoder wire rules:\n * - thinking rides each wire the way the live encoder sends it\n * (openai: `reasoning_content` field — hosts that demote inline as\n * `<think>…</think>` land in the same identity space anyway because\n * `openaiToCore` normalizes the inline form; anthropic: signed\n * `{type:\"thinking\"}` blocks; responses: `{type:\"reasoning\"}` items);\n * - whitespace-only text survives on the openai wire, is dropped on the\n * anthropic/responses wires (host encoder behaviour);\n * - tool calls/results map to each wire's native shape.\n */\n\nexport type MirrorBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"toolCall\"; id?: string; name?: string; arguments?: unknown };\n\nexport type MirrorMessage = {\n /** `meta` is anything the host sends as out-of-band/system-ish traffic. */\n role: \"user\" | \"assistant\" | \"toolResult\" | \"meta\";\n blocks?: MirrorBlock[];\n /** toolResult only. */\n toolCallId?: string;\n /** meta only: extracted text or summary. */\n text?: string;\n};\n\nfunction textBlocks(blocks: MirrorBlock[] | undefined): string[] {\n const out: string[] = [];\n for (const b of blocks ?? []) if (b.type === \"text\") out.push(b.text);\n return out;\n}\n\n/** Openai wire text: text blocks joined with \"\\n\" (whitespace-only kept). */\nfunction joinText(blocks: MirrorBlock[] | undefined): string {\n return textBlocks(blocks).join(\"\\n\");\n}\n\nfunction thinkingText(blocks: MirrorBlock[] | undefined): string {\n return blocks\n ?.filter((b) => b.type === \"thinking\" && b.thinking.trim().length > 0)\n .map((b) => (b as { thinking: string }).thinking)\n .join(\"\\n\") ?? \"\";\n}\n\n/** Openai/completions mirror: system message first, then the conversation\n * with thinking as the `reasoning_content` field (issue #103). */\nexport function mirrorOpenaiMessages(view: MirrorMessage[], systemText: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [{ role: \"system\", content: systemText }];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: text });\n } else if (message.role === \"assistant\") {\n const calls = (message.blocks ?? []).filter((b) => b.type === \"toolCall\") as Array<{ id?: string; name?: string; arguments?: unknown }>;\n const reasoning = thinkingText(message.blocks);\n const text = joinText(message.blocks);\n if (calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: text,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: calls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name ?? \"\", arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n });\n } else if (text || reasoning) {\n messages.push({ role: \"assistant\", content: text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n }\n } else if (message.role === \"toolResult\") {\n messages.push({ role: \"tool\", tool_call_id: message.toolCallId ?? \"\", content: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"developer\", content: text });\n }\n }\n return messages;\n}\n\n/** Anthropic/messages mirror: no system message (the live request carries it\n * as the top-level `system` field, out of the fold space — issue #64), tool\n * results folded into user messages, thinking as signed `{type:\"thinking\"}`\n * blocks (issue #103). Unsigned thinking is demoted to text by the live\n * encoder; sending it as a thinking block diverges, so callers that persist\n * unsigned thinking should send it as a text block instead. */\nexport function mirrorAnthropicMessages(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n } else if (message.role === \"assistant\") {\n const content: Array<Record<string, unknown>> = [];\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n content.push({\n type: \"thinking\",\n thinking: b.thinking,\n ...(typeof b.signature === \"string\" && b.signature ? { signature: b.signature } : {}),\n });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n content.push({ type: \"text\", text: b.text });\n } else if (b.type === \"toolCall\") {\n let input: unknown = {};\n try {\n input = b.arguments && typeof b.arguments === \"object\" ? b.arguments : JSON.parse(JSON.stringify(b.arguments ?? {}));\n } catch {\n input = {};\n }\n content.push({ type: \"tool_use\", id: b.id, name: b.name ?? \"\", input });\n }\n }\n if (content.length > 0) messages.push({ role: \"assistant\", content });\n } else if (message.role === \"toolResult\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: message.toolCallId ?? \"\", content: joinText(message.blocks) }],\n });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n }\n }\n return messages;\n}\n\n/** Responses mirror: the live /v1/responses request carries the system\n * prompt in the top-level `instructions` field and the conversation as an\n * `input` item array (issue #64, responses variant). Assistant blocks are\n * emitted in content order so the core sequence matches the live wire\n * (issue #103 parity). */\nexport function mirrorResponsesInput(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const input: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n } else if (message.role === \"assistant\") {\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n input.push({ type: \"reasoning\", summary: [{ type: \"summary_text\", text: b.thinking }] });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n input.push({ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: b.text }] });\n } else if (b.type === \"toolCall\") {\n let args = \"{}\";\n try {\n args = JSON.stringify(b.arguments ?? {});\n } catch {\n args = \"{}\";\n }\n input.push({ type: \"function_call\", call_id: b.id ?? \"\", name: b.name ?? \"\", arguments: args });\n }\n }\n } else if (message.role === \"toolResult\") {\n input.push({ type: \"function_call_output\", call_id: message.toolCallId ?? \"\", output: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n }\n }\n return input;\n}\n\n/** Fold the openai mirror through `openaiToCore`. */\nexport function mirrorOpenaiToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = openaiToCore({\n model: \"prime-fold\",\n messages: mirrorOpenaiMessages(view, systemText) as Parameters<typeof openaiToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the anthropic mirror through `anthropicToCore`. */\nexport function mirrorAnthropicToCore(view: MirrorMessage[]): BiliMessage[] {\n const { msgs } = anthropicToCore({\n model: \"prime-fold\",\n messages: mirrorAnthropicMessages(view) as Parameters<typeof anthropicToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the responses mirror through `responsesToCore`. */\nexport function mirrorResponsesToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = responsesToCore({\n model: \"prime-fold\",\n instructions: systemText,\n input: mirrorResponsesInput(view) as Parameters<typeof responsesToCore>[0][\"input\"],\n });\n return msgs;\n}\n","/**\n * Compress-call detection and replay-guard on the wire/core stream\n * (Phase K2, moved from billion-context-omp `src/wire-fold.ts`).\n *\n * Two layers:\n * - Detection: `compressToolArgs` accepts the two call shapes that exist in\n * the wild (direct `compress`; legacy `write` to `xd://compress`, args\n * JSON-encoded one or two levels deep), `findCompressCalls` /\n * `findCompressCallsCore` turn a stream tool-call into validated ranges.\n * - Guard: when compression state is REPLAYED against a rebuilt stream\n * (restart, mirror divergence, host re-serialization), every recorded\n * range must prove it still covers the same content — fingerprint match\n * (first/last piece content key), position fallback for drifted\n * boundaries, remap for dangling m-refs.\n *\n * Pure functions over BiliMessage/CoreMessage — no host types, no I/O.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { CoreMessage } from \"../types.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/** A compress call carried by a stream tool-call, normalized to validated\n * ranges. `id` is the tool-call id (replay dedup key). */\nexport interface StreamCompressCall {\n id: string;\n ranges: {\n startRef: string;\n endRef: string;\n summary: string;\n topic?: string;\n summaryMaxChars?: number;\n compressCallId: string;\n }[];\n}\n\n/** Extract a compress tool's arguments from a stream toolCall. Two call\n * shapes exist: (1) top-level — the tools are registered with\n * loadMode:\"essential\" so hosts do NOT mount them as xd:// devices; the\n * stream shows name:\"compress\" directly. (2) legacy xd:// — sessions\n * recorded before that change (or hosts forcing discoverable mounting)\n * invoked compress through the write tool with path \"xd://compress\" and\n * the tool args JSON-encoded in the content field. Both shapes must replay\n * from the stream. Returns normalized compress args (content array plus\n * optional topic / summaryMaxChars from wherever they live). */\nexport function compressToolArgs(call: { name: string; arguments?: unknown }): {\n content: unknown[];\n topic?: unknown;\n summaryMaxChars?: unknown;\n} | null {\n let args = call.arguments;\n if (typeof args === \"string\") {\n try { args = JSON.parse(args); } catch { return null; }\n }\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return null;\n const a = args as Record<string, unknown>;\n if (call.name === \"compress\") {\n return Array.isArray(a.content) ? { content: a.content, topic: a.topic, summaryMaxChars: a.summaryMaxChars } : null;\n }\n if (call.name !== \"write\") return null;\n const path = typeof a.path === \"string\" ? a.path.split(\"?\")[0]!.replace(/\\/+$/, \"\") : \"\";\n if (path !== \"xd://compress\") return null;\n let inner: unknown = a.content;\n if (typeof inner === \"string\") {\n try { inner = JSON.parse(inner); } catch { return null; }\n }\n if (!inner || typeof inner !== \"object\") return null;\n if (Array.isArray(inner)) return { content: inner };\n const ia = inner as Record<string, unknown>;\n return Array.isArray(ia.content) ? { content: ia.content, topic: ia.topic, summaryMaxChars: ia.summaryMaxChars } : { content: [ia] };\n}\n\n/** toolCallId → toolName for every tool-call piece (protected-piece\n * detection: compress + configured tools are never folded). */\nexport function toolCallNames(msgs: BiliMessage[]): Map<string, string> {\n const names = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType === \"tool-call\" && m.toolCallId && m.toolName) names.set(m.toolCallId, m.toolName);\n }\n return names;\n}\n\n/** toolCallId → result text for every tool-result piece (compress result\n * rendering inside rebuilt payloads). */\nexport function toolResultTextsCore(msgs: BiliMessage[]): Map<string, string> {\n const results = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType !== \"tool-result\" || !m.toolCallId) continue;\n results.set(m.toolCallId, m.text ?? \"\");\n }\n return results;\n}\n\n/** Compress calls carried by a core tool-call piece. Same two shapes as the\n * AgentMessage stream (direct compress; legacy xd://compress via write),\n * with the arguments JSON-encoded in the piece's text. */\nexport function findCompressCallsCore(msg: BiliMessage): StreamCompressCall[] {\n if (msg.contentType !== \"tool-call\" || !msg.toolName) return [];\n const args = compressToolArgs({ name: msg.toolName, arguments: msg.text });\n if (!args) return [];\n const content = args.content;\n if (!Array.isArray(content)) return [];\n const ranges: StreamCompressCall[\"ranges\"] = [];\n const callTopic = typeof args.topic === \"string\" ? args.topic : undefined;\n for (const item of content) {\n const r = item as { startId?: unknown; endId?: unknown; summary?: unknown; topic?: unknown };\n if (typeof r.startId !== \"string\" || typeof r.endId !== \"string\" || typeof r.summary !== \"string\" || r.summary.length === 0) continue;\n ranges.push({\n startRef: r.startId,\n endRef: r.endId,\n summary: r.summary,\n topic: typeof r.topic === \"string\" ? r.topic : callTopic,\n summaryMaxChars: typeof args.summaryMaxChars === \"number\" ? args.summaryMaxChars : undefined,\n compressCallId: msg.toolCallId ?? \"\",\n });\n }\n return ranges.length > 0 ? [{ id: msg.toolCallId ?? \"\", ranges }] : [];\n}\n\n/** Content key of a core piece for span fingerprints (issue #91): role,\n * contentType, toolName and the FIRST 4096 chars of text. The 4096 cap is\n * deliberate: a host re-serialization that drifts only the tail (beyond\n * char 4096, e.g. truncation of a long tool output) keeps the key intact,\n * so the replay guard tells a benign tail drift from a genuine rewrite. */\nexport function corePieceKey(cm: CoreMessage): string {\n return `${cm.role}|${cm.contentType}|${cm.toolName ?? \"\"}|${(cm.text ?? \"\").slice(0, 4096)}`;\n}\n\n/** Span fingerprint in content-hash space: hash the content keys of the\n * exact first/last covered pieces. Boundary ids are pre-resolved (byRef /\n * block lookup) — unlike the pN-space spanFingerprint there is no position\n * parsing, ids are unique per piece. */\nexport function spanFingerprintCore(coreMessages: CoreMessage[], startId: string, endId: string): string {\n const find = (id: string): CoreMessage | undefined => coreMessages.find((cm) => cm.id === id);\n const first = find(startId);\n const last = find(endId);\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Index-based span fingerprint (issue #91 replay fallback): hash the content\n * keys of the pieces AT the given stream positions. The stored fp still\n * decides keep/drop — the position is only a recovery hint for a drifted\n * boundary whose content-hash id no longer matches, so a benign tail drift\n * (first-4096 intact) is kept while a real rewrite mismatches. */\nexport function spanFingerprintCoreIdx(coreMessages: CoreMessage[], startIdx: number, endIdx: number): string {\n const first = coreMessages[startIdx];\n const last = coreMessages[endIdx];\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Structural subset the boundary resolvers need from a compression block\n * (kernel CompressionBlock satisfies this; keeps the guard usable from\n * downstreams that carry lighter block records). */\nexport interface BlockLike {\n blockId: string;\n effectiveMessageIds: string[];\n}\n\n/** Resolve a range boundary to the exact id of the piece it names, in\n * content-hash space. Message refs go through byRef; block refs resolve to\n * the earliest (min) or latest (max) covered piece by STREAM ORDER\n * (index in coreMessages — the hash ids carry no position). */\nexport function boundaryRawCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n): string {\n const raw = byRef[ref];\n if (raw) return raw;\n const m = /^b(\\d+)$/i.exec(ref.trim());\n if (!m) return \"\";\n const block = blocks.find((b) => b.blockId.toLowerCase() === `b${m[1]}`);\n if (!block) return \"\";\n const idx = (id: string): number => coreMessages.findIndex((cm) => cm.id === (byRef[id] ?? id));\n let best = -1;\n for (const id of block.effectiveMessageIds) {\n const i = idx(id);\n if (i < 0) continue;\n if (best < 0 || (pick === \"min\" ? i < best : i > best)) best = i;\n }\n return best < 0 ? \"\" : (coreMessages[best]?.id ?? \"\");\n}\n\n/** Resolve a range boundary to its STREAM INDEX in content-hash space. byRef /\n * block lookup first (the exact piece it names, by array order); on a missed\n * id (a drift re-hashed the piece so its carried ref dangles) fall back to\n * the compress-time recorded index — the position hint, issue #91. -1 =\n * unresolvable. */\nexport function boundaryIndexCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n fallbackIdx = -1,\n): number {\n const id = boundaryRawCore(ref, byRef, blocks, coreMessages, pick);\n if (id) {\n const i = coreMessages.findIndex((cm) => cm.id === id);\n if (i >= 0) return i;\n }\n return fallbackIdx >= 0 && fallbackIdx < coreMessages.length ? fallbackIdx : -1;\n}\n\n/** Structured replay-guard verdict (issue #91, rework): the position\n * fallback recovers the STREAM INDEX of a drifted boundary, but the kernel\n * resolves ranges by REF — so when a recorded m-ref dangles, the replay\n * must re-apply that boundary under the CURRENT ref of the recovered piece.\n * `remap` carries exactly that (only dangling m-refs are remapped; block\n * refs resolve themselves inside the kernel and are never touched). */\nexport type ReplayRangeVerdict = {\n /** Stale: the range must be dropped (master semantics, unchanged). */\n reject?: string;\n /** Dangling m-refs recovered by position, remapped to current refs. */\n remap?: { startRef?: string; endRef?: string };\n /** True when the result text carried a [pos=] pair for this range —\n * with `reject` set it marks a RECOVERY FAILURE (always logged). */\n hint?: boolean;\n /** Diagnostics — always logged when a recovery happens. */\n recovered?: { pos: string; startIdx: number; endIdx: number };\n};\n\n/** Current m-ref of the piece at stream index idx (inverse byRef scan).\n * \"\" when the piece has no ref (protected) — the replay must fail closed\n * rather than hand the kernel a ref it does not know. Replay-time only\n * (replayed compress calls), so the O(refs) scan stays off the hot path. */\nexport function refOfPieceCore(coreMessages: BiliMessage[], idx: number, byRef: Record<string, string>): string {\n const id = coreMessages[idx]?.id;\n if (!id) return \"\";\n for (const [ref, mapped] of Object.entries(byRef)) if (mapped === id) return ref;\n return \"\";\n}\n\nexport function staleRangeCore(\n r: { startRef: string; endRef: string },\n rangeIndex: number,\n resultText: string,\n coreMessages: BiliMessage[],\n callIndex: number,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): ReplayRangeVerdict {\n // Compress-time boundary positions (issue #91): the stream index each\n // boundary sat at when the call was recorded. A drift that re-hashes a\n // boundary piece dangles its carried ref — the position recovers it, and\n // the fingerprint below still decides keep/drop.\n const pm = resultText.match(/\\[pos=([0-9,-]+)\\]/);\n const pair = pm ? pm[1]!.split(\",\")[rangeIndex] ?? \"-\" : \"-\";\n const hinted = pair !== \"-\";\n const [ps, pe] = pair === \"-\" ? [\"\", \"\"] : pair.split(\"-\");\n const fbStart = ps && ps !== \"\" ? Number.parseInt(ps, 10) : -1;\n const fbEnd = pe && pe !== \"\" ? Number.parseInt(pe, 10) : -1;\n\n // Raw resolution (id → stream index) separately from the fallback, so a\n // dangling m-ref recovered by position can be flagged for remapping.\n const startRaw = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const endRaw = boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\");\n const rawStartIdx = startRaw ? coreMessages.findIndex((cm) => cm.id === startRaw) : -1;\n const rawEndIdx = endRaw ? coreMessages.findIndex((cm) => cm.id === endRaw) : -1;\n const startIdx = rawStartIdx >= 0 ? rawStartIdx : fbStart >= 0 && fbStart < coreMessages.length ? fbStart : -1;\n const endIdx = rawEndIdx >= 0 ? rawEndIdx : fbEnd >= 0 && fbEnd < coreMessages.length ? fbEnd : -1;\n if (startIdx < 0 || endIdx < 0) {\n if (!/^b\\d+$/i.test(r.startRef.trim()) && !/^b\\d+$/i.test(r.endRef.trim()))\n return { reject: `unresolved ${r.startRef}..${r.endRef} -> ${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n return {}; // block ref(s): the kernel resolves them itself (master)\n }\n // The end piece must precede the call that issued it — a rewrite moved\n // the call and the fingerprint check below is meaningless either way.\n if (endIdx > callIndex) return { reject: `end idx ${endIdx} > callIndex ${callIndex}`, ...(hinted ? { hint: true } : {}) };\n const m = resultText.match(/\\[fp=([0-9a-f,-]+)\\]/);\n if (m) {\n const want = m[1]!.split(\",\")[rangeIndex];\n if (want !== undefined && want !== \"-\") {\n const got = spanFingerprintCoreIdx(coreMessages, startIdx, endIdx);\n if (want !== got) return { reject: `fp ${r.startRef}..${r.endRef} want ${want} got ${got} @${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n }\n }\n // Remap only the boundaries that actually dangled (m-refs whose recorded id\n // no longer resolves); resolved boundaries keep their recorded ref, block\n // refs are the kernel's to resolve.\n const remap: { startRef?: string; endRef?: string } = {};\n if (/^m\\d+$/i.test(r.startRef.trim()) && rawStartIdx < 0) {\n const ref = refOfPieceCore(coreMessages, startIdx, byRef);\n if (!ref) return { reject: `recovered ${r.startRef} @${startIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.startRef = ref;\n }\n if (/^m\\d+$/i.test(r.endRef.trim()) && rawEndIdx < 0) {\n const ref = refOfPieceCore(coreMessages, endIdx, byRef);\n if (!ref) return { reject: `recovered ${r.endRef} @${endIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.endRef = ref;\n }\n if (!remap.startRef && !remap.endRef) return {};\n return { remap, recovered: { pos: pair, startIdx, endIdx } };\n}\n\n/** One fingerprint per range for the replay guard, content-hash space\n * (mirrors rangeFingerprints for the pN space). */\nexport function rangeFingerprintsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: BiliMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const start = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const end = start ? boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\") : \"\";\n if (start && end) {\n const fp = spanFingerprintCore(coreMessages, start, end);\n if (fp.length > 0) return fp;\n }\n return \"-\";\n });\n}\n\n/** One boundary-index pair per range for the replay fallback (issue #91),\n * aligned with rangeFingerprintsCore: the stream index of each range's exact\n * first/last covered piece at record time (\"-1\" pair when a boundary can't\n * be positioned), so the replay can recover a drifted boundary by position. */\nexport function rangePositionsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: CoreMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const s = boundaryIndexCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const e = s >= 0 ? boundaryIndexCore(r.endRef, byRef, blocks, coreMessages, \"max\") : -1;\n return s >= 0 && e >= 0 ? `${s}-${e}` : \"-\";\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAKpB,SAAS,OA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cAAc,KAAK;AAC5E,UAAM,MAAM,QAAQ,gBAAgB,EAAE,QAAQ,OAAO,QAAQ,cAAc,KAAK,IAAI;AACpF,QAAI,SAAS,KAAK;AAChB,YAAM,KAAK,oBAAoB,cAAc,OAAO,GAAG;AACvD,UAAI,GAAG,SAAS,EAAG,QAAO;AAAA,IAC5B;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAMO,SAAS,mBACd,QACA,cACA,OACA,QACU;AACV,SAAO,OAAO,IAAI,CAAC,MAAM;AACvB,UAAM,IAAI,kBAAkB,EAAE,UAAU,OAAO,QAAQ,cAAc,KAAK;AAC1E,UAAM,IAAI,KAAK,IAAI,kBAAkB,EAAE,QAAQ,OAAO,QAAQ,cAAc,KAAK,IAAI;AACrF,WAAO,KAAK,KAAK,KAAK,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK;AAAA,EAC1C,CAAC;AACH;","names":["createHash"]}
1
+ {"version":3,"sources":["../../src/wire/util.ts","../../src/wire/message-id.ts","../../src/wire/anthropic.ts","../../src/wire/demoted-thinking.ts","../../src/wire/bili-message.ts","../../src/wire/openai.ts","../../src/wire/responses.ts","../../src/wire/formats.ts","../../src/wire/mirror.ts","../../src/wire/compress-detect.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** SHA-256-derived short id — kept verbatim from the proxy so message ids\n * stay byte-identical across the extraction (re-keying would orphan every\n * downstream map keyed on these ids). */\nexport function hashId(s: string): string {\n return createHash(\"sha256\").update(s, \"utf8\").digest(\"hex\").slice(0, 16);\n}\n\n/** How a conversation's identity was derived (kept verbatim from the proxy's\n * session-id.ts — only the TYPE moves; session-key derivation stays in the\n * proxy, which owns multi-tenant state). */\nexport type ConversationIdentity = {\n value: string;\n source: \"header\" | \"body-session\" | \"metadata-session\" | \"previous-response\" | \"content-fingerprint\" | \"generated\";\n clientProvided: boolean;\n};\n","import { hashId } from \"./util.js\";\n\n/**\n * Derive a stable, content-based message id.\n *\n * PROBLEM: none of the three wire protocols (Anthropic Messages, OpenAI Chat\n * Completions, OpenAI Responses) attach a stable id to request-side message\n * items. Historically each converter used `raw-${idx}` — a *position* index,\n * not an identity. As soon as a client deletes/reorders messages (other plugins\n * summarizing away old turns, multi-agent setups, etc.) the index drifts:\n * downstream ids shift, so\n * - assignRefs reuses stale `byRaw` entries, hiding new messages, and\n * - compression `effectiveMessageIds` start pointing at the *wrong* messages,\n * silently swallowing live content under an unrelated summary.\n *\n * FIX: derive the id from a SHA-256 of the message identity:\n * role + contentType + toolCallId + toolName + text\n * Two messages with identical identity collide. To keep duplicates distinct\n * (and avoid `covered` sets collapsing unrelated turns onto one id) we append a\n * within-conversation *cluster index* `_N`: the Nth occurrence of the same\n * identity, counting from 0 in arrival order.\n *\n * Trade-off vs a real client id:\n * - deleting a duplicated message only disturbs the cluster of that identity\n * (local damage), never the whole downstream (global damage like position).\n * - fully distinct messages are completely immune to reordering/deletion.\n *\n * `idx` is passed purely to break ties *within a single conversion pass*; it is\n * not part of the identity, so two passes over the same content produce the\n * same cluster numbering (deterministic).\n */\nexport function deriveMessageId(\n role: string,\n contentType: string,\n text: string,\n options: {\n toolCallId?: string;\n toolName?: string;\n } = {},\n): string {\n const seed = `${role}|${contentType}|${options.toolCallId ?? \"\"}|${options.toolName ?? \"\"}|${text}`;\n return \"h_\" + hashId(seed);\n}\n\n/**\n * Stateful cluster counter. Each converter instantiates one per conversion\n * pass; it tracks how many times each base identity has been seen so that the\n * Nth duplicate gets a `_${N}` suffix.\n */\nexport class ClusterCounter {\n private counts = new Map<string, number>();\n\n next(baseId: string): string {\n const n = this.counts.get(baseId) ?? 0;\n this.counts.set(baseId, n + 1);\n return n === 0 ? baseId : `${baseId}_${n}`;\n }\n}\n","import type { BiliMessage } from \"./bili-message.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\n\nexport type AnthropicTextBlock = { type: \"text\"; text: string; cache_control?: unknown };\nexport type AnthropicToolUse = {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n cache_control?: unknown;\n};\nexport type AnthropicToolResult = {\n type: \"tool_result\";\n tool_use_id: string;\n content: string | AnthropicTextBlock[];\n is_error?: boolean;\n cache_control?: unknown;\n};\nexport type AnthropicImage = { type: \"image\"; source: unknown };\nexport type AnthropicThinking = { type: \"thinking\"; thinking: string; signature?: string };\nexport type AnthropicBlock =\n | AnthropicTextBlock\n | AnthropicToolUse\n | AnthropicToolResult\n | AnthropicImage\n | AnthropicThinking;\n\nexport type AnthropicMessage = {\n role: \"user\" | \"assistant\";\n content: string | AnthropicBlock[];\n};\n\nexport type AnthropicRequestBody = {\n model?: string;\n max_tokens?: number;\n system?: string | AnthropicTextBlock[];\n messages: AnthropicMessage[];\n tools?: unknown[];\n stream?: boolean;\n temperature?: number;\n [key: string]: unknown;\n};\n\n\nexport function extractSystem(system: AnthropicRequestBody[\"system\"]): string {\n if (!system) return \"\";\n if (typeof system === \"string\") return system;\n return system.map((b) => b.text).join(\"\\n\\n\");\n}\n\nexport function buildSystem(text: string, original: AnthropicRequestBody[\"system\"]): string | AnthropicTextBlock[] {\n if (Array.isArray(original) && original.length > 0) {\n const ccBlock = original.find((b) => b.cache_control);\n return [{ type: \"text\", text, ...(ccBlock ? { cache_control: ccBlock.cache_control } : {}) }];\n }\n return text;\n}\n\ntype Flat = { msgs: BiliMessage[]; cacheControls: Map<string, unknown> };\n\nexport function anthropicToCore(body: AnthropicRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const cacheControls = new Map<string, unknown>();\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n const blocks = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n for (const b of blocks) {\n switch (b.type) {\n case \"text\": {\n const base = deriveMessageId(m.role, \"text\", b.text);\n const id = clusters.next(base);\n msgs.push({ id, role: m.role, contentType: \"text\", text: b.text });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_use\": {\n const base = deriveMessageId(\"assistant\", \"tool-call\", safeStringify(b.input), {\n toolCallId: b.id,\n toolName: b.name,\n });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: b.name,\n toolCallId: b.id,\n text: safeStringify(b.input),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"tool_result\": {\n const text = typeof b.content === \"string\" ? b.content : b.content.map((c) => c.text).join(\"\\n\");\n const base = deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: b.tool_use_id });\n const id = clusters.next(base);\n msgs.push({\n id,\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: b.tool_use_id,\n text,\n ...(b.is_error === true ? { toolIsError: true } : {}),\n });\n if (b.cache_control) cacheControls.set(id, b.cache_control);\n break;\n }\n case \"thinking\": {\n const base = deriveMessageId(\"assistant\", \"reasoning\", b.thinking);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: b.thinking,\n ...(b.signature ? { thinkingSignature: b.signature } : {}),\n });\n break;\n }\n case \"image\": {\n const base = deriveMessageId(m.role, \"text\", \"[image]\");\n msgs.push({\n id: clusters.next(base),\n role: m.role,\n contentType: \"text\",\n text: \"[image]\",\n rawAnthropicBlock: b,\n });\n break;\n }\n }\n }\n }\n return { msgs, cacheControls };\n}\n\nexport function coreToAnthropic(messages: BiliMessage[], cacheControls?: Map<string, unknown>): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n let current: { role: \"user\" | \"assistant\"; blocks: AnthropicBlock[] } | null = null;\n const flush = () => {\n if (current && current.blocks.length > 0) {\n out.push({ role: current.role, content: current.blocks });\n }\n current = null;\n };\n const cc = (id: string): { cache_control?: unknown } => {\n const v = cacheControls?.get(id);\n return v ? { cache_control: v } : {};\n };\n for (const m of messages) {\n const target: \"user\" | \"assistant\" =\n m.role === \"assistant\" ? \"assistant\" : \"user\";\n if (!current || current.role !== target) {\n flush();\n current = { role: target, blocks: [] };\n }\n switch (m.contentType) {\n case \"text\": {\n if (m.rawAnthropicBlock) {\n current.blocks.push(m.rawAnthropicBlock as AnthropicBlock);\n break;\n }\n current.blocks.push({ type: \"text\", text: m.text ?? \"\", ...cc(m.id) });\n break;\n }\n case \"tool-call\":\n current.blocks.push({\n type: \"tool_use\",\n id: m.toolCallId ?? `call_${m.id}`,\n name: m.toolName ?? \"unknown\",\n input: safeParse(m.text),\n ...cc(m.id),\n });\n break;\n case \"tool-result\":\n current.blocks.push({\n type: \"tool_result\",\n tool_use_id: m.toolCallId ?? \"\",\n content: m.text ?? \"\",\n ...(m.toolIsError ? { is_error: true } : {}),\n ...cc(m.id),\n });\n break;\n case \"reasoning\":\n current.blocks.push({\n type: \"thinking\",\n thinking: m.text ?? \"\",\n ...(m.thinkingSignature ? { signature: m.thinkingSignature } : {}),\n });\n break;\n }\n }\n flush();\n return out;\n}\n\n/** Extract the conversation dimension for Anthropic: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. The protocol+upstream+key dimensions are mixed in by the caller\n * (server.ts) via deriveSessionId() — this function contributes only the\n * conversation axis. */\nexport function conversationSignalAnthropic(body: AnthropicRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? JSON.stringify(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v ?? {});\n } catch {\n return \"{}\";\n }\n}\n\nfunction safeParse(s: string | undefined): unknown {\n if (!s) return {};\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n","/** Inline \"demoted thinking\" normalization.\n *\n * Hosts that cannot replay prior-turn reasoning as a structured block\n * (pi-ai transform-messages demotion on model switch, openai-completions\n * `requiresThinkingAsText` profiles, gateways that inline native\n * reasoning) fold it INTO the assistant content string wrapped in a\n * dialect tag:\n *\n * glm / deepseek / kimi / qwen3 / hermes : <think>\\n{text}\\n</think>\n * anthropic / minimax / xml : <thinking>\\n{text}\\n</thinking>\n * gemini : ```thinking\\n{text}\\n```\n *\n * followed by a single \"\\n\" glue before the next content block. The same\n * logical turn can therefore arrive as a `reasoning_content` field (or a\n * separate reasoning item on /v1/responses) OR as this inline form. If the\n * wire codecs kept both as one text blob, the two serializations of one\n * turn would land in DIFFERENT core-id/fingerprint spaces — exactly the\n * issue #64 \"restart loses blocks\" class, where the mirror produced one\n * form and the live wire the other.\n *\n * splitDemotedThinking() reverses the rendering byte-exactly so both\n * codecs can normalize before identity derivation (deriveMessageId). It\n * only fires when the tag opens at offset 0 of the content, which is the\n * only position the demotion renderer can produce it in.\n *\n * One form is intentionally NOT recoverable here: the pi-ai anthropic\n * dialect demotes to BARE text (no tag), which is indistinguishable from\n * ordinary assistant prose; that case must be aligned upstream (mirror\n * uses the same bare rendering), not parsed. */\n\nexport type DemotedSplit = {\n reasoning: string;\n text: string;\n};\n\ntype DelimitedForm = {\n open: string;\n close: string;\n};\n\n/** The three inline tag forms hosts actually emit (see file comment). */\nconst FORMS: readonly DelimitedForm[] = [\n { open: \"<think>\\n\", close: \"\\n</think>\" },\n { open: \"<thinking>\\n\", close: \"\\n</thinking>\" },\n { open: \"```thinking\\n\", close: \"\\n```\" },\n];\n\n/** If `content` starts with one or more inline demoted-thinking blocks,\n * split them out. Returns null when no tag opens the content (the common\n * case — including every user message and every assistant message whose\n * reasoning traveled as a field/item), in which case callers keep the\n * content as-is. Malformed (unterminated) or empty blocks do not match;\n * the content is then treated as plain text, never dropped. */\nexport function splitDemotedThinking(content: string): DemotedSplit | null {\n let rest = content;\n const parts: string[] = [];\n for (;;) {\n let matched = false;\n for (const form of FORMS) {\n if (!rest.startsWith(form.open)) continue;\n const end = rest.indexOf(form.close, form.open.length);\n if (end < 0) continue;\n const inner = rest.slice(form.open.length, end);\n if (inner.length === 0) continue;\n parts.push(inner);\n rest = rest.slice(end + form.close.length);\n // Glue the demotion renderer inserts between a demoted block\n // and the block that follows it.\n if (rest.startsWith(\"\\n\")) rest = rest.slice(1);\n matched = true;\n break;\n }\n if (!matched) break;\n }\n if (parts.length === 0) return null;\n return { reasoning: parts.join(\"\\n\"), text: rest };\n}\n","/**\n * Lossless message bridge between protocol-specific message formats and the\n * kernel's CoreMessage.\n *\n * Problem: `anthropicToCore` / `openaiToCore` / `responsesToCore` flatten\n * rich protocol blocks (images, thinking signatures, tool_result.is_error,\n * developer-role messages, image_url) into plain `{ text }` placeholders.\n * The reverse `coreToX` then can't reconstruct them — `is_error` is lost\n * (upstream can't tell a tool error from a result), `thinking.signature` is\n * lost (Anthropic rejects thinking blocks without a matching signature),\n * images become \"[image]\" (the model never sees the picture).\n *\n * Solution: `BiliMessage` extends CoreMessage with optional sidecar fields.\n * The kernel only reads `{ ...message }` (spread copy) and known fields, so\n * the extra fields survive the compression pipeline unchanged and arrive back\n * at `coreToX`, which prefers them over the flattened `text`. No `as any`\n * needed — TypeScript array covariance lets `BiliMessage[]` satisfy a\n * `CoreMessage[]` parameter.\n */\n\nimport type { CoreMessage } from \"acp-kernel\";\n\n/** A message that carries its original protocol block(s) verbatim, so the\n * reverse conversion can reconstruct losslessly. Every field is optional —\n * plain text messages (the common case) have none set. */\nexport interface BiliMessage extends CoreMessage {\n /** Anthropic: the original content block for an image or a structured\n * tool_result. Restored verbatim by coreToAnthropic. */\n rawAnthropicBlock?: unknown;\n /** OpenAI chat: the original content part for an image_url, or the\n * original message object for a developer-role message. */\n rawOpenaiContent?: unknown;\n /** Responses API: the original input item (for input_image, or a raw\n * function_call / function_call_output we pass through). */\n rawResponsesItem?: unknown;\n /** Anthropic thinking signature. Anthropic verifies thinking+signature\n * pairs; without it the request is rejected. Stored alongside the\n * reasoning text so coreToAnthropic can reattach it. */\n thinkingSignature?: string;\n /** OpenAI reasoning_content (chain-of-thought from DeepSeek-R1, GLM-4.6\n * thinking, Qwen-QwQ). These models require reasoning_content be echoed\n * back on subsequent requests or the API returns HTTP 400; stored so\n * coreToOpenai can reattach it. */\n reasoningContent?: string;\n /** Anthropic tool_result.is_error. Marks the tool result as an error so\n * the model knows the tool failed (not just returned an error string). */\n toolIsError?: boolean;\n /** OpenAI: original role was \"developer\" (reconstructed as \"system\" by\n * openaiToCore for the kernel; coreToOpenai restores \"developer\"). */\n originalRole?: \"system\" | \"developer\";\n /** The original media type for an image (image/png, image/jpeg, image/gif,\n * image/webp). Lets coreToOpenai/coreToResponses rebuild image_url /\n * input_image with the right data URL. */\n imageMediaType?: string;\n /** The base64 data of an image (without the data: prefix). Lets the\n * reverse conversion rebuild the full image payload. */\n imageBase64?: string;\n /** OpenAI chat: ALL original image_url content parts (data: or remote\n * URL) for a user message carrying more than one image, in wire order.\n * coreToOpenai re-emits these verbatim (after the text part). The\n * singular `rawOpenaiContent` still covers the single-image case and\n * legacy persisted state. Typed as unknown[] (not OpenAIContentPart) to\n * avoid a circular import with the openai codec. */\n rawOpenaiContentParts?: unknown[];\n}\n\n/** Narrow a BiliMessage[] to CoreMessage[] for the kernel. The sidecar fields\n * are transparently carried along — the kernel's `{ ...msg }` copies them. */\nexport function toCoreMessages(msgs: BiliMessage[]): CoreMessage[] {\n return msgs as CoreMessage[];\n}\n\n/** Re-decode a base64 data URL into media type + data. Returns undefined if\n * the input is not a recognized data URL. Used by openaiToCore/responsesToCore\n * to split image_url/input_image into the sidecar fields. */\nexport function parseDataUrl(url: string): { mediaType: string; base64: string } | undefined {\n const m = /^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);\n if (!m) return undefined;\n return { mediaType: m[1]!, base64: m[2]! };\n}\n","import { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { hashId } from \"./util.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type OpenAIContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } }\n | { type: string; [k: string]: unknown };\n\nexport type OpenAIToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type OpenAIMessage = {\n role: \"system\" | \"developer\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | null | OpenAIContentPart[];\n reasoning_content?: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n name?: string;\n};\n\nexport type OpenAITool = {\n type: \"function\";\n function: { name: string; description?: string; parameters?: unknown };\n};\n\nexport type OpenAIRequestBody = {\n model?: string;\n messages: OpenAIMessage[];\n tools?: OpenAITool[];\n stream?: boolean;\n [key: string]: unknown;\n};\n\ntype Flat = { msgs: BiliMessage[]; systemText: string };\n\n/** Hoist the contiguous leading system/developer prefix out of the fold\n * space (openai-chat variant of the responses codec's systemParts and the\n * anthropic codec's top-level `system` field). The system prompt is host\n * runtime state: its content varies across restarts (injected reminders,\n * host-composed instructions), so keeping it inside the id space made every\n * downstream fingerprint spanning it unstable, and a compress range that\n * covered it removed the model's system prompt from the rebuilt wire\n * entirely. Mid-conversation system messages (rare, host-synthetic) stay in\n * the fold space unchanged. */\nexport function openaiToCore(body: OpenAIRequestBody): Flat {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const clusters = new ClusterCounter();\n for (const m of body.messages) {\n switch (m.role) {\n case \"system\":\n case \"developer\": {\n if (msgs.length === 0) {\n systemParts.push(stringContent(m.content));\n break;\n }\n const base = deriveMessageId(m.role, \"text\", stringContent(m.content));\n msgs.push({ id: clusters.next(base), role: \"system\", contentType: \"text\", text: stringContent(m.content), originalRole: m.role });\n break;\n }\n case \"user\": {\n // Image-only messages keep text \"\" (NO \"[image]\" placeholder as\n // in the responses/anthropic codecs): image-only msgs already\n // had \"\" pre-#187, and switching would shift their derived ids.\n const text = stringContent(m.content);\n const imgs = allImageParts(m.content);\n const firstImg = imgs[0];\n const firstUrl = firstImg ? firstImg.image_url.url : undefined;\n const firstParsed = firstUrl ? parseDataUrl(firstUrl) : undefined;\n const base = deriveMessageId(\"user\", \"text\", text);\n msgs.push({\n id: clusters.next(base),\n role: \"user\",\n contentType: \"text\",\n text,\n ...(imgs.length === 1\n ? {\n rawOpenaiContent: imgs[0],\n // data: URLs only — remote URLs ride rawOpenaiContent verbatim (issue #187)\n ...(firstParsed ? { imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 } : {}),\n }\n : imgs.length > 1\n ? { rawOpenaiContentParts: imgs }\n : {}),\n });\n break;\n }\n case \"assistant\": {\n const fieldReasoning = typeof m.reasoning_content === \"string\" ? m.reasoning_content : \"\";\n let reasoning = fieldReasoning;\n let text = stringContent(m.content);\n if (!reasoning) {\n // Hosts that cannot replay prior-turn reasoning as a\n // structured field inline it into content wrapped in a\n // dialect tag (<think>, <thinking>, ```thinking). Split\n // it back out BEFORE identity derivation so the inline\n // form and the reasoning_content field form of one turn\n // land in a single core-id/fingerprint space (issue #64\n // demoted variant).\n const split = splitDemotedThinking(text);\n if (split) {\n reasoning = split.reasoning;\n text = split.text;\n }\n }\n if (reasoning) {\n const base = deriveMessageId(\"assistant\", \"reasoning\", reasoning);\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: reasoning,\n reasoningContent: reasoning,\n });\n }\n if (text) {\n const base = deriveMessageId(\"assistant\", \"text\", text);\n msgs.push({ id: clusters.next(base), role: \"assistant\", contentType: \"text\", text });\n }\n if (Array.isArray(m.tool_calls)) {\n for (const tc of m.tool_calls) {\n const base = deriveMessageId(\"assistant\", \"tool-call\", tc.function.arguments ?? \"\", {\n toolCallId: tc.id,\n toolName: tc.function.name,\n });\n msgs.push({\n id: clusters.next(base),\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: tc.function.name,\n toolCallId: tc.id,\n text: tc.function.arguments ?? \"\",\n });\n }\n }\n break;\n }\n case \"tool\": {\n const base = deriveMessageId(\"tool\", \"tool-result\", stringContent(m.content), {\n toolCallId: m.tool_call_id ?? \"\",\n });\n msgs.push({\n id: clusters.next(base),\n role: \"tool\",\n contentType: \"tool-result\",\n toolCallId: m.tool_call_id ?? \"\",\n text: stringContent(m.content),\n });\n break;\n }\n }\n }\n return { msgs, systemText: systemParts.join(\"\\n\\n\") };\n}\n\nexport function coreToOpenai(messages: BiliMessage[]): OpenAIMessage[] {\n const out: OpenAIMessage[] = [];\n let pending: { text: string | null; toolCalls: OpenAIToolCall[]; reasoning: string | null } | null = null;\n const flush = () => {\n if (!pending) return;\n const reasoning = pending.reasoning !== null && pending.reasoning.length > 0 ? pending.reasoning : undefined;\n if (pending.toolCalls.length > 0) {\n out.push({\n role: \"assistant\",\n content: pending.text ?? null,\n tool_calls: pending.toolCalls,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n });\n } else if (pending.text !== null) {\n out.push({ role: \"assistant\", content: pending.text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n } else if (reasoning) {\n out.push({ role: \"assistant\", content: null, reasoning_content: reasoning });\n }\n pending = null;\n };\n for (const m of messages) {\n if (m.role === \"assistant\") {\n if (!pending) pending = { text: null, toolCalls: [], reasoning: null };\n if (m.contentType === \"reasoning\") {\n pending.reasoning = (pending.reasoning ?? \"\") + (m.reasoningContent ?? m.text ?? \"\");\n } else if (m.contentType === \"text\") {\n pending.text = (pending.text ?? \"\") + (m.text ?? \"\");\n } else if (m.contentType === \"tool-call\") {\n pending.toolCalls.push({\n id: m.toolCallId ?? `call_${m.id}`,\n type: \"function\",\n function: { name: m.toolName ?? \"unknown\", arguments: m.text ?? \"\" },\n });\n }\n } else {\n flush();\n if (m.role === \"system\") {\n out.push({ role: m.originalRole === \"developer\" ? \"developer\" : \"system\", content: m.text ?? \"\" });\n } else if (m.role === \"user\") {\n if (m.rawOpenaiContent || m.imageBase64 || m.rawOpenaiContentParts) {\n const parts: OpenAIContentPart[] = [];\n if (m.text) parts.push({ type: \"text\", text: m.text });\n if (m.rawOpenaiContentParts && m.rawOpenaiContentParts.length > 0) {\n for (const part of m.rawOpenaiContentParts) parts.push(part as OpenAIContentPart);\n } else if (m.rawOpenaiContent) {\n parts.push(m.rawOpenaiContent as OpenAIContentPart);\n } else if (m.imageBase64 && m.imageMediaType) {\n parts.push({ type: \"image_url\", image_url: { url: `data:${m.imageMediaType};base64,${m.imageBase64}` } });\n }\n out.push({ role: \"user\", content: parts });\n } else {\n out.push({ role: \"user\", content: m.text ?? \"\" });\n }\n } else if (m.role === \"tool\") {\n out.push({ role: \"tool\", tool_call_id: m.toolCallId ?? \"\", content: m.text ?? \"\" });\n }\n }\n }\n flush();\n return out;\n}\n\nexport function injectOpenaiSystem(messages: OpenAIMessage[], parts: string[]): OpenAIMessage[] {\n if (parts.length === 0) return messages;\n const extra = parts.join(\"\\n\\n\");\n if (messages.length > 0 && (messages[0]?.role === \"system\" || messages[0]?.role === \"developer\")) {\n const head = messages[0] as OpenAIMessage;\n const base = stringContent(head.content);\n const merged = base ? `${base}\\n\\n---\\n\\n${extra}` : extra;\n return [{ ...head, content: merged }, ...messages.slice(1)];\n }\n return [{ role: \"system\", content: extra }, ...messages];\n}\n\n/** Extract the conversation dimension for OpenAI Chat: a client-provided\n * session header if present, else a content fingerprint of the first user\n * message. See conversationSignalAnthropic for the full rationale. */\nexport function conversationSignalOpenai(body: OpenAIRequestBody, headerValue?: string): string {\n if (headerValue && headerValue.trim()) return headerValue.trim();\n const firstUser = body.messages.find((m) => m.role === \"user\");\n const seed = firstUser ? stringContent(firstUser.content) : \"default\";\n return hashId(seed);\n}\n\nfunction stringContent(content: OpenAIMessage[\"content\"]): string {\n if (content == null) return \"\";\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .map((p) => (typeof p === \"string\" ? p : p.type === \"text\" ? (p as { text?: string }).text ?? \"\" : \"\"))\n .join(\"\\n\");\n }\n return \"\";\n}\n\ntype OpenAIImagePart = { type: \"image_url\"; image_url: { url: string } };\n\n/** Collect ALL image_url parts in a user content array, in wire order —\n * data: URLs and remote http(s) URLs alike. (firstImagePart only kept the\n * first, silently dropping images 2..N; the data-URL-only filter then\n * silently dropped every remote-URL image — issue #187.) */\nfunction allImageParts(content: OpenAIMessage[\"content\"]): OpenAIImagePart[] {\n if (!Array.isArray(content)) return [];\n const out: OpenAIImagePart[] = [];\n for (const p of content) {\n if (typeof p !== \"object\" || p === null) continue;\n if (!(\"type\" in p) || p.type !== \"image_url\" || !(\"image_url\" in p)) continue;\n // The union's index-signature member leaves image_url as `unknown`, so\n // narrow via a named const before reading the url.\n const imagePart = p as { image_url: { url?: unknown } };\n const url = imagePart.image_url.url;\n if (typeof url === \"string\") out.push(p as OpenAIImagePart);\n }\n return out;\n}\n","import type { CoreMessage } from \"../types.js\";\nimport { splitDemotedThinking } from \"./demoted-thinking.js\";\nimport { ClusterCounter, deriveMessageId } from \"./message-id.js\";\nimport type { ConversationIdentity } from \"./util.js\";\nimport { hashId } from \"./util.js\";\nimport { parseDataUrl, type BiliMessage } from \"./bili-message.js\";\n\nexport type ResponseContentPart =\n | { type: \"input_text\"; text: string; [key: string]: unknown }\n | { type: \"output_text\"; text: string; [key: string]: unknown }\n | { type: \"input_image\"; image_url: string; [key: string]: unknown }\n | { type: string; [key: string]: unknown };\n\nexport type ResponseInputMessage = {\n type: \"message\";\n role: \"system\" | \"developer\" | \"user\" | \"assistant\";\n content: string | ResponseContentPart[];\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCall = {\n type: \"function_call\";\n id?: string;\n call_id: string;\n name: string;\n arguments: string;\n [key: string]: unknown;\n};\n\nexport type ResponseFunctionCallOutput = {\n type: \"function_call_output\";\n call_id: string;\n output: string;\n [key: string]: unknown;\n};\n\nexport type ResponseInputItem =\n | ResponseInputMessage\n | ResponseFunctionCall\n | ResponseFunctionCallOutput\n | { type: string; [key: string]: unknown };\n\nexport type ResponsesRequestBody = {\n model?: string;\n input: string | ResponseInputItem[];\n instructions?: string;\n tools?: unknown[];\n stream?: boolean;\n session_id?: string;\n previous_response_id?: string;\n prompt_cache_key?: string;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype ResponseLayoutSlot = {\n original: ResponseInputItem;\n coreId?: string;\n};\n\nexport type ResponsesProjection = {\n msgs: BiliMessage[];\n systemParts: string[];\n preamble: ResponseInputItem[];\n customToolCallIds: Set<string>;\n layout: ResponseLayoutSlot[];\n stringInput?: { original: string; coreId: string };\n /** Reasoning items dropped because ACP_REASONING_KEEP=none. 0 by default —\n * reasoning is normally routed through the compression pipeline so it is\n * hidden automatically once its turn is summarized. */\n droppedReasoning: number;\n};\n\n/** Item types that are host DIRECTIVES (tool/definition listings), not\n * conversation history: preserved verbatim and re-prepended at input[0..].\n * `additional_tools` carries the Codex code_mode exec/wait tool definitions\n * and MUST stay at input[0]. `mcp_list_tools` is a stable per-session listing.\n *\n * Only definitions belong here. Output/action items from a prior response\n * (reasoning, computer_call, function_call, mcp_call, ...) ARE conversation\n * history and are routed as tracked BiliMessages, so the compression pipeline\n * hides them once their turn is summarized — preserving them verbatim in the\n * preamble instead made them accumulate unbounded every turn and broke Codex's\n * prompt-cache prefix. */\nconst OPAQUE_ITEM_TYPES = new Set([\n \"additional_tools\",\n \"mcp_list_tools\",\n]);\n\nfunction isOpaqueItem(item: ResponseInputItem): boolean {\n return OPAQUE_ITEM_TYPES.has(item.type);\n}\n\nfunction shouldDropAllReasoning(): boolean {\n return (process.env.ACP_REASONING_KEEP ?? \"\").trim().toLowerCase() === \"none\";\n}\n\nfunction partText(part: ResponseContentPart): string {\n if (part.type === \"input_text\" || part.type === \"output_text\") {\n return typeof part.text === \"string\" ? part.text : \"\";\n }\n return \"\";\n}\n\nfunction messageContent(content: string | ResponseContentPart[]): string {\n return typeof content === \"string\" ? content : content.map(partText).join(\"\\n\");\n}\n\n/** Kernel-side text responsesToCore assigns to a user item: its content\n * text, or the \"[image]\" placeholder when no text part exists (image-only\n * items — note ≥2 image parts join into a truthy \"\\n\" that is not text).\n * coreToResponses re-emits the raw item verbatim exactly while the kernel\n * text still equals this form. MUST stay in lockstep with the displayText\n * computation in responsesToCore or the verbatim equality silently breaks. */\nfunction canonicalUserText(message: ResponseInputMessage): string {\n const contentText = messageContent(message.content);\n const hasImage = Array.isArray(message.content) && message.content.some((part) => part.type === \"input_image\");\n const hasTextPart = typeof message.content !== \"string\" && message.content.some((part) => part.type === \"input_text\" || part.type === \"output_text\");\n return !contentText || (hasImage && !hasTextPart) ? \"[image]\" : contentText;\n}\n\n/** Extract the reasoning text from a responses reasoning item. The host\n * carries it in `content` (reasoning_text parts); the primeFold mirror\n * carries it in `summary` (summary_text parts). Both must yield the same\n * text so the kernel derives the same core id (issue #64, responses). */\nfunction reasoningText(item: ResponseInputItem): string {\n const fromParts = (parts: unknown, type: string): string => {\n if (!Array.isArray(parts)) return \"\";\n const texts: string[] = [];\n for (const part of parts) {\n if (part && typeof part === \"object\" && \"type\" in part && \"text\" in part) {\n const rec = part as { type: unknown; text: unknown };\n if (rec.type === type && typeof rec.text === \"string\") texts.push(rec.text);\n }\n }\n return texts.join(\"\\n\");\n };\n const content = \"content\" in item ? item.content : undefined;\n const summary = \"summary\" in item ? item.summary : undefined;\n return fromParts(content, \"reasoning_text\") || fromParts(summary, \"summary_text\");\n}\n\nexport function responsesToCore(body: ResponsesRequestBody): ResponsesProjection {\n const msgs: BiliMessage[] = [];\n const systemParts: string[] = [];\n const preamble: ResponseInputItem[] = [];\n const customToolCallIds = new Set<string>();\n const layout: ResponseLayoutSlot[] = [];\n let droppedReasoning = 0;\n const clusters = new ClusterCounter();\n let idx = 0;\n if (typeof body.instructions === \"string\" && body.instructions.trim()) systemParts.push(body.instructions);\n if (typeof body.input === \"string\") {\n const id = clusters.next(deriveMessageId(\"user\", \"text\", body.input));\n msgs.push({ id, role: \"user\", contentType: \"text\", text: body.input });\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning, stringInput: { original: body.input, coreId: id } };\n }\n for (const item of body.input) {\n let coreId: string | undefined;\n if (isOpaqueItem(item)) preamble.push(item);\n switch (item.type) {\n case \"reasoning\": {\n if (shouldDropAllReasoning()) {\n droppedReasoning++;\n continue;\n }\n // Key the reasoning piece on its TEXT (deterministic), consistent\n // with the anthropic/openai codecs. The host mints a per-request\n // item id that the primeFold mirror cannot reproduce; keying on it\n // put the mirror in a different ref/fingerprint space, so restart\n // replay rejected every in-stream compress call (issue #64,\n // responses variant).\n const text = reasoningText(item);\n const rid =\n text.length > 0\n ? text\n : \"id\" in item && typeof item.id === \"string\"\n ? item.id\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"reasoning\", rid));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"reasoning\",\n text: rid,\n rawResponsesItem: item,\n });\n break;\n }\n case \"message\": {\n const message = item as ResponseInputMessage;\n const text = messageContent(message.content);\n if (message.role === \"system\" || message.role === \"developer\") {\n systemParts.push(text);\n idx++;\n continue;\n } else if (message.role === \"user\" || (message.role === \"assistant\" && text)) {\n const role = message.role;\n let effText = text;\n if (role === \"assistant\") {\n // Same normalization as openaiToCore: hosts that demote\n // prior-turn reasoning inline it as a dialect tag at the\n // head of the message text. Split it out before identity\n // derivation so the inline form and the separate\n // reasoning-item form of one turn share a single\n // core-id/fingerprint space.\n const split = splitDemotedThinking(text);\n if (split) {\n msgs.push({\n id: clusters.next(deriveMessageId(\"assistant\", \"reasoning\", split.reasoning)),\n role: \"assistant\",\n contentType: \"reasoning\",\n text: split.reasoning,\n rawResponsesItem: item,\n });\n effText = split.text;\n }\n }\n // Image-only user items have no text of their own (≥2 image\n // parts join to a truthy \"\\n\" — not real text). Track them\n // with the \"[image]\" placeholder (anthropic codec precedent)\n // so they enter the compression space instead of vanishing\n // from the rebuilt input (issue #187). displayText derives\n // from effText (post-split); the placeholder applies only\n // when no real text part exists.\n const hasImage = Array.isArray(message.content) && message.content.some((part) => part.type === \"input_image\");\n const hasTextPart = typeof message.content !== \"string\" && message.content.some((part) => part.type === \"input_text\" || part.type === \"output_text\");\n if (effText || (role === \"user\" && hasImage)) {\n const displayText = !effText || (role === \"user\" && hasImage && !hasTextPart) ? \"[image]\" : effText;\n coreId = clusters.next(deriveMessageId(role, \"text\", displayText));\n const imageUrl = Array.isArray(message.content)\n ? message.content.find((part) => part.type === \"input_image\" && typeof part.image_url === \"string\")?.image_url\n : undefined;\n const image = typeof imageUrl === \"string\" ? parseDataUrl(imageUrl) : undefined;\n msgs.push({\n id: coreId,\n role,\n contentType: \"text\",\n text: displayText,\n rawResponsesItem: item,\n ...(image ? { imageMediaType: image.mediaType, imageBase64: image.base64 } : {}),\n });\n }\n }\n break;\n }\n case \"function_call\": {\n const call = item as ResponseFunctionCall;\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", call.arguments ?? \"\", {\n toolCallId: call.call_id,\n toolName: call.name,\n }));\n msgs.push({\n id: coreId,\n role: \"assistant\",\n contentType: \"tool-call\",\n toolName: call.name,\n toolCallId: call.call_id,\n text: call.arguments ?? \"\",\n rawResponsesItem: item,\n });\n break;\n }\n case \"function_call_output\": {\n const output = item as ResponseFunctionCallOutput;\n const text = typeof output.output === \"string\" ? output.output : JSON.stringify(output.output);\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", text, { toolCallId: output.call_id }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: output.call_id, text, rawResponsesItem: item });\n break;\n }\n case \"computer_call\":\n case \"computer_call_output\":\n case \"file_search_call\":\n case \"web_search_call\":\n case \"image_generation_call\":\n case \"code_interpreter_call\":\n case \"mcp_call\": {\n const rid =\n typeof (item as { id?: unknown }).id === \"string\"\n ? String((item as { id?: string }).id)\n : hashId(JSON.stringify(item));\n coreId = clusters.next(deriveMessageId(\"assistant\", \"responses-call\", rid));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"reasoning\", text: rid, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call\": {\n const ctc = item as { call_id?: string; name?: string; input?: string; arguments?: string };\n const callId = ctc.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const argText = ctc.input ?? ctc.arguments ?? \"\";\n coreId = clusters.next(deriveMessageId(\"assistant\", \"tool-call\", argText, { toolCallId: callId, toolName: ctc.name ?? \"custom\" }));\n msgs.push({ id: coreId, role: \"assistant\", contentType: \"tool-call\", toolName: ctc.name ?? \"custom\", toolCallId: callId, text: argText, rawResponsesItem: item });\n break;\n }\n case \"custom_tool_call_output\": {\n const ctco = item as { call_id?: string; output?: string };\n const callId = ctco.call_id ?? `call_${idx}`;\n customToolCallIds.add(callId);\n const outText = typeof ctco.output === \"string\" ? ctco.output : JSON.stringify(ctco.output ?? \"\");\n coreId = clusters.next(deriveMessageId(\"tool\", \"tool-result\", outText, { toolCallId: callId }));\n msgs.push({ id: coreId, role: \"tool\", contentType: \"tool-result\", toolCallId: callId, text: outText, rawResponsesItem: item });\n break;\n }\n default:\n if (!isOpaqueItem(item)) preamble.push(item);\n break;\n }\n layout.push({ original: item, coreId });\n idx++;\n }\n return { msgs, systemParts, preamble, customToolCallIds, layout, droppedReasoning };\n}\n\nfunction patchTextParts(parts: ResponseContentPart[], text: string): ResponseContentPart[] {\n const textIndexes = parts.flatMap((part, index) =>\n part.type === \"input_text\" || part.type === \"output_text\" ? [index] : [],\n );\n if (textIndexes.length === 0) return [{ type: \"input_text\", text }, ...parts];\n const first = textIndexes[0];\n const remaining = new Set(textIndexes.slice(1));\n return parts.map((part, index) => {\n if (index === first) return { ...part, text };\n if (remaining.has(index)) return { ...part, text: \"\" };\n return part;\n });\n}\n\nfunction patchOriginalItem(original: ResponseInputItem, source: CoreMessage, next: CoreMessage): ResponseInputItem {\n if (\n source.text === next.text &&\n source.toolName === next.toolName &&\n source.toolCallId === next.toolCallId &&\n source.role === next.role &&\n source.contentType === next.contentType\n ) return original;\n if (original.type === \"message\") {\n const message = original as ResponseInputMessage;\n const content = typeof message.content === \"string\" ? next.text ?? \"\" : patchTextParts(message.content, next.text ?? \"\");\n return { ...message, content };\n }\n if (original.type === \"function_call\") {\n return {\n ...original,\n name: next.toolName ?? String(original.name ?? \"unknown\"),\n call_id: next.toolCallId ?? String(original.call_id ?? \"\"),\n arguments: next.text ?? \"\",\n };\n }\n if (original.type === \"function_call_output\") {\n return { ...original, call_id: next.toolCallId ?? String(original.call_id ?? \"\"), output: next.text ?? \"\" };\n }\n return original;\n}\n\nexport function patchResponsesInput(projection: ResponsesProjection, messages: CoreMessage[]): string | ResponseInputItem[] {\n if (projection.stringInput) {\n const original = projection.msgs.find((message) => message.id === projection.stringInput?.coreId);\n const next = messages.find((message) => message.id === projection.stringInput?.coreId);\n if (original && next && messages.length === 1 && next.role === \"user\" && next.contentType === \"text\") {\n return next.text === original.text ? projection.stringInput.original : next.text ?? \"\";\n }\n return coreToResponses(messages, projection.customToolCallIds);\n }\n const sourceById = new Map(projection.msgs.map((message) => [message.id, message]));\n const nextById = new Map(messages.map((message) => [message.id, message]));\n const slotById = new Map<string, number>();\n projection.layout.forEach((slot, index) => {\n if (slot.coreId) slotById.set(slot.coreId, index);\n });\n const insertions = new Map<number, ResponseInputItem[]>();\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (sourceById.has(message.id)) continue;\n let target = projection.layout.length;\n for (let nextIndex = index + 1; nextIndex < messages.length; nextIndex++) {\n const slot = slotById.get(messages[nextIndex]!.id);\n if (slot !== undefined) {\n target = slot;\n break;\n }\n }\n const generated = coreToResponses([message], projection.customToolCallIds);\n if (generated.length > 0) insertions.set(target, [...(insertions.get(target) ?? []), ...generated]);\n }\n const out: ResponseInputItem[] = [];\n projection.layout.forEach((slot, index) => {\n out.push(...(insertions.get(index) ?? []));\n if (!slot.coreId) {\n out.push(slot.original);\n return;\n }\n const source = sourceById.get(slot.coreId);\n const next = nextById.get(slot.coreId);\n if (source && next) out.push(patchOriginalItem(slot.original, source, next));\n });\n out.push(...(insertions.get(projection.layout.length) ?? []));\n return out;\n}\n\nexport function coreToResponses(\n messages: CoreMessage[],\n customToolCallIds: Set<string> = new Set(),\n): ResponseInputItem[] {\n const out: ResponseInputItem[] = [];\n for (const message of messages) {\n const biliMessage = message as BiliMessage;\n const raw = biliMessage.rawResponsesItem as ResponseInputItem | undefined;\n if (message.role === \"system\") {\n out.push({ type: \"message\", role: \"developer\", content: message.text ?? \"\" });\n } else if (message.role === \"user\") {\n if (raw?.type === \"message\" && canonicalUserText(raw as ResponseInputMessage) === (message.text ?? \"\")) out.push(raw);\n else out.push({ type: \"message\", role: \"user\", content: message.text ?? \"\" });\n } else if (message.role === \"assistant\") {\n if (message.contentType === \"text\") {\n out.push({ type: \"message\", role: \"assistant\", content: message.text ?? \"\" });\n } else if (message.contentType === \"tool-call\") {\n const callId = message.toolCallId ?? `call_${message.id}`;\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call\", call_id: callId, name: message.toolName ?? \"unknown\", input: message.text ?? \"\", status: \"completed\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call\", call_id: callId, name: message.toolName ?? \"unknown\", arguments: message.text ?? \"\" });\n }\n } else if (message.contentType === \"reasoning\") {\n if (raw) out.push(raw);\n }\n } else if (message.role === \"tool\") {\n const callId = message.toolCallId ?? \"\";\n if (customToolCallIds.has(callId)) {\n out.push({ type: \"custom_tool_call_output\", call_id: callId, output: message.text ?? \"\" } as ResponseInputItem);\n } else {\n out.push({ type: \"function_call_output\", call_id: callId, output: message.text ?? \"\" });\n }\n }\n }\n return out;\n}\n\nexport function injectResponsesDeveloperMessage(\n input: string | ResponseInputItem[],\n content: string,\n): ResponseInputItem[] {\n const items: ResponseInputItem[] = typeof input === \"string\"\n ? [{ type: \"message\", role: \"user\", content: input }]\n : [...input];\n let index = 0;\n while (items[index]?.type === \"additional_tools\") index++;\n items.splice(index, 0, { type: \"message\", role: \"developer\", content });\n return items;\n}\n\nexport function conversationIdentityResponses(\n body: ResponsesRequestBody,\n headerValue?: string,\n): ConversationIdentity {\n if (headerValue?.trim()) return { value: headerValue.trim(), source: \"header\", clientProvided: true };\n if (typeof body.session_id === \"string\" && body.session_id.trim()) {\n return { value: body.session_id.trim(), source: \"body-session\", clientProvided: true };\n }\n const metadataSession = body.metadata?.session_id;\n if (typeof metadataSession === \"string\" && metadataSession.trim()) {\n return { value: metadataSession.trim(), source: \"metadata-session\", clientProvided: true };\n }\n if (typeof body.previous_response_id === \"string\" && body.previous_response_id.trim()) {\n return { value: body.previous_response_id.trim(), source: \"previous-response\", clientProvided: false };\n }\n return { value: hashId(JSON.stringify(body.input ?? [])), source: \"content-fingerprint\", clientProvided: false };\n}\n\nexport function conversationSignalResponses(body: ResponsesRequestBody, headerValue?: string): string {\n return conversationIdentityResponses(body, headerValue).value;\n}\n\n// Codex subagents (guardian approval reviewer, etc.) reuse the main\n// conversation's body.session_id, so identity alone collapses their requests\n// onto the main session's compression state — a compressed subagent request\n// loses the verbatim user authorization it must read back (#150). Subagent\n// requests carry their own `instructions` (the agent's role prompt), so the\n// FIRST instructions seen for an identity anchor the main namespace (it never\n// changes for the conversation, even if the main prompt drifts), and any other\n// instructions value maps to a separate `|sub:` namespace with its own empty\n// compression state. Subagent requests are self-contained replays, so the\n// fresh namespace is lossless.\nexport interface SubagentNamespaces {\n /** Resolve the compression-state namespace for a request: the identity\n * itself for the anchored (main) instructions, `identity|sub:<fp>` for\n * any other instructions value. First-seen instructions anchor. */\n namespaceFor(identityValue: string, instructions: unknown): string;\n}\n\n/** Host-owned subagent-namespace store.\n *\n * The anchor map is per-conversation mutable state, so it belongs to the\n * host — NOT to a library module global. Create one instance and keep it for\n * the process lifetime (or persist it alongside your session store if you\n * need namespaces to survive restarts: a fresh instance re-anchors on the\n * first request it sees, which after a restart may be a subagent request,\n * orphaning the main conversation's stored compression state). */\nexport function createSubagentNamespaces(): SubagentNamespaces {\n const anchors = new Map<string, string>();\n return {\n namespaceFor(identityValue: string, instructions: unknown): string {\n if (typeof instructions !== \"string\" || instructions.trim().length === 0) return identityValue;\n const fp = hashId(instructions);\n const anchor = anchors.get(identityValue);\n if (anchor === undefined) {\n anchors.set(identityValue, fp);\n return identityValue;\n }\n return anchor === fp ? identityValue : `${identityValue}|sub:${fp}`;\n },\n };\n}\n\n// Convenience singleton for single-process proxies that don't manage\n// per-session state themselves. Hosts needing isolation between\n// conversations, deterministic namespaces across restarts, or a bound on\n// anchor memory should create their own instance via\n// createSubagentNamespaces() and own its lifecycle.\nconst defaultNamespaces = createSubagentNamespaces();\n\nexport function subagentNamespace(identityValue: string, instructions: unknown): string {\n return defaultNamespaces.namespaceFor(identityValue, instructions);\n}\n","export const WIRE_FORMATS = [\"anthropic\", \"openai\", \"responses\"] as const;\nexport type WireFormat = (typeof WIRE_FORMATS)[number];\n\nexport function isWireFormat(value: unknown): value is WireFormat {\n return (\n typeof value === \"string\" &&\n (WIRE_FORMATS as readonly string[]).includes(value)\n );\n}\n\n/**\n * Classify a provider request body by the codec that can parse it.\n * Returns undefined when no codec handles the body — the caller must\n * pass such payloads through untransformed.\n */\nexport function detectWireFormat(payload: unknown): WireFormat | undefined {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const p = payload as Record<string, unknown>;\n if (Array.isArray(p.input)) return \"responses\";\n const messages = p.messages;\n if (!Array.isArray(messages)) return undefined;\n if (\"system\" in p || \"anthropic_version\" in p) return \"anthropic\";\n for (const m of messages as Array<Record<string, unknown>>) {\n if (m === null || typeof m !== \"object\") continue;\n const c = m.content;\n if (Array.isArray(c)) {\n for (const b of c as Array<Record<string, unknown>>) {\n if (b && typeof b === \"object\" && typeof b.type === \"string\") {\n if (\n b.type === \"tool_use\" ||\n b.type === \"tool_result\" ||\n b.type === \"thinking\"\n )\n return \"anthropic\";\n if (b.type === \"text\" && \"cache_control\" in b) return \"anthropic\";\n }\n }\n }\n if (Array.isArray(m.tool_calls)) return \"openai\";\n if (m.role === \"tool\" && typeof m.tool_call_id === \"string\")\n return \"openai\";\n if (m.role === \"system\" || m.role === \"developer\") return \"openai\";\n }\n // Both chat formats share role+messages; default to openai — the safer\n // guess for OpenAI-compatible endpoints (GLM, DeepSeek, vLLM).\n return \"openai\";\n}\n","import { anthropicToCore } from \"./anthropic.js\";\nimport { openaiToCore } from \"./openai.js\";\nimport { responsesToCore } from \"./responses.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/**\n * Mirror constructors: rebuild the WIRE-SHAPE projection of a persisted\n * conversation (the mirror of \"what the host will put on the wire after a\n * restart\") for each protocol family, then fold it through the matching\n * `*ToCore` codec so the projection lands in the same identity/fingerprint\n * space as the live request.\n *\n * This used to live as three hand-rolled builders in the omp plugin\n * (wire-fold.ts) — protocol knowledge scattered across consumers is exactly\n * how the issue-#64 class of restart divergences happened (one place fixed,\n * another broke). The wire layouts now live here, next to the codecs that\n * define their identity space.\n *\n * CONTRACT: the caller maps its own persisted message shape into\n * {@link MirrorMessage} FIRST and normalizes text there (e.g. ref-tag\n * stripping is a host-app concern, not a wire concern). Builders only apply\n * host-encoder wire rules:\n * - thinking rides each wire the way the live encoder sends it\n * (openai: `reasoning_content` field — hosts that demote inline as\n * `<think>…</think>` land in the same identity space anyway because\n * `openaiToCore` normalizes the inline form; anthropic: signed\n * `{type:\"thinking\"}` blocks; responses: `{type:\"reasoning\"}` items);\n * - whitespace-only text survives on the openai wire, is dropped on the\n * anthropic/responses wires (host encoder behaviour);\n * - tool calls/results map to each wire's native shape.\n */\n\nexport type MirrorBlock =\n | { type: \"text\"; text: string }\n | { type: \"thinking\"; thinking: string; signature?: string }\n | { type: \"toolCall\"; id?: string; name?: string; arguments?: unknown };\n\nexport type MirrorMessage = {\n /** `meta` is anything the host sends as out-of-band/system-ish traffic. */\n role: \"user\" | \"assistant\" | \"toolResult\" | \"meta\";\n blocks?: MirrorBlock[];\n /** toolResult only. */\n toolCallId?: string;\n /** meta only: extracted text or summary. */\n text?: string;\n};\n\nfunction textBlocks(blocks: MirrorBlock[] | undefined): string[] {\n const out: string[] = [];\n for (const b of blocks ?? []) if (b.type === \"text\") out.push(b.text);\n return out;\n}\n\n/** Openai wire text: text blocks joined with \"\\n\" (whitespace-only kept). */\nfunction joinText(blocks: MirrorBlock[] | undefined): string {\n return textBlocks(blocks).join(\"\\n\");\n}\n\nfunction thinkingText(blocks: MirrorBlock[] | undefined): string {\n return blocks\n ?.filter((b) => b.type === \"thinking\" && b.thinking.trim().length > 0)\n .map((b) => (b as { thinking: string }).thinking)\n .join(\"\\n\") ?? \"\";\n}\n\n/** Openai/completions mirror: system message first, then the conversation\n * with thinking as the `reasoning_content` field (issue #103). */\nexport function mirrorOpenaiMessages(view: MirrorMessage[], systemText: string): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [{ role: \"system\", content: systemText }];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: text });\n } else if (message.role === \"assistant\") {\n const calls = (message.blocks ?? []).filter((b) => b.type === \"toolCall\") as Array<{ id?: string; name?: string; arguments?: unknown }>;\n const reasoning = thinkingText(message.blocks);\n const text = joinText(message.blocks);\n if (calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: text,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n tool_calls: calls.map((c) => ({\n id: c.id,\n type: \"function\",\n function: { name: c.name ?? \"\", arguments: JSON.stringify(c.arguments ?? {}) },\n })),\n });\n } else if (text || reasoning) {\n messages.push({ role: \"assistant\", content: text, ...(reasoning ? { reasoning_content: reasoning } : {}) });\n }\n } else if (message.role === \"toolResult\") {\n messages.push({ role: \"tool\", tool_call_id: message.toolCallId ?? \"\", content: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"developer\", content: text });\n }\n }\n return messages;\n}\n\n/** Anthropic/messages mirror: no system message (the live request carries it\n * as the top-level `system` field, out of the fold space — issue #64), tool\n * results folded into user messages, thinking as signed `{type:\"thinking\"}`\n * blocks (issue #103). Unsigned thinking is demoted to text by the live\n * encoder; sending it as a thinking block diverges, so callers that persist\n * unsigned thinking should send it as a text block instead. */\nexport function mirrorAnthropicMessages(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const messages: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n } else if (message.role === \"assistant\") {\n const content: Array<Record<string, unknown>> = [];\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n content.push({\n type: \"thinking\",\n thinking: b.thinking,\n ...(typeof b.signature === \"string\" && b.signature ? { signature: b.signature } : {}),\n });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n content.push({ type: \"text\", text: b.text });\n } else if (b.type === \"toolCall\") {\n let input: unknown = {};\n try {\n input = b.arguments && typeof b.arguments === \"object\" ? b.arguments : JSON.parse(JSON.stringify(b.arguments ?? {}));\n } catch {\n input = {};\n }\n content.push({ type: \"tool_use\", id: b.id, name: b.name ?? \"\", input });\n }\n }\n if (content.length > 0) messages.push({ role: \"assistant\", content });\n } else if (message.role === \"toolResult\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"tool_result\", tool_use_id: message.toolCallId ?? \"\", content: joinText(message.blocks) }],\n });\n } else {\n const text = message.text ?? \"\";\n if (text) messages.push({ role: \"user\", content: [{ type: \"text\", text }] });\n }\n }\n return messages;\n}\n\n/** Responses mirror: the live /v1/responses request carries the system\n * prompt in the top-level `instructions` field and the conversation as an\n * `input` item array (issue #64, responses variant). Assistant blocks are\n * emitted in content order so the core sequence matches the live wire\n * (issue #103 parity). */\nexport function mirrorResponsesInput(view: MirrorMessage[]): Array<Record<string, unknown>> {\n const input: Array<Record<string, unknown>> = [];\n for (const message of view) {\n if (message.role === \"user\") {\n const text = joinText(message.blocks);\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n } else if (message.role === \"assistant\") {\n for (const b of message.blocks ?? []) {\n if (b.type === \"thinking\" && b.thinking.trim().length > 0) {\n input.push({ type: \"reasoning\", summary: [{ type: \"summary_text\", text: b.thinking }] });\n } else if (b.type === \"text\" && b.text.trim().length > 0) {\n input.push({ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: b.text }] });\n } else if (b.type === \"toolCall\") {\n let args = \"{}\";\n try {\n args = JSON.stringify(b.arguments ?? {});\n } catch {\n args = \"{}\";\n }\n input.push({ type: \"function_call\", call_id: b.id ?? \"\", name: b.name ?? \"\", arguments: args });\n }\n }\n } else if (message.role === \"toolResult\") {\n input.push({ type: \"function_call_output\", call_id: message.toolCallId ?? \"\", output: joinText(message.blocks) });\n } else {\n const text = message.text ?? \"\";\n if (text) input.push({ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text }] });\n }\n }\n return input;\n}\n\n/** Fold the openai mirror through `openaiToCore`. */\nexport function mirrorOpenaiToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = openaiToCore({\n model: \"prime-fold\",\n messages: mirrorOpenaiMessages(view, systemText) as Parameters<typeof openaiToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the anthropic mirror through `anthropicToCore`. */\nexport function mirrorAnthropicToCore(view: MirrorMessage[]): BiliMessage[] {\n const { msgs } = anthropicToCore({\n model: \"prime-fold\",\n messages: mirrorAnthropicMessages(view) as Parameters<typeof anthropicToCore>[0][\"messages\"],\n });\n return msgs;\n}\n\n/** Fold the responses mirror through `responsesToCore`. */\nexport function mirrorResponsesToCore(view: MirrorMessage[], systemText: string): BiliMessage[] {\n const { msgs } = responsesToCore({\n model: \"prime-fold\",\n instructions: systemText,\n input: mirrorResponsesInput(view) as Parameters<typeof responsesToCore>[0][\"input\"],\n });\n return msgs;\n}\n","/**\n * Compress-call detection and replay-guard on the wire/core stream\n * (Phase K2, moved from billion-context-omp `src/wire-fold.ts`).\n *\n * Two layers:\n * - Detection: `compressToolArgs` accepts the two call shapes that exist in\n * the wild (direct `compress`; legacy `write` to `xd://compress`, args\n * JSON-encoded one or two levels deep), `findCompressCalls` /\n * `findCompressCallsCore` turn a stream tool-call into validated ranges.\n * - Guard: when compression state is REPLAYED against a rebuilt stream\n * (restart, mirror divergence, host re-serialization), every recorded\n * range must prove it still covers the same content — fingerprint match\n * (first/last piece content key), position fallback for drifted\n * boundaries, remap for dangling m-refs.\n *\n * Pure functions over BiliMessage/CoreMessage — no host types, no I/O.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { CoreMessage } from \"../types.js\";\nimport type { BiliMessage } from \"./bili-message.js\";\n\n/** A compress call carried by a stream tool-call, normalized to validated\n * ranges. `id` is the tool-call id (replay dedup key). */\nexport interface StreamCompressCall {\n id: string;\n ranges: {\n startRef: string;\n endRef: string;\n summary: string;\n topic?: string;\n summaryMaxChars?: number;\n compressCallId: string;\n }[];\n}\n\n/** Extract a compress tool's arguments from a stream toolCall. Two call\n * shapes exist: (1) top-level — the tools are registered with\n * loadMode:\"essential\" so hosts do NOT mount them as xd:// devices; the\n * stream shows name:\"compress\" directly. (2) legacy xd:// — sessions\n * recorded before that change (or hosts forcing discoverable mounting)\n * invoked compress through the write tool with path \"xd://compress\" and\n * the tool args JSON-encoded in the content field. Both shapes must replay\n * from the stream. Returns normalized compress args (content array plus\n * optional topic / summaryMaxChars from wherever they live). */\nexport function compressToolArgs(call: { name: string; arguments?: unknown }): {\n content: unknown[];\n topic?: unknown;\n summaryMaxChars?: unknown;\n} | null {\n let args = call.arguments;\n if (typeof args === \"string\") {\n try { args = JSON.parse(args); } catch { return null; }\n }\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return null;\n const a = args as Record<string, unknown>;\n if (call.name === \"compress\") {\n return Array.isArray(a.content) ? { content: a.content, topic: a.topic, summaryMaxChars: a.summaryMaxChars } : null;\n }\n if (call.name !== \"write\") return null;\n const path = typeof a.path === \"string\" ? a.path.split(\"?\")[0]!.replace(/\\/+$/, \"\") : \"\";\n if (path !== \"xd://compress\") return null;\n let inner: unknown = a.content;\n if (typeof inner === \"string\") {\n try { inner = JSON.parse(inner); } catch { return null; }\n }\n if (!inner || typeof inner !== \"object\") return null;\n if (Array.isArray(inner)) return { content: inner };\n const ia = inner as Record<string, unknown>;\n return Array.isArray(ia.content) ? { content: ia.content, topic: ia.topic, summaryMaxChars: ia.summaryMaxChars } : { content: [ia] };\n}\n\n/** toolCallId → toolName for every tool-call piece (protected-piece\n * detection: compress + configured tools are never folded). */\nexport function toolCallNames(msgs: BiliMessage[]): Map<string, string> {\n const names = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType === \"tool-call\" && m.toolCallId && m.toolName) names.set(m.toolCallId, m.toolName);\n }\n return names;\n}\n\n/** toolCallId → result text for every tool-result piece (compress result\n * rendering inside rebuilt payloads). */\nexport function toolResultTextsCore(msgs: BiliMessage[]): Map<string, string> {\n const results = new Map<string, string>();\n for (const m of msgs) {\n if (m.contentType !== \"tool-result\" || !m.toolCallId) continue;\n results.set(m.toolCallId, m.text ?? \"\");\n }\n return results;\n}\n\n/** Compress calls carried by a core tool-call piece. Same two shapes as the\n * AgentMessage stream (direct compress; legacy xd://compress via write),\n * with the arguments JSON-encoded in the piece's text. */\nexport function findCompressCallsCore(msg: BiliMessage): StreamCompressCall[] {\n if (msg.contentType !== \"tool-call\" || !msg.toolName) return [];\n const args = compressToolArgs({ name: msg.toolName, arguments: msg.text });\n if (!args) return [];\n const content = args.content;\n if (!Array.isArray(content)) return [];\n const ranges: StreamCompressCall[\"ranges\"] = [];\n const callTopic = typeof args.topic === \"string\" ? args.topic : undefined;\n for (const item of content) {\n const r = item as { startId?: unknown; endId?: unknown; summary?: unknown; topic?: unknown };\n if (typeof r.startId !== \"string\" || typeof r.endId !== \"string\" || typeof r.summary !== \"string\" || r.summary.length === 0) continue;\n ranges.push({\n startRef: r.startId,\n endRef: r.endId,\n summary: r.summary,\n topic: typeof r.topic === \"string\" ? r.topic : callTopic,\n summaryMaxChars: typeof args.summaryMaxChars === \"number\" ? args.summaryMaxChars : undefined,\n compressCallId: msg.toolCallId ?? \"\",\n });\n }\n return ranges.length > 0 ? [{ id: msg.toolCallId ?? \"\", ranges }] : [];\n}\n\n/** Content key of a core piece for span fingerprints (issue #91): role,\n * contentType, toolName and the FIRST 4096 chars of text. The 4096 cap is\n * deliberate: a host re-serialization that drifts only the tail (beyond\n * char 4096, e.g. truncation of a long tool output) keeps the key intact,\n * so the replay guard tells a benign tail drift from a genuine rewrite. */\nexport function corePieceKey(cm: CoreMessage): string {\n return `${cm.role}|${cm.contentType}|${cm.toolName ?? \"\"}|${(cm.text ?? \"\").slice(0, 4096)}`;\n}\n\n/** Span fingerprint in content-hash space: hash the content keys of the\n * exact first/last covered pieces. Boundary ids are pre-resolved (byRef /\n * block lookup) — unlike the pN-space spanFingerprint there is no position\n * parsing, ids are unique per piece. */\nexport function spanFingerprintCore(coreMessages: CoreMessage[], startId: string, endId: string): string {\n const find = (id: string): CoreMessage | undefined => coreMessages.find((cm) => cm.id === id);\n const first = find(startId);\n const last = find(endId);\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Index-based span fingerprint (issue #91 replay fallback): hash the content\n * keys of the pieces AT the given stream positions. The stored fp still\n * decides keep/drop — the position is only a recovery hint for a drifted\n * boundary whose content-hash id no longer matches, so a benign tail drift\n * (first-4096 intact) is kept while a real rewrite mismatches. */\nexport function spanFingerprintCoreIdx(coreMessages: CoreMessage[], startIdx: number, endIdx: number): string {\n const first = coreMessages[startIdx];\n const last = coreMessages[endIdx];\n if (!first || !last) return \"\";\n return createHash(\"sha1\").update(`${corePieceKey(first)}\\u0000${corePieceKey(last)}`).digest(\"hex\").slice(0, 8);\n}\n\n/** Structural subset the boundary resolvers need from a compression block\n * (kernel CompressionBlock satisfies this; keeps the guard usable from\n * downstreams that carry lighter block records). */\nexport interface BlockLike {\n blockId: string;\n effectiveMessageIds: string[];\n}\n\n/** Resolve a range boundary to the exact id of the piece it names, in\n * content-hash space. Message refs go through byRef; block refs resolve to\n * the earliest (min) or latest (max) covered piece by STREAM ORDER\n * (index in coreMessages — the hash ids carry no position). */\nexport function boundaryRawCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n): string {\n const raw = byRef[ref];\n if (raw) return raw;\n const m = /^b(\\d+)$/i.exec(ref.trim());\n if (!m) return \"\";\n const block = blocks.find((b) => b.blockId.toLowerCase() === `b${m[1]}`);\n if (!block) return \"\";\n const idx = (id: string): number => coreMessages.findIndex((cm) => cm.id === (byRef[id] ?? id));\n let best = -1;\n for (const id of block.effectiveMessageIds) {\n const i = idx(id);\n if (i < 0) continue;\n if (best < 0 || (pick === \"min\" ? i < best : i > best)) best = i;\n }\n return best < 0 ? \"\" : (coreMessages[best]?.id ?? \"\");\n}\n\n/** Resolve a range boundary to its STREAM INDEX in content-hash space. byRef /\n * block lookup first (the exact piece it names, by array order); on a missed\n * id (a drift re-hashed the piece so its carried ref dangles) fall back to\n * the compress-time recorded index — the position hint, issue #91. -1 =\n * unresolvable. */\nexport function boundaryIndexCore(\n ref: string,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n coreMessages: CoreMessage[],\n pick: \"min\" | \"max\",\n fallbackIdx = -1,\n): number {\n const id = boundaryRawCore(ref, byRef, blocks, coreMessages, pick);\n if (id) {\n const i = coreMessages.findIndex((cm) => cm.id === id);\n if (i >= 0) return i;\n }\n return fallbackIdx >= 0 && fallbackIdx < coreMessages.length ? fallbackIdx : -1;\n}\n\n/** Structured replay-guard verdict (issue #91, rework): the position\n * fallback recovers the STREAM INDEX of a drifted boundary, but the kernel\n * resolves ranges by REF — so when a recorded m-ref dangles, the replay\n * must re-apply that boundary under the CURRENT ref of the recovered piece.\n * `remap` carries exactly that (only dangling m-refs are remapped; block\n * refs resolve themselves inside the kernel and are never touched). */\nexport type ReplayRangeVerdict = {\n /** Stale: the range must be dropped (master semantics, unchanged). */\n reject?: string;\n /** Dangling m-refs recovered by position, remapped to current refs. */\n remap?: { startRef?: string; endRef?: string };\n /** True when the result text carried a [pos=] pair for this range —\n * with `reject` set it marks a RECOVERY FAILURE (always logged). */\n hint?: boolean;\n /** Diagnostics — always logged when a recovery happens. */\n recovered?: { pos: string; startIdx: number; endIdx: number };\n};\n\n/** Current m-ref of the piece at stream index idx (inverse byRef scan).\n * \"\" when the piece has no ref (protected) — the replay must fail closed\n * rather than hand the kernel a ref it does not know. Replay-time only\n * (replayed compress calls), so the O(refs) scan stays off the hot path. */\nexport function refOfPieceCore(coreMessages: BiliMessage[], idx: number, byRef: Record<string, string>): string {\n const id = coreMessages[idx]?.id;\n if (!id) return \"\";\n for (const [ref, mapped] of Object.entries(byRef)) if (mapped === id) return ref;\n return \"\";\n}\n\nexport function staleRangeCore(\n r: { startRef: string; endRef: string },\n rangeIndex: number,\n resultText: string,\n coreMessages: BiliMessage[],\n callIndex: number,\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): ReplayRangeVerdict {\n // Compress-time boundary positions (issue #91): the stream index each\n // boundary sat at when the call was recorded. A drift that re-hashes a\n // boundary piece dangles its carried ref — the position recovers it, and\n // the fingerprint below still decides keep/drop.\n const pm = resultText.match(/\\[pos=([0-9,-]+)\\]/);\n const pair = pm ? pm[1]!.split(\",\")[rangeIndex] ?? \"-\" : \"-\";\n const hinted = pair !== \"-\";\n const [ps, pe] = pair === \"-\" ? [\"\", \"\"] : pair.split(\"-\");\n const fbStart = ps && ps !== \"\" ? Number.parseInt(ps, 10) : -1;\n const fbEnd = pe && pe !== \"\" ? Number.parseInt(pe, 10) : -1;\n\n // Raw resolution (id → stream index) separately from the fallback, so a\n // dangling m-ref recovered by position can be flagged for remapping.\n const startRaw = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const endRaw = boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\");\n const rawStartIdx = startRaw ? coreMessages.findIndex((cm) => cm.id === startRaw) : -1;\n const rawEndIdx = endRaw ? coreMessages.findIndex((cm) => cm.id === endRaw) : -1;\n const startIdx = rawStartIdx >= 0 ? rawStartIdx : fbStart >= 0 && fbStart < coreMessages.length ? fbStart : -1;\n const endIdx = rawEndIdx >= 0 ? rawEndIdx : fbEnd >= 0 && fbEnd < coreMessages.length ? fbEnd : -1;\n if (startIdx < 0 || endIdx < 0) {\n if (!/^b\\d+$/i.test(r.startRef.trim()) && !/^b\\d+$/i.test(r.endRef.trim()))\n return { reject: `unresolved ${r.startRef}..${r.endRef} -> ${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n return {}; // block ref(s): the kernel resolves them itself (master)\n }\n // The end piece must precede the call that issued it — a rewrite moved\n // the call and the fingerprint check below is meaningless either way.\n if (endIdx > callIndex) return { reject: `end idx ${endIdx} > callIndex ${callIndex}`, ...(hinted ? { hint: true } : {}) };\n const m = resultText.match(/\\[fp=([0-9a-f,-]+)\\]/);\n if (m) {\n const want = m[1]!.split(\",\")[rangeIndex];\n if (want !== undefined && want !== \"-\") {\n const got = spanFingerprintCoreIdx(coreMessages, startIdx, endIdx);\n if (want !== got) return { reject: `fp ${r.startRef}..${r.endRef} want ${want} got ${got} @${startIdx}..${endIdx}`, ...(hinted ? { hint: true } : {}) };\n }\n }\n // Remap only the boundaries that actually dangled (m-refs whose recorded id\n // no longer resolves); resolved boundaries keep their recorded ref, block\n // refs are the kernel's to resolve.\n const remap: { startRef?: string; endRef?: string } = {};\n if (/^m\\d+$/i.test(r.startRef.trim()) && rawStartIdx < 0) {\n const ref = refOfPieceCore(coreMessages, startIdx, byRef);\n if (!ref) return { reject: `recovered ${r.startRef} @${startIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.startRef = ref;\n }\n if (/^m\\d+$/i.test(r.endRef.trim()) && rawEndIdx < 0) {\n const ref = refOfPieceCore(coreMessages, endIdx, byRef);\n if (!ref) return { reject: `recovered ${r.endRef} @${endIdx} has no ref (protected piece)`, ...(hinted ? { hint: true } : {}) };\n remap.endRef = ref;\n }\n if (!remap.startRef && !remap.endRef) return {};\n return { remap, recovered: { pos: pair, startIdx, endIdx } };\n}\n\n/** One fingerprint per range for the replay guard, content-hash space\n * (mirrors rangeFingerprints for the pN space). */\nexport function rangeFingerprintsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: BiliMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const start = boundaryRawCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const end = start ? boundaryRawCore(r.endRef, byRef, blocks, coreMessages, \"max\") : \"\";\n if (start && end) {\n const fp = spanFingerprintCore(coreMessages, start, end);\n if (fp.length > 0) return fp;\n }\n return \"-\";\n });\n}\n\n/** One boundary-index pair per range for the replay fallback (issue #91),\n * aligned with rangeFingerprintsCore: the stream index of each range's exact\n * first/last covered piece at record time (\"-1\" pair when a boundary can't\n * be positioned), so the replay can recover a drifted boundary by position. */\nexport function rangePositionsCore(\n ranges: Array<{ startRef: string; endRef: string }>,\n coreMessages: CoreMessage[],\n byRef: Record<string, string>,\n blocks: BlockLike[],\n): string[] {\n return ranges.map((r) => {\n const s = boundaryIndexCore(r.startRef, byRef, blocks, coreMessages, \"min\");\n const e = s >= 0 ? boundaryIndexCore(r.endRef, byRef, blocks, coreMessages, \"max\") : -1;\n return s >= 0 && e >= 0 ? `${s}-${e}` : \"-\";\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAKpB,SAAS,OAAO,GAAmB;AACtC,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAC3E;;;ACwBO,SAAS,gBACZ,MACA,aACA,MACA,UAGI,CAAC,GACC;AACN,QAAM,OAAO,GAAG,IAAI,IAAI,WAAW,IAAI,QAAQ,cAAc,EAAE,IAAI,QAAQ,YAAY,EAAE,IAAI,IAAI;AACjG,SAAO,OAAO,OAAO,IAAI;AAC7B;AAOO,IAAM,iBAAN,MAAqB;AAAA,EAChB,SAAS,oBAAI,IAAoB;AAAA,EAEzC,KAAK,QAAwB;AACzB,UAAM,IAAI,KAAK,OAAO,IAAI,MAAM,KAAK;AACrC,SAAK,OAAO,IAAI,QAAQ,IAAI,CAAC;AAC7B,WAAO,MAAM,IAAI,SAAS,G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B,EAAE,CAQrB;AAED,wBAAgB,6BAA6B,CACzC,IAAI,EAAE,oBAAoB,EAC1B,WAAW,CAAC,EAAE,MAAM,GACrB,oBAAoB,CAatB;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,oBAAoB,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,CAEpG;AAYD,MAAM,WAAW,kBAAkB;IAC/B;;wEAEoE;IACpE,YAAY,CAAC,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,GAAG,MAAM,CAAC;CACtE;AAED;;;;;;;kEAOkE;AAClE,wBAAgB,wBAAwB,IAAI,kBAAkB,CAc7D;AASD,wBAAgB,iBAAiB,CAAC,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,GAAG,MAAM,CAEtF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acp-kernel",
3
- "version": "0.0.49-pr.186.40",
3
+ "version": "0.0.49-pr.189.41",
4
4
  "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
5
5
  "license": "MIT",
6
6
  "author": "ranxianglei",