dsh-boost 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +97 -33
- package/README.md +85 -32
- package/dist/gate/decide.js +33 -2
- package/dist/gate/decide.js.map +1 -1
- package/dist/hooks/llm-stream.js +129 -54
- package/dist/hooks/llm-stream.js.map +1 -1
- package/dist/hooks/post-execute.js +104 -21
- package/dist/hooks/post-execute.js.map +1 -1
- package/dist/hooks/session-state.js +18 -8
- package/dist/hooks/session-state.js.map +1 -1
- package/dist/index.js +371 -67
- package/dist/index.js.map +1 -1
- package/dist/scope/doc.js.map +1 -1
- package/dist/scope/store.js +24 -9
- package/dist/scope/store.js.map +1 -1
- package/package.json +8 -4
- package/dist/admission/fixed-cost.d.ts +0 -23
- package/dist/admission/ledger.d.ts +0 -113
- package/dist/admission/retrieval.d.ts +0 -65
- package/dist/admission/usage.d.ts +0 -75
- package/dist/config.d.ts +0 -43
- package/dist/gate/binding.d.ts +0 -113
- package/dist/gate/decide.d.ts +0 -82
- package/dist/gate/guard.d.ts +0 -69
- package/dist/gate/invalidate.d.ts +0 -112
- package/dist/gate/plan.d.ts +0 -86
- package/dist/hooks/clock.d.ts +0 -68
- package/dist/hooks/execute.d.ts +0 -79
- package/dist/hooks/llm-stream.d.ts +0 -283
- package/dist/hooks/pending.d.ts +0 -89
- package/dist/hooks/post-execute.d.ts +0 -257
- package/dist/hooks/session-state.d.ts +0 -158
- package/dist/hooks/synthesize.d.ts +0 -74
- package/dist/host/loader.d.ts +0 -23
- package/dist/host/platform.d.ts +0 -18
- package/dist/host/root.d.ts +0 -25
- package/dist/projection/apply.d.ts +0 -174
- package/dist/projection/canonicalise.d.ts +0 -43
- package/dist/projection/counters.d.ts +0 -65
- package/dist/projection/truncate.d.ts +0 -47
- package/dist/prompt/protocol.d.ts +0 -45
- package/dist/receipts/store.d.ts +0 -198
- package/dist/scope/doc.d.ts +0 -117
- package/dist/scope/resolve.d.ts +0 -91
- package/dist/scope/store.d.ts +0 -135
- package/dist/selector/jev.d.ts +0 -93
- package/dist/tools/boost.d.ts +0 -380
- package/dist/tools/family.d.ts +0 -26
package/dist/scope/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,SAAS,GAAG,YAAY,CAAA;AAC9B,0FAA0F;AAC1F,MAAM,aAAa,GAAG,MAAM,CAAA;AAC5B;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,EAAE,GAAG,aAAa,CAAA;AAC3C,qEAAqE;AACrE,MAAM,OAAO,GAAG,aAAa,CAAA;AAC7B,yEAAyE;AACzE,MAAM,CAAC,MAAM,uBAAuB,GAAG,yBAAyB,CAAA;AAChE,wFAAwF;AACxF,MAAM,UAAU,GAAG,UAAU,EAAE,CAAA;AAwB/B,8EAA8E;AAC9E,SAAS,UAAU,CAAC,IAAe,EAAE,MAAc;IACjD,OAAO,MA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A;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\nfunction errorCode(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined\n}\n\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A corrupt or version 1 file\n * is also based on the strict default, which is how `boost scope set`\n * explicitly upgrades a version 1 document. A **future** version (a numeric\n * version greater than 2) is refused with `ERR_SCOPE_FUTURE_VERSION` before\n * the mutation: the newer field set cannot be represented here, so rewriting\n * it would silently drop configuration. An existing file that cannot be read\n * at all is `ERR_SCOPE_READ_FAILED` — never overwritten blindly.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade ?? current.doc\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // Serialization and disk failures are storage failures too; rule 8\n // requires a stable code on every error the write path raises.\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,yBAAyB,EACzB,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,SAAS,GAAG,YAAY,CAAA;AAC9B,0FAA0F;AAC1F,MAAM,aAAa,GAAG,MAAM,CAAA;AAC5B;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,EAAE,GAAG,aAAa,CAAA;AAC3C,qEAAqE;AACrE,MAAM,OAAO,GAAG,aAAa,CAAA;AAC7B,yEAAyE;AACzE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EAAsB,CAAA;QAC1B,IAAI,CAAC;YACH,EAAE,GAAG,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;YAC5B,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YACvB,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,EAAE,GAAG,SAAS,CAAA;YACd,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAA;YAC1C,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;gBACrB,IAAI,CAAC;oBACH,SAAS,CAAC,EAAE,CAAC,CAAA;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_UNKNOWN_VERSION,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\nfunction errorCode(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined\n}\n\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A version 1 file is based on\n * the fields it actually carries, which is how `boost scope set` explicitly\n * upgrades it. Every other present-but-unusable document is refused before\n * the mutation: a **future** version (a numeric version greater than 2) with\n * `ERR_SCOPE_FUTURE_VERSION`, a non-document with\n * `ERR_SCOPE_PARSE_FAILED`, a missing or non-numeric version with\n * `ERR_SCOPE_UNKNOWN_VERSION`, and an unreadable file with\n * `ERR_SCOPE_READ_FAILED`. Each refusal leaves the file byte-identical.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // Both remaining codes mean the bytes are present but unusable. Key on\n // the code, not on this branch: only a v1 document (whose `upgrade`\n // `decode` supplied) has recognised fields worth preserving, and only\n // its documented `scope-set` upgrade may rewrite the file. A parse\n // failure has no fields at all, and a missing or non-numeric version is\n // equally unrepresentable; basing a write on DEFAULT_SCOPE for either\n // would silently replace the user's document, which `docs/RELEASE.md`\n // promises not to do (\"写拒绝\" / \"写不盲改\").\n if (current.code === ERR_SCOPE_PARSE_FAILED) {\n throw scopeError(\n ERR_SCOPE_PARSE_FAILED,\n `refusing to rewrite ${this.file}: it is not a scope document`,\n )\n }\n if (current.upgrade === undefined) {\n throw scopeError(\n ERR_SCOPE_UNKNOWN_VERSION,\n `refusing to rewrite ${this.file}: it declares an unknown scope version`,\n )\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // Serialization and disk failures are storage failures too; rule 8\n // requires a stable code on every error the write path raises.\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-boost",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Cut DSH token usage by projecting tool receipts and substituting deterministic read-only calls.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -40,8 +40,7 @@
|
|
|
40
40
|
"stats": "node scripts/session-stats.mjs",
|
|
41
41
|
"ci": "npm run typecheck && npm test && npm run build",
|
|
42
42
|
"verify:package": "node scripts/verify-package.mjs",
|
|
43
|
-
"
|
|
44
|
-
"prepublishOnly": "npm run ci && npm run verify:package"
|
|
43
|
+
"prepublishOnly": "npm run ci && npm run verify:package -- --prebuilt"
|
|
45
44
|
},
|
|
46
45
|
"devDependencies": {
|
|
47
46
|
"@deepseek-ai/dsh-llm": "0.2.2-rc.4",
|
|
@@ -49,6 +48,8 @@
|
|
|
49
48
|
"@deepseek-ai/dsh-spill-policy": "0.2.2-rc.4",
|
|
50
49
|
"@deepseek-ai/dsh-token-meter": "0.2.2-rc.4",
|
|
51
50
|
"@types/node": "^24",
|
|
51
|
+
"js-yaml": "^4.3.2",
|
|
52
|
+
"semver": "^7.8.5",
|
|
52
53
|
"tsx": "^4.19.0",
|
|
53
54
|
"typescript": "^5.6.0"
|
|
54
55
|
},
|
|
@@ -58,7 +59,7 @@
|
|
|
58
59
|
},
|
|
59
60
|
"engines": {
|
|
60
61
|
"node": ">=24.9.0",
|
|
61
|
-
"dsh": "0.2.2-rc.4"
|
|
62
|
+
"dsh": ">=0.2.2-rc.4 <0.2.3-0"
|
|
62
63
|
},
|
|
63
64
|
"dsh": {
|
|
64
65
|
"bundle": {
|
|
@@ -67,6 +68,9 @@
|
|
|
67
68
|
},
|
|
68
69
|
"files": [
|
|
69
70
|
"dist",
|
|
71
|
+
"!dist/**/*.d.ts",
|
|
72
|
+
"dist/index.d.ts",
|
|
73
|
+
"dist/types.d.ts",
|
|
70
74
|
"locale",
|
|
71
75
|
"cordis.patch.yml",
|
|
72
76
|
"README.md",
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/** The import seam, injectable so a test can simulate an absent/broken peer. */
|
|
2
|
-
type ModuleLoader = <T>(specifier: string) => Promise<T | undefined>;
|
|
3
|
-
/** One measured fixed-overhead breakdown, in tokens. */
|
|
4
|
-
export interface FixedOverheadMeasurement {
|
|
5
|
-
/** The protocol section alone (`estimateSystemMessage`). */
|
|
6
|
-
protocolTokens: number;
|
|
7
|
-
/** The `boost` tool schema alone (`estimateToolsTokens`). */
|
|
8
|
-
toolSchemaTokens: number;
|
|
9
|
-
/** The per-request total the design budgets at ≤800. */
|
|
10
|
-
totalTokens: number;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Measure the full fixed overhead: the protocol section **and** the tool schema.
|
|
14
|
-
*
|
|
15
|
-
* Both components are priced by the same host estimator module. Any failure
|
|
16
|
-
* (missing package/export, a throw, a non-finite part) makes the whole result
|
|
17
|
-
* `'unknown'`; a partial total would be a fabricated number. The tool schema is
|
|
18
|
-
* wrapped in the canonical-envelope shape `estimateToolsTokens` reads
|
|
19
|
-
* (`{ tools: [...] }`), never stringified by hand, so the measurement stays the
|
|
20
|
-
* host's rather than a second heuristic.
|
|
21
|
-
*/
|
|
22
|
-
export declare function measureFixedOverhead(toolSchema: unknown, text?: string, load?: ModuleLoader): Promise<FixedOverheadMeasurement | 'unknown'>;
|
|
23
|
-
export {};
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Admission arithmetic: is a substitution worth its overhead, and how many
|
|
3
|
-
* steps may the current turn still take?
|
|
4
|
-
*
|
|
5
|
-
* Both are pure arithmetic. This module performs no I/O, reads no config and
|
|
6
|
-
* keeps no time window; callers pass the resolved `BoostConfig` values in
|
|
7
|
-
* (design §5.3). The mutable state is `StepBudget` (per session/turn, hence
|
|
8
|
-
* `reset()` at every turn start) and `RuntimeStepHorizon` (per-session turn
|
|
9
|
-
* history, cleared on session disposal). The assembly feeds the latter from
|
|
10
|
-
* the host's `agent/pre-step` and reads it at status time, which is what makes
|
|
11
|
-
* `historyTurns` a production input rather than an unused config key.
|
|
12
|
-
*
|
|
13
|
-
* @module dsh-boost/admission/ledger
|
|
14
|
-
*/
|
|
15
|
-
/**
|
|
16
|
-
* Conservative bound on the steps left in this turn (design §5.3).
|
|
17
|
-
*
|
|
18
|
-
* Fewer than `historyTurns` sizes in `stepsSoFar` means there is no usable
|
|
19
|
-
* mean: the horizon is returned verbatim, never an estimate from a short
|
|
20
|
-
* history. Otherwise this is
|
|
21
|
-
* `Math.min(horizonSteps, Math.round(mean(last historyTurns)))`.
|
|
22
|
-
*
|
|
23
|
-
* Degenerate inputs are defined and never NaN:
|
|
24
|
-
* - `historyTurns` is floored once, and that same N gates both the short-
|
|
25
|
-
* history check and the window, so `2.5` with two entries averages them.
|
|
26
|
-
* A floored `historyTurns <= 0` has no window to average, so it takes the
|
|
27
|
-
* horizon path; the literal mean branch would divide by zero.
|
|
28
|
-
* - a non-finite `horizonSteps` (`NaN` or `Infinity`) degrades to `0`
|
|
29
|
-
* (fail-closed).
|
|
30
|
-
* - a non-finite mean (a `NaN` or `Infinity` in the window) falls back to the
|
|
31
|
-
* horizon.
|
|
32
|
-
*
|
|
33
|
-
* The return is a raw estimate, not a sanitised count: a finite `horizonSteps`
|
|
34
|
-
* is passed through unclamped, so a fractional (`20.5`) or negative (`-1`)
|
|
35
|
-
* horizon — and a negative mean — reach the caller as-is. Callers must not
|
|
36
|
-
* assume a non-negative integer; `0` means zero remaining steps.
|
|
37
|
-
*/
|
|
38
|
-
export declare function remainingSteps(input: {
|
|
39
|
-
stepsSoFar: number[];
|
|
40
|
-
horizonSteps: number;
|
|
41
|
-
historyTurns: number;
|
|
42
|
-
}): number;
|
|
43
|
-
/**
|
|
44
|
-
* Per-session history of completed-turn step counts.
|
|
45
|
-
*
|
|
46
|
-
* Design §5.3 asks runtime admission to bound the remaining steps by
|
|
47
|
-
* `min(horizonSteps, mean of the last historyTurns turns)` instead of trusting
|
|
48
|
-
* the fixed horizon, so the plugin never overstates a projection's replay
|
|
49
|
-
* saving. The host reports `(turn, step)` on every model request; this class
|
|
50
|
-
* folds a turn's highest host step into history when the next turn starts. A
|
|
51
|
-
* retried step cannot inflate the count (the maximum is kept), a backwards
|
|
52
|
-
* turn is ignored, and malformed observations create no entry.
|
|
53
|
-
*
|
|
54
|
-
* The state is per session and cleared on `session/disposed` by the assembly;
|
|
55
|
-
* `remaining()` is the conservative aggregate status reports: the minimum over
|
|
56
|
-
* every live session, or the configured horizon when no session has enough
|
|
57
|
-
* completed turns yet.
|
|
58
|
-
*/
|
|
59
|
-
export declare class RuntimeStepHorizon {
|
|
60
|
-
private readonly horizonSteps;
|
|
61
|
-
private readonly historyTurns;
|
|
62
|
-
private readonly bySession;
|
|
63
|
-
constructor(horizonSteps: number, historyTurns: number);
|
|
64
|
-
/** Record one proposed model request for `sessionId` at host `(turn, step)`. */
|
|
65
|
-
observe(sessionId: string, turn: number, step: number): void;
|
|
66
|
-
/** This session's conservative remaining-step estimate. */
|
|
67
|
-
remainingFor(sessionId: string): number;
|
|
68
|
-
/** The conservative minimum across live sessions, or the horizon when none has history. */
|
|
69
|
-
remaining(): number;
|
|
70
|
-
/** Drop one session's history on disposal. */
|
|
71
|
-
clear(sessionId: string): void;
|
|
72
|
-
/** Number of sessions with retained history (diagnostics/tests). */
|
|
73
|
-
size(): number;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Admission gate for one candidate (design §5.3).
|
|
77
|
-
*
|
|
78
|
-
* A deterministic single candidate has no selector call and no plan to pay
|
|
79
|
-
* for, so it skips the threshold entirely. Everything else must clear the
|
|
80
|
-
* threshold strictly: breaking even is not a win.
|
|
81
|
-
*/
|
|
82
|
-
export declare function worthSubstituting(input: {
|
|
83
|
-
savedTokens: number;
|
|
84
|
-
overheadTokens: number;
|
|
85
|
-
thresholdTokens: number;
|
|
86
|
-
deterministicSingle: boolean;
|
|
87
|
-
}): boolean;
|
|
88
|
-
/**
|
|
89
|
-
* Per-turn substitution budget (default 8, design §5.2-6).
|
|
90
|
-
*
|
|
91
|
-
* The plugin owns one instance for its whole lifetime, so calling `reset()` at
|
|
92
|
-
* turn start is mandatory: without it the budget would be spent once and then
|
|
93
|
-
* silently disable substitution for the rest of the process.
|
|
94
|
-
*
|
|
95
|
-
* A non-positive `max` is an empty budget — `take()` always returns `false`
|
|
96
|
-
* and `exhausted()` is already `true`. A fractional max floors, so `count()`
|
|
97
|
-
* can never exceed it. A non-finite max — including `Infinity`, whose literal
|
|
98
|
-
* reading would be "unlimited" — is also an empty budget: fail-closed, and
|
|
99
|
-
* unreachable through `resolveConfig`, which keeps only finite numbers.
|
|
100
|
-
*/
|
|
101
|
-
export declare class StepBudget {
|
|
102
|
-
private readonly max;
|
|
103
|
-
private taken;
|
|
104
|
-
constructor(max: number);
|
|
105
|
-
/** Claim one step; false without incrementing once the budget is spent. */
|
|
106
|
-
take(): boolean;
|
|
107
|
-
/** Start a new turn: the budget is per-turn, not per-plugin-lifetime. */
|
|
108
|
-
reset(): void;
|
|
109
|
-
/** True when no further `take()` can succeed. */
|
|
110
|
-
exhausted(): boolean;
|
|
111
|
-
/** Steps taken since construction or the last `reset()`. */
|
|
112
|
-
count(): number;
|
|
113
|
-
}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Projection retrieval accounting: the denominator of `projection_net_tokens`.
|
|
3
|
-
*
|
|
4
|
-
* The projection ledger's gross saving is what the plugin removed from the
|
|
5
|
-
* history; the net saving must subtract what the model spent reading the
|
|
6
|
-
* spilled original back. `projection_retrievals` counts those reads (design
|
|
7
|
-
* §5.3), and its producer is the `read`/`grep` call that names one of this
|
|
8
|
-
* session's spill locators. A retrieval that is not counted would make every
|
|
9
|
-
* projection look free, which is why this is a ledger and not a statistic.
|
|
10
|
-
*
|
|
11
|
-
* The matcher is pure — `(params, locators) → boolean` — so the hook can call
|
|
12
|
-
* it against the locators recorded when a receipt was actually spilled. The
|
|
13
|
-
* per-session ledger is deliberately small and bounded: it keeps the most
|
|
14
|
-
* recent {@link MAX_LOCATORS_PER_SESSION} locators, because a long session
|
|
15
|
-
* projects far more artifacts than its model ever reads back and the ledger is
|
|
16
|
-
* an audit aid, not a cache of the spill store.
|
|
17
|
-
*
|
|
18
|
-
* @module dsh-boost/admission/retrieval
|
|
19
|
-
*/
|
|
20
|
-
/**
|
|
21
|
-
* Whether a tool call's arguments name one of the given spill locators.
|
|
22
|
-
*
|
|
23
|
-
* Total by construction: malformed, cyclic or hostile arguments return `false`
|
|
24
|
-
* rather than throwing, because this runs inside the host's `post-execute`
|
|
25
|
-
* waterfall where a throw would replace the tool result with an error.
|
|
26
|
-
*/
|
|
27
|
-
export declare function recordRetrieval(params: unknown, locators: ReadonlySet<string>): boolean;
|
|
28
|
-
/**
|
|
29
|
-
* The spill locators a session's projected receipts left behind.
|
|
30
|
-
*
|
|
31
|
-
* One instance belongs to the plugin instance; `apply` passes it through
|
|
32
|
-
* `HookDeps` and `clearSession` drops a session's set on `session/disposed`, so
|
|
33
|
-
* a disposed session cannot leak locators into the next one.
|
|
34
|
-
*/
|
|
35
|
-
export declare class RetrievalLedger {
|
|
36
|
-
private readonly bySession;
|
|
37
|
-
/** Locators dropped by the cap, across every session; exposed by status. */
|
|
38
|
-
private evictedCount;
|
|
39
|
-
/** Remember one applied projection's locator; `true` when it was new. */
|
|
40
|
-
record(sessionId: string, locator: string): boolean;
|
|
41
|
-
/** The locators currently remembered for `sessionId` (empty when unknown). */
|
|
42
|
-
locatorsOf(sessionId: string): ReadonlySet<string>;
|
|
43
|
-
/**
|
|
44
|
-
* The matched locator for this call, or `undefined` when it is not a retrieval.
|
|
45
|
-
*
|
|
46
|
-
* Goes through the exported {@link recordRetrieval} predicate first, so the
|
|
47
|
-
* production hook and the documented obligation share one decision; the
|
|
48
|
-
* second walk only runs on a hit and is what puts the locator on the receipt.
|
|
49
|
-
*/
|
|
50
|
-
locate(sessionId: string, params: unknown): string | undefined;
|
|
51
|
-
/** Whether this call retrieves a spilled artifact. */
|
|
52
|
-
hit(sessionId: string, params: unknown): boolean;
|
|
53
|
-
/** Drop one session's locators (session end). */
|
|
54
|
-
clear(sessionId: string): void;
|
|
55
|
-
/** Number of sessions currently holding locators. */
|
|
56
|
-
size(): number;
|
|
57
|
-
/**
|
|
58
|
-
* Locators the cap has dropped since process start.
|
|
59
|
-
*
|
|
60
|
-
* A silent eviction would make later re-reads uncounted and flatter the net
|
|
61
|
-
* account; status reports this so an operator can see the ledger is lossy
|
|
62
|
-
* rather than assume every retrieval was seen.
|
|
63
|
-
*/
|
|
64
|
-
evictions(): number;
|
|
65
|
-
}
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usage pairing: turn two consecutive model requests into the measured saving
|
|
3
|
-
* of one substitution (design §5.3).
|
|
4
|
-
*
|
|
5
|
-
* When the plugin substitutes a call, the model is not asked for that step, so
|
|
6
|
-
* the next real request replays a shorter history. The saving is therefore
|
|
7
|
-
* measured as the size of that next request — `input + cacheRead`, because the
|
|
8
|
-
* host reports `inputTokens` excluding cache reads — never estimated. A missing
|
|
9
|
-
* next request is `'unknown'`; an interpolated number would be indistinguishable
|
|
10
|
-
* from a measurement once written to a receipt.
|
|
11
|
-
*
|
|
12
|
-
* The ledger keeps two request slots plus a mark: `latest`, the first request
|
|
13
|
-
* after the mark, and the mark itself — which holds the request that preceded
|
|
14
|
-
* it and the candidate id. No whole-history table (YAGNI). Pure arithmetic: no
|
|
15
|
-
* timers, no I/O, no host calls.
|
|
16
|
-
*
|
|
17
|
-
* @module dsh-boost/admission/usage
|
|
18
|
-
*/
|
|
19
|
-
/** One model request's raw counts, mapped from the `llm/stream` usage chunk. */
|
|
20
|
-
export interface Usage {
|
|
21
|
-
input: number;
|
|
22
|
-
cacheRead: number;
|
|
23
|
-
output: number;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Pairs two consecutive model requests around one substitution.
|
|
27
|
-
*
|
|
28
|
-
* The pairing target is the FIRST request after the mark, never the latest:
|
|
29
|
-
* when a caller forgets to settle, a later unrelated request must not be
|
|
30
|
-
* attributed to the substitution. `settle()` consumes the mark and clears the
|
|
31
|
-
* pairing slots; `last()` is a pure reader and survives it.
|
|
32
|
-
*/
|
|
33
|
-
export declare class UsageLedger {
|
|
34
|
-
private latest;
|
|
35
|
-
private hasMark;
|
|
36
|
-
private beforeMark;
|
|
37
|
-
private afterMark;
|
|
38
|
-
private candidateId;
|
|
39
|
-
/**
|
|
40
|
-
* Record one real request. The first request after a mark claims the pairing
|
|
41
|
-
* slot and keeps it; later requests only advance `last()`.
|
|
42
|
-
*/
|
|
43
|
-
request(u: Usage): void;
|
|
44
|
-
/** Most recent request, or `undefined` before the first one. Never consumes. */
|
|
45
|
-
last(): Usage | undefined;
|
|
46
|
-
/**
|
|
47
|
-
* Record that a substitution just happened.
|
|
48
|
-
*
|
|
49
|
-
* `candidateId` is kept only so the caller can pair `settle()` with the right
|
|
50
|
-
* substitution receipt (`pendingCandidateId()`); it never changes the
|
|
51
|
-
* arithmetic. A new mark discards any unconsumed pairing and starts over from
|
|
52
|
-
* the current latest request.
|
|
53
|
-
*/
|
|
54
|
-
markSubstituted(candidateId: string): void;
|
|
55
|
-
/** Id of the pending mark, or `undefined` before a mark and after `settle()`. */
|
|
56
|
-
pendingCandidateId(): string | undefined;
|
|
57
|
-
/**
|
|
58
|
-
* Consume the mark and report the substitution's measured cost.
|
|
59
|
-
*
|
|
60
|
-
* `saved_input_tokens` is the first after-mark request's `input + cacheRead`;
|
|
61
|
-
* `output_tokens` is that request's `output`, a third count that is never
|
|
62
|
-
* folded into input. Both are `'unknown'` when no usable request arrived after
|
|
63
|
-
* the mark — never a copy of the previous request's numbers. `cache_hit_delta`
|
|
64
|
-
* is the after-mark hit rate minus the pre-mark hit rate, `null` when either
|
|
65
|
-
* side cannot be told (a `null` delta means "cannot tell", not zero).
|
|
66
|
-
*
|
|
67
|
-
* A second `settle()` has nothing left to consume and reports the same
|
|
68
|
-
* `'unknown'` / `null`.
|
|
69
|
-
*/
|
|
70
|
-
settle(): {
|
|
71
|
-
saved_input_tokens: number | 'unknown';
|
|
72
|
-
cache_hit_delta: number | null;
|
|
73
|
-
output_tokens: number | 'unknown';
|
|
74
|
-
};
|
|
75
|
-
}
|
package/dist/config.d.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Configuration defaults and resolution.
|
|
3
|
-
*
|
|
4
|
-
* The host's patch replaces the plugin `config` wholesale (design §11), so a
|
|
5
|
-
* missing key never means "keep the previous value": `resolveConfig` merges the
|
|
6
|
-
* host object over `DEFAULT_CONFIG` one key at a time. A key whose value is
|
|
7
|
-
* malformed falls back to its own default rather than raising — a bad overlay
|
|
8
|
-
* degrades to design defaults, it does not break plugin loading.
|
|
9
|
-
*
|
|
10
|
-
* ## Validation
|
|
11
|
-
*
|
|
12
|
-
* A finite number is not automatically a usable value. Negative or fractional
|
|
13
|
-
* projection windows, budgets and counts are rejected or clamped here rather
|
|
14
|
-
* than flowing into the decision path: a negative `triggerChars` would make
|
|
15
|
-
* every receipt a candidate and a negative `selector.maxTokens` would reach the
|
|
16
|
-
* selector LLM. Every repair is reported through the optional callback so the
|
|
17
|
-
* operator sees the effective value instead of a silent fallback, and
|
|
18
|
-
* `projection.*.headChars + tailChars` must stay below `triggerChars` (design
|
|
19
|
-
* §5.3: a window at or above the trigger cannot cut anything).
|
|
20
|
-
*
|
|
21
|
-
* Unknown keys are ignored: hosts may hand a superset of `BoostConfig`.
|
|
22
|
-
*
|
|
23
|
-
* @module dsh-boost/config
|
|
24
|
-
*/
|
|
25
|
-
import type { BoostConfig } from './types.js';
|
|
26
|
-
/** Design defaults; must stay verbatim in sync with `cordis.patch.yml` (§5.3). */
|
|
27
|
-
export declare const DEFAULT_CONFIG: BoostConfig;
|
|
28
|
-
/** Receives one human-readable line per repaired configuration key. */
|
|
29
|
-
export type ConfigRepair = (message: string) => void;
|
|
30
|
-
/**
|
|
31
|
-
* Turn whatever the host hands `apply` into a complete `BoostConfig`.
|
|
32
|
-
*
|
|
33
|
-
* Always returns a fresh deep copy, so callers cannot mutate `DEFAULT_CONFIG`.
|
|
34
|
-
* Non-object input resolves to the defaults. `onRepair` receives one line per
|
|
35
|
-
* key that was rejected, clamped or repaired; it is never called for a valid
|
|
36
|
-
* value.
|
|
37
|
-
*
|
|
38
|
-
* Total: it never throws. The host hands `apply` an arbitrary object, so a
|
|
39
|
-
* throwing getter anywhere in the tree (or a throwing `onRepair` sink) aborts
|
|
40
|
-
* the resolution and returns a fresh copy of `DEFAULT_CONFIG` rather than
|
|
41
|
-
* escaping as a plugin-load failure (review row 68).
|
|
42
|
-
*/
|
|
43
|
-
export declare function resolveConfig(raw: unknown, onRepair?: ConfigRepair): BoostConfig;
|