dsh-llm-verifier 0.8.0-beta.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -604,6 +604,7 @@ Workflow 候选在被记录后的**下一步主模型请求之前**就会评审
604
604
  插件默认优先请求 `top_logprobs: 20`。它通过读取判定标签后第一个 Token 的 A–T 候选分布,经重新归一化后计算得分期望值。仅在当前路由通道无法提供概率分布时,才降级使用模型生成的最终文本标签。
605
605
 
606
606
  - **支持直接透传 logprobs 的通道**:官方 `deepseek-official` 路由,以及在 DSH `llm-pi-ai` 中明确声明 `api: openai-completions` 且使用 HTTPS `baseURL` 的路由;
607
+ - **读取宿主设置的两代接缝**:DSH 0.1.1–0.1.6 用 `settings.get(ns)` 读命名空间;0.1.7 把注册式接缝换成了 `SettingsForms`,**它根本没有 `get`**,唯一的公开读取是 `describe()` 的描述符 `value`。插件按能力探测两代接缝,任一代读不到都只意味着不启用直连通道;
607
608
  - **回退通道**:其他私有 Adapter 则通过标准 DSH Stream 稳定回退到显式标签模式。
608
609
 
609
610
  结果中的模式计数使插件行为完全透明可观测,而非静默假设所有模型都具备概率输出能力。
@@ -39,10 +39,35 @@ async function credential(ctx, name) {
39
39
  if (!name) return void 0;
40
40
  return (await ctx.get("credentials")?.resolve(credentialRef(name)))?.value;
41
41
  }
42
- async function resolveTopLogprobRoute(ctx, provider) {
42
+ /**
43
+ * Read one host settings namespace as a plain object.
44
+ *
45
+ * DSH 0.1.1-0.1.6 answered this with `settings.get(ns)` on the register-based seam.
46
+ * DSH 0.1.7 replaced that seam with `SettingsForms`, which has no `get` method at
47
+ * all: the only public read is `describe()`, whose descriptors carry each
48
+ * namespace's projected live value. Probing both keeps the direct logprob route
49
+ * working across the whole supported line, and a seam that throws degrades to the
50
+ * explicit-tag channel instead of failing the verification outright.
51
+ * @param ctx - Plugin context carrying the optional settings service.
52
+ * @param ns - Host namespace id, e.g. `llm-deepseek`.
53
+ * @returns The namespace value, or `undefined` when it cannot be read.
54
+ */
55
+ function settingsNamespace(ctx, ns) {
43
56
  const settings = ctx.get("settings");
57
+ if (!settings) return void 0;
58
+ try {
59
+ if (typeof settings.get === "function") return object(settings.get(ns));
60
+ if (typeof settings.describe !== "function") return void 0;
61
+ const rows = settings.describe();
62
+ if (!Array.isArray(rows)) return void 0;
63
+ return object(rows.map(object).find((candidate) => candidate?.ns === ns)?.value);
64
+ } catch {
65
+ return;
66
+ }
67
+ }
68
+ async function resolveTopLogprobRoute(ctx, provider) {
44
69
  if (provider === "deepseek-official") {
45
- const value = settings ? object(settings.get("llm-deepseek")) ?? {} : {};
70
+ const value = settingsNamespace(ctx, "llm-deepseek") ?? {};
46
71
  const apiKey = await credential(ctx, text(value.apiKeyEnv) ?? "DEEPSEEK_API_KEY");
47
72
  if (!apiKey) return void 0;
48
73
  return {
@@ -51,8 +76,9 @@ async function resolveTopLogprobRoute(ctx, provider) {
51
76
  deepSeekThinking: true
52
77
  };
53
78
  }
54
- if (!settings) return void 0;
55
- const profile = object(object(object(settings.get("llm-pi-ai"))?.providers)?.[provider]);
79
+ const root = settingsNamespace(ctx, "llm-pi-ai");
80
+ if (root === void 0) return void 0;
81
+ const profile = object(object(root?.providers)?.[provider]);
56
82
  if (!profile || profile.api !== "openai-completions") return void 0;
57
83
  const baseURL = text(profile.baseURL);
58
84
  if (!baseURL || !/^https:\/\//i.test(baseURL)) return void 0;
@@ -759,4 +785,4 @@ function emptyUsage() {
759
785
  //#endregion
760
786
  export { attachUsage as a, emptyUsage as c, generationClient as d, partialUsage as f, resolveCapabilityFile as g, TopLogprobCapabilityCache as h, addUsage as i, fallbackDeepFreeze as l, requestAttempts as m, GENERATION_TEMPERATURE as n, callVerifier as o, predictScoringChannel as p, RequestLimiter as r, callVerifierText as s, GENERATION_MAX_TOKENS as t, generateCandidate as u };
761
787
 
762
- //# sourceMappingURL=caller-l5JwNkI3.js.map
788
+ //# sourceMappingURL=caller-Bfp4HPK_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caller-Bfp4HPK_.js","names":[],"sources":["../src/top-logprobs.ts","../src/caller.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis'\nimport { credentialRef } from '@deepseek-ai/dsh-credentials'\nimport { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport type { CompletionLogprobs, TokenAlternative } from './core.ts'\nimport type { UsageStats, VerifierImage } from './caller.ts'\n\n/**\n * The two scoring channels are the logprob expectation (this file) and the explicit tag reply\n * (caller.ts). Upstream has a THIRD one worth knowing about before inventing anything new:\n * when an open-model server does not emit the score tags at all, it prefills the tag itself and\n * constrains the next token to the twenty scale letters, then reads that token's distribution\n * (llm-as-a-verifier `_score_tags_by_prefill`: vLLM/SGLang `continue_final_message` plus\n * `structured_outputs`). That turns ANY OpenAI-compatible server into a distribution-scoring\n * judge, which is strictly more informative than our explicit-tag channel's single sampled letter\n * — it is why upstream can run K=1 and we average repeats instead.\n *\n * NOT implemented here, deliberately: the direct transport below speaks to whichever\n * OpenAI-compatible endpoint a provider declares, and the prefill/grammar parameters are\n * vLLM/SGLang extensions that a normal endpoint rejects. Two preconditions before adding it:\n * (1) the DSH stream adapter exposes prefill or a constrained-decoding option, or the route is\n * known to be a local inference server; (2) the capability probe can detect support at runtime and\n * degrade to explicit tags — NEVER keyed off a provider or model name (AGENTS.md rule 7). If it\n * lands, it belongs in `callTopLogprobs` as an opt-in third mode, and `autoTrackRepeats` could\n * then drop.\n */\nexport interface TopLogprobRoute {\n baseURL: string\n apiKey?: string\n headers?: Record<string, string>\n deepSeekThinking: boolean\n}\nexport interface TopLogprobCompletion extends CompletionLogprobs { usage: UsageStats; scoringMode: 'top-logprobs' }\nexport class TopLogprobsUnsupportedError extends Error { constructor(message: string) { super(message); this.name = 'TopLogprobsUnsupportedError' } }\n/**\n * A provider-level rejection of the direct transport that is not a logprobs\n * capability answer (bad request, auth, quota, malformed body). It downgrades\n * this topic to the DSH stream instead of failing the whole verification.\n */\nexport class TopLogprobsRouteError extends TopLogprobsUnsupportedError { constructor(message: string, readonly status?: number) { super(message); this.name = 'TopLogprobsRouteError' } }\n\nfunction object(value: unknown): Record<string, unknown> | undefined { return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined }\nfunction text(value: unknown): string | undefined { return typeof value === 'string' && value.trim() ? value.trim() : undefined }\nfunction endpoint(baseURL: string): string { return baseURL.replace(/\\/+$/, '') + '/chat/completions' }\nfunction dataUrl(image: VerifierImage): string { return 'data:' + image.mediaType + ';base64,' + Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength).toString('base64') }\n\nasync function credential(ctx: Context, name: string | undefined): Promise<string | undefined> {\n if (!name) return undefined\n const provider = ctx.get('credentials')\n return (await provider?.resolve(credentialRef(name)))?.value\n}\n\n/**\n * Read one host settings namespace as a plain object.\n *\n * DSH 0.1.1-0.1.6 answered this with `settings.get(ns)` on the register-based seam.\n * DSH 0.1.7 replaced that seam with `SettingsForms`, which has no `get` method at\n * all: the only public read is `describe()`, whose descriptors carry each\n * namespace's projected live value. Probing both keeps the direct logprob route\n * working across the whole supported line, and a seam that throws degrades to the\n * explicit-tag channel instead of failing the verification outright.\n * @param ctx - Plugin context carrying the optional settings service.\n * @param ns - Host namespace id, e.g. `llm-deepseek`.\n * @returns The namespace value, or `undefined` when it cannot be read.\n */\nfunction settingsNamespace(ctx: Context, ns: string): Record<string, unknown> | undefined {\n const settings = ctx.get('settings') as unknown as { get?: unknown; describe?: unknown } | undefined\n if (!settings) return undefined\n try {\n if (typeof settings.get === 'function') return object((settings.get as (ns: string) => unknown)(ns))\n if (typeof settings.describe !== 'function') return undefined\n const rows: unknown = (settings.describe as () => unknown)()\n if (!Array.isArray(rows)) return undefined\n const row = rows.map(object).find(candidate => candidate?.ns === ns)\n return object(row?.value)\n } catch {\n return undefined\n }\n}\n\nexport async function resolveTopLogprobRoute(ctx: Context, provider: string): Promise<TopLogprobRoute | undefined> {\n if (provider === 'deepseek-official') {\n const value = settingsNamespace(ctx, 'llm-deepseek') ?? {}\n const apiKeyEnv = text(value.apiKeyEnv) ?? 'DEEPSEEK_API_KEY'\n const apiKey = await credential(ctx, apiKeyEnv)\n if (!apiKey) return undefined\n return { baseURL: text(value.baseURL) ?? 'https://api.deepseek.com', apiKey, deepSeekThinking: true }\n }\n const root = settingsNamespace(ctx, 'llm-pi-ai')\n if (root === undefined) return undefined\n const profiles = object(root?.providers)\n const profile = object(profiles?.[provider])\n // Only explicitly OpenAI-compatible profiles are safe to serialize directly.\n // Other DSH adapters keep their private protocol and use the explicit-tag fallback.\n if (!profile || profile.api !== 'openai-completions') return undefined\n const baseURL = text(profile.baseURL)\n if (!baseURL || !/^https:\\/\\//i.test(baseURL)) return undefined\n const apiKey = await credential(ctx, text(profile.apiKeyEnv))\n const rawHeaders = object(profile.headers)\n const headers = rawHeaders === undefined ? undefined : Object.fromEntries(Object.entries(rawHeaders).filter((entry): entry is [string, string] => typeof entry[1] === 'string'))\n return { baseURL, ...(apiKey ? { apiKey } : {}), ...(headers ? { headers } : {}), deepSeekThinking: false }\n}\n\nexport async function callTopLogprobs(route: TopLogprobRoute, model: string, prompt: string, maxTokens: number, reasoningEffort: string | undefined, signal?: AbortSignal, images?: readonly VerifierImage[], attempt = 1, temperature = 0.2): Promise<TopLogprobCompletion> {\n const content: string | Record<string, unknown>[] = images?.length ? [{ type: 'text', text: prompt }, ...images.map(image => ({ type: 'image_url', image_url: { url: dataUrl(image) } }))] : prompt\n const thinking = route.deepSeekThinking && reasoningEffort ? reasoningEffort === 'off' ? { thinking: { type: 'disabled' } } : { thinking: { type: 'enabled' }, reasoning_effort: reasoningEffort } : {}\n const response = await fetch(endpoint(route.baseURL), {\n method: 'POST', redirect: 'error', signal,\n headers: { 'content-type': 'application/json', ...(route.apiKey ? { authorization: 'Bearer ' + route.apiKey } : {}), ...route.headers },\n body: JSON.stringify({ model, messages: [{ role: 'user', content }], max_tokens: maxTokens, temperature, logprobs: true, top_logprobs: 20, ...thinking }),\n })\n const raw = await response.text()\n if (!response.ok) {\n const excerpt = raw.slice(0, 1000)\n const message = 'llm-verifier: top_logprobs request failed with HTTP ' + response.status + ': ' + excerpt\n if ([400, 404, 405, 415, 422].includes(response.status) && /logprob|top_logprobs|unsupported|unknown (?:field|parameter)|unrecognized (?:field|parameter)|not support/i.test(excerpt)) throw new TopLogprobsUnsupportedError('provider rejected top_logprobs: HTTP ' + response.status + ' ' + excerpt)\n // Throttling and server faults stay generic so the shared retry wrapper can\n // attempt again; every other rejection downgrades to the DSH stream.\n if (response.status === 408 || response.status === 409 || response.status === 429 || response.status >= 500) throw new Error(message)\n throw new TopLogprobsRouteError(message, response.status)\n }\n let body: Record<string, unknown>\n try { body = object(JSON.parse(raw)) ?? {} } catch { throw new TopLogprobsRouteError('llm-verifier: top_logprobs endpoint returned invalid JSON', response.status) }\n const choices = Array.isArray(body.choices) ? body.choices : []\n const choice = object(choices[0])\n const message = object(choice?.message)\n const answer = typeof message?.content === 'string' ? message.content : ''\n const logprobs = object(choice?.logprobs)\n const rows = Array.isArray(logprobs?.content) ? logprobs.content : []\n if (!rows.length) throw new TopLogprobsUnsupportedError('provider returned no token logprobs')\n const tokens: string[] = []\n const positions: TokenAlternative[][] = []\n for (const rawRow of rows) {\n const row = object(rawRow) ?? {}\n const token = typeof row.token === 'string' ? row.token : ''\n tokens.push(token)\n const top = Array.isArray(row.top_logprobs) ? row.top_logprobs : []\n const alternatives = top.flatMap(value => { const item = object(value); return item && typeof item.token === 'string' && typeof item.logprob === 'number' ? [{ token: item.token, logprob: item.logprob }] : [] })\n if (!alternatives.length && typeof row.logprob === 'number') alternatives.push({ token, logprob: row.logprob })\n positions.push(alternatives)\n }\n const rawUsage = object(body.usage) ?? {}\n const promptDetails = object(rawUsage.prompt_tokens_details) ?? {}\n const completionDetails = object(rawUsage.completion_tokens_details) ?? {}\n const cached = Number(rawUsage.prompt_cache_hit_tokens ?? promptDetails.cached_tokens ?? 0) || 0\n const input = Number(rawUsage.prompt_tokens ?? 0) || 0\n return { text: answer, tokens, positions, scoringMode: 'top-logprobs', usage: { calls: 1, attempts: attempt, retries: attempt - 1, inputTokens: Math.max(0, input - cached), cachedInputTokens: cached, outputTokens: Number(rawUsage.completion_tokens ?? 0) || 0, reasoningTokens: Number(completionDetails.reasoning_tokens ?? 0) || 0 } }\n}\n\n/** Marks older than this are dropped on hydration so a provider that later gains logprobs support is re-probed. */\nexport const CAPABILITY_TTL_MS = 24 * 60 * 60 * 1000\n\ninterface CapabilityDocument { version: 1; entries: Record<string, number> }\n\n/** Resolves the capability memory file beside the score cache inside the topic verifier directory. */\nexport function resolveCapabilityFile(cacheDir: string, cwd = process.cwd()): string {\n const root = isAbsolute(cacheDir) ? cacheDir : resolve(cwd, cacheDir)\n return join(root, 'capabilities-v1.json')\n}\n\n/** Replace failures that are a transient lock rather than a verdict about the capability file directory. */\nconst TRANSIENT_REPLACE_CODES = new Set(['EPERM', 'EACCES', 'EBUSY'])\n\nlet replaceOrdinal = 0\n\nasync function replaceFile(temporary: string, target: string): Promise<void> {\n for (let attempt = 1; ; attempt += 1) {\n try {\n await rename(temporary, target)\n return\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (attempt >= 5 || code === undefined || !TRANSIENT_REPLACE_CODES.has(code)) throw error\n await new Promise(resolve => setTimeout(resolve, attempt * 10))\n }\n }\n}\n\nexport class TopLogprobCapabilityCache {\n private readonly unsupported = new Map<string, number>()\n private loaded = false\n private hydrating: Promise<void> | undefined\n private writing: Promise<void> = Promise.resolve()\n\n constructor(private readonly file?: string, private readonly now: () => number = Date.now) {}\n\n /** Expired marks are dropped so a provider that later gains logprobs support is re-probed. */\n isUnsupported(provider: string, model: string): boolean {\n const key = provider + '\\0' + model\n const markedAt = this.unsupported.get(key)\n if (markedAt === undefined) return false\n if (this.now() - markedAt > CAPABILITY_TTL_MS) { this.unsupported.delete(key); return false }\n return true\n }\n\n /** Hydrates persisted marks once; in-process marks always win over file contents. */\n async ensureLoaded(): Promise<void> {\n if (this.loaded || this.file === undefined) return\n this.hydrating ??= (async () => {\n try {\n const document = JSON.parse(await readFile(this.file!, 'utf8')) as CapabilityDocument\n const entries = document !== null && typeof document === 'object' && document.version === 1 && typeof document.entries === 'object' && document.entries !== null ? document.entries : {}\n const now = this.now()\n for (const [key, markedAt] of Object.entries(entries)) {\n if (typeof markedAt !== 'number' || !Number.isFinite(markedAt) || markedAt < 0 || now - markedAt > CAPABILITY_TTL_MS) continue\n // Max-merge: never let an older persisted stamp clobber a fresher in-process probe.\n const existing = this.unsupported.get(key)\n if (existing === undefined || existing < markedAt) this.unsupported.set(key, markedAt)\n }\n } catch { /* a missing or unreadable file simply starts empty */ }\n this.loaded = true\n })()\n await this.hydrating\n }\n\n markUnsupported(provider: string, model: string): void {\n this.unsupported.set(provider + '\\0' + model, this.now())\n this.persist()\n }\n\n /**\n * Forget one provider/model mark so the next call re-probes instead of replaying a cached answer.\n *\n * The judge probe exists to answer \"which scoring channel is this judge on\". Replaying a mark\n * written up to {@link CAPABILITY_TTL_MS} ago — possibly under a different provider\n * configuration — would answer a different, stale question. The removal is persisted, so a host\n * restart cannot resurrect the old mark.\n *\n * The delete is repeated INSIDE the serialized write: hydration max-merges the file into memory,\n * so deleting only beforehand would let the very write we schedule put the entry back.\n * @param provider - provider id the mark belongs to.\n * @param model - model id the mark belongs to.\n */\n forget(provider: string, model: string): void {\n const key = provider + '\\0' + model\n this.unsupported.delete(key)\n if (this.file === undefined) return\n const next = this.writing\n .catch(() => {})\n .then(() => this.ensureLoaded())\n .then(() => { this.unsupported.delete(key); return this.writeDocument() })\n this.writing = next\n next.catch(() => { /* capability memory is best-effort */ })\n }\n\n /** Serialize behind hydration so an early mark never clobbers not-yet-loaded entries. */\n private persist(): void {\n if (this.file === undefined) return\n const next = this.writing\n .catch(() => {})\n .then(() => this.ensureLoaded())\n .then(() => this.writeDocument())\n this.writing = next\n next.catch(() => { /* capability memory is best-effort; the next mark rewrites the file */ })\n }\n\n private async writeDocument(): Promise<void> {\n const snapshot: CapabilityDocument = { version: 1, entries: Object.fromEntries(this.unsupported) }\n await mkdir(dirname(this.file!), { recursive: true })\n const temporary = this.file! + '.tmp-' + process.pid + '-' + (++replaceOrdinal)\n await writeFile(temporary, JSON.stringify(snapshot), 'utf8')\n try { await replaceFile(temporary, this.file!) } catch (error) { await unlink(temporary).catch(() => {}); throw error }\n }\n\n /** Resolves once the trailing persistence attempt settles; exposed for tests. */\n flush(): Promise<void> { return this.writing }\n}\n","import { BlockAssembler, ReasoningEffortId, createUserMessage, type ContentBlock, type FinishReason, type LlmRuntime } from '@deepseek-ai/dsh-llm'\nimport * as LlmModule from '@deepseek-ai/dsh-llm'\n// Supplies the `'llm-verifier'` MessageSourceMap member named by the judge request below.\nimport type {} from './message-source.ts'\n\n/**\n * Deep-freeze a call-options graph, leaving any live AbortSignal mutable.\n *\n * The host re-exports its own `deepFreeze` from `@deepseek-ai/dsh-llm` on the 0.1.1 line; the\n * 0.1.5 line moved the helper to `@deepseek-ai/dsh-util-values` and no longer re-exports it, so\n * the fallback below is what actually runs there. Both implementations must carry the same rule\n * (\"leaving live AbortSignal objects mutable\" — the host's own wording), because freezing a\n * signal breaks the transport twice over: Node >= 26.5 initializes the signal's internal event\n * map lazily, so the first `addEventListener` throws \"Cannot assign to read only property\n * 'Symbol(kEvents)'\", and on every Node version the attempt timeout's `controller.abort()` throws\n * the same way on 'Symbol(kAborted)'. The signal belongs to this call's retry loop and is still\n * unsubscribed when the options are frozen, which is what makes the ordering fatal.\n */\nfunction deepFreeze<T>(value: T): T {\n const mod = LlmModule as unknown as Record<string, unknown>\n if (typeof mod.deepFreeze === 'function') {\n return (mod.deepFreeze as Function)(value)\n }\n return fallbackDeepFreeze(value)\n}\n\n/**\n * The graph walk used when the host exports no `deepFreeze`; exported for tests.\n * @param value - value to freeze.\n * @returns The same value, with every reachable enumerable child frozen except live AbortSignals.\n */\nexport function fallbackDeepFreeze<T>(value: T): T {\n // See deepFreeze(): a frozen signal fails on the transport's first subscription.\n if (value instanceof AbortSignal) return value\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value)\n for (const key of Object.keys(value)) {\n fallbackDeepFreeze((value as Record<string, unknown>)[key])\n }\n }\n return value\n}\nimport type { AttachmentStore } from '@deepseek-ai/dsh-attachment'\nimport type { CompletionLogprobs } from './core.ts'\nimport { TopLogprobCapabilityCache, TopLogprobsUnsupportedError, callTopLogprobs, resolveTopLogprobRoute } from './top-logprobs.ts'\nimport type { Context } from '@deepseek-ai/cordis'\n\nexport interface VerifierClientConfig {\n ctx: Context\n llm: LlmRuntime\n attachments: AttachmentStore\n topLogprobCapabilities: TopLogprobCapabilityCache\n provider: string\n model: string\n /** User-facing judge name for tool output; cosmetic only, never part of the scoring cache identity. */\n label?: string\n reasoningEffort?: string\n maxTokens: number\n temperature: number\n timeoutMs: number\n maxRetries: number\n retryBaseDelayMs: number\n limiter?: RequestLimiter\n}\n\nexport interface VerifierImage {\n data: Uint8Array\n mediaType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif'\n}\n\nexport interface UsageStats {\n calls: number\n attempts: number\n retries: number\n inputTokens: number\n cachedInputTokens: number\n outputTokens: number\n reasoningTokens: number\n /**\n * At least one attempt's usage is UNKNOWN (an earlier attempt failed and was retried, or a\n * response came back unusable). The token counts are a floor, never a confident total.\n */\n usageIncomplete?: boolean\n}\n\nexport type ScoringMode = 'top-logprobs' | 'explicit-tag'\nexport interface VerifierCompletion extends CompletionLogprobs {\n usage: UsageStats\n scoringMode: ScoringMode\n /**\n * The direct logprob transport was attempted and the provider rejected it, so this\n * answer came from the explicit-tag fallback. Diagnostics only: it never changes the\n * score, and it is recorded so a silent downgrade is visible in the statistics.\n */\n channelFallback?: boolean\n}\n\n/**\n * Where a finally-failed request records how many attempts it already spent.\n *\n * A failure that never returned usage leaves the tokens UNKNOWN, not zero. The attempt\n * count is the one fact the transport does know, so it is carried on the error itself\n * (the engine catches per-judge errors) instead of being discarded.\n */\nconst REQUEST_ATTEMPTS = Symbol('llm-verifier.requestAttempts')\n\n/** Attempts one failed verifier request already spent; 0 when the error carries none. */\nexport function requestAttempts(error: unknown): number {\n if (typeof error !== 'object' || error === null) return 0\n const value = (error as { [REQUEST_ATTEMPTS]?: unknown })[REQUEST_ATTEMPTS]\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : 0\n}\n\n/**\n * Usage the transport DID return for a response that then turned out unusable.\n *\n * A parse failure or a truncated judge answer happened after the request was billed, so the\n * engine must not fold it into a zero-cost failure. The usage rides on the error next to the\n * attempt count; one error can carry both (a retried call whose final answer also failed).\n */\nconst PARTIAL_USAGE = Symbol('llm-verifier.partialUsage')\n\n/** Usage a completed-but-unusable response already cost; undefined when the error carries none. */\nexport function partialUsage<T = UsageStats>(error: unknown): T | undefined {\n if (typeof error !== 'object' || error === null) return undefined\n const value = (error as { [PARTIAL_USAGE]?: unknown })[PARTIAL_USAGE]\n return typeof value === 'object' && value !== null ? value as T : undefined\n}\n\n/** Attach the usage a completed-but-unusable response already cost to its error. */\nexport function attachUsage(error: unknown, usage: UsageStats): void {\n if (typeof error === 'object' && error !== null) (error as { [PARTIAL_USAGE]?: UsageStats })[PARTIAL_USAGE] = usage\n}\n\n/**\n * An error for a response that came back and was billed but produced no usable verdict.\n *\n * The usage is attached so the failure row reports known requests and tokens instead of zero.\n */\nfunction unusable(reason: string, attempt: number, raw: { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number } | undefined): Error {\n const error = new Error('llm-verifier: ' + reason)\n attachUsage(error, usage(attempt, raw ?? {}))\n return error\n}\n\n/**\n * Describe why a finished stream is unusable.\n *\n * `FinishReason.failure` is the host's SERIALIZABLE facts record (`{message, code, status?,\n * providerRetryAfterMs?, requestId?}`), not the error the adapter threw: `normalizeLlmFailure`\n * detaches the facts at the adapter boundary, so the stack and the cause are already gone before\n * this plugin sees them. The machine code and the provider status ARE carried, and dropping them\n * left the board with one line and no way to tell an auth failure from a transport one.\n */\nfunction failureMessage(finish: FinishReason): string | undefined {\n if (finish.kind === 'error' || finish.kind === 'aborted') {\n const failure = finish.failure\n const facts = [\n failure.code,\n failure.status === undefined ? undefined : 'HTTP ' + failure.status,\n failure.requestId === undefined ? undefined : 'request ' + failure.requestId,\n ].filter((fact): fact is string => typeof fact === 'string' && fact.length > 0)\n return facts.length > 0 ? failure.message + ' [' + facts.join(', ') + ']' : failure.message\n }\n if (finish.kind === 'max-tokens') return 'verifier response reached max tokens before completing its answer'\n return undefined\n}\n\nasync function delay(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw signal.reason\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, ms)\n const abort = () => { clearTimeout(timer); reject(signal?.reason) }\n signal?.addEventListener('abort', abort, { once: true })\n })\n}\n\nfunction usage(attempts: number, value = {} as { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number }): UsageStats {\n return { calls: 1, attempts, retries: attempts - 1, inputTokens: value.inputTokens ?? 0, cachedInputTokens: (value.cacheReadTokens ?? 0) + (value.cacheWriteTokens ?? 0), outputTokens: value.outputTokens ?? 0, reasoningTokens: value.reasoningTokens ?? 0 }\n}\n\n/** Transient failures worth another attempt; anything else fails fast. */\nconst RETRYABLE_MESSAGE = /rate|quota|timeout|timed out|temporar|network|fetch|socket|5\\d\\d/i\n\n/**\n * Run one logical verifier request under the configured timeout, retrying\n * transient failures with exponential backoff.\n *\n * Every channel goes through this wrapper — including the direct top_logprobs\n * transport, which used to bypass both the timeout and the retry budget.\n * @param config - resolved verifier client configuration.\n * @param signal - caller's abort signal (tool call or turn boundary).\n * @param run - one attempt; receives its own deadline signal and 1-based attempt number.\n * @returns The first successful completion.\n */\nfunction attachAttempts(error: unknown, attempt: number): void {\n if (typeof error === 'object' && error !== null) (error as { [REQUEST_ATTEMPTS]?: number })[REQUEST_ATTEMPTS] = attempt\n}\n\n/**\n * A fresh error for one aborted call.\n *\n * Never annotate and rethrow the shared `signal.reason`: several concurrent requests share it,\n * and the engine attaches its accumulator to the thrown error, so one object carries several\n * accumulators and they get merged repeatedly. The wrapper preserves the message and name.\n */\nfunction abortFailure(reason: unknown, attempt: number): Error {\n const source = reason instanceof Error ? reason : new Error(reason === undefined ? 'llm-verifier: request aborted' : String(reason))\n const error = new Error(source.message)\n error.name = source.name\n attachAttempts(error, attempt)\n return error\n}\n\n/** Token-only addition: call/attempt counters already describe the logical request. */\nfunction addTokens(target: Pick<UsageStats, 'inputTokens' | 'cachedInputTokens' | 'outputTokens' | 'reasoningTokens'>, source: Pick<UsageStats, 'inputTokens' | 'cachedInputTokens' | 'outputTokens' | 'reasoningTokens'>): void {\n target.inputTokens += source.inputTokens\n target.cachedInputTokens += source.cachedInputTokens\n target.outputTokens += source.outputTokens\n target.reasoningTokens += source.reasoningTokens\n}\n\nasync function retrying<T>(config: VerifierClientConfig, signal: AbortSignal | undefined, run: (signal: AbortSignal, attempt: number) => Promise<T>): Promise<T> {\n let attempt = 0\n // Tokens an earlier attempt already paid for but never delivered a usable result. They are\n // real cost, so they follow the chain into whichever exit happens (success, final failure or\n // cancellation) instead of being discarded when no attempt ultimately succeeds.\n const carried = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0 }\n let unknownFailure = false\n // The usage the chain must be able to report: everything already spent plus this attempt's own\n // billed response. `unknown` (some attempt's tokens never came back) is what makes it a floor.\n const spent = (billed: UsageStats | undefined, unknown: boolean): UsageStats => ({\n calls: billed === undefined ? 0 : billed.calls,\n attempts: attempt,\n retries: Math.max(0, attempt - 1),\n inputTokens: carried.inputTokens + (billed?.inputTokens ?? 0),\n cachedInputTokens: carried.cachedInputTokens + (billed?.cachedInputTokens ?? 0),\n outputTokens: carried.outputTokens + (billed?.outputTokens ?? 0),\n reasoningTokens: carried.reasoningTokens + (billed?.reasoningTokens ?? 0),\n ...(unknown ? { usageIncomplete: true } : {}),\n })\n const cancel = (reason: unknown, billed: UsageStats | undefined, unknown: boolean): never => {\n const error = abortFailure(reason, attempt)\n attachUsage(error, spent(billed, unknown))\n throw error\n }\n while (true) {\n if (signal?.aborted) cancel(signal.reason, undefined, false)\n attempt += 1\n const controller = new AbortController()\n let timedOut = false\n const timeout = setTimeout(() => { timedOut = true; controller.abort(new Error('llm-verifier: request timed out')) }, config.timeoutMs)\n const abort = () => controller.abort(signal?.reason)\n signal?.addEventListener('abort', abort, { once: true })\n try {\n const value = await run(controller.signal, attempt)\n if (typeof value === 'object' && value !== null) {\n const usage = (value as { usage?: UsageStats }).usage\n if (usage !== undefined) {\n addTokens(usage, carried)\n // Only a failed attempt whose tokens never came back makes the total a floor.\n if (unknownFailure) usage.usageIncomplete = true\n }\n }\n return value\n } catch (error) {\n const billed = partialUsage<UsageStats>(error)\n if (signal?.aborted) cancel(signal.reason ?? error, billed, unknownFailure || billed === undefined)\n // A deadline abort is retryable even when the adapter wraps the reason in\n // its own error type with an unrelated message.\n const retryable = timedOut || (error instanceof Error && RETRYABLE_MESSAGE.test(error.message))\n if (attempt > config.maxRetries || !retryable) {\n // Every attempt of the chain goes onto the thrown error: the last response alone would\n // report a fraction of the requests and tokens the invocation really spent.\n if (billed === undefined) unknownFailure = true\n const failure = typeof error === 'object' && error !== null ? error : new Error(String(error))\n attachAttempts(failure, attempt)\n attachUsage(failure, spent(billed, unknownFailure || billed === undefined))\n throw failure\n }\n if (billed === undefined) unknownFailure = true\n else addTokens(carried, billed)\n try {\n await delay(Math.min(30000, config.retryBaseDelayMs * 2 ** (attempt - 1) * (0.8 + Math.random() * 0.4)), signal)\n } catch (waitError) {\n // Cancelled while waiting to retry: the attempts and the tokens already spent are real.\n cancel(signal?.reason ?? waitError, undefined, unknownFailure)\n }\n } finally {\n clearTimeout(timeout)\n signal?.removeEventListener('abort', abort)\n }\n }\n}\n\n/** One attachment per image object per process: retries must not duplicate attachments. */\nconst imageRefs = new WeakMap<VerifierImage, Promise<unknown>>()\n\n/**\n * One plain-text completion through the DSH stream.\n *\n * Shared by the explicit-tag judge path and by best-of-N generation, which differ in exactly one\n * place: a `max-tokens` finish. A truncated JUDGE answer is unusable — its verdict tags may never\n * have been emitted — so it stays a hard error. A truncated DRAFT is still a candidate the operator\n * already paid for, and the judge can see that the text stops mid-sentence and score it accordingly,\n * so generation receives the text plus a `truncated` flag.\n * @param config - resolved verifier client configuration.\n * @param prompt - the rendered prompt.\n * @param signal - the attempt's deadline signal.\n * @param images - attachments to send, if any.\n * @param attempt - 1-based attempt number for usage accounting.\n * @param tolerateTruncation - return the text of a max-tokens finish instead of throwing.\n * @returns The completion (with `truncated`) when it produced text.\n */\nasync function callTextCompletion(config: VerifierClientConfig, prompt: string, signal: AbortSignal | undefined, images: readonly VerifierImage[] | undefined, attempt: number, tolerateTruncation: boolean): Promise<VerifierCompletion & { truncated: boolean }> {\n const content: ContentBlock[] = [{ type: 'text', text: prompt }]\n for (const image of images ?? []) {\n let pending = imageRefs.get(image)\n if (pending === undefined) {\n const promise = Promise.resolve()\n .then(() => config.attachments.saveImage({ data: image.data, mediaType: image.mediaType }))\n .catch(error => {\n if (imageRefs.get(image) === pending) {\n imageRefs.delete(image)\n }\n throw error\n })\n pending = promise\n imageRefs.set(image, pending)\n }\n content.push({ type: 'image', attachment: await pending as never })\n }\n const messages = [createUserMessage({ content, source: { kind: 'llm-verifier' } })]\n const assembler = new BlockAssembler()\n const options = deepFreeze({\n provider: config.provider,\n model: config.model,\n ...(config.reasoningEffort ? { reasoningEffort: ReasoningEffortId(config.reasoningEffort) } : {}),\n messages,\n maxTokens: config.maxTokens,\n temperature: config.temperature,\n signal,\n })\n for await (const chunk of config.llm.stream(options)) assembler.push(chunk)\n let truncated = false\n if (assembler.finish.kind === 'max-tokens') {\n if (!tolerateTruncation) throw unusable('model call failed: ' + failureMessage(assembler.finish), attempt, assembler.usage)\n truncated = true\n } else {\n const failed = failureMessage(assembler.finish)\n if (failed !== undefined) throw unusable('model call failed: ' + failed, attempt, assembler.usage)\n }\n const text = assembler.blocks().filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text').map(block => block.text).join('')\n if (!text.trim()) throw unusable('selected DSH model produced no text', attempt, assembler.usage)\n // DSH adapters expose provider-neutral text/usage but not top-logprob candidates.\n // extractScore() therefore uses the model's explicit final A–T tags.\n return { text, tokens: [], positions: [], scoringMode: 'explicit-tag', usage: usage(attempt, assembler.usage), truncated }\n}\n\n/** Explicit-tag judge completion: fail-closed, so a truncated answer is an error and never a score. */\nasync function callExplicitTag(config: VerifierClientConfig, prompt: string, signal: AbortSignal | undefined, images: readonly VerifierImage[] | undefined, attempt: number): Promise<VerifierCompletion> {\n return callTextCompletion(config, prompt, signal, images, attempt, false)\n}\n\nexport class RequestLimiter {\n private active = 0\n private readonly queue: Array<() => void> = []\n constructor(readonly limit: number) { if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('llm-verifier: request concurrency limit must be a positive integer') }\n async run<T>(operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {\n if (signal?.aborted) throw signal.reason\n if (this.active >= this.limit) await new Promise<void>((resolve, reject) => {\n const enter = () => { signal?.removeEventListener('abort', abort); resolve() }\n const abort = () => { const index = this.queue.indexOf(enter); if (index >= 0) this.queue.splice(index, 1); reject(signal?.reason) }\n this.queue.push(enter); signal?.addEventListener('abort', abort, { once: true })\n })\n if (signal?.aborted) {\n this.queue.shift()?.()\n throw signal.reason\n }\n this.active += 1\n try { return await operation() } finally { this.active -= 1; this.queue.shift()?.() }\n }\n}\n\n/** Best-effort pre-call channel prediction for cache identity only; callAutomatic() stays the runtime source of truth. */\nexport async function predictScoringChannel(config: VerifierClientConfig): Promise<ScoringMode> {\n await config.topLogprobCapabilities.ensureLoaded()\n return config.topLogprobCapabilities.isUnsupported(config.provider, config.model) ? 'explicit-tag' : 'top-logprobs'\n}\n\nasync function callAutomatic(config: VerifierClientConfig, prompt: string, signal: AbortSignal | undefined, images: readonly VerifierImage[] | undefined, attempt: number): Promise<VerifierCompletion> {\n await config.topLogprobCapabilities.ensureLoaded()\n let fellBack = false\n if (!config.topLogprobCapabilities.isUnsupported(config.provider, config.model)) {\n const route = await resolveTopLogprobRoute(config.ctx, config.provider)\n if (route !== undefined) {\n try { return await callTopLogprobs(route, config.model, prompt, config.maxTokens, config.reasoningEffort, signal, images, attempt, config.temperature) }\n catch (error) {\n // Both a capability rejection and a non-retryable provider rejection of\n // the direct transport fall back to the DSH stream instead of failing\n // the whole verification.\n if (!(error instanceof TopLogprobsUnsupportedError)) throw error\n config.topLogprobCapabilities.markUnsupported(config.provider, config.model)\n // A runtime downgrade AFTER a live attempt, unlike the capability probe that\n // finds no route at all: only this one is a fallback worth counting.\n fellBack = true\n }\n } else config.topLogprobCapabilities.markUnsupported(config.provider, config.model)\n }\n const completion = await callExplicitTag(config, prompt, signal, images, attempt)\n return fellBack ? { ...completion, channelFallback: true } : completion\n}\n\nexport async function callVerifier(config: VerifierClientConfig, prompt: string, signal?: AbortSignal, images?: readonly VerifierImage[]): Promise<VerifierCompletion> {\n const invoke = () => retrying(config, signal, (attemptSignal, attempt) => callAutomatic(config, prompt, attemptSignal, images, attempt))\n return config.limiter === undefined ? invoke() : config.limiter.run(invoke, signal)\n}\n\n/**\n * Best-of-N generation sampling constants.\n *\n * Deliberately NOT the judge's temperature: best-of-N only pays off when the drafts actually\n * differ, and the judge's low default (0.2) would produce N near-copies — the tool would then\n * spend N times the money choosing between the same answer.\n */\nexport const GENERATION_TEMPERATURE = 1\n/**\n * Output ceiling for one draft.\n *\n * 4096 was a guess in the plan, and the first real end-to-end acceptance disproved it: a\n * \"function + 12 test cases + a note\" task truncated ALL THREE drafts, so the tool returned\n * nothing at all. The measured cause is reasoning tokens: on a trivial 2-draft run the session\n * model (deepseek-official/deepseek-flash) spent 16363 reasoning tokens out of 17254 output\n * tokens — roughly 8k of reasoning PER DRAFT, which eats any 4096 budget before the answer starts.\n *\n * 16384 is about 2x that measured per-draft spend, and it is also the largest ceiling that keeps\n * a pairwise judge prompt inside the plugin's own evidence limit: two drafts at 16384 tokens are\n * roughly 130k characters against a 240k explicit-evidence ceiling (EXPLICIT_MAX_TOTAL_CHARS).\n * `maxTokens` is a ceiling rather than a reservation, so a draft that needs less room costs\n * exactly what it did before. A task whose answer genuinely needs more is too large for this tool,\n * and its truncation is REPORTED instead of being silently returned.\n */\nexport const GENERATION_MAX_TOKENS = 16384\n\nexport interface GenerationTarget {\n provider: string\n model: string\n reasoningEffort?: string\n}\n\n/** One draft: plain text, never scored, plus whether it ran into the output ceiling. */\nexport interface GeneratedCandidate extends VerifierCompletion { truncated: boolean }\n\n/**\n * Re-point an existing verifier client at the model that should draft the candidates.\n *\n * Everything transport-shaped (context, llm runtime, attachments, capability memory, limiter,\n * timeout, retry budget) is inherited; only the route and the two generation-specific scalars\n * are replaced. `reasoningEffort` comes from the target and is never inherited from the base,\n * because the base is a judge: a leftover judge effort would silently draft with the wrong model\n * settings.\n * @param base - any configured verifier client (the primary judge is the cheapest source).\n * @param target - the model that writes the drafts.\n * @param maxTokens - output ceiling for this attempt.\n * @returns A client config safe to pass to {@link callGeneratedText}.\n */\nexport function generationClient(base: VerifierClientConfig, target: GenerationTarget, maxTokens = GENERATION_MAX_TOKENS): VerifierClientConfig {\n return {\n ctx: base.ctx,\n llm: base.llm,\n attachments: base.attachments,\n topLogprobCapabilities: base.topLogprobCapabilities,\n provider: target.provider,\n model: target.model,\n label: target.provider + '/' + target.model,\n ...(target.reasoningEffort === undefined ? {} : { reasoningEffort: target.reasoningEffort }),\n maxTokens,\n temperature: GENERATION_TEMPERATURE,\n timeoutMs: base.timeoutMs,\n maxRetries: base.maxRetries,\n retryBaseDelayMs: base.retryBaseDelayMs,\n ...(base.limiter === undefined ? {} : { limiter: base.limiter }),\n }\n}\n\n/**\n * One best-of-N draft.\n *\n * A named seam over the plain-text path: generation has no A–T contract and no scoring channel, and\n * the name keeps it distinct from the judge calls at every call site and in the decision snapshot.\n *\n * Hitting the output ceiling is deliberately NOT an error here. The operator already paid for those\n * tokens, and the judge can see for itself that the text stops mid-sentence. That is exactly why the\n * judge's fail-closed max-tokens handling was split out of this path: before the split, one long\n * task made the whole tool return zero candidates.\n * @param base - any configured verifier client (the primary judge is the cheapest source).\n * @param target - the model that writes the draft (normally the session model).\n * @param prompt - the rendered drafting prompt.\n * @param signal - caller's abort signal.\n * @returns The draft text, token usage, and whether it ran into the ceiling.\n */\nexport async function generateCandidate(base: VerifierClientConfig, target: GenerationTarget, prompt: string, signal?: AbortSignal): Promise<GeneratedCandidate> {\n return callGeneratedText(generationClient(base, target), prompt, signal)\n}\n\n/** Generation transport: the judge's timeout/retry/limiter wrappers, with truncation as a result. */\nasync function callGeneratedText(config: VerifierClientConfig, prompt: string, signal: AbortSignal | undefined): Promise<GeneratedCandidate> {\n const invoke = () => retrying(config, signal, (attemptSignal, attempt) => callTextCompletion(config, prompt, attemptSignal, undefined, attempt, true))\n return config.limiter === undefined ? invoke() : config.limiter.run(invoke, signal)\n}\n\n/** Plain-text verifier call for conservative JSON routing; probability labels are intentionally bypassed. */\nexport async function callVerifierText(config: VerifierClientConfig, prompt: string, signal?: AbortSignal): Promise<VerifierCompletion> {\n const invoke = () => retrying(config, signal, (attemptSignal, attempt) => callExplicitTag(config, prompt, attemptSignal, undefined, attempt))\n return config.limiter === undefined ? invoke() : config.limiter.run(invoke, signal)\n}\nexport function addUsage(target: UsageStats, source: UsageStats): void { for (const key of ['calls', 'attempts', 'retries', 'inputTokens', 'cachedInputTokens', 'outputTokens', 'reasoningTokens'] as const) target[key] += source[key] ?? 0 }\nexport function emptyUsage(): UsageStats { return { calls: 0, attempts: 0, retries: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0 } }\n"],"mappings":";;;;;;AAiCA,IAAa,8BAAb,cAAiD,MAAM;CAAE,YAAY,SAAiB;EAAE,MAAM,OAAO;EAAG,KAAK,OAAO;CAA8B;AAAE;;;;;;AAMpJ,IAA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AAI,OAAO,QAAQ,IAAI,QAAQ,MAAM;AACpF;;AAGA,eAAsB,iBAAiB,QAA8B,QAAgB,QAAmD;CACtI,MAAM,eAAe,SAAS,QAAQ,SAAS,eAAe,YAAY,gBAAgB,QAAQ,QAAQ,eAAe,KAAA,GAAW,OAAO,CAAC;CAC5I,OAAO,OAAO,YAAY,KAAA,IAAY,OAAO,IAAI,OAAO,QAAQ,IAAI,QAAQ,MAAM;AACpF;AACA,SAAgB,SAAS,QAAoB,QAA0B;CAAE,KAAK,MAAM,OAAO;EAAC;EAAS;EAAY;EAAW;EAAe;EAAqB;EAAgB;CAAiB,GAAY,OAAO,QAAQ,OAAO,QAAQ;AAAE;AAC7O,SAAgB,aAAyB;CAAE,OAAO;EAAE,OAAO;EAAG,UAAU;EAAG,SAAS;EAAG,aAAa;EAAG,mBAAmB;EAAG,cAAc;EAAG,iBAAiB;CAAE;AAAE"}
package/lib/caller.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as attachUsage, c as emptyUsage, d as generationClient, f as partialUsage, i as addUsage, l as fallbackDeepFreeze, m as requestAttempts, n as GENERATION_TEMPERATURE, o as callVerifier, p as predictScoringChannel, r as RequestLimiter, s as callVerifierText, t as GENERATION_MAX_TOKENS, u as generateCandidate } from "./caller-l5JwNkI3.js";
1
+ import { a as attachUsage, c as emptyUsage, d as generationClient, f as partialUsage, i as addUsage, l as fallbackDeepFreeze, m as requestAttempts, n as GENERATION_TEMPERATURE, o as callVerifier, p as predictScoringChannel, r as RequestLimiter, s as callVerifierText, t as GENERATION_MAX_TOKENS, u as generateCandidate } from "./caller-Bfp4HPK_.js";
2
2
  export { GENERATION_MAX_TOKENS, GENERATION_TEMPERATURE, RequestLimiter, addUsage, attachUsage, callVerifier, callVerifierText, emptyUsage, fallbackDeepFreeze, generateCandidate, generationClient, partialUsage, predictScoringChannel, requestAttempts };
package/lib/client.js CHANGED
@@ -2568,17 +2568,119 @@ window.__ModuleLoader__.load({
2568
2568
  return import_lib.default.transform(import_lib.default.union([...AUTO_PROCESS_SELECTION_MODES, import_lib.default.boolean()]).default("off"), (value) => normalizeAutoProcessSelection(value) ?? "off").default("off");
2569
2569
  }
2570
2570
  /**
2571
+ * Cross-copy identity of the cosmokit volatile reference protocol.
2572
+ *
2573
+ * `cosmokit` publishes this symbol through `Symbol.for` exactly so that separate copies of the
2574
+ * library (the host ESM bundle, this plugin's CJS bundle) recognise each other's references. The
2575
+ * plugin implements the same protocol locally instead of importing `@deepseek-ai/cosmokit`: the
2576
+ * harness resolves its vendor packages only for hosts that publish them, and `config.ts` is also
2577
+ * evaluated inside the browser settings bundle, where neither a Node require nor a host-only import
2578
+ * may appear.
2579
+ */
2580
+ const VOLATILE_WRITE = Symbol.for("cosmokit.volatile.write");
2581
+ /** Schemas that already carry the volatile reference protocol. */
2582
+ const volatileRefSchemas = /* @__PURE__ */ new WeakSet();
2583
+ /** Whether a value implements the shared cosmokit volatile reference protocol. */
2584
+ function isVolatileConfigRef(value) {
2585
+ return typeof value === "object" && value !== null && VOLATILE_WRITE in value;
2586
+ }
2587
+ /**
2588
+ * Deep-freeze one plain snapshot for a volatile reference.
2589
+ *
2590
+ * Mirrors cosmokit's own snapshot rules: primitives pass through, arrays and plain objects are
2591
+ * copied and frozen, and functions, cycles and class instances are rejected.
2592
+ */
2593
+ function freezeVolatileSnapshot(value, ancestors = /* @__PURE__ */ new Set()) {
2594
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
2595
+ if (value === null || typeof value !== "object") return value;
2596
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
2597
+ ancestors.add(value);
2598
+ try {
2599
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => freezeVolatileSnapshot(item, ancestors)));
2600
+ const prototype = Object.getPrototypeOf(value);
2601
+ if (prototype !== Object.prototype && prototype !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
2602
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, freezeVolatileSnapshot(item, ancestors)])));
2603
+ } finally {
2604
+ ancestors.delete(value);
2605
+ }
2606
+ }
2607
+ /**
2608
+ * Create a stable reference holding an immutable copy of the supplied data.
2609
+ *
2610
+ * The returned object is frozen and exposes only `get()` plus the shared write symbol, so the
2611
+ * owning runtime (the host Loader) is the only writer.
2612
+ * @param value - validated config data produced by the schema itself.
2613
+ * @returns a reference whose snapshot is replaced only through the volatile protocol.
2614
+ */
2615
+ function createVolatileConfigRef(value) {
2616
+ let current = freezeVolatileSnapshot(value);
2617
+ const ref = { get: () => current };
2618
+ Object.defineProperty(ref, VOLATILE_WRITE, {
2619
+ value: (next) => {
2620
+ current = next;
2621
+ },
2622
+ enumerable: false
2623
+ });
2624
+ return Object.freeze(ref);
2625
+ }
2626
+ /**
2627
+ * Make a schema's successful parses return a volatile reference.
2628
+ *
2629
+ * A volatile-marked schema must not only set `meta.volatile` (which is all the community
2630
+ * `schemastery` builder can express): the host Loader identifies live configuration by walking
2631
+ * `fiber.config` for cosmokit references, so a schema that returns a plain object is treated as
2632
+ * having no live fields. The entry then takes the volatile-only update path, finds zero references,
2633
+ * and silently drops every saved value.
2634
+ *
2635
+ * The shadow is installed on the instance, leaving the community prototype untouched, and is
2636
+ * idempotent: a schema already handling the protocol is returned unchanged.
2637
+ * @param schema - schema to extend with the volatile reference protocol.
2638
+ * @returns the same schema, now returning references from `~standard.validate`.
2639
+ */
2640
+ function installVolatileRefProtocol(schema) {
2641
+ if (volatileRefSchemas.has(schema)) return schema;
2642
+ const standard = schema["~standard"];
2643
+ if (!standard || typeof standard.validate !== "function") return schema;
2644
+ volatileRefSchemas.add(schema);
2645
+ const validate = standard.validate;
2646
+ const shadow = {
2647
+ version: standard.version ?? 1,
2648
+ vendor: standard.vendor ?? "schemastery",
2649
+ validate(value) {
2650
+ const result = validate(value);
2651
+ if (!result || typeof result !== "object" || "issues" in result) return result;
2652
+ if (isVolatileConfigRef(result.value)) return result;
2653
+ return {
2654
+ ...result,
2655
+ value: createVolatileConfigRef(result.value)
2656
+ };
2657
+ }
2658
+ };
2659
+ Object.defineProperty(schema, "~standard", {
2660
+ value: shadow,
2661
+ enumerable: false,
2662
+ configurable: true
2663
+ });
2664
+ return schema;
2665
+ }
2666
+ /**
2571
2667
  * Mark a Schemastery schema as volatile so DSH 0.1.7+ projects its fields into SettingsForms.
2572
2668
  *
2573
- * Compatible with both `@deepseek-ai/schemastery` (which provides `.volatile()`) and community
2574
- * `schemastery` (where `.extra('volatile', true)` or direct `meta.volatile = true` attaches the
2575
- * metadata).
2669
+ * Sets the `volatile` metadata that drives `volatileForm` / `isVolatilePath`, then installs the
2670
+ * volatile reference protocol so the host Loader can actually commit live values into the running
2671
+ * fiber. Compatible with both `@deepseek-ai/schemastery` (which provides `.volatile()`) and
2672
+ * community `schemastery` (where `.extra('volatile', true)` attaches the metadata alone).
2576
2673
  */
2577
2674
  function markVolatile(schema) {
2578
- if (typeof schema.volatile === "function") return schema.volatile();
2579
- const result = typeof schema.extra === "function" ? schema.extra("volatile", true) : schema;
2580
- if (result && result.meta) result.meta.volatile = true;
2581
- return result;
2675
+ let marked;
2676
+ if (schema.meta?.volatile) marked = schema;
2677
+ else if (typeof schema.volatile === "function") marked = schema.volatile();
2678
+ else {
2679
+ const result = typeof schema.extra === "function" ? schema.extra("volatile", true) : schema;
2680
+ if (result && result.meta) result.meta.volatile = true;
2681
+ marked = result;
2682
+ }
2683
+ return installVolatileRefProtocol(marked);
2582
2684
  }
2583
2685
  import_lib.default.object({
2584
2686
  provider: import_lib.default.string(),