@jeffusion/bungee-core 6.16.2 → 6.18.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.
Files changed (45) hide show
  1. package/dist/main.js +5691 -2189
  2. package/dist/observability-worker.js +3257 -1491
  3. package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
  4. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
  5. package/dist/plugins/chatgpt-oauth/index.js +37 -15
  6. package/dist/plugins/chatgpt-oauth/index.js.map +5 -5
  7. package/dist/plugins/codex-router/index.js +21 -3
  8. package/dist/plugins/codex-router/index.js.map +5 -5
  9. package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
  10. package/dist/plugins/key-access/index.js +1 -1
  11. package/dist/plugins/key-access/index.js.map +4 -4
  12. package/dist/plugins/key-access/ingress.js +1 -1
  13. package/dist/plugins/key-access/ingress.js.map +3 -3
  14. package/dist/plugins/key-rate-limit/index.js.map +2 -2
  15. package/dist/plugins/llm-protocol-adapter/control.js +1 -1
  16. package/dist/plugins/llm-protocol-adapter/control.js.map +3 -3
  17. package/dist/plugins/llm-protocol-adapter/index.js +1 -1
  18. package/dist/plugins/llm-protocol-adapter/index.js.map +5 -5
  19. package/dist/plugins/llm-tps/index.js.map +2 -2
  20. package/dist/plugins/model-mapping/index.js +1 -1
  21. package/dist/plugins/model-mapping/index.js.map +4 -4
  22. package/dist/plugins/models-dev/index.js.map +2 -2
  23. package/dist/plugins/request-body-redaction/control.js +58 -0
  24. package/dist/plugins/request-body-redaction/control.js.map +10 -0
  25. package/dist/plugins/request-body-redaction/index.js +7049 -0
  26. package/dist/plugins/request-body-redaction/index.js.map +28 -0
  27. package/dist/plugins/request-body-redaction/manifest.json +83 -0
  28. package/dist/plugins/request-body-redaction/ui/RedactionRulesEditor.svelte +475 -0
  29. package/dist/plugins/request-body-redaction/ui/RequestBodyRedactionPage.svelte +674 -0
  30. package/dist/plugins/request-body-redaction/ui/RequestBodyRedactionStats.svelte +218 -0
  31. package/dist/plugins/request-body-redaction/ui/route-bindings.ts +69 -0
  32. package/dist/plugins/request-logs/index.js +505 -118
  33. package/dist/plugins/request-logs/index.js.map +11 -10
  34. package/dist/plugins/request-logs/ingress.js +3 -23
  35. package/dist/plugins/request-logs/ingress.js.map +3 -3
  36. package/dist/plugins/request-logs/ui/RequestLogsPage.svelte +215 -130
  37. package/dist/plugins/signature-repair/index.js.map +2 -2
  38. package/dist/plugins/token-budget/index.js.map +2 -2
  39. package/dist/plugins/token-metering/index.js.map +2 -2
  40. package/dist/plugins/token-stats/control.js +111 -40
  41. package/dist/plugins/token-stats/control.js.map +6 -6
  42. package/dist/plugins/token-stats/index.js +92 -39
  43. package/dist/plugins/token-stats/index.js.map +5 -5
  44. package/dist/plugins/user-auth/index.js.map +2 -2
  45. package/package.json +3 -2
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "/** Shared process sink; the public SDK must not bundle file transports into plugins. */\ntype Context = Readonly<Record<string, unknown>>;\ntype LogMethod = { (context: Context, message?: string): void; (message: string): void };\nexport interface PluginLogSink {\n info: LogMethod; warn: LogMethod; error: LogMethod; debug: LogMethod; fatal: LogMethod;\n child(bindings: Context): PluginLogSink;\n}\nconst sinkKey = Symbol.for('@jeffusion/bungee/plugin-log-sink');\nexport function installPluginLogSink(sink: PluginLogSink): void {\n (globalThis as Record<symbol, unknown>)[sinkKey] = sink;\n}\nfunction createLogger(bindings: Context = {}): PluginLogSink {\n const method = (level: 'info' | 'warn' | 'error' | 'debug' | 'fatal'): LogMethod =>\n (value: Context | string, message?: string) => {\n const sink = (globalThis as Record<symbol, unknown>)[sinkKey] as PluginLogSink | undefined;\n if (sink) {\n if (typeof value === 'string') sink[level](bindings, value);\n else sink[level]({...bindings, ...value}, message);\n } else if (level !== 'debug' || process.env.LOG_LEVEL === 'debug') {\n const write = level === 'fatal' ? console.error : console[level];\n write(message ?? (typeof value === 'string' ? value : ''), typeof value === 'string' ? bindings : {...bindings, ...value});\n }\n };\n return {info: method('info'), warn: method('warn'), error: method('error'), debug: method('debug'),\n fatal: method('fatal'), child: extra => createLogger({...bindings, ...extra})};\n}\nexport const logger = createLogger();\n",
6
6
  "/**\n * Hook 实现类\n *\n * 提供 4 种 Hook 类型的实现:\n * - AsyncParallelHook: 异步并行执行\n * - AsyncSeriesHook: 异步串行执行\n * - AsyncSeriesBailHook: 异步串行可中断\n * - AsyncSeriesWaterfallHook: 异步串行瀑布\n */\n\nimport { logger } from '../plugin-logger';\n/** Host-supplied view refresh, run between every waterfall tap. */\nexport const WATERFALL_VIEW_TRANSFORM = Symbol('waterfall-view-transform');\nimport type {\n TapInfo,\n Tap,\n IAsyncParallelHook,\n IAsyncSeriesHook,\n IAsyncSeriesBailHook,\n IAsyncSeriesWaterfallHook,\n IAsyncSeriesMapHook,\n HookStats,\n} from './types';\n\n/**\n * 标准化 TapInfo\n */\nfunction normalizeTapInfo(info: TapInfo | string): TapInfo {\n if (typeof info === 'string') {\n return { name: info, stage: 0 };\n }\n return { ...info, stage: info.stage ?? 0 };\n}\n\n/**\n * 基础 Hook 类\n */\nabstract class BaseHook<T extends any[]> {\n protected taps: Tap<T, any>[] = [];\n protected name: string;\n protected callCount = 0;\n protected totalTimeMs = 0;\n\n constructor(name?: string) {\n this.name = name ?? 'anonymous';\n }\n\n /**\n * 同步注册\n */\n tap(info: TapInfo | string, fn: (...args: T) => any): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'sync', fn });\n this.sortTaps();\n }\n\n /**\n * 异步回调风格注册\n */\n tapAsync(info: TapInfo | string, fn: (...args: any[]) => void): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'async', fn });\n this.sortTaps();\n }\n\n /**\n * Promise 风格注册\n */\n tapPromise(info: TapInfo | string, fn: (...args: T) => Promise<any>): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'promise', fn });\n this.sortTaps();\n }\n\n /**\n * 检查是否有注册的回调\n */\n hasCallbacks(): boolean {\n return this.taps.length > 0;\n }\n\n /**\n * 获取统计信息\n */\n getStats(): HookStats {\n return {\n name: this.name,\n tapCount: this.taps.length,\n callCount: this.callCount,\n totalTimeMs: this.totalTimeMs,\n avgTimeMs: this.callCount > 0 ? this.totalTimeMs / this.callCount : 0,\n };\n }\n\n /**\n * 重置统计信息\n */\n resetStats(): void {\n this.callCount = 0;\n this.totalTimeMs = 0;\n }\n\n /**\n * 清空所有注册的回调\n */\n clear(): void {\n this.taps = [];\n }\n\n /**\n * 按 stage 排序(稳定排序)\n */\n private sortTaps(): void {\n this.taps.sort((a, b) => (a.info.stage ?? 0) - (b.info.stage ?? 0));\n }\n\n /**\n * 执行单个 tap\n */\n protected async executeTap<R>(\n tap: Tap<T, R>,\n args: T\n ): Promise<R | undefined> {\n try {\n if (tap.type === 'sync') {\n return tap.fn(...args);\n } else if (tap.type === 'promise') {\n return await tap.fn(...args);\n } else {\n // async (callback style)\n return await new Promise<R | undefined>((resolve, reject) => {\n const done = (err?: Error, result?: R) => {\n if (err) reject(err);\n else resolve(result);\n };\n tap.fn(...args, done);\n });\n }\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n}\n\n/** Synchronous providers use the same registration, ordering and statistics as async hooks. */\nexport class SyncBailHook<T extends any[] = [], R = unknown> extends BaseHook<T> {\n override tapAsync(): never { throw new Error('synchronous provider requires tap'); }\n override tapPromise(): never { throw new Error('synchronous provider requires tap'); }\n call(...args: T): R | undefined {\n const started = performance.now();\n this.callCount++;\n try {\n for (const tap of this.taps) {\n const result = tap.fn(...args);\n if (result && typeof result.then === 'function') throw new Error('synchronous provider returned a Promise');\n if (result !== undefined) return result as R;\n }\n return undefined;\n } finally { this.totalTimeMs += performance.now() - started; }\n }\n}\n\n/**\n * 异步并行 Hook\n * 所有回调并行执行,全部完成后返回\n */\nexport class AsyncParallelHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncParallelHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 并行执行所有回调,错误独立处理不影响其他\n await Promise.all(\n this.taps.map(async (tap) => {\n try {\n await this.executeTap(tap, args);\n } catch (error) {\n // 并行 Hook 中单个回调的错误不应影响其他回调\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in parallel hook callback (ignored)'\n );\n }\n })\n );\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行 Hook\n * 所有回调按顺序串行执行\n */\nexport class AsyncSeriesHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncSeriesHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n await this.executeTap(tap, args);\n }\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行可中断 Hook\n * 任意回调返回非 undefined 值则停止执行并返回该值\n */\nexport class AsyncSeriesBailHook<T extends any[] = [], R = any>\n extends BaseHook<T>\n implements IAsyncSeriesBailHook<T, R>\n{\n async promise(...args: T): Promise<R | undefined> {\n if (this.taps.length === 0) return undefined;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n const result = await this.executeTap<R>(tap, args);\n if (result !== undefined) {\n logger.debug(\n { hookName: this.name, pluginName: tap.info.name },\n 'Hook bailed with result'\n );\n return result;\n }\n }\n return undefined;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行瀑布 Hook\n * 每个回调的返回值作为下一个回调的第一个参数\n */\nexport class AsyncSeriesWaterfallHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesWaterfallHook<T, A>\n{\n async promise(value: T, ...args: A): Promise<T> {\n if (this.taps.length === 0) return value;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n let current = value;\n for (const tap of this.taps) {\n const result = await this.executeTap<T>(tap, [current, ...args] as [T, ...A]);\n // 只有返回非 undefined 时才更新值\n if (result !== undefined) {\n const transform = args[0]?.[WATERFALL_VIEW_TRANSFORM];\n current = typeof transform === 'function' ? await transform(result,current) : result;\n }\n }\n return current;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行映射 Hook\n * 支持 N:M 转换:每个回调处理输入,可以返回 0 到多个输出\n *\n * 执行流程:\n * 1. 初始输入:单个 chunk\n * 2. 每个插件处理当前的所有 chunks,返回新的 chunks 数组\n * 3. 下一个插件处理上一步的所有输出\n *\n * 返回值约定:\n * - null/undefined: 不处理,原样输出当前 chunk\n * - []: 缓冲当前 chunk,不输出(N:0)\n * - [chunk]: 1:1 转换\n * - [chunk1, chunk2, ...]: 1:M 拆分\n *\n * 性能优化:\n * - 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n * - 适用于流式响应处理等高频调用场景\n */\nexport class AsyncSeriesMapHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesMapHook<T, A>\n{\n /**\n * 同步执行单个 tap(跳过 Promise 开销)\n */\n private executeTapSync<R>(tap: Tap<[T, ...A], R>, args: [T, ...A]): R | undefined {\n try {\n return tap.fn(...args);\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n\n async promise(value: T, ...args: A): Promise<T[]> {\n // 如果没有注册任何回调,直接返回原始值\n if (this.taps.length === 0) return [value];\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 初始输入为单个 chunk\n let chunks: T[] = [value];\n\n // 依次应用每个插件的转换\n for (const tap of this.taps) {\n const newChunks: T[] = [];\n\n // 对当前的每个 chunk 应用转换\n for (const chunk of chunks) {\n try {\n // 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n const result = tap.type === 'sync'\n ? this.executeTapSync<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A])\n : await this.executeTap<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A]);\n\n if (result === null || result === undefined) {\n // 不处理,原样输出\n newChunks.push(chunk);\n } else if (Array.isArray(result)) {\n // N:M 转换\n // [] = 缓冲(不输出)\n // [item] = 1:1 转换\n // [item1, item2, ...] = 1:M 拆分\n newChunks.push(...result);\n } else {\n // 非法返回值,警告并原样输出\n logger.warn(\n { hookName: this.name, pluginName: tap.info.name, result },\n 'AsyncSeriesMapHook callback must return an array or null'\n );\n newChunks.push(chunk);\n }\n } catch (error) {\n // 单个 chunk 处理失败,记录错误并原样输出\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in AsyncSeriesMapHook callback'\n );\n if ((args[0] as { strict?: boolean } | undefined)?.strict) {\n throw error;\n }\n newChunks.push(chunk);\n }\n }\n\n chunks = newChunks;\n }\n\n return chunks;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n",
7
- "import type { PluginConfigConstraint, PluginRuntimeScope } from '@jeffusion/bungee-types';\nexport type { PluginConfigConstraint, PluginAllowedTuplesConstraint, PluginRuntimeScope } from '@jeffusion/bungee-types';\n/**\n * Plugin 系统类型定义\n */\n\n/**\n * 插件配置值类型\n * 定义了插件配置中允许的值类型,比 `any` 更具体\n */\nexport type PluginConfigValue =\n | string\n | number\n | boolean\n | null\n | PluginConfigValue[]\n | { [key: string]: PluginConfigValue };\n\nexport interface CredentialOutboundHeaderProfile {\n readonly passthrough: readonly string[];\n readonly set: Readonly<Record<string, string>>;\n}\n\nexport interface CredentialRequestPolicy {\n readonly pathname: string;\n readonly methods: readonly string[];\n readonly outboundHeaders?: CredentialOutboundHeaderProfile;\n}\n\n// ============ Manifest 类型定义 ============\n\n/**\n * 插件 manifest.json 规范\n *\n * manifest.json 是插件的声明性配置文件,作为插件元数据的唯一真相来源。\n * 框架通过读取此文件来发现插件能力,无需执行插件代码。\n *\n * @example\n * ```json\n * {\n * \"name\": \"token-stats\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Track AI API token usage\",\n * \"main\": \"server/index.ts\",\n * \"ui\": {\n * \"components\": [\n * { \"name\": \"TokenStatsChart\", \"entry\": \"ui/TokenStatsChart.svelte\" }\n * ]\n * },\n * \"contributes\": {\n * \"nativeWidgets\": [...],\n * \"api\": [...]\n * },\n * \"translations\": { \"en\": {...}, \"zh-CN\": {...} }\n * }\n * ```\n */\nexport interface PluginManifest {\n /**\n * 插件唯一标识符(必填)\n * 用于路由、存储命名空间等\n */\n name: string;\n\n /**\n * 插件版本号(必填)\n * 遵循 semver 规范\n */\n version: string;\n\n schemaVersion?: number | string;\n artifactKind?: string;\n\n /**\n * 插件描述(支持翻译键)\n */\n description?: string;\n\n /**\n * 图标(Material Icon 名称或 URL)\n */\n icon?: string;\n\n /**\n * 作者信息\n */\n author?: string | {\n name: string;\n email?: string;\n url?: string;\n };\n\n /**\n * 许可证\n */\n license?: string;\n\n /**\n * 项目主页\n */\n homepage?: string;\n\n /**\n * 代码仓库\n */\n repository?: string | {\n type: string;\n url: string;\n };\n\n /**\n * 关键词(用于搜索)\n */\n keywords?: string[];\n\n /**\n * 服务端入口配置\n */\n main?: string;\n\n capabilities?: string[];\n /** Global providers run once whenever activated; global-and-scoped also retains application bindings. Defaults to scoped. */\n runtimeScope?: PluginRuntimeScope;\n services?: import('./plugin-services').PluginServiceDeclarations;\n /** Optional control-plane runtime capability. */\n ingress?: { entry: string };\n management?: { loginComponent?: string; setupComponent?: string };\n control?: {\n entry: string;\n rpc: Array<{\n name: string;\n access: 'bound-attempt';\n }>;\n };\n /**\n * UI 扩展模式(冻结边界)\n * - none: 无 UI 扩展\n * - native-static: 原生静态组件(依赖构建期注册表,不支持运行时注入)\n * - sandbox-iframe: 独立沙箱扩展(通过 iframe 隔离,独立服务资源)\n */\n uiExtensionMode?: 'none' | 'native-static' | 'sandbox-iframe';\n\n /**\n * UI 组件配置\n */\n ui?: {\n /**\n * 组件列表\n * 用于自动注册到组件白名单\n */\n components?: Array<{\n /** 组件名称(用于 nativeWidgets.component 引用) */\n name: string;\n /** 组件入口文件路径(相对于插件根目录) */\n entry: string;\n }>;\n };\n\n /**\n * 权限声明\n * 用于安全预检(用户上传插件场景)\n */\n permissions?: Array<\n | 'network' // 网络访问\n | 'storage' // 持久化存储\n | 'filesystem' // 文件系统访问\n | string // 自定义权限\n >;\n\n /**\n * 插件依赖\n */\n dependencies?: Record<string, string>;\n\n /** Optional providers are never included in automatic activation closure. */\n optionalDependencies?: Record<string, string>;\n\n /**\n * 引擎版本要求\n */\n engines?: {\n bungee?: string;\n node?: string;\n };\n\n /**\n * 贡献点配置\n */\n contributes?: {\n /**\n * 原生仪表板组件\n */\n nativeWidgets?: Array<{\n id: string;\n title: string;\n size: 'small' | 'medium' | 'large' | 'full';\n component: string;\n presentation?: 'kpi';\n props?: Record<string, any>;\n }>;\n\n /**\n * API 端点\n */\n api?: Array<{\n path: string;\n methods: Array<'GET' | 'POST' | 'PUT' | 'DELETE'>;\n handler: string;\n execution: 'control';\n capability?: string;\n methodCapabilities?: Record<string,string>;\n }>;\n resourceExtensions?: Array<{resource:'api-key';component:string;path:'/keys/:keyId'}>;\n upstreamSources?: Array<{\n id: string;\n label: string;\n listAccounts: string;\n createDraft: string;\n credentialPolicy: {\n allowedOrigins: string[];\n allowedRequests: CredentialRequestPolicy[];\n allowedHeaderNames: string[];\n };\n }>;\n\n /**\n * iframe 仪表板组件(Legacy)\n */\n widgets?: Array<{\n title: string;\n path: string;\n size?: 'small' | 'medium' | 'large' | 'full';\n }>;\n\n /**\n * 导航菜单\n */\n navigation?: Array<{\n label: string;\n path: string;\n icon?: string;\n target?: 'sidebar' | 'header';\n component?: string;\n layout?: 'standalone';\n }>;\n\n /**\n * 设置页路径\n */\n settings?: string;\n\n /**\n * 原生静态设置组件名称(仅 builtin 插件可声明)\n */\n nativeSettingsComponent?: string;\n\n /**\n * 命令贡献\n */\n commands?: Array<{\n command: string;\n title: string;\n category?: string;\n icon?: string;\n }>;\n };\n\n /**\n * UI 展示元数据(新架构)\n * 用于存放 UI 相关的元数据,支持翻译键\n */\n metadata?: {\n /** 显示名称(支持翻译键) */\n name?: string;\n /** 描述(支持翻译键) */\n description?: string;\n /** 图标 */\n icon?: string;\n /** 贡献点配置(与顶层 contributes 合并) */\n contributes?: PluginManifest['contributes'];\n };\n\n /**\n * 配置 Schema\n * 用于动态生成配置表单\n */\n configSchema?: PluginConfigField[];\n configConstraints?: readonly PluginConfigConstraint[];\n\n /**\n * 多语言翻译\n */\n translations?: PluginTranslations;\n}\n\n/**\n * 从 manifest 加载的插件信息\n * 包含 manifest 数据和解析后的路径信息\n */\nexport interface LoadedPluginManifest extends PluginManifest {\n /** 插件根目录的绝对路径 */\n pluginDir: string;\n /** manifest.json 文件的绝对路径 */\n manifestPath: string;\n /** 服务端入口的绝对路径 */\n mainPath?: string;\n /** 控制面入口的绝对路径 */\n controlPath?: string;\n uiAssetsPath?: string;\n}\n\n// 导出 Hook 系统类型\nexport type {\n PluginHooks,\n RequestContext,\n MutableRequestContext,\n ResponseContext,\n ErrorContext,\n StreamChunkContext,\n FinallyContext,\n PluginInitContext,\n PluginLogger,\n} from './hooks';\n\nexport { createPluginHooks, clearHooks, getHooksStats, resetHooksStats } from './hooks';\nexport type { TapInfo } from './hooks';\n\n/**\n * 插件配置字段类型\n */\nexport type PluginConfigFieldType =\n | 'string' // 文本输入\n | 'number' // 数字输入\n | 'boolean' // 复选框\n | 'select' // 单选下拉\n | 'multiselect' // 多选下拉\n | 'textarea' // 多行文本\n | 'json' // JSON 编辑器\n | 'gateway_target'\n | 'model_mapping'\n | 'object' // 对象(嵌套表单)\n | 'array'; // 数组(列表编辑器)\n\n/**\n * 验证规则\n */\nexport interface ValidationRule {\n /**\n * 正则表达式模式\n */\n pattern?: string;\n\n /**\n * 最小值/最小长度\n */\n min?: number;\n\n /**\n * 最大值/最大长度\n */\n max?: number;\n\n /**\n * 自定义错误消息\n */\n message?: string;\n}\n\n/**\n * 字段转换规则(可序列化)\n * 用于定义虚拟字段与实际字段之间的转换关系\n */\nexport interface FieldTransform {\n /**\n * 转换类型\n */\n type: 'split' | 'concat' | 'compute';\n\n /**\n * split 类型专用:分隔符\n * @example '-' 将 \"a-b\" 拆分为 [\"a\", \"b\"]\n */\n separator?: string;\n\n /**\n * split/concat 类型专用:目标字段列表\n * @example ['from', 'to']\n */\n fields?: string[];\n}\n\nexport type PluginShowIfCondition =\n | {\n field: string;\n value: PluginConfigValue;\n }\n | {\n all: PluginShowIfCondition[];\n }\n | {\n any: PluginShowIfCondition[];\n };\n\n/**\n * 插件翻译内容\n *\n * 用于为插件的 UI 元素提供多语言支持\n *\n * 格式说明:\n * - 第一层 key 为语言代码(如 'en', 'zh-CN')\n * - 第二层 key 为翻译键(使用点号分隔的扁平结构)\n * - 系统会自动为所有翻译键添加 `plugins.{pluginName}` 前缀\n *\n * @example\n * ```typescript\n * static readonly translations: PluginTranslations = {\n * 'en': {\n * 'field.label': 'Field Label',\n * 'field.description': 'Field description text',\n * 'options.value1.label': 'Option 1'\n * },\n * 'zh-CN': {\n * 'field.label': '字段标签',\n * 'field.description': '字段描述文本',\n * 'options.value1.label': '选项 1'\n * }\n * };\n * ```\n */\nexport type PluginTranslations = Record<string, Record<string, string>>;\n\n/**\n * 插件配置字段定义\n * 用于动态生成配置表单\n */\nexport interface PluginConfigField {\n /**\n * 字段名(配置对象的 key)\n */\n name: string;\n\n /**\n * 字段类型\n */\n type: PluginConfigFieldType;\n\n /**\n * 显示标签(支持 i18n key 或直接字符串)\n */\n label: string;\n\n /**\n * 是否必填\n */\n required?: boolean;\n\n /**\n * 默认值\n */\n default?: PluginConfigValue;\n\n /**\n * select/multiselect 的选项列表\n */\n options?: Array<{\n label: string;\n value: string;\n description?: string;\n }>;\n\n /**\n * 描述/帮助文本\n */\n description?: string;\n\n /**\n * 占位符文本\n */\n placeholder?: string;\n\n catalogPlugin?: string;\n sourceCatalogProviderField?: string;\n targetCatalogProviderField?: string;\n\n /**\n * 验证规则\n */\n validation?: ValidationRule;\n\n /**\n * 条件显示(依赖其他字段的值)\n */\n showIf?: PluginShowIfCondition;\n\n /**\n * 子字段定义(type=object 时使用)\n */\n properties?: PluginConfigField[];\n\n /**\n * 数组元素类型(type=array 时使用)\n */\n items?: PluginConfigField;\n\n /**\n * 字段转换规则(可序列化)\n * 定义虚拟字段与实际字段之间的映射关系\n *\n * 当设置此属性时:\n * - 该字段为\"虚拟字段\",仅用于 UI 交互\n * - UI 输入值会根据转换规则展开为多个实际字段\n * - 实际字段的值会根据转换规则合并显示在 UI 中\n * - 虚拟字段本身不会保存到配置中\n *\n * @example\n * // 将 \"anthropic-openai\" 拆分为 { from: \"anthropic\", to: \"openai\" }\n * fieldTransform: {\n * type: 'split',\n * separator: '-',\n * fields: ['from', 'to']\n * }\n */\n fieldTransform?: FieldTransform;\n}\n\n/**\n * 类型守卫:检查插件类是否有 configSchema\n */\nexport function hasConfigSchema(\n PluginClass: any\n): PluginClass is { configSchema: PluginConfigField[] } {\n return 'configSchema' in PluginClass && Array.isArray(PluginClass.configSchema);\n}\n\n/**\n * Plugin 存储接口\n * 提供基于 Key-Value 的持久化存储能力\n */\n/** Trusted observation plugins may execute SQL only against access.db, never config.db.\n * Callers must perform database work within the callback; hosts revoke subsequent operations.\n */\nexport interface PluginObservationStorage {\n withDatabase<T>(operation: (database: import('bun:sqlite').Database) => T): T;\n}\n\n/** Result of a strict, side-effect-free namespaced KV read. */\nexport type PluginStorageReadResult<T> =\n | { readonly found: false }\n | { readonly found: true; readonly value: T };\n\nexport interface PluginStorage {\n readonly observation?: PluginObservationStorage;\n /** Invoke a registered observation adapter method in this plugin namespace. */\n invokeObservation?<T>(operation: string, args: readonly unknown[]): Promise<T>;\n /** Immediate namespaced KV access for cross-process shared values. */\n uncached?(): PluginStorage;\n /** Flush pending KV writes during host disposal. */\n flush?(): Promise<void>;\n\n /** Legacy embedder extension; the core does not construct or grant it by name. */\n readonly metering?: TokenStatsMeteringStorage;\n /**\n * 获取值\n * @param key 键\n * @returns 值,如果不存在则返回 null\n */\n get<T = any>(key: string): Promise<T | null>;\n\n /**\n * 严格只读获取值:直接读取当前命名空间的已提交数据。\n * 不访问/回填/刷新 LRU 缓存,也不清除过期记录;SQL/JSON 错误直接抛出。\n * 有效 JSON null 视为 found:true,缺失或已过期视为 found:false。\n * 可选仅为既有 embedder / 测试 fixture 的源码兼容;Bungee 实际存储实现必须提供。\n */\n readStrict?<T = unknown>(key: string): Promise<PluginStorageReadResult<T>>;\n\n /**\n * 设置值\n * @param key 键\n * @param value 值(必须可序列化)\n * @param ttlSeconds 过期时间(秒),可选\n */\n set(key: string, value: any, ttlSeconds?: number): Promise<void>;\n\n /**\n * 删除值\n * @param key 键\n */\n delete(key: string): Promise<void>;\n\n /**\n * 获取所有键(支持前缀过滤)\n * @param prefix 前缀,可选\n */\n keys(prefix?: string): Promise<string[]>;\n\n /**\n * 清空存储(仅限当前插件的命名空间)\n */\n clear(): Promise<void>;\n\n /**\n * 原子递增操作\n * 原子地递增指定对象字段的值,避免并发竞争\n * @param key 键\n * @param field 字段名\n * @param delta 递增量(默认1,可为负数)\n * @returns 递增后的新值\n */\n increment(key: string, field: string, delta?: number): Promise<number>;\n\n /**\n * 比较并交换操作\n * 仅当当前值等于期望值时,才更新为新值(原子操作)\n * @param key 键\n * @param field 字段名\n * @param expected 期望的当前值\n * @param newValue 新值\n * @returns 是否更新成功\n */\n compareAndSet(key: string, field: string, expected: any, newValue: any): Promise<boolean>;\n}\n\nexport type TokenStatsMetricName =\n | 'inputTokens' | 'outputTokens' | 'officialInputTokens' | 'officialOutputTokens'\n | 'estimatedInputTokens' | 'estimatedOutputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'\n | 'partialOutputs' | 'logicalRequests' | 'upstreamAttempts' | 'observationIncompleteAttempts'\n | 'inputAuthorityOfficial' | 'inputAuthorityLocal' | 'inputAuthorityHeuristic' | 'inputAuthorityPartial' | 'inputAuthorityNone'\n | 'outputAuthorityOfficial' | 'outputAuthorityLocal' | 'outputAuthorityHeuristic' | 'outputAuthorityPartial' | 'outputAuthorityNone';\n\nexport type TokenStatsMetrics = Partial<Record<TokenStatsMetricName, number>>;\n\nexport type TokenStatsGroupBy = 'model' | 'time';\nexport type TokenStatsRange = '1h' | '12h' | '24h' | '1d' | '7d' | '30d' | 'day' | 'week' | 'month';\n\nexport type TokenStatsValueSource = 'usage' | 'estimated' | 'partial' | 'unknown';\n\n/** One ended upstream attempt; provider is the wire protocol family, not a vendor name. */\nexport interface TokenStatsAttempt {\n readonly key_id?: string | null;\n readonly attempt_id: string;\n readonly request_id: string;\n readonly finished_at_ms: number;\n readonly route_id: string;\n readonly upstream_id: string;\n readonly provider: string;\n readonly outcome: string;\n readonly model: string;\n readonly input_tokens: number | null;\n readonly output_tokens: number | null;\n readonly input_source: TokenStatsValueSource;\n readonly output_source: TokenStatsValueSource;\n readonly cache_read_tokens: number | null;\n readonly cache_write_tokens: number | null;\n readonly cost_usd: number | null;\n readonly observation_incomplete: boolean;\n}\n\nexport type TokenStatsSnapshotMetrics = Record<TokenStatsMetricName, number> & {\n readonly estimatedCostUsd: number | null;\n};\n\nexport interface TokenStatsMeteringStorage {\n listClientModels?(input: {page?:number;pageSize?:number;keyword?:string}): Promise<{models:string[];total:number;page:number;pageSize:number}>;\n recordAttempt(row: TokenStatsAttempt): Promise<void>;\n queryWindowSnapshot(input: {\n asOfMs: number;\n range: TokenStatsRange;\n groupBy: TokenStatsGroupBy;\n timeZone?: string;\n keyId?: string;\n }): Promise<{\n all: TokenStatsSnapshotMetrics;\n data: Array<{ dimension: string; bucketStartMs?: number; metrics: TokenStatsSnapshotMetrics }>;\n bucketMs?: number;\n bucketStarts?: number[];\n /** Exclusive end of the last displayed bucket; calendar axes include future periods. */\n bucketEndMs?: number;\n present: boolean;\n }>;\n}\n\n/**\n * Plugin 元数据接口\n * 用于 UI 展示和系统集成\n */\nexport interface PluginMetadata {\n /**\n * 显示名称(支持翻译键或直接字符串)\n * 默认使用插件的 name,此字段用于提供更友好的 UI 显示名\n *\n * 支持翻译键格式:包含 `.` 且不包含空格\n * @example 'metadata.displayName' // 翻译键,会自动翻译\n * @example 'My Plugin' // 直接字符串,不翻译\n */\n name?: string;\n\n /**\n * 插件描述(支持翻译键或直接字符串)\n * 用于 UI 展示插件的详细说明\n *\n * 支持翻译键格式:包含 `.` 且不包含空格\n * @example 'metadata.description' // 翻译键,会自动翻译\n * @example 'A demo plugin for testing' // 直接字符串,不翻译\n */\n description?: string;\n\n /**\n * 图标(Material Icon 名称或 URL)\n */\n icon?: string;\n\n /**\n * 作者信息\n */\n author?: {\n name: string;\n email?: string;\n url?: string;\n } | string;\n\n /**\n * 许可证\n */\n license?: string;\n\n /**\n * 项目主页\n */\n homepage?: string;\n\n /**\n * 代码仓库\n */\n repository?: {\n type: string;\n url: string;\n } | string;\n\n /**\n * 关键词(用于搜索)\n */\n keywords?: string[];\n\n /**\n * 分类\n */\n categories?: string[];\n\n /**\n * 插件激活事件\n * 声明插件何时被激活\n */\n activationEvents?: string[];\n\n /**\n * 插件能力声明\n * 声明插件使用的系统能力\n */\n /**\n * 插件权限声明\n * 声明插件需要的系统权限(如 network, storage, api:routes 等)\n */\n permissions?: string[];\n\n capabilities?: {\n /**\n * 是否需要网络访问\n */\n network?: boolean;\n\n /**\n * 是否需要文件系统访问\n */\n filesystem?: boolean;\n\n /**\n * 是否需要数据库访问\n */\n database?: boolean;\n\n /**\n * 自定义能力声明\n */\n custom?: string[];\n };\n\n /**\n * 依赖的其他插件\n */\n dependencies?: Record<string, string>;\n\n /**\n * 可选依赖\n */\n optionalDependencies?: Record<string, string>;\n\n /**\n * 引擎版本要求\n */\n engines?: {\n bungee?: string;\n node?: string;\n };\n\n /**\n * 贡献点配置\n * 统一声明插件提供的 UI 和功能能力\n */\n contributes?: {\n /**\n * 导航集成\n */\n navigation?: Array<{\n label: string;\n path: string;\n icon?: string;\n target?: 'sidebar' | 'header'; // 默认 sidebar\n /** Optional statically registered native page component. */\n component?: string;\n layout?: 'standalone';\n }>;\n\n /**\n * 仪表板集成\n */\n widgets?: Array<{\n title: string;\n path: string;\n size?: 'small' | 'medium' | 'large' | 'full'; // small=1x1, medium=2x1, large=2x2, full=4x2\n }>;\n\n /**\n * 设置页路径\n */\n settings?: string;\n\n /**\n * 命令贡献\n * 声明插件提供的命令\n */\n commands?: Array<{\n command: string;\n title: string;\n category?: string;\n icon?: string;\n }>;\n\n /**\n * 配置贡献\n * 声明插件的配置项\n */\n configuration?: {\n title?: string;\n properties: Record<string, {\n type: 'string' | 'number' | 'boolean' | 'array' | 'object';\n default?: any;\n description?: string;\n enum?: any[];\n items?: any;\n properties?: any;\n }>;\n };\n\n /**\n * 原生仪表板组件(非 iframe)\n *\n * 与 widgets 不同,nativeWidgets 直接渲染为 Svelte 组件,\n * 可以复用主应用的图表库和样式系统。\n *\n * 安全说明:组件必须是内置的,插件只能通过 component 名称引用白名单中的组件\n *\n * @example\n * ```typescript\n * nativeWidgets: [{\n * id: 'token-stats-chart',\n * title: 'Token 统计',\n * size: 'medium',\n * component: 'TokenStatsChart',\n * props: { days: 7 }\n * }]\n * ```\n */\n nativeWidgets?: Array<{\n /** 唯一标识符 */\n id: string;\n /** 显示标题(支持 i18n key) */\n title: string;\n /** 尺寸:small=1x1, medium=2x1, large=2x2, full=4x2 */\n size: 'small' | 'medium' | 'large' | 'full';\n /** 组件名称(映射到内置组件白名单) */\n component: string;\n presentation?: 'kpi';\n /** 传递给组件的 props */\n props?: Record<string, any>;\n }>;\n\n /**\n * API 端点贡献\n *\n * 允许插件注册自己的 API 端点,端点路径强制在 /api/plugins/:pluginName/ 命名空间下。\n * 只有 global scope 的插件实例才能处理 API 请求。\n *\n * @example\n * ```typescript\n * api: [{\n * path: '/stats', // 实际路径: /api/plugins/my-plugin/stats\n * methods: ['GET'],\n * handler: 'getStats', // 调用控制面处理器的 getStats 方法\n * execution: 'control'\n * }]\n * ```\n */\n api?: Array<{\n /** 相对路径(相对于 /api/plugins/:pluginName) */\n path: string;\n /** 支持的 HTTP 方法 */\n methods: Array<'GET' | 'POST' | 'PUT' | 'DELETE'>;\n /** 处理器方法名(Plugin 类的方法) */\n handler: string;\n execution: 'control';\n capability?: string;\n methodCapabilities?: Record<string,string>;\n }>;\n };\n\n /**\n * @deprecated 使用 contributes.widgets 和 contributes.settings 代替\n */\n ui?: {\n dashboard?: Array<{\n id: string;\n title: string;\n path: string;\n size?: { w: number; h: number };\n }>;\n settings?: string;\n };\n}\n\n\n// ============ Plugin 接口 ============\n\nimport type { PluginHooks, PluginInitContext } from './hooks';\n\n/**\n * Plugin 接口(基于 Hook Registry 模式)\n *\n * 所有插件必须实现此接口。插件不再直接定义钩子方法,而是通过 register(hooks) 方法注册回调。\n *\n * @example\n * ```typescript\n * export const MyPlugin = definePlugin(\n * class implements Plugin {\n * static readonly name = 'my-plugin';\n * static readonly version = '1.0.0';\n *\n * bodyRequirements(): PluginBodyRequirements { return { request: 'none' }; }\n * register(hooks: PluginHooks) {\n * // 并行执行的初始化(非阻塞)\n * hooks.onRequestInit.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * await this.recordMetric();\n * });\n *\n * // 串行执行的请求修改(阻塞)\n * hooks.onBeforeRequest.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * ctx.headers['X-Custom'] = 'value';\n * return ctx;\n * });\n * }\n * }\n * );\n * ```\n */\n/** SDK 3: content demand is evaluated before reading each selected request body. */\nexport interface PluginBodyRequirementContext {\n readonly requestId: string;\n readonly method: string;\n readonly url: URL;\n readonly routeId?: string;\n readonly serviceId?: string;\n readonly upstreamId?: string;\n readonly stage: 'route' | 'selected';\n}\nexport interface PluginBodyRequirements {\n readonly request: 'none' | 'json-read' | 'json-write';\n readonly response?: readonly ('json' | 'sse-json')[];\n /** Replay retention is independent of content decoding. */\n readonly replay?: boolean;\n /** Optional bounded observation never upgrades forwarding demands. */\n readonly observe?: Readonly<{ request?: boolean; response?: boolean; sse?: boolean }>;\n}\nexport interface SSEEnvelope {\n data: string;\n json?: unknown;\n event?: string;\n id?: string;\n retry?: string;\n comments?: string[];\n /** Original complete event; remove after modifying data or metadata. */\n raw?: string;\n}\nexport interface Plugin {\n bodyRequirements(context: PluginBodyRequirementContext): PluginBodyRequirements;\n resolveAdmissionModel?: import('./data-admission/worker').WorkerAdmissionPlugin['resolveAdmissionModel'];\n prepareAdmissionAttempt?: import('./data-admission/worker').WorkerAdmissionPlugin['prepareAdmissionAttempt'];\n /**\n * 插件初始化\n * 在 register 之前调用,用于初始化配置和资源\n */\n init?(context: PluginInitContext): Promise<void>;\n\n /**\n * 注册 Hooks\n * 插件在此方法中选择需要的 hooks 并注册回调\n *\n * 流式处理现在也通过 Hook 注册:\n * - hooks.onStreamChunk: 处理流式响应的每个 chunk(支持 N:M 转换)\n * - hooks.onFlushStream: 流结束时刷新缓冲区\n */\n register(hooks: PluginHooks): void;\n\n /**\n * 重置状态(对象池使用)\n */\n reset?(): void | Promise<void>;\n\n /**\n * 插件销毁\n */\n onDestroy?(): Promise<void>;\n}\n\n/**\n * Plugin 构造器类型\n * 约束插件类必须提供静态元数据\n */\nexport type PluginConstructor = {\n new (...args: any[]): Plugin;\n\n /**\n * 插件唯一标识符(静态属性,必填)\n */\n readonly name: string;\n\n /**\n * 插件版本号(静态属性,必填)\n */\n readonly version: string;\n\n /**\n * 插件配置 Schema(静态属性,可选)\n * 如果插件需要配置,应定义此静态属性来描述配置项\n */\n readonly configSchema?: PluginConfigField[];\n\n /**\n * 插件扩展元数据(静态属性,可选)\n * 用于 UI 集成、权限声明、依赖管理等高级功能\n */\n readonly metadata?: PluginMetadata;\n\n /**\n * 插件翻译内容(静态属性,可选)\n *\n * 用于提供插件 UI 元素的多语言翻译\n * 系统会自动收集并注册到前端 i18n 系统\n */\n readonly translations?: PluginTranslations;\n\n};\n\n/**\n * 插件定义辅助函数\n * 提供编译时类型检查,确保插件满足所有静态和实例要求\n *\n * @example\n * ```typescript\n * export const MyPlugin = definePlugin(\n * class implements Plugin {\n * static readonly name = 'my-plugin';\n * static readonly version = '1.0.0';\n * static readonly metadata = {\n * name: 'My Plugin',\n * description: 'My plugin description',\n * icon: 'extension'\n * };\n *\n * constructor(options: MyOptions) { }\n *\n * bodyRequirements(): PluginBodyRequirements { return { request: 'none' }; }\n * register(hooks: PluginHooks) {\n * hooks.onBeforeRequest.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * // Plugin logic here\n * return ctx;\n * });\n * }\n * }\n * );\n *\n * export default MyPlugin;\n * ```\n */\nexport function definePlugin<T extends Plugin>(\n plugin: PluginConstructor & { new(...args: any[]): T }\n): typeof plugin {\n return plugin;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的名称\n * 从插件类的静态属性读取\n */\nexport function getPluginName(plugin: Plugin): string {\n return (plugin.constructor as PluginConstructor).name;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的版本\n * 从插件类的静态属性读取\n */\nexport function getPluginVersion(plugin: Plugin): string {\n return (plugin.constructor as PluginConstructor).version;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的描述\n * 从插件类的 metadata.description 静态属性读取\n */\nexport function getPluginDescription(plugin: Plugin): string | undefined {\n return (plugin.constructor as PluginConstructor).metadata?.description;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的元数据\n * 从插件类的静态属性读取\n */\nexport function getPluginMetadata(plugin: Plugin): PluginMetadata | undefined {\n return (plugin.constructor as PluginConstructor).metadata;\n}\n",
7
+ "import type { PluginConfigConstraint, PluginRuntimeScope } from '@jeffusion/bungee-types';\nexport type { PluginConfigConstraint, PluginAllowedTuplesConstraint, PluginRuntimeScope } from '@jeffusion/bungee-types';\n/**\n * Plugin 系统类型定义\n */\n\n/**\n * 插件配置值类型\n * 定义了插件配置中允许的值类型,比 `any` 更具体\n */\nexport type PluginConfigValue =\n | string\n | number\n | boolean\n | null\n | PluginConfigValue[]\n | { [key: string]: PluginConfigValue };\n\nexport interface CredentialOutboundHeaderProfile {\n readonly passthrough: readonly string[];\n readonly set: Readonly<Record<string, string>>;\n}\n\nexport interface CredentialRequestPolicy {\n readonly pathname: string;\n readonly methods: readonly string[];\n readonly outboundHeaders?: CredentialOutboundHeaderProfile;\n}\n\n// ============ Manifest 类型定义 ============\n\n/**\n * 插件 manifest.json 规范\n *\n * manifest.json 是插件的声明性配置文件,作为插件元数据的唯一真相来源。\n * 框架通过读取此文件来发现插件能力,无需执行插件代码。\n *\n * @example\n * ```json\n * {\n * \"name\": \"token-stats\",\n * \"version\": \"1.0.0\",\n * \"description\": \"Track AI API token usage\",\n * \"main\": \"server/index.ts\",\n * \"ui\": {\n * \"components\": [\n * { \"name\": \"TokenStatsChart\", \"entry\": \"ui/TokenStatsChart.svelte\" }\n * ]\n * },\n * \"contributes\": {\n * \"nativeWidgets\": [...],\n * \"api\": [...]\n * },\n * \"translations\": { \"en\": {...}, \"zh-CN\": {...} }\n * }\n * ```\n */\nexport interface PluginManifest {\n /**\n * 插件唯一标识符(必填)\n * 用于路由、存储命名空间等\n */\n name: string;\n\n /**\n * 插件版本号(必填)\n * 遵循 semver 规范\n */\n version: string;\n\n schemaVersion?: number | string;\n artifactKind?: string;\n\n /**\n * 插件描述(支持翻译键)\n */\n description?: string;\n\n /**\n * 图标(Material Icon 名称或 URL)\n */\n icon?: string;\n\n /**\n * 作者信息\n */\n author?: string | {\n name: string;\n email?: string;\n url?: string;\n };\n\n /**\n * 许可证\n */\n license?: string;\n\n /**\n * 项目主页\n */\n homepage?: string;\n\n /**\n * 代码仓库\n */\n repository?: string | {\n type: string;\n url: string;\n };\n\n /**\n * 关键词(用于搜索)\n */\n keywords?: string[];\n\n /**\n * 服务端入口配置\n */\n main?: string;\n\n capabilities?: string[];\n /** Global providers run once whenever activated; global-and-scoped also retains application bindings. Defaults to scoped. */\n runtimeScope?: PluginRuntimeScope;\n services?: import('./plugin-services').PluginServiceDeclarations;\n /** Optional control-plane runtime capability. */\n ingress?: { entry: string };\n management?: { loginComponent?: string; setupComponent?: string };\n control?: {\n entry: string;\n rpc: Array<{\n name: string;\n access: 'bound-attempt';\n }>;\n };\n /**\n * UI 扩展模式(冻结边界)\n * - none: 无 UI 扩展\n * - native-static: 原生静态组件(依赖构建期注册表,不支持运行时注入)\n * - sandbox-iframe: 独立沙箱扩展(通过 iframe 隔离,独立服务资源)\n */\n uiExtensionMode?: 'none' | 'native-static' | 'sandbox-iframe';\n\n /**\n * UI 组件配置\n */\n ui?: {\n /**\n * 组件列表\n * 用于自动注册到组件白名单\n */\n components?: Array<{\n /** 组件名称(用于 nativeWidgets.component 引用) */\n name: string;\n /** 组件入口文件路径(相对于插件根目录) */\n entry: string;\n }>;\n };\n\n /**\n * 权限声明\n * 用于安全预检(用户上传插件场景)\n */\n permissions?: Array<\n | 'network' // 网络访问\n | 'storage' // 持久化存储\n | 'filesystem' // 文件系统访问\n | string // 自定义权限\n >;\n\n /**\n * 插件依赖\n */\n dependencies?: Record<string, string>;\n\n /** Optional providers are never included in automatic activation closure. */\n optionalDependencies?: Record<string, string>;\n\n /**\n * 引擎版本要求\n */\n engines?: {\n bungee?: string;\n node?: string;\n };\n\n /**\n * 贡献点配置\n */\n contributes?: {\n /**\n * 原生仪表板组件\n */\n nativeWidgets?: Array<{\n id: string;\n title: string;\n size: 'small' | 'medium' | 'large' | 'full';\n component: string;\n presentation?: 'kpi';\n props?: Record<string, any>;\n }>;\n\n /**\n * API 端点\n */\n api?: Array<{\n path: string;\n methods: Array<'GET' | 'POST' | 'PUT' | 'DELETE'>;\n handler: string;\n execution: 'control';\n capability?: string;\n methodCapabilities?: Record<string,string>;\n }>;\n resourceExtensions?: Array<{resource:'api-key';component:string;path:'/keys/:keyId'}>;\n upstreamSources?: Array<{\n id: string;\n label: string;\n listAccounts: string;\n createDraft: string;\n credentialPolicy: {\n allowedOrigins: string[];\n allowedRequests: CredentialRequestPolicy[];\n allowedHeaderNames: string[];\n };\n }>;\n\n /**\n * iframe 仪表板组件(Legacy)\n */\n widgets?: Array<{\n title: string;\n path: string;\n size?: 'small' | 'medium' | 'large' | 'full';\n }>;\n\n /**\n * 导航菜单\n */\n navigation?: Array<{\n label: string;\n path: string;\n icon?: string;\n target?: 'sidebar' | 'header';\n component?: string;\n layout?: 'standalone';\n }>;\n\n /**\n * 设置页路径\n */\n settings?: string;\n\n /**\n * 原生静态设置组件名称(仅 builtin 插件可声明)\n */\n nativeSettingsComponent?: string;\n\n /**\n * 命令贡献\n */\n commands?: Array<{\n command: string;\n title: string;\n category?: string;\n icon?: string;\n }>;\n };\n\n /**\n * UI 展示元数据(新架构)\n * 用于存放 UI 相关的元数据,支持翻译键\n */\n metadata?: {\n /** 显示名称(支持翻译键) */\n name?: string;\n /** 描述(支持翻译键) */\n description?: string;\n /** 图标 */\n icon?: string;\n /** 贡献点配置(与顶层 contributes 合并) */\n contributes?: PluginManifest['contributes'];\n };\n\n /**\n * 配置 Schema\n * 用于动态生成配置表单\n */\n configSchema?: PluginConfigField[];\n configConstraints?: readonly PluginConfigConstraint[];\n\n /**\n * 多语言翻译\n */\n translations?: PluginTranslations;\n}\n\n/**\n * 从 manifest 加载的插件信息\n * 包含 manifest 数据和解析后的路径信息\n */\nexport interface LoadedPluginManifest extends PluginManifest {\n /** 插件根目录的绝对路径 */\n pluginDir: string;\n /** manifest.json 文件的绝对路径 */\n manifestPath: string;\n /** 服务端入口的绝对路径 */\n mainPath?: string;\n /** 控制面入口的绝对路径 */\n controlPath?: string;\n uiAssetsPath?: string;\n}\n\n// 导出 Hook 系统类型\nexport type {\n PluginHooks,\n RequestContext,\n MutableRequestContext,\n ResponseContext,\n ErrorContext,\n StreamChunkContext,\n FinallyContext,\n PluginInitContext,\n PluginLogger,\n} from './hooks';\n\nexport { createPluginHooks, clearHooks, getHooksStats, resetHooksStats } from './hooks';\nexport type { TapInfo } from './hooks';\n\n/**\n * 插件配置字段类型\n */\nexport type PluginConfigFieldType =\n | 'string' // 文本输入\n | 'number' // 数字输入\n | 'boolean' // 复选框\n | 'select' // 单选下拉\n | 'multiselect' // 多选下拉\n | 'textarea' // 多行文本\n | 'json' // JSON 编辑器\n | 'gateway_target'\n | 'model_mapping'\n | 'object' // 对象(嵌套表单)\n | 'array'; // 数组(列表编辑器)\n\n/**\n * 验证规则\n */\nexport interface ValidationRule {\n /**\n * 正则表达式模式\n */\n pattern?: string;\n\n /**\n * 最小值/最小长度\n */\n min?: number;\n\n /**\n * 最大值/最大长度\n */\n max?: number;\n\n /**\n * 自定义错误消息\n */\n message?: string;\n}\n\n/**\n * 字段转换规则(可序列化)\n * 用于定义虚拟字段与实际字段之间的转换关系\n */\nexport interface FieldTransform {\n /**\n * 转换类型\n */\n type: 'split' | 'concat' | 'compute';\n\n /**\n * split 类型专用:分隔符\n * @example '-' 将 \"a-b\" 拆分为 [\"a\", \"b\"]\n */\n separator?: string;\n\n /**\n * split/concat 类型专用:目标字段列表\n * @example ['from', 'to']\n */\n fields?: string[];\n}\n\nexport type PluginShowIfCondition =\n | {\n field: string;\n value: PluginConfigValue;\n }\n | {\n all: PluginShowIfCondition[];\n }\n | {\n any: PluginShowIfCondition[];\n };\n\n/**\n * 插件翻译内容\n *\n * 用于为插件的 UI 元素提供多语言支持\n *\n * 格式说明:\n * - 第一层 key 为语言代码(如 'en', 'zh-CN')\n * - 第二层 key 为翻译键(使用点号分隔的扁平结构)\n * - 系统会自动为所有翻译键添加 `plugins.{pluginName}` 前缀\n *\n * @example\n * ```typescript\n * static readonly translations: PluginTranslations = {\n * 'en': {\n * 'field.label': 'Field Label',\n * 'field.description': 'Field description text',\n * 'options.value1.label': 'Option 1'\n * },\n * 'zh-CN': {\n * 'field.label': '字段标签',\n * 'field.description': '字段描述文本',\n * 'options.value1.label': '选项 1'\n * }\n * };\n * ```\n */\nexport type PluginTranslations = Record<string, Record<string, string>>;\n\n/**\n * 插件配置字段定义\n * 用于动态生成配置表单\n */\nexport interface PluginConfigField {\n /**\n * 字段名(配置对象的 key)\n */\n name: string;\n\n /**\n * 字段类型\n */\n type: PluginConfigFieldType;\n\n /**\n * 显示标签(支持 i18n key 或直接字符串)\n */\n label: string;\n\n /**\n * 是否必填\n */\n required?: boolean;\n\n /**\n * 默认值\n */\n default?: PluginConfigValue;\n\n /**\n * select/multiselect 的选项列表\n */\n options?: Array<{\n label: string;\n value: string;\n description?: string;\n }>;\n\n /**\n * 描述/帮助文本\n */\n description?: string;\n\n /**\n * 占位符文本\n */\n placeholder?: string;\n\n catalogPlugin?: string;\n sourceCatalogProviderField?: string;\n targetCatalogProviderField?: string;\n\n /**\n * 验证规则\n */\n validation?: ValidationRule;\n\n /**\n * 条件显示(依赖其他字段的值)\n */\n showIf?: PluginShowIfCondition;\n\n /**\n * 子字段定义(type=object 时使用)\n */\n properties?: PluginConfigField[];\n\n /**\n * 数组元素类型(type=array 时使用)\n */\n items?: PluginConfigField;\n\n /**\n * 字段转换规则(可序列化)\n * 定义虚拟字段与实际字段之间的映射关系\n *\n * 当设置此属性时:\n * - 该字段为\"虚拟字段\",仅用于 UI 交互\n * - UI 输入值会根据转换规则展开为多个实际字段\n * - 实际字段的值会根据转换规则合并显示在 UI 中\n * - 虚拟字段本身不会保存到配置中\n *\n * @example\n * // 将 \"anthropic-openai\" 拆分为 { from: \"anthropic\", to: \"openai\" }\n * fieldTransform: {\n * type: 'split',\n * separator: '-',\n * fields: ['from', 'to']\n * }\n */\n fieldTransform?: FieldTransform;\n}\n\n/**\n * 类型守卫:检查插件类是否有 configSchema\n */\nexport function hasConfigSchema(\n PluginClass: any\n): PluginClass is { configSchema: PluginConfigField[] } {\n return 'configSchema' in PluginClass && Array.isArray(PluginClass.configSchema);\n}\n\n/**\n * Plugin 存储接口\n * 提供基于 Key-Value 的持久化存储能力\n */\n/** Trusted observation plugins may execute SQL only against access.db, never config.db.\n * Callers must perform database work within the callback; hosts revoke subsequent operations.\n */\nexport interface PluginObservationStorage {\n withDatabase<T>(operation: (database: import('bun:sqlite').Database) => T): T;\n /** Returns a bounded remaining-time reader for a same-host kernel deadline in milliseconds. */\n writeBudgetMs?(deadlineAt: number): () => number;\n}\n\n/** Result of a strict, side-effect-free namespaced KV read. */\nexport type PluginStorageReadResult<T> =\n | { readonly found: false }\n | { readonly found: true; readonly value: T };\n\nexport interface PluginStorage {\n readonly observation?: PluginObservationStorage;\n /** Invoke a registered observation adapter method in this plugin namespace. */\n invokeObservation?<T>(operation: string, args: readonly unknown[]): Promise<T>;\n /** Immediate namespaced KV access for cross-process shared values. */\n uncached?(): PluginStorage;\n /** Flush pending KV writes during host disposal. */\n flush?(): Promise<void>;\n\n /** Legacy embedder extension; the core does not construct or grant it by name. */\n readonly metering?: TokenStatsMeteringStorage;\n /**\n * 获取值\n * @param key 键\n * @returns 值,如果不存在则返回 null\n */\n get<T = any>(key: string): Promise<T | null>;\n\n /**\n * 严格只读获取值:直接读取当前命名空间的已提交数据。\n * 不访问/回填/刷新 LRU 缓存,也不清除过期记录;SQL/JSON 错误直接抛出。\n * 有效 JSON null 视为 found:true,缺失或已过期视为 found:false。\n * 可选仅为既有 embedder / 测试 fixture 的源码兼容;Bungee 实际存储实现必须提供。\n */\n readStrict?<T = unknown>(key: string): Promise<PluginStorageReadResult<T>>;\n\n /**\n * 设置值\n * @param key 键\n * @param value 值(必须可序列化)\n * @param ttlSeconds 过期时间(秒),可选\n */\n set(key: string, value: any, ttlSeconds?: number): Promise<void>;\n\n /**\n * 删除值\n * @param key 键\n */\n delete(key: string): Promise<void>;\n\n /**\n * 获取所有键(支持前缀过滤)\n * @param prefix 前缀,可选\n */\n keys(prefix?: string): Promise<string[]>;\n\n /**\n * 清空存储(仅限当前插件的命名空间)\n */\n clear(): Promise<void>;\n\n /**\n * 原子递增操作\n * 原子地递增指定对象字段的值,避免并发竞争\n * @param key 键\n * @param field 字段名\n * @param delta 递增量(默认1,可为负数)\n * @returns 递增后的新值\n */\n increment(key: string, field: string, delta?: number): Promise<number>;\n\n /**\n * 比较并交换操作\n * 仅当当前值等于期望值时,才更新为新值(原子操作)\n * @param key 键\n * @param field 字段名\n * @param expected 期望的当前值\n * @param newValue 新值\n * @returns 是否更新成功\n */\n compareAndSet(key: string, field: string, expected: any, newValue: any): Promise<boolean>;\n}\n\nexport type TokenStatsMetricName =\n | 'inputTokens' | 'outputTokens' | 'officialInputTokens' | 'officialOutputTokens'\n | 'estimatedInputTokens' | 'estimatedOutputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'\n | 'partialOutputs' | 'logicalRequests' | 'upstreamAttempts' | 'observationIncompleteAttempts'\n | 'inputAuthorityOfficial' | 'inputAuthorityLocal' | 'inputAuthorityHeuristic' | 'inputAuthorityPartial' | 'inputAuthorityNone'\n | 'outputAuthorityOfficial' | 'outputAuthorityLocal' | 'outputAuthorityHeuristic' | 'outputAuthorityPartial' | 'outputAuthorityNone';\n\nexport type TokenStatsMetrics = Partial<Record<TokenStatsMetricName, number>>;\n\nexport type TokenStatsGroupBy = 'model' | 'time';\nexport type TokenStatsRange = '1h' | '12h' | '24h' | '1d' | '7d' | '30d' | 'day' | 'week' | 'month';\n\nexport type TokenStatsValueSource = 'usage' | 'estimated' | 'partial' | 'unknown';\n\n/** One ended upstream attempt; provider is the wire protocol family, not a vendor name. */\nexport interface TokenStatsAttempt {\n readonly key_id?: string | null;\n readonly attempt_id: string;\n readonly request_id: string;\n readonly finished_at_ms: number;\n readonly route_id: string;\n readonly upstream_id: string;\n readonly provider: string;\n readonly outcome: string;\n readonly model: string;\n readonly input_tokens: number | null;\n readonly output_tokens: number | null;\n readonly input_source: TokenStatsValueSource;\n readonly output_source: TokenStatsValueSource;\n readonly cache_read_tokens: number | null;\n readonly cache_write_tokens: number | null;\n readonly cost_usd: number | null;\n readonly observation_incomplete: boolean;\n}\n\nexport type TokenStatsSnapshotMetrics = Record<TokenStatsMetricName, number> & {\n readonly estimatedCostUsd: number | null;\n};\n\nexport interface TokenStatsMeteringStorage {\n listClientModels?(input: {page?:number;pageSize?:number;keyword?:string}): Promise<{models:string[];total:number;page:number;pageSize:number}>;\n recordAttempt(row: TokenStatsAttempt): Promise<void>;\n queryWindowSnapshot(input: {\n asOfMs: number;\n range: TokenStatsRange;\n groupBy: TokenStatsGroupBy;\n timeZone?: string;\n keyId?: string;\n }): Promise<{\n all: TokenStatsSnapshotMetrics;\n data: Array<{ dimension: string; bucketStartMs?: number; metrics: TokenStatsSnapshotMetrics }>;\n bucketMs?: number;\n bucketStarts?: number[];\n /** Exclusive end of the last displayed bucket; calendar axes include future periods. */\n bucketEndMs?: number;\n present: boolean;\n }>;\n}\n\n/**\n * Plugin 元数据接口\n * 用于 UI 展示和系统集成\n */\nexport interface PluginMetadata {\n /**\n * 显示名称(支持翻译键或直接字符串)\n * 默认使用插件的 name,此字段用于提供更友好的 UI 显示名\n *\n * 支持翻译键格式:包含 `.` 且不包含空格\n * @example 'metadata.displayName' // 翻译键,会自动翻译\n * @example 'My Plugin' // 直接字符串,不翻译\n */\n name?: string;\n\n /**\n * 插件描述(支持翻译键或直接字符串)\n * 用于 UI 展示插件的详细说明\n *\n * 支持翻译键格式:包含 `.` 且不包含空格\n * @example 'metadata.description' // 翻译键,会自动翻译\n * @example 'A demo plugin for testing' // 直接字符串,不翻译\n */\n description?: string;\n\n /**\n * 图标(Material Icon 名称或 URL)\n */\n icon?: string;\n\n /**\n * 作者信息\n */\n author?: {\n name: string;\n email?: string;\n url?: string;\n } | string;\n\n /**\n * 许可证\n */\n license?: string;\n\n /**\n * 项目主页\n */\n homepage?: string;\n\n /**\n * 代码仓库\n */\n repository?: {\n type: string;\n url: string;\n } | string;\n\n /**\n * 关键词(用于搜索)\n */\n keywords?: string[];\n\n /**\n * 分类\n */\n categories?: string[];\n\n /**\n * 插件激活事件\n * 声明插件何时被激活\n */\n activationEvents?: string[];\n\n /**\n * 插件能力声明\n * 声明插件使用的系统能力\n */\n /**\n * 插件权限声明\n * 声明插件需要的系统权限(如 network, storage, api:routes 等)\n */\n permissions?: string[];\n\n capabilities?: {\n /**\n * 是否需要网络访问\n */\n network?: boolean;\n\n /**\n * 是否需要文件系统访问\n */\n filesystem?: boolean;\n\n /**\n * 是否需要数据库访问\n */\n database?: boolean;\n\n /**\n * 自定义能力声明\n */\n custom?: string[];\n };\n\n /**\n * 依赖的其他插件\n */\n dependencies?: Record<string, string>;\n\n /**\n * 可选依赖\n */\n optionalDependencies?: Record<string, string>;\n\n /**\n * 引擎版本要求\n */\n engines?: {\n bungee?: string;\n node?: string;\n };\n\n /**\n * 贡献点配置\n * 统一声明插件提供的 UI 和功能能力\n */\n contributes?: {\n /**\n * 导航集成\n */\n navigation?: Array<{\n label: string;\n path: string;\n icon?: string;\n target?: 'sidebar' | 'header'; // 默认 sidebar\n /** Optional statically registered native page component. */\n component?: string;\n layout?: 'standalone';\n }>;\n\n /**\n * 仪表板集成\n */\n widgets?: Array<{\n title: string;\n path: string;\n size?: 'small' | 'medium' | 'large' | 'full'; // small=1x1, medium=2x1, large=2x2, full=4x2\n }>;\n\n /**\n * 设置页路径\n */\n settings?: string;\n\n /**\n * 命令贡献\n * 声明插件提供的命令\n */\n commands?: Array<{\n command: string;\n title: string;\n category?: string;\n icon?: string;\n }>;\n\n /**\n * 配置贡献\n * 声明插件的配置项\n */\n configuration?: {\n title?: string;\n properties: Record<string, {\n type: 'string' | 'number' | 'boolean' | 'array' | 'object';\n default?: any;\n description?: string;\n enum?: any[];\n items?: any;\n properties?: any;\n }>;\n };\n\n /**\n * 原生仪表板组件(非 iframe)\n *\n * 与 widgets 不同,nativeWidgets 直接渲染为 Svelte 组件,\n * 可以复用主应用的图表库和样式系统。\n *\n * 安全说明:组件必须是内置的,插件只能通过 component 名称引用白名单中的组件\n *\n * @example\n * ```typescript\n * nativeWidgets: [{\n * id: 'token-stats-chart',\n * title: 'Token 统计',\n * size: 'medium',\n * component: 'TokenStatsChart',\n * props: { days: 7 }\n * }]\n * ```\n */\n nativeWidgets?: Array<{\n /** 唯一标识符 */\n id: string;\n /** 显示标题(支持 i18n key) */\n title: string;\n /** 尺寸:small=1x1, medium=2x1, large=2x2, full=4x2 */\n size: 'small' | 'medium' | 'large' | 'full';\n /** 组件名称(映射到内置组件白名单) */\n component: string;\n presentation?: 'kpi';\n /** 传递给组件的 props */\n props?: Record<string, any>;\n }>;\n\n /**\n * API 端点贡献\n *\n * 允许插件注册自己的 API 端点,端点路径强制在 /api/plugins/:pluginName/ 命名空间下。\n * 只有 global scope 的插件实例才能处理 API 请求。\n *\n * @example\n * ```typescript\n * api: [{\n * path: '/stats', // 实际路径: /api/plugins/my-plugin/stats\n * methods: ['GET'],\n * handler: 'getStats', // 调用控制面处理器的 getStats 方法\n * execution: 'control'\n * }]\n * ```\n */\n api?: Array<{\n /** 相对路径(相对于 /api/plugins/:pluginName) */\n path: string;\n /** 支持的 HTTP 方法 */\n methods: Array<'GET' | 'POST' | 'PUT' | 'DELETE'>;\n /** 处理器方法名(Plugin 类的方法) */\n handler: string;\n execution: 'control';\n capability?: string;\n methodCapabilities?: Record<string,string>;\n }>;\n };\n\n /**\n * @deprecated 使用 contributes.widgets 和 contributes.settings 代替\n */\n ui?: {\n dashboard?: Array<{\n id: string;\n title: string;\n path: string;\n size?: { w: number; h: number };\n }>;\n settings?: string;\n };\n}\n\n\n// ============ Plugin 接口 ============\n\nimport type { PluginHooks, PluginInitContext } from './hooks';\n\n/**\n * Plugin 接口(基于 Hook Registry 模式)\n *\n * 所有插件必须实现此接口。插件不再直接定义钩子方法,而是通过 register(hooks) 方法注册回调。\n *\n * @example\n * ```typescript\n * export const MyPlugin = definePlugin(\n * class implements Plugin {\n * static readonly name = 'my-plugin';\n * static readonly version = '1.0.0';\n *\n * bodyRequirements(): PluginBodyRequirements { return { request: 'none' }; }\n * register(hooks: PluginHooks) {\n * // 并行执行的初始化(非阻塞)\n * hooks.onRequestInit.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * await this.recordMetric();\n * });\n *\n * // 串行执行的请求修改(阻塞)\n * hooks.onBeforeRequest.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * ctx.headers['X-Custom'] = 'value';\n * return ctx;\n * });\n * }\n * }\n * );\n * ```\n */\n/** SDK 3: content demand is evaluated before reading each selected request body. */\nexport interface PluginBodyRequirementContext {\n readonly requestId: string;\n readonly method: string;\n readonly url: URL;\n readonly routeId?: string;\n readonly serviceId?: string;\n readonly upstreamId?: string;\n readonly stage: 'route' | 'selected';\n}\nexport interface PluginBodyRequirements {\n readonly request: 'none' | 'json-read' | 'json-write';\n readonly response?: readonly ('json' | 'sse-json')[];\n /** Replay retention is independent of content decoding. */\n readonly replay?: boolean;\n /** Optional bounded observation never upgrades forwarding demands. */\n readonly observe?: Readonly<{ request?: boolean; response?: boolean; sse?: boolean }>;\n}\nexport interface SSEEnvelope {\n data: string;\n json?: unknown;\n event?: string;\n id?: string;\n retry?: string;\n comments?: string[];\n /** Original complete event; remove after modifying data or metadata. */\n raw?: string;\n}\nexport interface Plugin {\n bodyRequirements(context: PluginBodyRequirementContext): PluginBodyRequirements;\n resolveAdmissionModel?: import('./data-admission/worker').WorkerAdmissionPlugin['resolveAdmissionModel'];\n prepareAdmissionAttempt?: import('./data-admission/worker').WorkerAdmissionPlugin['prepareAdmissionAttempt'];\n /**\n * 插件初始化\n * 在 register 之前调用,用于初始化配置和资源\n */\n init?(context: PluginInitContext): Promise<void>;\n\n /**\n * 注册 Hooks\n * 插件在此方法中选择需要的 hooks 并注册回调\n *\n * 流式处理现在也通过 Hook 注册:\n * - hooks.onStreamChunk: 处理流式响应的每个 chunk(支持 N:M 转换)\n * - hooks.onFlushStream: 流结束时刷新缓冲区\n */\n register(hooks: PluginHooks): void;\n\n /**\n * 重置状态(对象池使用)\n */\n reset?(): void | Promise<void>;\n\n /**\n * 插件销毁\n */\n onDestroy?(): Promise<void>;\n}\n\n/**\n * Plugin 构造器类型\n * 约束插件类必须提供静态元数据\n */\nexport type PluginConstructor = {\n new (...args: any[]): Plugin;\n\n /**\n * 插件唯一标识符(静态属性,必填)\n */\n readonly name: string;\n\n /**\n * 插件版本号(静态属性,必填)\n */\n readonly version: string;\n\n /**\n * 插件配置 Schema(静态属性,可选)\n * 如果插件需要配置,应定义此静态属性来描述配置项\n */\n readonly configSchema?: PluginConfigField[];\n\n /**\n * 插件扩展元数据(静态属性,可选)\n * 用于 UI 集成、权限声明、依赖管理等高级功能\n */\n readonly metadata?: PluginMetadata;\n\n /**\n * 插件翻译内容(静态属性,可选)\n *\n * 用于提供插件 UI 元素的多语言翻译\n * 系统会自动收集并注册到前端 i18n 系统\n */\n readonly translations?: PluginTranslations;\n\n};\n\n/**\n * 插件定义辅助函数\n * 提供编译时类型检查,确保插件满足所有静态和实例要求\n *\n * @example\n * ```typescript\n * export const MyPlugin = definePlugin(\n * class implements Plugin {\n * static readonly name = 'my-plugin';\n * static readonly version = '1.0.0';\n * static readonly metadata = {\n * name: 'My Plugin',\n * description: 'My plugin description',\n * icon: 'extension'\n * };\n *\n * constructor(options: MyOptions) { }\n *\n * bodyRequirements(): PluginBodyRequirements { return { request: 'none' }; }\n * register(hooks: PluginHooks) {\n * hooks.onBeforeRequest.tapPromise({ name: 'my-plugin' }, async (ctx) => {\n * // Plugin logic here\n * return ctx;\n * });\n * }\n * }\n * );\n *\n * export default MyPlugin;\n * ```\n */\nexport function definePlugin<T extends Plugin>(\n plugin: PluginConstructor & { new(...args: any[]): T }\n): typeof plugin {\n return plugin;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的名称\n * 从插件类的静态属性读取\n */\nexport function getPluginName(plugin: Plugin): string {\n return (plugin.constructor as PluginConstructor).name;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的版本\n * 从插件类的静态属性读取\n */\nexport function getPluginVersion(plugin: Plugin): string {\n return (plugin.constructor as PluginConstructor).version;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的描述\n * 从插件类的 metadata.description 静态属性读取\n */\nexport function getPluginDescription(plugin: Plugin): string | undefined {\n return (plugin.constructor as PluginConstructor).metadata?.description;\n}\n\n/**\n * 运行时辅助函数:获取插件实例的元数据\n * 从插件类的静态属性读取\n */\nexport function getPluginMetadata(plugin: Plugin): PluginMetadata | undefined {\n return (plugin.constructor as PluginConstructor).metadata;\n}\n",
8
8
  "import type { PluginDurableState, DurableJson } from './plugin-durable-state';\n\n/** Anonymous is an explicit, signed data identity; it carries no key authority. */\nexport type DataPrincipal = { readonly domain: string; readonly keyId: string; readonly credentialVersion: number };\nexport const ANONYMOUS_PRINCIPAL: DataPrincipal = Object.freeze({domain: 'anonymous', keyId: '', credentialVersion: 0});\nexport interface AdmissionRequirement { readonly plugin: string; readonly routeIds: readonly string[] }\n/** Public contracts. Business rules belong to the implementing plugin. */\nexport interface ManagementSubject {\n readonly id: string;\n readonly provider: string;\n readonly capabilities: readonly string[];\n readonly requiresPasswordChange?: boolean;\n}\nexport interface ManagementProvider {\n setupStatus(): Promise<'uninitialized' | 'ready'>;\n initialize(request: Request): Promise<Response>;\n authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): Promise<boolean>;\n login(request: Request): Promise<Response>;\n /** Public login interactions are dispatched only to the selected provider. */\n loginOptions?(request: Request): Promise<Response>;\n beginLogin?(request: Request): Promise<Response>;\n completeLogin?(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): Promise<boolean>;\n revokeSessions(): Promise<void>;\n validateWrite?(request: Request): void;\n csrfToken?(request: Request): string | undefined;\n /** Optional browser cookie renewal after successful session verification. Must not extend the server-side absolute deadline. */\n sessionCookie?(request: Request): Promise<string | undefined>;\n}\nexport interface AdmissionTarget {\n /** Host-pinned entry scope for one internal handoff. */\n readonly entryRouteId?: string;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n readonly routeId: string;\n readonly serviceId: string | null;\n readonly upstreamId: string;\n readonly url: string;\n readonly model: string | null;\n readonly now: number;\n}\nexport interface AdmissionDenial {\n readonly error: string;\n readonly status: 401 | 403 | 429 | 503 | 422;\n readonly retryAfter?: number;\n}\nexport interface AdmissionPlan {\n /** A complete JSON state replacement, staged by Host before the common decision. */\n readonly state?: DurableJson;\n /** Immutable policy snapshot retained by the grant for subsequent attempts. */\n readonly snapshot?: DurableJson;\n readonly denial?: AdmissionDenial;\n}\nexport interface IngressPlugin {\n /** Effective policy demand; no policy means no content decoding. */\n bodyRequirements(target: AdmissionTarget, policy: DurableJson): { readonly request: 'none' | 'json-read' };\n /** Optional per-principal state. Policies are frozen; plans receive only this key's clones.\n * Expiry must mean absence is behaviorally equivalent to retaining the state. */\n keyedState?: {\n readonly capacity: number;\n policyForKey(policy: DurableJson, keyId: string): DurableJson;\n expiresAt(state: DurableJson): number;\n reconcile(state: DurableJson, policy: DurableJson, now: number,\n transition?: { readonly previousActivation: number; readonly deferUntilActivation: boolean }): DurableJson;\n };\n authenticate?(request: Request, policy: DurableJson, now: number): DataPrincipal | null;\n resolveIdentity?(target: AdmissionTarget, policy: DurableJson): DataPrincipal;\n /** Pure access decision before preparation/cache reuse; never plans or debits state. */\n authorize?(target: AdmissionTarget, policy: DurableJson): AdmissionDenial | null;\n plan(target: AdmissionTarget, policy: DurableJson, state: DurableJson, policyActivatedAt?: number): AdmissionPlan;\n beforeAttempt?(target: AdmissionTarget, snapshot: DurableJson): AdmissionDenial | null;\n}\nexport interface IngressPluginModule { createIngress(): IngressPlugin }\nexport interface PluginStateRpcContext {\n readonly state: PluginDurableState;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n}\nexport interface PluginPolicyPublication {\n readonly version: number;\n readonly value: DurableJson;\n}\n",
9
9
  "import type { Database } from 'bun:sqlite';\n\n/** Plugin state initialization owns this DDL; constructors never modify schema. */\nexport const PLUGIN_DURABLE_STATE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS plugin_durable_records (\n namespace TEXT NOT NULL, key TEXT NOT NULL, version INTEGER NOT NULL CHECK(version > 0),\n value_json TEXT NOT NULL, PRIMARY KEY(namespace, key)\n) STRICT;\n`;\nexport type DurableJson = null | boolean | number | string | DurableJson[] | { [key: string]: DurableJson };\nexport interface DurableRecord { readonly key: string; readonly version: number; readonly value: DurableJson }\nexport interface DurableMutation { key: string; expectedVersion: number; value: DurableJson }\n/** Pure data outbox request; callbacks and command identifiers are never accepted. */\nexport interface DurableTransactionOptions {\n readonly outbox: { readonly topic: string; readonly major: number;\n readonly maxEvents: number; readonly payload: Uint8Array };\n}\nexport interface PluginDurableState {\n get(key: string): Promise<DurableRecord | null>;\n list(): Promise<readonly DurableRecord[]>;\n transact(mutations: readonly DurableMutation[], options?: DurableTransactionOptions): Promise<readonly DurableRecord[]>;\n}\n/** Synchronous leaf, usable only by storage workers and offline tooling. */\nexport interface StorageDurableState {\n get(key: string): DurableRecord | null;\n list(): readonly DurableRecord[];\n transact(mutations: readonly DurableMutation[], extend?: () => void): readonly DurableRecord[];\n}\nexport class DurableStateConflictError extends Error {\n readonly code = 'durable_state_conflict';\n constructor() { super('Durable state version conflict'); this.name = 'DurableStateConflictError'; }\n}\n/** Plugins load as independent bundles, so the host's error has a different constructor. */\nexport function isDurableStateConflictError(error: unknown): error is DurableStateConflictError {\n return error instanceof Error && 'code' in error && error.code === 'durable_state_conflict';\n}\nconst MAX_BYTES = 1024 * 1024;\nfunction identifier(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(value)) throw new Error('Invalid durable state identifier');\n}\n/** Reject objects with behavior, lossy JSON values and cycles before JSON.stringify. */\nfunction encode(value: unknown): string {\n const ancestors = new Set<object>();\n function check(current: unknown, depth: number): void {\n if (depth > 64) throw new Error('Durable state nesting limit exceeded');\n if (current === null || typeof current === 'string' || typeof current === 'boolean') return;\n if (typeof current === 'number' && Number.isFinite(current)) return;\n if (typeof current !== 'object' || current === null || ancestors.has(current)) throw new Error('Durable state must be pure JSON');\n const array = Array.isArray(current);\n if (!array && Object.getPrototypeOf(current) !== Object.prototype && Object.getPrototypeOf(current) !== null) throw new Error('Durable state must be pure JSON');\n ancestors.add(current);\n const descriptors = Object.getOwnPropertyDescriptors(current);\n if (Reflect.ownKeys(current).some(key => typeof key === 'symbol')) throw new Error('Durable state must be pure JSON');\n if (array) {\n const length = (current as unknown[]).length;\n const indices = Object.keys(descriptors).filter(key => key !== 'length');\n if (indices.length !== length || indices.some((key, index) => key !== String(index))) throw new Error('Durable state must be pure JSON');\n }\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (array && key === 'length') continue;\n if (!descriptor.enumerable || !('value' in descriptor)) throw new Error('Durable state must be pure JSON');\n check(descriptor.value, depth + 1);\n }\n ancestors.delete(current);\n }\n check(value, 0);\n const json = JSON.stringify(value);\n if (Buffer.byteLength(json) > MAX_BYTES) throw new Error('Durable state size limit exceeded');\n return json;\n}\n/** Validate data before IPC structured cloning can erase prototypes or evaluate getters. */\nexport function validateDurableJson(value: unknown): void { encode(value); }\ntype Row = { key: string; version: number; value_json: string };\nfunction record(row: Row): DurableRecord {\n return Object.freeze({ key: row.key, version: row.version, value: JSON.parse(row.value_json) as DurableJson });\n}\n\n/** Host-only factory. Inject only the returned namespace capability into trusted plugins.\n * Consumers validate their own record schema. expectedVersion=0 requires absence.\n * Null values are retained records, so versions never reset.\n */\nexport class PluginDurableStateStore {\n constructor(private readonly db: Database) {}\n /**\n * Host-only: the shared database this store's records live in, so a host-owned\n * durable journal can run its own atomic planner/reader against exactly the\n * same `plugin_durable_records` rows the plugin sees. Never exposed through\n * `PluginServices` and never handed to a plugin.\n */\n get database(): Database { return this.db; }\n /** Async SDK shape for offline tools and leaf fixtures; production uses PluginStateClient. */\n forNamespace(namespace: string): PluginDurableState {\n const leaf = this.forStorageNamespace(namespace);\n return Object.freeze({get: async (key: string) => leaf.get(key), list: async () => leaf.list(),\n transact: async (mutations: readonly DurableMutation[], options?: DurableTransactionOptions) => {\n if (options !== undefined) throw new Error('Outbox requires the storage worker');\n return leaf.transact(mutations);\n }});\n }\n forStorageNamespace(namespace: string): StorageDurableState {\n identifier(namespace);\n const db = this.db;\n const get = (key: string): DurableRecord | null => {\n identifier(key);\n const row = db.query<Row, [string, string]>('SELECT key,version,value_json FROM plugin_durable_records WHERE namespace = ? AND key = ?').get(namespace, key);\n return row ? record(row) : null;\n };\n return Object.freeze({\n get,\n list: () => Object.freeze(db.query<Row, [string]>('SELECT key,version,value_json FROM plugin_durable_records WHERE namespace = ? ORDER BY key').all(namespace).map(record)),\n transact: (input: readonly DurableMutation[], extend?: () => void): readonly DurableRecord[] => {\n if (!Array.isArray(input) || input.length === 0 || input.length > 256) throw new Error('Invalid durable state command');\n const keys = new Set<string>();\n const mutations = input.map(mutation => {\n identifier(mutation.key);\n if (keys.has(mutation.key) || !Number.isSafeInteger(mutation.expectedVersion) || mutation.expectedVersion < 0 || mutation.expectedVersion >= Number.MAX_SAFE_INTEGER) throw new Error('Invalid durable state mutation');\n keys.add(mutation.key);\n return { key: mutation.key, expectedVersion: mutation.expectedVersion, json: encode(mutation.value) };\n });\n const commandJson = JSON.stringify(mutations);\n if (Buffer.byteLength(commandJson) > MAX_BYTES) throw new Error('Durable state command size limit exceeded');\n return db.transaction(() => {\n const results: DurableRecord[] = [];\n for (const mutation of mutations) {\n const current = get(mutation.key);\n if ((current?.version ?? 0) !== mutation.expectedVersion) throw new DurableStateConflictError();\n const version = mutation.expectedVersion + 1;\n db.query(`INSERT INTO plugin_durable_records(namespace,key,version,value_json) VALUES (?,?,?,?)\n ON CONFLICT(namespace,key) DO UPDATE SET version=excluded.version,value_json=excluded.value_json`).run(namespace, mutation.key, version, mutation.json);\n results.push(record({ key: mutation.key, version, value_json: mutation.json }));\n }\n extend?.();\n return Object.freeze(results);\n }).immediate();\n },\n });\n }\n}\n",
10
10
  "import { logger } from '../logger';\nimport type { AtomicReadSetResolver } from '../plugin-state/client';\n/**\n * Same-process host RPC adapter (P4): lets the canonical `PluginServiceHost`\n * lifecycle own RPC publications/consumption without a second plugin framework\n * and without faking a wire transport.\n *\n * The parent injects the trusted owner token, endpoint identity, required\n * placement/callee/journal callbacks, and the real host lease callback. Real\n * cross-process transport is NOT implemented: the required placement resolver\n * returns an exact endpoint registered in the exposed runtime, `ambiguous`, or\n * `null` meaning \"use the explicit local channel\". Commands run only through the\n * accepted runtime kernel. Journal-backed policies require `CommandJournal`;\n * application-owned `none` commands may execute without a journal and expose no\n * journal result/reconciliation capability. Caller identity, purpose, scope,\n * leases, and deadlines are host decisions; plugin call options may only carry\n * `signal`/`timeoutMs`/`operationId`, snapshotted without invoking accessors.\n *\n * Command binding errors are mapped once by the kernel to its fixed-code\n * `RpcInvocationError` (own `code`, no cause/message/raw operation id); the\n * client rebuilds a fresh public `RpcServiceError` from that code and the\n * validated operation id of the current call. No error instance is reused.\n */\nimport { assertSupportedServiceDeclarations, isCrossProcessSelfService } from './contracts';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { isProxy } from 'node:util/types';\nimport type {\n PluginServiceConsumption,\n PluginServiceDeclarations,\n PluginServiceProcess,\n PluginServicePublication,\n PluginServiceScope,\n} from './contracts';\nimport {\n RpcServiceRuntime,\n type RpcAdmissionGrant,\n type RpcAdmissionRequest,\n type RpcCaller,\n type RpcCommandAction,\n type RpcCommandExecution,\n type RpcCommandExecutor,\n type RpcDrainResult,\n type RpcEndpointBinding,\n type RpcEndpointHandle,\n type RpcHandlerContext,\n type RpcHandlerMap,\n type RpcInvocationErrorCode,\n type RpcInvokeRequest,\n type RpcRuntimeLimits,\n type RpcRuntimeStatus,\n} from './rpc-runtime';\nimport {\n type CommandAtomicPlanner,\n type CommandExternalExecutor,\n type CommandJournal,\n} from './command-journal';\nimport type { AsyncCommandJournal } from '../plugin-state/client';\nimport {\n defineRpcService,\n assertRpcData,\n encodeRpcJson,\n decodeRpcJson,\n RPC_JSON_MAX_BYTES,\n type RpcCallPurpose,\n type InferRpcData,\n type RpcCommandPolicy,\n type RpcJson,\n type RpcMethodDefinition,\n} from './wire-contract';\n\n/* -------------------------------------------------------------------------- */\n/* Fixed-code public errors */\n/* -------------------------------------------------------------------------- */\n\nexport type RpcServiceErrorCode =\n | RpcInvocationErrorCode\n | 'undeclared'\n | 'unavailable'\n | 'ambiguous_placement'\n | 'invalid_registration';\n\nconst SERVICE_ERROR_MESSAGES: Record<RpcServiceErrorCode, string> = {\n unauthorized: 'RPC call is not authorized',\n not_ready: 'RPC endpoint is not ready',\n retired: 'RPC endpoint is retiring',\n revoked: 'RPC endpoint generation was revoked',\n unsupported_method: 'RPC method is not published',\n wrong_purpose: 'RPC method is not published for this purpose',\n invalid_input: 'RPC input is not valid',\n invalid_output: 'RPC output is not valid',\n invalid_operation_id: 'RPC command operation id is invalid',\n overloaded: 'RPC runtime is at capacity',\n cancelled: 'RPC call was cancelled',\n timeout: 'RPC call deadline exceeded',\n unknown: 'RPC command outcome is unknown',\n capability_unavailable: 'RPC command execution is unavailable',\n closed: 'RPC runtime is closed',\n failed: 'RPC call failed',\n conflict: 'RPC command identity conflicts with an existing record',\n expired: 'RPC command result has expired',\n pending: 'RPC command is still pending',\n rejected: 'RPC command was rejected',\n missing: 'RPC command has no stored result',\n storage_failure: 'RPC command storage failed',\n deadlock: 'RPC call chain would deadlock',\n call_depth_exceeded: 'RPC call depth exceeded',\n undeclared: 'RPC service is not declared by the manifest',\n unavailable: 'RPC service is unavailable',\n ambiguous_placement: 'RPC service placement is ambiguous',\n invalid_registration: 'RPC registration is invalid',\n};\n\nconst SERVICE_ERROR_CODES = new Set<RpcServiceErrorCode>(Object.keys(SERVICE_ERROR_MESSAGES) as RpcServiceErrorCode[]);\n\n/** Fixed-code error. It never carries a provider cause, message, or payload. */\nexport class RpcServiceError extends Error {\n readonly name = 'RpcServiceError';\n readonly code: RpcServiceErrorCode;\n readonly operationId: string | null;\n\n constructor(code: RpcServiceErrorCode, operationId: string | null = null) {\n super(SERVICE_ERROR_MESSAGES[code]);\n this.code = code;\n this.operationId = operationId;\n }\n}\n\nfunction ownStringProperty(target: unknown, name: string): string | null {\n if (target === null || (typeof target !== 'object' && typeof target !== 'function')) return null;\n let descriptor: PropertyDescriptor | undefined;\n try { descriptor = Object.getOwnPropertyDescriptor(target, name); } catch { return null; }\n if (descriptor === undefined || !('value' in descriptor) || typeof descriptor.value !== 'string') return null;\n return descriptor.value;\n}\n\n/**\n * Rebuilds a fresh public error from the kernel's fixed code and the validated\n * operation id of THIS call. It never reuses the incoming instance, never reads\n * its operation id, and never reads a cause or message.\n */\nexport function toRpcServiceError(error: unknown, operationId: string | null): RpcServiceError {\n const raw = ownStringProperty(error, 'code');\n const code = raw !== null && SERVICE_ERROR_CODES.has(raw as RpcServiceErrorCode)\n ? raw as RpcServiceErrorCode\n : 'failed';\n return new RpcServiceError(code, operationId);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Public types */\n/* -------------------------------------------------------------------------- */\n\nexport interface RpcCallOptions {\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly operationId?: string;\n}\n\nexport type RpcCommandClientExtras<D extends RpcMethodDefinition> = D extends { readonly command: RpcCommandPolicy }\n ? {\n /** Durable committed result query; runs through the same runtime lease/deadline as execute. */\n queryResult(operationId: string): Promise<InferRpcData<D['output']>>;\n /** Explicit host-authorized reconciliation for an unknown command outcome. */\n reconcile(operationId: string, input: InferRpcData<D['input']>): Promise<InferRpcData<D['output']>>;\n }\n : Record<never, never>;\n\nexport type RpcMethodClient<D extends RpcMethodDefinition> =\n ((input: InferRpcData<D['input']>, options?: RpcCallOptions) => Promise<InferRpcData<D['output']>>)\n & RpcCommandClientExtras<D>;\n\n/** Public plugin-facing RPC client derived from a literal contract. */\nexport type AsyncRpcClient<M extends Record<string, RpcMethodDefinition>> = {\n readonly [K in keyof M]: RpcMethodClient<M[K]>;\n};\n\n/** Logical placement identity, independent of any physical address or generation. */\nexport interface HostRpcServiceDescriptor {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly kind: 'rpc';\n readonly process: PluginServiceProcess;\n readonly scope: PluginServiceScope;\n}\n\n/** Physical endpoint identity supplied by the trusted host for one owner instance. */\nexport interface HostRpcLifecycleIdentity {\n readonly endpoint: string;\n readonly instance: string;\n readonly generation: number;\n readonly catalog: string;\n /** Trusted callee subject; never derived from plugin input. */\n readonly subject: string;\n}\n\n/** Canonical owner lifecycle view; the adapter never keeps a second copy. */\nexport interface HostRpcLifecycleState {\n readonly ready: boolean;\n readonly retiring: boolean;\n readonly revoked: boolean;\n}\n\n/** Host-minted invocation frame; the real principal lives in the host callee frame. */\nexport interface HostRpcInvocationContext {\n readonly purpose: RpcCallPurpose;\n /** Opaque host correlation token; the leaf only trusts the required resolver. */\n readonly token: object;\n readonly signal?: AbortSignal;\n readonly deadlineAt?: number;\n}\n\nexport interface HostRpcLeaseRequest {\n readonly role: 'caller' | 'callee';\n readonly plugin: string;\n readonly scope: string;\n readonly state: HostRpcLifecycleState;\n readonly purpose: RpcCallPurpose;\n readonly operationId: string | null;\n /** Logical target provider. */\n readonly provider: string;\n}\n\nexport interface HostRpcLeaseGrant {\n readonly release: () => void;\n /** Host-verified existing request lease; only honored for request/attempt. */\n readonly allowRetired?: boolean;\n}\n\nexport type HostRpcAcquireLease = (request: HostRpcLeaseRequest) => HostRpcLeaseGrant;\n\nexport interface HostRpcMethodCapability {\n /** Synchronous private-state CAS planner for a `local-transaction` command. */\n readonly atomic?: CommandAtomicPlanner;\n /** Explicit bounded read set for the production storage Worker. */\n readonly atomicReadSet?: AtomicReadSetResolver;\n /** Reconcile capability for an `external-contract` command. */\n readonly external?: CommandExternalExecutor;\n}\n\nexport type HostRpcCommandCapabilities<M extends Record<string, RpcMethodDefinition>> = {\n readonly [K in keyof M]?: HostRpcMethodCapability;\n};\n\n/** Everything the canonical host exposes for one owner to use RPC services. */\nexport interface HostRpcOwnerInput {\n readonly token: object;\n readonly plugin: string;\n /** Canonical owner scope: `'global'` or a trusted binding scope key. */\n readonly scope: string;\n readonly declarations: PluginServiceDeclarations;\n readonly dependencies: Readonly<Record<string, string>>;\n readonly lifecycle: HostRpcLifecycleIdentity;\n /** Canonical lifecycle source of truth; the adapter copies nothing. */\n readonly getLifecycleState: () => HostRpcLifecycleState;\n readonly acquireLease: HostRpcAcquireLease;\n readonly registerPublication?: (publication: PluginServicePublication) => void;\n readonly registerConsumption?: (consumption: PluginServiceConsumption, localProviderToken?: object) => void;\n readonly onDispose?: (cleanup: () => void) => void;\n readonly canCall?: (target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string }) => boolean;\n /** Required host invocation-frame resolver; null for plain plugin background calls. */\n readonly resolveInvocationContext: () => HostRpcInvocationContext | null;\n}\n\n/** Trusted peer broker input. This capability is never part of PluginServices. */\nexport interface HostRpcRemoteCallerInput extends HostRpcOwnerInput {\n readonly process: PluginServiceProcess;\n /** Must verify the current authenticated peer frame and logical caller authority. */\n readonly authorizeIncoming: (request: RpcAdmissionRequest, endpoint: NonNullable<ReturnType<RpcServiceRuntime['endpointInfo']>>) => boolean;\n}\n\nexport interface HostRpcRemoteCallerHandle {\n invokeTracked(request: Omit<RpcInvokeRequest, 'caller' | 'callerToken'>): ReturnType<RpcServiceRuntime['invokeTracked']>;\n dispose(): Promise<RpcDrainResult>;\n}\n\n/** Exact placement delegated to the host. `null` means \"use the explicit local channel\". */\nexport type HostRpcPlacementResolution =\n | { readonly kind: 'endpoint'; readonly endpoint: RpcEndpointHandle }\n | { readonly kind: 'ambiguous' }\n | null\n | undefined;\n\nexport interface HostRpcPlacementRequest {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly method: string;\n readonly scope: PluginServiceScope;\n readonly bindingScope?: string;\n readonly caller: RpcCaller;\n readonly purpose?: RpcCallPurpose;\n}\n\nexport type HostRpcPlacementResolver = (request: HostRpcPlacementRequest) => HostRpcPlacementResolution;\n\nexport interface HostRpcJournalRequest {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly method: string;\n readonly scope: PluginServiceScope;\n /** Binding scope key when `scope` is `binding`; keeps two bindings apart. */\n readonly bindingScope?: string;\n readonly policy: RpcCommandPolicy;\n readonly atomic?: CommandAtomicPlanner;\n /** Explicit bounded read set for the production storage Worker. */\n readonly atomicReadSet?: AtomicReadSetResolver;\n readonly external?: CommandExternalExecutor;\n}\n\n/** Host-owned durable journal factory; `null` refuses commands for this key. */\nexport type HostRpcJournalResolver = (request: HostRpcJournalRequest) => AsyncCommandJournal | CommandJournal | null;\n\n/** Trusted opaque callee context resolver. */\nexport type HostRpcCalleeResolver = (request: RpcAdmissionRequest, publication: HostRpcServiceDescriptor) => unknown;\n\n/**\n * Host-provided frame for one admitted native RPC handler. It lets the SAME\n * `PluginServiceHost` invocation store the real purpose/deadline/cancellation\n * for the duration of the handler, bound to the exact published owner, so a\n * channel operation started inside a native handler is authorized by the real\n * frame (never downgraded to `background`, never given a forged purpose).\n */\nexport interface HostRpcHandlerFrame {\n readonly purpose: RpcCallPurpose;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n /** Exact published owner the call targets; `null` for a remote (peer) route. */\n readonly ownerToken: object | null;\n readonly operationId: string | null;\n}\n\nexport interface HostRpcJournalCleanupFailure {\n readonly operationId: string;\n readonly code: string;\n}\nexport interface HostRpcAdapterOptions {\n /** Resource cleanup reports separately and never replaces a business outcome. */\n readonly onJournalCleanupFailure?: (failure:HostRpcJournalCleanupFailure)=>void;\n readonly process: PluginServiceProcess;\n readonly limits?: RpcRuntimeLimits;\n readonly hostLifetime?: AbortSignal;\n readonly maxCallDepth?: number;\n /** Required host placement authority. */\n readonly resolvePlacement: HostRpcPlacementResolver;\n /** Required host journal authority. */\n readonly resolveJournal: HostRpcJournalResolver;\n /** Required trusted opaque callee frame authority. */\n readonly resolveCallee: HostRpcCalleeResolver;\n /**\n * Host callback that enters the exact published owner's trusted invocation\n * frame for one native handler call. The canonical `PluginServiceHost` wires\n * it to its OWN invocation store, so a native RPC handler shares one\n * purpose/deadline/cancel resolver with local dispatch and channel work.\n */\n readonly enterHostHandlerFrame?: (frame: HostRpcHandlerFrame, run: () => unknown) => unknown;\n}\n\nexport interface HostRpcPublication {\n readonly descriptor: HostRpcServiceDescriptor;\n}\n\n/** Host-only readonly directory entry for one real registered publication. */\nexport interface HostRpcPublicationView {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly scope: PluginServiceScope;\n readonly scopeKey: string;\n readonly ready: boolean;\n readonly lifecycle: HostRpcLifecycleIdentity;\n /** The kernel-selected binding of the exact endpoint handle; never re-derived. */\n readonly binding: RpcEndpointBinding;\n}\n\nexport interface HostRpcOwnerHandle {\n readonly owner: HostRpcOwnerInput;\n publish<const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ): HostRpcPublication;\n consume<const M extends Record<string, RpcMethodDefinition>>(\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n ): AsyncRpcClient<M>;\n /** Canonical host hook: ready maps to kernel `markReady`. */\n markReady(): void;\n /** Canonical host hook: retirement maps to kernel `retire`. */\n retire(): void;\n /**\n * Canonical host hook: disposal maps to kernel `revoke` + bounded `drain`.\n * Returns the REAL drain verdict; `drained: false` is reported, never hidden.\n */\n dispose(): Promise<RpcDrainResult>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Internal helpers */\n/* -------------------------------------------------------------------------- */\n\nconst SEP = '\\0';\nconst DEFAULT_MAX_CALL_DEPTH = 32;\nconst CALL_OPTION_KEYS = ['signal', 'timeoutMs', 'operationId'] as const;\nconst EMPTY_OPTIONS: RpcCallOptions = Object.freeze({});\n\ninterface ActiveFrame {\n readonly purpose: RpcCallPurpose;\n readonly depth: number;\n readonly chain: readonly string[];\n readonly deadlineAt: number;\n readonly signal: AbortSignal;\n}\n\n/** Host frame inheritance only: purpose, call chain, deadline, and cancellation. */\nconst FRAME_STORE = new AsyncLocalStorage<ActiveFrame>();\n\ninterface RegisteredPublication {\n readonly key: string;\n readonly handle: RpcEndpointHandle;\n readonly provider: string;\n readonly scopeKey: string;\n readonly scope: PluginServiceScope;\n readonly contractId: string;\n readonly contractVersion: number;\n readonly ownerState: OwnerState;\n}\n\ninterface OwnerState {\n readonly owner: HostRpcOwnerInput;\n readonly plugin: string;\n readonly scope: string;\n readonly scopeKind: PluginServiceScope;\n readonly callerSubject: string;\n readonly lifecycle: HostRpcLifecycleIdentity;\n readonly publications: Set<RegisteredPublication>;\n readonly process: PluginServiceProcess;\n readonly local: boolean;\n readonly authorizeIncoming?: HostRpcRemoteCallerInput['authorizeIncoming'];\n /** RPC capability revocation, independent of eventual resource reclamation. */\n revoked: boolean;\n released: boolean;\n}\n\ninterface CalleeInfo {\n readonly provider: string;\n readonly scopeKey: string;\n readonly scope: PluginServiceScope;\n readonly frame: unknown;\n /** Exact published owner token, or `null` for a remote (peer) route. */\n readonly ownerToken: object | null;\n}\n\ntype Handler = (input: unknown, context: RpcHandlerContext<unknown>) => unknown;\n\ntype RouteResolution =\n | { readonly kind: 'publication'; readonly publication: RegisteredPublication }\n | { readonly kind: 'remote'; readonly handle: RpcEndpointHandle }\n | { readonly kind: 'ambiguous' }\n | { readonly kind: 'missing' };\n\nconst CALLEE_INFO = new WeakMap<object, CalleeInfo>();\n\n/** Reads the trusted opaque callee frame the host resolver produced for an admitted call. */\nexport function readHostRpcCalleeFrame(callee: unknown): unknown {\n if (callee === null || typeof callee !== 'object') return null;\n return CALLEE_INFO.get(callee as object)?.frame ?? null;\n}\n\nfunction publicationKey(provider: string, scopeKey: string, service: string, major: number): string {\n return `${provider}${SEP}${scopeKey}${SEP}${service}${SEP}${major}`;\n}\n\nfunction scopeKindOf(scope: string): PluginServiceScope {\n return scope === 'global' ? 'global' : 'binding';\n}\n\nfunction callerSubjectFor(plugin: string, scope: string): string {\n return scope === 'global' ? plugin : `${plugin}@${scope}`;\n}\n\nfunction normalizeOperationId(operationId: unknown): string {\n if (typeof operationId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(operationId)) {\n throw new RpcServiceError('invalid_operation_id');\n }\n return operationId;\n}\n\n/** Combines cancellation signals without depending on `AbortSignal.any` being present. */\nfunction anySignal(signals: readonly AbortSignal[]): AbortSignal {\n if (signals.length === 1) return signals[0];\n const native = (AbortSignal as unknown as { any?: (values: AbortSignal[]) => AbortSignal }).any;\n if (typeof native === 'function') return native.call(AbortSignal, [...signals]);\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n for (const signal of signals) {\n if (signal.aborted) { abort(); break; }\n signal.addEventListener('abort', abort, { once: true });\n }\n return controller.signal;\n}\n\nfunction requirePurpose(definition: RpcMethodDefinition, purpose: RpcCallPurpose): RpcCallPurpose {\n if (!definition.purposes.includes(purpose)) throw new RpcServiceError('wrong_purpose');\n return purpose;\n}\n\n/** Own-descriptor snapshot of the trusted lifecycle identity; no accessor ever runs. */\nfunction snapshotLifecycle(value: unknown): HostRpcLifecycleIdentity {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const read = (name: string): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n return descriptor.value;\n };\n const allowed = new Set(['endpoint', 'instance', 'generation', 'catalog', 'subject']);\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw new RpcServiceError('invalid_registration');\n }\n const endpoint = read('endpoint');\n const instance = read('instance');\n const generation = read('generation');\n const catalog = read('catalog');\n const subject = read('subject');\n if (typeof endpoint !== 'string' || !endpoint || typeof instance !== 'string' || !instance\n || !Number.isSafeInteger(generation) || (generation as number) < 1\n || typeof catalog !== 'string' || typeof subject !== 'string' || !subject) {\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ endpoint, instance, generation: generation as number, catalog, subject });\n}\n\n/** Own-descriptor snapshot of a dependencies record; accessors are rejected, never invoked. */\nfunction snapshotDependencies(value: unknown): Readonly<Record<string, string>> {\n if (value === undefined) return Object.freeze({});\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const result: Record<string, string> = {};\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string') throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'string') {\n throw new RpcServiceError('invalid_registration');\n }\n result[key] = descriptor.value;\n }\n return Object.freeze(result);\n}\n\n/**\n * Copies own enumerable data-function properties only. Accessors, proxies,\n * prototype methods, symbol keys, and unknown keys are rejected before any value\n * is read, so no plugin getter ever runs.\n */\nfunction snapshotHandlers(methods: Record<string, RpcMethodDefinition>, handler: unknown): Map<string, Handler> {\n if (handler === null || typeof handler !== 'object' || isProxy(handler)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(handler);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const allowed = new Set(Object.keys(methods));\n const collected = new Map<string, Handler>();\n for (const key of Reflect.ownKeys(handler)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(handler, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n collected.set(key, descriptor.value as Handler);\n }\n for (const name of allowed) if (!collected.has(name)) throw new RpcServiceError('invalid_registration');\n return collected;\n}\n\n/**\n * Snapshots one command capability through own descriptors only. Proxies, accessors,\n * unknown keys, and non-function planner/reconcile values are rejected before any\n * value is read, so no plugin getter ever runs and no mutable capability object is\n * retained.\n */\nfunction snapshotCapability(value: unknown): HostRpcMethodCapability {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n let atomic: CommandAtomicPlanner | undefined;\n let atomicReadSet: AtomicReadSetResolver | undefined;\n let external: CommandExternalExecutor | undefined;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || (key !== 'atomic' && key !== 'atomicReadSet' && key !== 'external')) throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n if (key === 'atomicReadSet') {\n if (typeof descriptor.value !== 'function') throw new RpcServiceError('invalid_registration');\n atomicReadSet = descriptor.value as AtomicReadSetResolver;\n } else if (key === 'atomic') {\n if (typeof descriptor.value !== 'function') throw new RpcServiceError('invalid_registration');\n atomic = descriptor.value as CommandAtomicPlanner;\n } else {\n external = snapshotExternal(descriptor.value);\n }\n }\n const record: { atomic?: CommandAtomicPlanner; atomicReadSet?: AtomicReadSetResolver; external?: CommandExternalExecutor } = {};\n if (atomic !== undefined) record.atomic = atomic;\n if (atomicReadSet !== undefined) record.atomicReadSet = atomicReadSet;\n if (external !== undefined) record.external = external;\n return Object.freeze(record);\n}\n\n/** Snapshots the `external.reconcile` function without retaining the plugin's object. */\nfunction snapshotExternal(value: unknown): CommandExternalExecutor {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n for (const key of Reflect.ownKeys(value)) {\n if (key !== 'reconcile') throw new RpcServiceError('invalid_registration');\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, 'reconcile');\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ reconcile: descriptor.value as CommandExternalExecutor['reconcile'] });\n}\n\n/**\n * Descriptor-safe snapshot of the command capabilities record. Every key must name a\n * declared command method; accessors, proxies, symbol keys, unknown/non-command\n * methods, and unknown capability fields are rejected before `register`, so a failed\n * snapshot can never leave a ghost endpoint. The snapshot is frozen and independent\n * of the plugin's mutable objects.\n */\nfunction snapshotCapabilities(\n methodTable: Record<string, RpcMethodDefinition>,\n value: unknown,\n): Readonly<Record<string, HostRpcMethodCapability>> | null {\n if (value === undefined) return null;\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const record: Record<string, HostRpcMethodCapability> = {};\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || !Object.hasOwn(methodTable, key)) throw new RpcServiceError('invalid_registration');\n const definition = methodTable[key];\n if (definition === undefined || definition.kind !== 'command') throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n if (descriptor.value === undefined) continue;\n record[key] = snapshotCapability(descriptor.value);\n }\n return Object.freeze(record);\n}\n\n/** Snapshots plugin call options without invoking accessors or accepting unknown keys. */\nfunction snapshotCallOptions(options: RpcCallOptions | undefined): RpcCallOptions {\n if (options === undefined) return EMPTY_OPTIONS;\n if (options === null || typeof options !== 'object' || isProxy(options)) throw new RpcServiceError('invalid_input');\n const prototype = Object.getPrototypeOf(options);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_input');\n const result: { signal?: AbortSignal; timeoutMs?: number; operationId?: string } = {};\n for (const key of Reflect.ownKeys(options)) {\n if (typeof key !== 'string' || !(CALL_OPTION_KEYS as readonly string[]).includes(key)) {\n throw new RpcServiceError('invalid_input');\n }\n const descriptor = Object.getOwnPropertyDescriptor(options, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_input');\n }\n (result as Record<string, unknown>)[key] = descriptor.value;\n }\n if (result.signal !== undefined && !(result.signal instanceof AbortSignal)) throw new RpcServiceError('invalid_input');\n if (result.timeoutMs !== undefined\n && (typeof result.timeoutMs !== 'number' || !Number.isSafeInteger(result.timeoutMs) || result.timeoutMs < 0)) {\n throw new RpcServiceError('invalid_input');\n }\n if (result.operationId !== undefined && typeof result.operationId !== 'string') throw new RpcServiceError('invalid_input');\n return Object.freeze(result);\n}\n\nfunction defineContract<const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n): { readonly id: string; readonly version: number; readonly methods: M } {\n try {\n return defineRpcService(contract) as unknown as { readonly id: string; readonly version: number; readonly methods: M };\n } catch {\n throw new RpcServiceError('invalid_registration');\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Adapter */\n/* -------------------------------------------------------------------------- */\n\nexport class HostRpcAdapter {\n readonly runtime: RpcServiceRuntime<unknown>;\n readonly #options: HostRpcAdapterOptions;\n readonly #process: PluginServiceProcess;\n readonly #maxCallDepth: number;\n readonly #ownersByToken = new WeakMap<object, OwnerState>();\n readonly #ownersByCaller = new Map<string, OwnerState>();\n readonly #publications = new Map<string, RegisteredPublication>();\n readonly #capabilities = new Map<string, Readonly<Record<string, HostRpcMethodCapability>>>();\n #closed = false;\n\n constructor(options: HostRpcAdapterOptions) {\n if (options === null || typeof options !== 'object' || typeof options.process !== 'string') {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof options.resolvePlacement !== 'function' || typeof options.resolveJournal !== 'function'\n || typeof options.resolveCallee !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n this.#options = options;\n this.#process = options.process;\n this.#maxCallDepth = Number.isSafeInteger(options.maxCallDepth) && (options.maxCallDepth as number) > 0\n ? options.maxCallDepth as number : DEFAULT_MAX_CALL_DEPTH;\n this.runtime = new RpcServiceRuntime<unknown>({\n admit: (request) => this.#admit(request),\n commandExecutor: this.#commandExecutor(),\n hostLifetime: options.hostLifetime,\n limits: options.limits,\n });\n }\n\n status(): RpcRuntimeStatus {\n return this.runtime.status();\n }\n\n /**\n * Host-only readonly directory of this adapter's *real* registered\n * publications: the kernel-selected binding (endpoint/process/instance/\n * generation/catalog/scope/subject) of the exact endpoint handle, its owner\n * lifecycle identity and its current readiness. It is a plain snapshot for\n * host decision making (peer routing/validation); it grants nothing, exposes\n * no SDK surface and is never exposed through `PluginServices`.\n */\n publicationView(): readonly HostRpcPublicationView[] {\n const view: HostRpcPublicationView[] = [];\n for (const publication of this.#publications.values()) {\n const info = this.runtime.endpointInfo(publication.handle);\n if (info === null) continue;\n const lifecycle = publication.ownerState.lifecycle;\n const state = publication.ownerState.owner.getLifecycleState();\n view.push(Object.freeze({\n provider: publication.provider,\n service: publication.contractId,\n major: publication.contractVersion,\n scope: publication.scope,\n scopeKey: publication.scopeKey,\n ready: state.ready && !state.retiring && !state.revoked,\n lifecycle: Object.freeze({\n endpoint: lifecycle.endpoint, instance: lifecycle.instance,\n generation: lifecycle.generation, catalog: lifecycle.catalog, subject: lifecycle.subject,\n }),\n binding: info.binding,\n }));\n }\n return Object.freeze(view);\n }\n\n /** Closes the process runtime; the parent awaits this in the canonical shutdown. */\n async dispose(options: { readonly timeoutMs?: number } = {}) {\n this.#closed = true;\n return this.runtime.dispose(options);\n }\n\n /* ------------------------------ owners ---------------------------------- */\n\n createOwner(input: HostRpcOwnerInput): HostRpcOwnerHandle {\n return this.#ownerHandle(this.#createOwnerState(input, this.#process, true));\n }\n\n /** Imports an authenticated concrete caller, not a plugin instance or SDK facade. */\n createRemoteCaller(input: HostRpcRemoteCallerInput): HostRpcRemoteCallerHandle {\n if (!['control', 'worker', 'ingress'].includes(input?.process) || typeof input?.authorizeIncoming !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n const authorize = input.authorizeIncoming;\n const state = this.#createOwnerState(input, input.process, false, authorize);\n return Object.freeze({\n invokeTracked: (request: Omit<RpcInvokeRequest, 'caller' | 'callerToken'>) => this.runtime.invokeTracked({\n ...request, caller: Object.freeze({ subject: state.callerSubject, scope: state.scopeKind }), callerToken: state.owner.token,\n }),\n dispose: () => this.#disposeOwner(state),\n });\n }\n\n #createOwnerState(input: HostRpcOwnerInput, process: PluginServiceProcess, local: boolean,\n authorizeIncoming?: HostRpcRemoteCallerInput['authorizeIncoming']): OwnerState {\n if (this.#closed) throw new RpcServiceError('closed');\n if (input === null || typeof input !== 'object' || input.token === null || typeof input.token !== 'object') {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof input.plugin !== 'string' || !input.plugin || typeof input.scope !== 'string' || !input.scope) {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof input.getLifecycleState !== 'function' || typeof input.acquireLease !== 'function'\n || typeof input.resolveInvocationContext !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n if (this.#ownersByToken.has(input.token)) throw new RpcServiceError('invalid_registration');\n const callerSubject = callerSubjectFor(input.plugin, input.scope);\n if (local && this.#ownersByCaller.has(callerSubject)) throw new RpcServiceError('invalid_registration');\n const state: OwnerState = {\n owner: input,\n plugin: input.plugin,\n scope: input.scope,\n scopeKind: scopeKindOf(input.scope),\n callerSubject,\n lifecycle: snapshotLifecycle(input.lifecycle),\n publications: new Set(),\n process, local, authorizeIncoming,\n revoked: false,\n released: false,\n };\n // Fail closed before any publication: dependency records must be snapshot-clean.\n snapshotDependencies(input.dependencies);\n if (Object.hasOwn(input, 'optionalDependencies')) throw new RpcServiceError('invalid_registration');\n try { assertSupportedServiceDeclarations(input.declarations); } catch { throw new RpcServiceError('invalid_registration'); }\n this.#ownersByToken.set(input.token, state);\n if (local) this.#ownersByCaller.set(callerSubject, state);\n return state;\n }\n\n #ownerHandle(state: OwnerState): HostRpcOwnerHandle {\n return Object.freeze({\n owner: state.owner,\n publish: <const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ) => this.#publish(state, contract, handlers, capabilities),\n consume: <const M extends Record<string, RpcMethodDefinition>>(\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n ) => this.#consume(state, provider, contract),\n markReady: () => { this.#markReady(state); },\n retire: () => { this.#retire(state); },\n dispose: () => this.#disposeOwner(state),\n });\n }\n\n #markReady(state: OwnerState): void {\n if (state.revoked || state.released || this.#closed) throw new RpcServiceError('closed');\n for (const publication of state.publications) this.runtime.markReady(publication.handle);\n }\n\n #retire(state: OwnerState): void {\n if (state.released) return;\n for (const publication of state.publications) this.runtime.retire(publication.handle);\n }\n\n /** Revoke + REAL bounded drain. Resources are dropped only after a drained verdict. */\n async #disposeOwner(state: OwnerState): Promise<RpcDrainResult> {\n if (state.released) return Object.freeze({ drained: true, active: 0 });\n state.revoked = true;\n this.runtime.revokeCaller(state.callerSubject, state.owner.token);\n for (const publication of state.publications) this.runtime.revoke(publication.handle);\n const result = await this.runtime.drainOwner(state.callerSubject, [...state.publications].map(publication => publication.handle), { callerToken: state.owner.token });\n if (result.drained) this.#releaseOwner(state);\n return result;\n }\n\n /** Drops publication/capability/owner mapping so the same logical owner can be recreated. */\n #releaseOwner(state: OwnerState): void {\n for (const publication of state.publications) {\n this.#publications.delete(publication.key);\n this.#capabilities.delete(publication.key);\n }\n state.publications.clear();\n state.released = true;\n if (this.#ownersByCaller.get(state.callerSubject) === state) this.#ownersByCaller.delete(state.callerSubject);\n }\n\n /* ---------------------------- publications ------------------------------ */\n\n #publish<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n contractInput: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ): HostRpcPublication {\n const lifecycleState = state.owner.getLifecycleState();\n if (state.revoked || state.released || this.#closed || lifecycleState.revoked || lifecycleState.retiring) {\n throw new RpcServiceError('closed');\n }\n const contract = defineContract(contractInput);\n if (this.#matchPublication(state, contract.id, contract.version) === null) throw new RpcServiceError('undeclared');\n const key = publicationKey(state.plugin, state.scope, contract.id, contract.version);\n // Duplicate detection happens BEFORE register so no ghost endpoint is created.\n if (this.#publications.has(key)) throw new RpcServiceError('invalid_registration');\n const methodTable = contract.methods as Record<string, RpcMethodDefinition>;\n const collected = snapshotHandlers(methodTable, handlers);\n // Snapshot capabilities BEFORE `register`: a hostile accessor must fail closed with\n // zero endpoints and no parent publication callback, never leave a ghost endpoint.\n const capabilityRecord = snapshotCapabilities(methodTable, capabilities);\n const wrapped: Record<string, Handler> = {};\n for (const [name, definition] of Object.entries(methodTable)) {\n const chainKey = `${state.plugin}${SEP}${state.scope}${SEP}${contract.id}${SEP}${contract.version}${SEP}${name}`;\n wrapped[name] = this.#wrapHandler(collected.get(name) as Handler, definition, chainKey);\n }\n const binding: RpcEndpointBinding = {\n endpoint: state.lifecycle.endpoint,\n process: this.#process,\n instance: state.lifecycle.instance,\n generation: state.lifecycle.generation,\n catalog: state.lifecycle.catalog,\n scope: state.scopeKind,\n subject: state.lifecycle.subject,\n };\n let handle: RpcEndpointHandle;\n try {\n handle = this.runtime.register({\n provider: state.plugin,\n binding,\n contract,\n handler: wrapped as unknown as RpcHandlerMap<M, unknown>,\n });\n } catch {\n throw new RpcServiceError('invalid_registration');\n }\n const descriptor: HostRpcServiceDescriptor = Object.freeze({\n provider: state.plugin, service: contract.id, major: contract.version, kind: 'rpc',\n process: this.#process, scope: state.scopeKind,\n });\n const publication: RegisteredPublication = {\n key, handle, provider: state.plugin, scopeKey: state.scope, scope: state.scopeKind,\n contractId: contract.id, contractVersion: contract.version, ownerState: state,\n };\n this.#publications.set(key, publication);\n state.publications.add(publication);\n if (capabilityRecord !== null && Object.keys(capabilityRecord).length > 0) {\n this.#capabilities.set(key, capabilityRecord);\n }\n try {\n state.owner.registerPublication?.({\n id: contract.id, version: contract.version, kind: 'rpc', process: this.#process, scope: 'global',\n });\n } catch {\n // Roll back completely: no ghost endpoint, no reservation, no capability.\n this.runtime.revoke(handle);\n this.#publications.delete(key);\n this.#capabilities.delete(key);\n state.publications.delete(publication);\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ descriptor });\n }\n\n #wrapHandler(original: Handler, definition: RpcMethodDefinition, chainKey: string): Handler {\n // Commands are framed once by `#commandExecutor` for the whole journal capability\n // (execute/query/reconcile); framing the business handler again here would inflate\n // depth and could manufacture false same-method cycles.\n if (definition.kind === 'command') return original;\n return (input, context) => this.#runInFrame(context, chainKey, () => original(input, context));\n }\n\n /** Runs `run` inside one inherited host frame: purpose, chain, deadline, cancellation. */\n #runInFrame(context: RpcHandlerContext<unknown>, chainKey: string, run: () => unknown): unknown {\n const parent = FRAME_STORE.getStore() ?? null;\n const depth = (parent?.depth ?? 0) + 1;\n if (depth > this.#maxCallDepth) throw new RpcServiceError('call_depth_exceeded', context.operationId);\n const actualDeadline = typeof context.deadlineAt === 'number' ? context.deadlineAt : Number.POSITIVE_INFINITY;\n const frame: ActiveFrame = Object.freeze({\n purpose: context.purpose,\n depth,\n chain: Object.freeze([...(parent?.chain ?? []), chainKey]),\n deadlineAt: parent === null ? actualDeadline : Math.min(parent.deadlineAt, actualDeadline),\n // A nested call must also abort when the parent call is cancelled.\n signal: parent === null ? context.signal : anySignal([parent.signal, context.signal]),\n });\n const enter = this.#options.enterHostHandlerFrame;\n if (enter === undefined) return FRAME_STORE.run(frame, run);\n // The canonical host enters its OWN live invocation frame for the exact\n // published owner, so channel work and nested local dispatch inside this\n // handler inherit the real purpose/deadline/cancel and the exact owner\n // authority instead of being re-interpreted as an unauthenticated background\n // task. `ownerToken` is host-private (`CALLEE_INFO`), never a payload field.\n const info = context.callee !== null && typeof context.callee === 'object'\n ? CALLEE_INFO.get(context.callee as object)\n : undefined;\n const hostFrame: HostRpcHandlerFrame = {\n purpose: frame.purpose,\n ...(Number.isFinite(frame.deadlineAt) ? { deadlineAt: frame.deadlineAt } : {}),\n signal: frame.signal,\n ownerToken: info?.ownerToken ?? null,\n operationId: context.operationId ?? null,\n };\n return FRAME_STORE.run(frame, () => enter(hostFrame, run));\n }\n\n /* ----------------------------- consumption ------------------------------ */\n\n #consume<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n provider: string,\n contractInput: { readonly id: string; readonly version: number; readonly methods: M },\n ): AsyncRpcClient<M> {\n if (state.released || this.#closed) throw new RpcServiceError('closed');\n if (typeof provider !== 'string' || !provider) throw new RpcServiceError('invalid_registration');\n const contract = defineContract(contractInput);\n const declaration = this.#matchConsumption(state, provider, contract.id, contract.version);\n if (declaration === null) throw new RpcServiceError('undeclared');\n if (!isCrossProcessSelfService(state.plugin, declaration, state.owner.declarations) && (provider === state.plugin || !Object.hasOwn(state.owner.dependencies, provider))) throw new RpcServiceError('undeclared');\n const scopeKey = 'global';\n const firstMethod = Object.keys(contract.methods as Record<string, RpcMethodDefinition>)[0];\n const route = this.#resolveRoute(state, { provider, service: contract.id, major: contract.version, method: firstMethod }, scopeKey);\n if (route.kind === 'ambiguous') throw new RpcServiceError('ambiguous_placement');\n if (route.kind === 'missing') {\n throw new RpcServiceError('unavailable');\n }\n state.owner.registerConsumption?.(declaration, route.kind === 'publication' ? route.publication.ownerState.owner.token : undefined);\n const methodTable = contract.methods as Record<string, RpcMethodDefinition>;\n const client: Record<string, unknown> = {};\n for (const [method, definition] of Object.entries(methodTable)) {\n client[method] = this.#makeMethodClient(state, provider, contract, method, definition);\n }\n return Object.freeze(client) as AsyncRpcClient<M>;\n }\n\n #makeMethodClient<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n method: string,\n definition: RpcMethodDefinition,\n ): unknown {\n const target = { provider, service: contract.id, major: contract.version, method };\n const invoke = (action: RpcCommandAction | undefined, input: unknown, operationId: string | null, options: RpcCallOptions) =>\n this.#invokeAction(state, target, definition, action, input, operationId, options);\n const call = async (input: unknown, options?: RpcCallOptions): Promise<unknown> => {\n const snapshot = snapshotCallOptions(options);\n const operationId = this.#operationId(definition, snapshot);\n return invoke(definition.kind === 'command' ? 'execute' : undefined, input, operationId, snapshot);\n };\n if (definition.kind !== 'command') return call;\n const queryResult = (operationId: string): Promise<unknown> =>\n invoke('query-result', null, normalizeOperationId(operationId), EMPTY_OPTIONS);\n const reconcile = (operationId: string, input: unknown): Promise<unknown> =>\n invoke('reconcile', input, normalizeOperationId(operationId), EMPTY_OPTIONS);\n return Object.assign(call, { queryResult, reconcile });\n }\n\n #operationId(definition: RpcMethodDefinition, options: RpcCallOptions): string | null {\n const raw = options.operationId;\n if (definition.kind === 'query') {\n if (raw !== undefined) throw new RpcServiceError('invalid_operation_id');\n return null;\n }\n if (raw === undefined) throw new RpcServiceError('invalid_operation_id');\n return normalizeOperationId(raw);\n }\n\n async #invokeAction(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n definition: RpcMethodDefinition,\n action: RpcCommandAction | undefined,\n input: unknown,\n operationId: string | null,\n options: RpcCallOptions,\n ): Promise<RpcJson> {\n if (state.revoked || state.released || this.#closed) throw new RpcServiceError('closed', operationId);\n // The manifest consumption and its canonical dependency record are re-validated on\n // every call: a removed declaration or dependency is refused.\n const scopeKey = this.#targetScope(state, target);\n if (scopeKey === null) throw new RpcServiceError('undeclared', operationId);\n const parent = FRAME_STORE.getStore() ?? null;\n if (parent !== null && parent.chain.includes(`${target.provider}${SEP}${scopeKey}${SEP}${target.service}${SEP}${target.major}${SEP}${target.method}`)) {\n throw new RpcServiceError('deadlock');\n }\n // Enforce the consumer contract's own input schema/byte bound before the provider\n // sees the call. `query-result` carries only the null control DTO, never business input.\n if (action !== 'query-result') {\n try {\n const limit = definition.maxInputBytes ?? RPC_JSON_MAX_BYTES;\n input = decodeRpcJson(encodeRpcJson(input, limit), limit);\n assertRpcData(definition.input, input, limit);\n } catch {\n throw new RpcServiceError('invalid_input', operationId);\n }\n }\n const caller = Object.freeze({ subject: state.callerSubject, scope: state.scopeKind });\n // Resolve the host invocation frame exactly once; purpose and request share that snapshot.\n const invocation = state.owner.resolveInvocationContext();\n const purpose = this.#selectPurpose(state, definition, invocation);\n const route = this.#resolveRoute(state, target, scopeKey, purpose);\n if (route.kind === 'ambiguous') throw new RpcServiceError('ambiguous_placement');\n if (route.kind === 'missing') throw new RpcServiceError('unavailable');\n const request = this.#buildRequest(target, caller, purpose, input, operationId, action, options, parent, invocation, state.owner.token);\n try {\n const result = await this.runtime.invoke(request);\n try { assertRpcData(definition.output, result, definition.maxOutputBytes); }\n catch { throw new RpcServiceError('invalid_output', operationId); }\n return result;\n } catch (error) {\n throw toRpcServiceError(error, operationId);\n }\n }\n\n /** Purpose is inherited, never rank-converted; the method must explicitly allow it. */\n #selectPurpose(state: OwnerState, definition: RpcMethodDefinition, invocation: HostRpcInvocationContext | null): RpcCallPurpose {\n const parent = FRAME_STORE.getStore() ?? null;\n if (parent !== null) return requirePurpose(definition, parent.purpose);\n if (invocation !== null) return requirePurpose(definition, invocation.purpose);\n const ready = state.owner.getLifecycleState().ready;\n return requirePurpose(definition, ready ? 'background' : 'bootstrap');\n }\n\n #buildRequest(\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n caller: RpcCaller,\n purpose: RpcCallPurpose,\n input: unknown,\n operationId: string | null,\n action: RpcCommandAction | undefined,\n options: RpcCallOptions,\n parent: ActiveFrame | null,\n invocation: HostRpcInvocationContext | null,\n callerToken: object,\n ) {\n let timeoutMs = options.timeoutMs;\n const deadlineAt = Math.min(parent?.deadlineAt ?? Infinity, invocation?.deadlineAt ?? Infinity);\n if (parent !== null && Number.isFinite(parent.deadlineAt)) {\n const remaining = Math.floor(parent.deadlineAt - Date.now());\n timeoutMs = timeoutMs === undefined ? remaining : Math.min(timeoutMs, remaining);\n }\n if (invocation?.deadlineAt !== undefined) {\n const remaining = Math.floor(invocation.deadlineAt - Date.now());\n timeoutMs = timeoutMs === undefined ? remaining : Math.min(timeoutMs, remaining);\n }\n if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)) {\n throw new RpcServiceError('timeout', operationId);\n }\n const explicitSignal = options.signal;\n const parentSignal = parent?.signal;\n let signal = explicitSignal === undefined\n ? parentSignal\n : parentSignal === undefined ? explicitSignal : anySignal([explicitSignal, parentSignal]);\n if (invocation?.signal !== undefined) signal = signal === undefined ? invocation.signal : anySignal([signal, invocation.signal]);\n const request: {\n target: { provider: string; service: string; major: number; method: string };\n caller: RpcCaller;\n callerToken: object;\n purpose: RpcCallPurpose;\n input: unknown;\n operationId?: string;\n commandAction?: RpcCommandAction;\n signal?: AbortSignal;\n timeoutMs?: number;\n deadlineAt?: number;\n } = {\n target: { provider: target.provider, service: target.service, major: target.major, method: target.method },\n caller,\n callerToken,\n purpose,\n input,\n };\n if (operationId !== null) request.operationId = operationId;\n if (action !== undefined) request.commandAction = action;\n if (signal !== undefined) request.signal = signal;\n if (timeoutMs !== undefined) request.timeoutMs = timeoutMs;\n if (Number.isFinite(deadlineAt)) request.deadlineAt = deadlineAt;\n return request;\n }\n\n /* ------------------------------- routing -------------------------------- */\n\n #matchPublication(state: OwnerState, id: string, version: number): PluginServicePublication | null {\n return state.owner.declarations.provides?.find((value) =>\n value.id === id && value.version === version\n && (value.kind ?? 'local') === 'rpc'\n && value.process === this.#process\n && (value.scope ?? 'global') === 'global' && state.scope === 'global') ?? null;\n }\n\n #matchConsumption(state: OwnerState, provider: string, id: string, version: number): PluginServiceConsumption | null {\n return state.owner.declarations.consumes?.find((value) =>\n value.plugin === provider && value.id === id && value.version === version\n && (value.kind ?? 'local') === 'rpc'\n && value.process === state.process) ?? null;\n }\n\n #targetScope(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number },\n ): string | null {\n const consumption = state.owner.declarations.consumes?.find((value) =>\n value.plugin === target.provider && value.id === target.service && value.version === target.major\n && (value.kind ?? 'local') === 'rpc' && value.process === state.process) ?? null;\n if (consumption === null) return null;\n if (!isCrossProcessSelfService(state.plugin, consumption, state.owner.declarations) && (target.provider === state.plugin || !Object.hasOwn(state.owner.dependencies, target.provider))) return null;\n return 'global';\n }\n\n /** Host placement authority runs first; `null` opts into the explicit local channel. */\n #resolveRoute(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n scopeKey: string,\n purpose?: RpcCallPurpose,\n ): RouteResolution {\n let placement: HostRpcPlacementResolution;\n try {\n placement = this.#options.resolvePlacement({\n provider: target.provider,\n service: target.service,\n major: target.major,\n method: target.method,\n scope: scopeKey === 'global' ? 'global' : 'binding',\n ...(scopeKey === 'global' ? {} : { bindingScope: scopeKey }),\n caller: Object.freeze({ subject: state.callerSubject, scope: state.scopeKind }),\n purpose,\n });\n } catch {\n return { kind: 'missing' };\n }\n if (placement !== null && placement !== undefined) {\n if (placement.kind === 'ambiguous') return { kind: 'ambiguous' };\n return { kind: 'remote', handle: placement.endpoint };\n }\n const publication = this.#publications.get(publicationKey(target.provider, scopeKey, target.service, target.major));\n return publication === undefined ? { kind: 'missing' } : { kind: 'publication', publication };\n }\n\n /* ----------------------------- admission -------------------------------- */\n\n #admit(request: RpcAdmissionRequest): RpcAdmissionGrant<unknown> | null {\n if (this.#closed) return null;\n const state = request.callerToken === undefined ? this.#ownersByCaller.get(request.caller.subject)\n : this.#ownersByToken.get(request.callerToken);\n if (state === undefined || state.revoked || state.released) return null;\n if (state.callerSubject !== request.caller.subject\n || (request.caller.scope !== undefined && state.scopeKind !== request.caller.scope)) return null;\n const callerState = state.owner.getLifecycleState();\n if (callerState.revoked) return null;\n if (state.owner.canCall !== undefined && !state.owner.canCall({ ...request.target })) return null;\n if (!callerState.ready && request.purpose !== 'bootstrap') return null;\n const target = { ...request.target };\n const scopeKey = this.#targetScope(state, target);\n if (scopeKey === null) return null;\n const route = this.#resolveRoute(state, target, scopeKey, request.purpose);\n if (route.kind === 'ambiguous' || route.kind === 'missing') return null;\n const publication = route.kind === 'publication' ? route.publication : null;\n const endpoint = route.kind === 'publication' ? route.publication.handle : route.handle;\n // The callee publication is built from the REAL kernel-bound endpoint identity, never\n // from the adapter process or a plugin-supplied location. A foreign/unconfirmable\n // endpoint, or one whose provider/service/major/scope disagrees with the requested\n // target, is refused before any lease or callee frame is produced.\n const info = this.runtime.endpointInfo(endpoint);\n if (info === null) return null;\n if (info.provider !== target.provider || info.contract.id !== target.service || info.contract.version !== target.major) {\n return null;\n }\n const scope = info.binding.scope;\n if ((scopeKey === 'global') !== (scope === 'global')) return null;\n if (!state.local) {\n try { if (state.authorizeIncoming?.(request, info) !== true) return null; }\n catch { return null; }\n if (state.revoked || state.released || this.#closed) return null;\n }\n const provider = info.provider;\n // Logical clients can be relocated without retaining an unrelated local provider.\n const consumption = this.#matchConsumption(state, target.provider, target.service, target.major)!;\n state.owner.registerConsumption?.(consumption, publication?.ownerState.owner.token);\n // Resolve the trusted callee frame before any lease so a throwing host\n // resolver cannot leak leases.\n const hostFrame = this.#options.resolveCallee(\n request,\n Object.freeze({ provider, service: target.service, major: target.major, kind: 'rpc', process: info.binding.process, scope }),\n );\n // Caller lease holds the issuing owner for the whole call lifespan.\n let callerRelease: () => void = () => undefined;\n try {\n const lease = state.owner.acquireLease({\n role: 'caller', plugin: state.plugin, scope: state.scope, state: callerState,\n purpose: request.purpose, operationId: request.operationId, provider: target.provider,\n });\n if (lease === null || typeof lease !== 'object' || typeof lease.release !== 'function') return null;\n callerRelease = once(() => { try { lease.release(); } catch { /* host-owned */ } });\n } catch { return null; }\n // Callee lease holds the provider (local only). A callee the kernel will refuse\n // (revoked / retiring without an existing-lease proof / unready non-bootstrap)\n // is NOT leased here, so the kernel reports the exact state instead of a lease error.\n let calleeRelease: (() => void) | null = null;\n let allowRetired = false;\n if (publication !== null) {\n const calleeState = publication.ownerState.owner.getLifecycleState();\n const runnable = calleeState.revoked ? false\n : calleeState.retiring ? (request.purpose === 'request' || request.purpose === 'attempt')\n : (calleeState.ready || request.purpose === 'bootstrap');\n if (runnable) {\n try {\n const lease = publication.ownerState.owner.acquireLease({\n role: 'callee', plugin: publication.provider, scope: publication.scopeKey, state: calleeState,\n purpose: request.purpose, operationId: request.operationId, provider: target.provider,\n });\n if (lease === null || typeof lease !== 'object' || typeof lease.release !== 'function') {\n callerRelease();\n return null;\n }\n calleeRelease = once(() => { try { lease.release(); } catch { /* host-owned */ } });\n allowRetired = lease.allowRetired === true\n && (request.purpose === 'request' || request.purpose === 'attempt');\n } catch { callerRelease(); return null; }\n }\n }\n const callee = Object.freeze({});\n CALLEE_INFO.set(callee, { provider, scopeKey, scope, frame: hostFrame, ownerToken: publication?.ownerState.owner.token ?? null });\n const release = once(() => {\n try { calleeRelease?.(); } catch { /* host-owned */ }\n try { callerRelease(); } catch { /* host-owned */ }\n });\n // A host callback can synchronously dispose this capability before a task exists.\n // Recheck after every admission callback has returned, before handing the kernel a grant.\n if (state.revoked || state.released || this.#closed) { release(); return null; }\n return {\n endpoint, callee, release, callerToken: state.owner.token,\n allowUnready: request.purpose === 'bootstrap',\n allowRetired,\n };\n }\n\n /* ------------------------------ commands -------------------------------- */\n\n #commandExecutor(): RpcCommandExecutor<unknown> {\n const run = async (\n execution: Omit<RpcCommandExecution<unknown>, 'executeBusiness'>,\n action: RpcCommandAction,\n ): Promise<unknown> => {\n const callee = execution.context.callee;\n const info = callee !== null && typeof callee === 'object' ? CALLEE_INFO.get(callee as object) : undefined;\n if (info === undefined) throw new RpcServiceError('capability_unavailable', execution.operationId);\n const chainKey = `${info.provider}${SEP}${info.scopeKey}${SEP}${execution.contract.id}${SEP}${execution.contract.version}${SEP}${execution.method}`;\n const journal = this.#journalFor(info, execution);\n // Application-owned CAS/idempotency (e.g. a budget ledger or credential\n // version fence) has one transaction authority. No parallel journal is\n // created for an explicitly non-deduplicated command.\n if (journal === null && execution.definition.command?.deduplication === 'none') {\n if (action !== 'execute') throw new RpcServiceError('capability_unavailable', execution.operationId);\n return this.#runInFrame(execution.context, chainKey, () => (execution as RpcCommandExecution<unknown>).executeBusiness());\n }\n if (journal === null) throw new RpcServiceError('capability_unavailable', execution.operationId);\n // Every journal action (execute/query/reconcile) runs inside the real RPC frame so\n // the business handler and any nested external-reconcile RPC inherit purpose,\n // chain, deadline, and cancellation. Commands are framed once here, not in #wrapHandler.\n try {\n return await this.#runInFrame(execution.context, chainKey, () => {\n if (action === 'execute') return journal.execute(execution as RpcCommandExecution<unknown>);\n if (action === 'query-result') return journal.query(execution.operationId, execution.context.caller);\n return journal.reconcile(execution);\n });\n } finally {\n if ('close' in journal) {\n // Capability release is resource cleanup, separate from the acknowledged command.\n // A stuck or failed cleanup must not replace success, unknown, or its operation ID.\n void Promise.resolve().then(()=>journal.close()).catch(error=>{\n const rawCode=ownStringProperty(error,'code');\n const code=rawCode!==null&&['worker_failed','request_timeout','request_failed','close_unconfirmed','cleanup_overloaded','queue_full','result_unknown','storage_failure'].includes(rawCode)?rawCode:'failed';\n const failure=Object.freeze({operationId:execution.operationId,code});\n try{logger.error(failure,'Host RPC journal cleanup failed');}catch{/* Reporting cannot change the command outcome. */}\n try{this.#options.onJournalCleanupFailure?.(failure);}catch{/* Host reporting is independent of business completion. */}\n });\n }\n }\n\n };\n return {\n execute: (execution) => run(execution, 'execute'),\n queryResult: (execution) => run(execution, 'query-result'),\n reconcile: (execution) => run(execution, 'reconcile'),\n };\n }\n\n #journalFor(\n info: CalleeInfo,\n execution: Omit<RpcCommandExecution<unknown>, 'executeBusiness'>,\n ): AsyncCommandJournal | CommandJournal | null {\n const policy = execution.definition.command;\n if (policy === undefined) throw new RpcServiceError('capability_unavailable', execution.operationId);\n const capability = this.#capabilities.get(\n publicationKey(info.provider, info.scopeKey, execution.contract.id, execution.contract.version),\n )?.[execution.method];\n try {\n return this.#options.resolveJournal({\n provider: info.provider,\n service: execution.contract.id,\n major: execution.contract.version,\n method: execution.method,\n scope: info.scope,\n ...(info.scope === 'binding' ? { bindingScope: info.scopeKey } : {}),\n policy,\n ...(capability?.atomic === undefined ? {} : { atomic: capability.atomic }),\n ...(capability?.atomicReadSet === undefined ? {} : { atomicReadSet: capability.atomicReadSet }),\n ...(capability?.external === undefined ? {} : { external: capability.external }),\n }) ?? null;\n } catch {\n throw new RpcServiceError('capability_unavailable', execution.operationId);\n }\n }\n}\n\nfunction once(action: () => void): () => void {\n let done = false;\n return () => { if (done) return; done = true; action(); };\n}\n",
@@ -17,13 +17,13 @@
17
17
  "/** Declarative repair request; the host owns the next upstream attempt. */\nconst retryActionBrand=Symbol.for('@jeffusion/bungee/request-retry-action');\nexport class RequestRetryAction extends Error {\n readonly body:unknown;\n constructor(body: unknown, readonly reason: string) {\n super('gateway request repair retry');\n this.name = 'RequestRetryAction';\n Object.defineProperty(this,retryActionBrand,{value:true});\n Object.defineProperty(this,'body',{value:body,enumerable:false});\n }\n /** Plugins and host may bundle the SDK independently in the same process. */\n static [Symbol.hasInstance](value:unknown):boolean {\n return value instanceof Error && (value as unknown as Record<symbol,unknown>)[retryActionBrand]===true;\n }\n}\n",
18
18
  "import type { TokenStatsRange } from './plugin.types';\n\nconst HOUR = 3_600_000;\nexport const TOKEN_STATS_RETENTION_MS = 31 * 24 * HOUR;\nexport const TOKEN_STATS_RANGES = ['1h', '12h', '24h', '1d', '7d', '30d', 'day', 'week', 'month'] as const;\n\n/** Recent page ranges are consecutive elapsed hours; calendar ranges use local dates. */\nexport function tokenStatsWindow(range: TokenStatsRange, asOfMs: number, timeZone = 'UTC') {\n if (range === '1h' || range === '12h' || range === '24h') {\n const duration = { '1h': HOUR, '12h': 12 * HOUR, '24h': 24 * HOUR };\n const bucketMs = { '1h': 300_000, '12h': HOUR, '24h': 2 * HOUR }[range];\n return { startMs: asOfMs - duration[range], endMs: asOfMs, bucketMs };\n }\n if (range === '1d' || range === '7d' || range === '30d') {\n const days = { '1d': 1, '7d': 7, '30d': 30 }[range];\n const bucketMs = range === '1d' ? HOUR : 24 * HOUR;\n const startMs = asOfMs - days * 24 * HOUR;\n const bucketStarts = Array.from({ length: range === '1d' ? 24 : days }, (_, i) => startMs + i * bucketMs);\n return { startMs, endMs: asOfMs, bucketMs, bucketStarts };\n }\n const format = new Intl.DateTimeFormat('en-US', {\n timeZone, year: 'numeric', month: 'numeric', day: 'numeric',\n hour: 'numeric', minute: 'numeric', second: 'numeric', hourCycle: 'h23',\n });\n const parts = (ms: number) => Object.fromEntries(format.formatToParts(ms)\n .filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));\n const today = parts(asOfMs);\n const day = Date.UTC(today.year!, today.month! - 1, today.day!);\n // Resolve each local midnight separately so DST days can contain 23 or 25 hours.\n const midnight = (date: number) => {\n let candidate = date;\n for (let i = 0; i < 4; i++) {\n const p = parts(candidate);\n const local = Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!, p.second!);\n const next = candidate + date - local;\n if (next === candidate) return candidate;\n candidate = next;\n }\n return candidate;\n };\n if (range === 'day') {\n const startMs = midnight(day);\n const bucketEndMs = midnight(day + 24 * HOUR);\n const bucketStarts = Array.from({ length: Math.ceil((bucketEndMs - startMs) / HOUR) }, (_, i) => startMs + i * HOUR);\n return { startMs, endMs: asOfMs, bucketMs: HOUR, bucketStarts, bucketEndMs };\n }\n const firstDay = range === 'month' ? Date.UTC(today.year!, today.month! - 1, 1)\n : day - ((new Date(day).getUTCDay() + 6) % 7) * 24 * HOUR;\n const nextPeriod = range === 'month' ? Date.UTC(today.year!, today.month!, 1) : firstDay + 7 * 24 * HOUR;\n const days = (nextPeriod - firstDay) / (24 * HOUR);\n const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));\n return { startMs: bucketStarts[0]!, endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };\n}\n",
19
19
  "/**\n * Token-stats pricing.\n *\n * There is no download, scheduler or cache here: prices come from the models-dev\n * public catalog service, and only the explicit alias mappings are owned by\n * token-stats. Protocol detection and price-provider identification are separate:\n * explicit mappings remain strict; automatic pricing uses the catalog's bounded\n * estimate lookups, including normalized names and original-lab reference prices.\n */\n\nimport type { ModelsDevCatalogService, ModelsDevModelMatch } from '../../models-dev/contract';\nimport type { PriceModelMapping } from './model-mappings';\n\nexport interface TokenStatsPricingInput {\n readonly model?: string;\n readonly provider?: string;\n /** Real upstream URL, when the caller has it; used only for provider.api matching. */\n readonly url?: string;\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly cacheReadTokens?: number;\n readonly cacheWriteTokens?: number;\n}\n\nconst TOKENS_PER_UNIT = 1_000_000;\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nexport function costOf(match: ModelsDevModelMatch, input: TokenStatsPricingInput): number | null {\n const inputTokens = input.inputTokens;\n const outputTokens = input.outputTokens;\n if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens)) return null;\n const cacheReads = input.cacheReadTokens ?? 0;\n const cacheWrites = input.cacheWriteTokens ?? 0;\n if (!isNonNegativeInteger(cacheReads) || !isNonNegativeInteger(cacheWrites)\n || cacheReads + cacheWrites > inputTokens) return null;\n let rates: Pick<ModelsDevModelMatch, 'input' | 'output' | 'cacheRead' | 'cacheWrite'> = match;\n // Bands are ascending and apply to the entire request, including cached input.\n for (const tier of match.contextTiers ?? []) {\n if (inputTokens < tier.minimumInputTokens) break;\n rates = tier;\n }\n const cacheRead = rates.cacheRead ?? match.cacheRead ?? rates.input;\n const cacheWrite = rates.cacheWrite ?? match.cacheWrite ?? rates.input;\n const baseInput = inputTokens - cacheReads - cacheWrites;\n const total =\n baseInput * rates.input\n + outputTokens * rates.output\n + cacheReads * cacheRead\n + cacheWrites * cacheWrite;\n const cost = total / TOKENS_PER_UNIT;\n return Number.isFinite(cost) && cost >= 0 ? cost : null;\n}\n\nexport function costNanoUsdOf(cost: number | null): number | null {\n if (cost === null || !Number.isFinite(cost) || cost < 0) return null;\n const nano = Math.round(cost * 1e9);\n return Number.isSafeInteger(nano) ? nano : null;\n}\n\n/**\n * Resolve one price. Explicit aliases are exact and case-sensitive and take\n * priority over every inferred match; a missing alias target stays unknown rather\n * than falling back to another provider.\n */\nexport function calculateTokenStatsCost(\n catalog: ModelsDevCatalogService | null,\n input: TokenStatsPricingInput,\n mappings: readonly PriceModelMapping[] = [],\n): number | null {\n if (catalog === null || typeof input.model !== 'string' || input.model.length === 0) return null;\n const mapping = mappings.find(item => item.source === input.model);\n if (mapping !== undefined) {\n const target = catalog.resolveModel({ model: mapping.model, pricingProvider: mapping.provider });\n return target === null ? null : costOf(target, input);\n }\n const match = catalog.resolveModel({\n model: input.model,\n mode: 'estimate',\n ...(input.provider === undefined ? {} : { pricingProvider: input.provider }),\n ...(input.url === undefined ? {} : { url: input.url }),\n });\n return match === null ? null : costOf(match, input);\n}\n\n/** Reads the models-dev catalog service and applies token-stats aliases. */\nexport class TokenStatsPricing {\n private mappings: PriceModelMapping[] | undefined = [];\n\n constructor(private readonly catalog: ModelsDevCatalogService | null) {}\n\n /** Alias read failures must keep pricing unknown, not select a fallback price. */\n setMappings(mappings: PriceModelMapping[] | undefined): void { this.mappings = mappings; }\n\n hasMappings(): boolean { return this.mappings !== undefined; }\n\n estimate(input: TokenStatsPricingInput): number | null {\n if (this.mappings === undefined) return null;\n return calculateTokenStatsCost(this.catalog, input, this.mappings);\n }\n\n /** Catalog availability is reported separately; nothing is awaited here. */\n ready(): Promise<void> { return Promise.resolve(); }\n}\n",
20
- "import type { Database } from 'bun:sqlite';\nimport type { PluginStorage, PluginObservationStorage, TokenStatsAttempt, TokenStatsGroupBy, TokenStatsMeteringStorage,\n TokenStatsMetricName, TokenStatsSnapshotMetrics, TokenStatsValueSource, TokenStatsRange } from '@jeffusion/bungee-core/plugin';\nimport { TOKEN_STATS_RETENTION_MS, TOKEN_STATS_RANGES, tokenStatsWindow } from '@jeffusion/bungee-core/plugin';\nimport type { ModelsDevModelMatch } from '../../models-dev/contract';\nimport { costNanoUsdOf, costOf } from './pricing';\n\n/** Explicit assembly for legacy fixtures and embedders; the host never checks a business name. */\nexport function withTokenStatsMetering<T extends PluginStorage>(storage: T): T & { metering: SQLiteTokenStatsMetering } {\n if (!storage.observation) throw new Error('token-stats metering storage is required');\n return Object.assign(storage, { metering: new SQLiteTokenStatsMetering(storage.observation) });\n}\n\nconst TOKEN_STATS_METRICS: readonly TokenStatsMetricName[] = [\n 'inputTokens', 'outputTokens', 'officialInputTokens', 'officialOutputTokens',\n 'estimatedInputTokens', 'estimatedOutputTokens', 'cacheReadTokens', 'cacheWriteTokens',\n 'partialOutputs', 'logicalRequests', 'upstreamAttempts', 'observationIncompleteAttempts',\n 'inputAuthorityOfficial', 'inputAuthorityLocal', 'inputAuthorityHeuristic', 'inputAuthorityPartial', 'inputAuthorityNone',\n 'outputAuthorityOfficial', 'outputAuthorityLocal', 'outputAuthorityHeuristic', 'outputAuthorityPartial', 'outputAuthorityNone',\n];\nconst TOKEN_STATS_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;\nconst TOKEN_STATS_BUSY_TIMEOUT_MS = 5;\n\nconst EMPTY_METRICS: Record<TokenStatsMetricName, number> = Object.fromEntries(\n TOKEN_STATS_METRICS.map((name) => [name, 0]),\n) as Record<TokenStatsMetricName, number>;\n\ntype WindowQuery = Parameters<TokenStatsMeteringStorage['queryWindowSnapshot']>[0];\ntype QueryPricing = {\n throughRow: number;\n prices: readonly (readonly [string, ModelsDevModelMatch])[];\n};\ntype UnpricedUsage = Pick<TokenStatsAttempt, 'model' | 'input_tokens' | 'output_tokens' | 'cache_read_tokens' | 'cache_write_tokens'> & {\n bucketStartMs: number | null;\n};\nconst PRICEABLE_USAGE = `cost_usd IS NULL AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL AND model <> 'unknown'`;\n\nexport class SQLiteTokenStatsMetering implements TokenStatsMeteringStorage {\n constructor(private readonly observation: PluginObservationStorage) {}\n\n async recordAttempt(row: TokenStatsAttempt): Promise<void> {\n return this.observation.withDatabase((db) => {\n validateTokenStatsAttempt(row);\n const transaction = db.transaction(() => {\n db.query(`\n INSERT OR IGNORE INTO token_stats_attempts (\n attempt_id, request_id, finished_at_ms, route_id, upstream_id, provider, outcome, model, key_id,\n input_tokens, output_tokens, input_source, output_source,\n cache_read_tokens, cache_write_tokens, cost_usd, observation_incomplete\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n row.attempt_id, row.request_id, row.finished_at_ms, row.route_id, row.upstream_id, row.provider,\n row.outcome, row.model, row.key_id ?? null, row.input_tokens, row.output_tokens, row.input_source, row.output_source,\n row.cache_read_tokens, row.cache_write_tokens, row.cost_usd, row.observation_incomplete ? 1 : 0,\n );\n // A fixed one-batch cleanup keeps the write transaction bounded.\n db.query(`\n DELETE FROM token_stats_attempts WHERE attempt_id IN (\n SELECT attempt_id FROM token_stats_attempts INDEXED BY idx_token_stats_attempts_finished\n WHERE finished_at_ms < ? ORDER BY finished_at_ms LIMIT 500\n )\n `).run(Date.now() - TOKEN_STATS_RETENTION_MS);\n });\n withReportingWriteTimeout(db, () => transaction.immediate());\n });\n }\n\n async queryPricingModels(input: WindowQuery): Promise<{ models: string[]; throughRow: number }> {\n const window = queryBounds(input);\n return this.observation.withDatabase((db) => db.transaction(() => {\n // Do not include newly inserted rows between the model lookup and the priced query.\n const { throughRow } = db.query<{ throughRow: number }, []>(\n 'SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts',\n ).get()!;\n const { index, where, params } = attemptWindow({ ...window, throughRow });\n const rows = db.query<{ model: string }, (number | string)[]>(`\n SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}\n WHERE ${where} AND ${PRICEABLE_USAGE}\n `).all(...params);\n return { models: rows.map(row => row.model), throughRow };\n }).deferred());\n }\n\n async queryWindowSnapshot(input: WindowQuery & { pricing?: QueryPricing }): Promise<{\n all: TokenStatsSnapshotMetrics;\n data: Array<{ dimension: string; bucketStartMs?: number; metrics: TokenStatsSnapshotMetrics }>;\n bucketMs?: number;\n bucketStarts?: number[];\n bucketEndMs?: number;\n present: boolean;\n }> {\n const window = queryBounds(input);\n const { bucketMs, bucketStarts, bucketEndMs } = window;\n const pricing = input.pricing;\n const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });\n return this.observation.withDatabase((db) => {\n const read = () => {\n const rows = db.query<Record<string, number | string | null>, (number | string)[]>(sql).all(...params);\n if (!pricing?.prices.length) return rows;\n const prices = new Map(pricing.prices);\n const missing = db.query<UnpricedUsage, (number | string)[]>(missingSql)\n .iterate(...params, JSON.stringify([...prices.keys()]));\n const byGroup = new Map<string, number>();\n let total: number | undefined;\n for (const row of missing) {\n const nano = costNanoUsdOf(costOf(prices.get(row.model)!, {\n inputTokens: row.input_tokens ?? undefined, outputTokens: row.output_tokens ?? undefined,\n cacheReadTokens: row.cache_read_tokens ?? undefined, cacheWriteTokens: row.cache_write_tokens ?? undefined,\n }));\n if (nano === null) continue;\n const cost = nano / 1e9;\n total = (total ?? 0) + cost;\n const key = JSON.stringify([row.model, row.bucketStartMs]);\n byGroup.set(key, (byGroup.get(key) ?? 0) + cost);\n }\n for (const row of rows) {\n const extra = row.kind === 'all' ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));\n if (extra !== undefined) row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;\n }\n return rows;\n };\n const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();\n const allRow = rows.find((row) => row.kind === 'all');\n const dataRows = rows.filter((row) => row.kind === 'data');\n const metrics = (row: Record<string, number | string | null> | undefined): TokenStatsSnapshotMetrics => {\n const base = !row ? { ...EMPTY_METRICS } : Object.fromEntries(TOKEN_STATS_METRICS.map((key) => {\n const value = Number(row[key] ?? 0);\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`invalid token-stats aggregate: ${key}`);\n return [key, value];\n })) as Record<TokenStatsMetricName, number>;\n const rawCost = row?.estimatedCostUsd;\n const estimatedCostUsd = rawCost === undefined || rawCost === null ? null : Number(rawCost);\n if (estimatedCostUsd !== null && (!Number.isFinite(estimatedCostUsd) || estimatedCostUsd < 0)) {\n throw new RangeError('invalid token-stats aggregate: estimatedCostUsd');\n }\n return { ...base, estimatedCostUsd };\n };\n return {\n all: metrics(allRow),\n data: dataRows.map((row) => ({\n dimension: String(row.dimension),\n ...(input.groupBy === 'time' ? { bucketStartMs: Number(row.bucketStartMs) } : {}),\n metrics: metrics(row),\n })),\n ...(bucketMs === undefined ? {} : { bucketMs }),\n ...(bucketStarts === undefined ? {} : { bucketStarts }),\n ...(bucketEndMs === undefined ? {} : { bucketEndMs }),\n present: Number(allRow?.present ?? 0) === 1,\n };\n });\n }\n async listClientModels(input: {page?:number;pageSize?:number;keyword?:string}) {\n const page=input.page ?? 1,pageSize=input.pageSize ?? 20,keyword=input.keyword;\n if(!Number.isSafeInteger(page)||page<1||page>400||!Number.isSafeInteger(pageSize)||pageSize<1||pageSize>100\n || keyword!==undefined&&(typeof keyword!=='string'||keyword.length>256))throw new Error('invalid token-stats client models page');\n const since=Date.now()-TOKEN_STATS_RETENTION_MS;\n const search=keyword ? `%${keyword.replace(/[\\\\%_]/g, character=>`\\\\${character}`)}%` : null;\n return this.observation.withDatabase(db=>{\n const filter=search ? \" AND model LIKE ? ESCAPE '\\\\'\" : '';\n const params:(string|number)[]=search ? [since,search] : [since];\n const total=Number(db.query<{total:number},(string|number)[]>(`SELECT COUNT(DISTINCT model) AS total FROM token_stats_attempts WHERE finished_at_ms >= ?${filter}`).get(...params)?.total ?? 0);\n const rows=db.query<{model:string},(string|number)[]>(`SELECT DISTINCT model FROM token_stats_attempts WHERE finished_at_ms >= ?${filter} ORDER BY model ASC LIMIT ? OFFSET ?`).all(...params,pageSize,(page-1)*pageSize);\n return {models:rows.map(row=>String(row.model)),total:Number.isSafeInteger(total)&&total>=0 ? total : 0,page,pageSize};\n });\n }\n\n}\n\nfunction queryBounds(input: WindowQuery) {\n validateTokenStatsTimestamp(input.asOfMs, 'asOfMs');\n if (!(TOKEN_STATS_RANGES as readonly string[]).includes(input.range)) throw new Error('invalid token-stats range');\n if (!['model', 'time'].includes(input.groupBy)) throw new Error('invalid token-stats groupBy');\n const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);\n return {\n ...window,\n startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),\n groupBy: input.groupBy,\n bucketMs: input.groupBy === 'time' ? window.bucketMs : undefined,\n bucketStarts: input.groupBy === 'time' ? window.bucketStarts : undefined,\n bucketEndMs: input.groupBy === 'time' ? window.bucketEndMs : undefined,\n keyId: input.keyId,\n };\n}\n\nfunction attemptWindow(input: { startMs: number; endMs: number; keyId?: string; throughRow?: number }) {\n const { startMs, endMs, keyId, throughRow } = input;\n if (keyId !== undefined && (typeof keyId !== 'string' || !keyId || keyId.length > 128)) throw new Error('invalid token-stats keyId');\n if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0)) throw new Error('invalid token-stats row boundary');\n const keyFilter = keyId === undefined ? '' : keyId === '__unattributed__' ? ' AND key_id IS NULL' : ' AND key_id = ?';\n return {\n index: keyId === undefined ? 'idx_token_stats_attempts_finished' : 'idx_token_stats_attempts_key_finished',\n where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? '' : ' AND rowid <= ?'}`,\n params: [startMs, endMs, ...(keyId !== undefined && keyId !== '__unattributed__' ? [keyId] : []), ...(throughRow === undefined ? [] : [throughRow])],\n };\n}\n\nexport function buildTokenStatsWindowSnapshotQuery(input: {\n startMs: number;\n endMs: number;\n groupBy: TokenStatsGroupBy;\n bucketMs?: number;\n bucketStarts?: readonly number[];\n keyId?: string;\n throughRow?: number;\n}): { sql: string; missingSql: string; params: (number | string)[] } {\n const metrics = (alias: string) => `\n COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source = 'usage' THEN ${alias}.output_tokens ELSE 0 END), 0) AS officialOutputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.input_source IN ('estimated', 'partial') THEN ${alias}.input_tokens ELSE 0 END), 0) AS estimatedInputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source IN ('estimated', 'partial') THEN ${alias}.output_tokens ELSE 0 END), 0) AS estimatedOutputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.input_source IN ('usage', 'estimated', 'partial') THEN ${alias}.input_tokens ELSE 0 END), 0) AS inputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source IN ('usage', 'estimated', 'partial') THEN ${alias}.output_tokens ELSE 0 END), 0) AS outputTokens,\n COALESCE(SUM(${alias}.cache_read_tokens), 0) AS cacheReadTokens,\n COALESCE(SUM(${alias}.cache_write_tokens), 0) AS cacheWriteTokens,\n SUM(${alias}.cost_usd) AS estimatedCostUsd,\n SUM(CASE WHEN ${alias}.observation_incomplete = 1 AND ${alias}.output_source = 'usage' THEN 1 ELSE 0 END) AS partialOutputs,\n COUNT(DISTINCT ${alias}.request_id) AS logicalRequests,\n COUNT(*) AS upstreamAttempts,\n SUM(${alias}.observation_incomplete) AS observationIncompleteAttempts,\n SUM(${alias}.input_source = 'usage') AS inputAuthorityOfficial,\n 0 AS inputAuthorityLocal, SUM(${alias}.input_source = 'estimated') AS inputAuthorityHeuristic,\n SUM(${alias}.input_source = 'partial') AS inputAuthorityPartial, SUM(${alias}.input_source = 'unknown') AS inputAuthorityNone,\n SUM(${alias}.output_source = 'usage') AS outputAuthorityOfficial,\n 0 AS outputAuthorityLocal, SUM(${alias}.output_source = 'estimated') AS outputAuthorityHeuristic,\n SUM(${alias}.output_source = 'partial') AS outputAuthorityPartial, SUM(${alias}.output_source = 'unknown') AS outputAuthorityNone`;\n if (input.groupBy === 'time' && (!Number.isSafeInteger(input.bucketMs) || input.bucketMs! <= 0)) {\n throw new Error('invalid token-stats bucketMs');\n }\n if (input.bucketStarts && (!input.bucketStarts.length || input.bucketStarts.length > 31\n || input.bucketStarts.some((start, i, starts) => !Number.isSafeInteger(start) || start < 0 || i > 0 && start <= starts[i - 1]!))) {\n throw new Error('invalid token-stats bucketStarts');\n }\n const { index, where, params } = attemptWindow(input);\n const origin = input.bucketStarts?.[0] ?? 0;\n const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs!);\n const bucketStart = input.groupBy !== 'time' ? 'NULL' : uniform\n ? `CAST((attempt.finished_at_ms - ${origin}) / ${input.bucketMs} AS INTEGER) * ${input.bucketMs} + ${origin}`\n : `CASE ${[...input.bucketStarts!].reverse().map(start => `WHEN attempt.finished_at_ms >= ${start} THEN ${start}`).join(' ')} END`;\n const groupColumns = input.groupBy === 'time' ? `attempt.model, bucketStartMs` : 'attempt.model';\n const grouped = `\n UNION ALL\n SELECT 'data' AS kind, attempt.model AS dimension, ${bucketStart} AS bucketStartMs, ${metrics('attempt')}, 0 AS present\n FROM window_rows AS attempt GROUP BY ${groupColumns}`;\n return {\n sql: `\n WITH window_rows AS MATERIALIZED (\n SELECT * FROM token_stats_attempts INDEXED BY ${index}\n WHERE ${where}\n )\n SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics('attempt')}, (COUNT(*) > 0) AS present\n FROM window_rows AS attempt\n ${grouped}\n ORDER BY kind, bucketStartMs, dimension\n `,\n missingSql: `\n SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs\n FROM token_stats_attempts AS attempt INDEXED BY ${index}\n WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))\n `,\n params,\n };\n}\n\nfunction validateTokenStatsAttempt(row: TokenStatsAttempt): void {\n if (!row || typeof row !== 'object' || Array.isArray(row)) throw new Error('invalid token-stats attempt');\n for (const key of ['attempt_id', 'request_id', 'route_id', 'upstream_id', 'provider', 'outcome', 'model'] as const) {\n if (typeof row[key] !== 'string' || row[key].length === 0) throw new Error(`invalid token-stats ${key}`);\n }\n if (row.key_id != null && (typeof row.key_id !== 'string' || !row.key_id || row.key_id.length > 128)) throw new Error('invalid token-stats key_id');\n validateTokenStatsTimestamp(row.finished_at_ms, 'finished_at_ms');\n for (const [key, value] of [\n ['input_tokens', row.input_tokens], ['output_tokens', row.output_tokens],\n ['cache_read_tokens', row.cache_read_tokens], ['cache_write_tokens', row.cache_write_tokens],\n ] as const) {\n if (value !== null && (!Number.isSafeInteger(value) || value < 0)) throw new Error(`invalid token-stats ${key}`);\n }\n if (row.cost_usd !== null && (!Number.isFinite(row.cost_usd) || row.cost_usd < 0)) throw new Error('invalid token-stats cost_usd');\n if (!isTokenStatsSource(row.input_source) || !isTokenStatsSource(row.output_source)) throw new Error('invalid token-stats value source');\n if (typeof row.observation_incomplete !== 'boolean') throw new Error('invalid token-stats observation_incomplete');\n if ((row.input_source === 'unknown') !== (row.input_tokens === null)\n || (row.output_source === 'unknown') !== (row.output_tokens === null)) throw new Error('token-stats value/source mismatch');\n}\n\nfunction isTokenStatsSource(value: unknown): value is TokenStatsValueSource {\n return value === 'usage' || value === 'estimated' || value === 'partial' || value === 'unknown';\n}\n\nfunction validateTokenStatsTimestamp(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error(`invalid token-stats ${name}`);\n const now = Date.now();\n if (value < now - TOKEN_STATS_RETENTION_MS) throw new RangeError(`token-stats ${name} exceeds 31-day retention`);\n if (value > now + TOKEN_STATS_MAX_FUTURE_SKEW_MS) throw new RangeError(`token-stats ${name} is too far in the future`);\n}\n\n\n/** Reporting writes have a short lock deadline and never retain a changed connection pragma. */\nexport function withReportingWriteTimeout<T>(db: Database, operation: () => T): T {\n const busyTimeout = db.query<{ timeout: number }, []>('PRAGMA busy_timeout').get()?.timeout;\n if (!Number.isSafeInteger(busyTimeout) || busyTimeout! < 0) throw new Error('unable to read SQLite busy_timeout');\n try {\n db.run(`PRAGMA busy_timeout = ${TOKEN_STATS_BUSY_TIMEOUT_MS}`);\n return operation();\n } finally {\n db.run(`PRAGMA busy_timeout = ${busyTimeout}`);\n }\n}\n",
20
+ "import type { Database } from 'bun:sqlite';\nimport type { PluginStorage, PluginObservationStorage, TokenStatsAttempt, TokenStatsGroupBy, TokenStatsMeteringStorage,\n TokenStatsMetricName, TokenStatsSnapshotMetrics, TokenStatsValueSource, TokenStatsRange } from '@jeffusion/bungee-core/plugin';\nimport { TOKEN_STATS_RETENTION_MS, TOKEN_STATS_RANGES, tokenStatsWindow } from '@jeffusion/bungee-core/plugin';\nimport type { ModelsDevModelMatch } from '../../models-dev/contract';\nimport { costNanoUsdOf, costOf } from './pricing';\n\n/** Explicit assembly for legacy fixtures and embedders; the host never checks a business name. */\nexport function withTokenStatsMetering<T extends PluginStorage>(storage: T): T & { metering: SQLiteTokenStatsMetering } {\n if (!storage.observation) throw new Error('token-stats metering storage is required');\n return Object.assign(storage, { metering: new SQLiteTokenStatsMetering(storage.observation) });\n}\n\nconst TOKEN_STATS_METRICS: readonly TokenStatsMetricName[] = [\n 'inputTokens', 'outputTokens', 'officialInputTokens', 'officialOutputTokens',\n 'estimatedInputTokens', 'estimatedOutputTokens', 'cacheReadTokens', 'cacheWriteTokens',\n 'partialOutputs', 'logicalRequests', 'upstreamAttempts', 'observationIncompleteAttempts',\n 'inputAuthorityOfficial', 'inputAuthorityLocal', 'inputAuthorityHeuristic', 'inputAuthorityPartial', 'inputAuthorityNone',\n 'outputAuthorityOfficial', 'outputAuthorityLocal', 'outputAuthorityHeuristic', 'outputAuthorityPartial', 'outputAuthorityNone',\n];\nconst TOKEN_STATS_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;\nconst TOKEN_STATS_BUSY_TIMEOUT_MS = 5;\n\nconst EMPTY_METRICS: Record<TokenStatsMetricName, number> = Object.fromEntries(\n TOKEN_STATS_METRICS.map((name) => [name, 0]),\n) as Record<TokenStatsMetricName, number>;\n\ntype WindowQuery = Parameters<TokenStatsMeteringStorage['queryWindowSnapshot']>[0];\ntype QueryPricing = {\n throughRow: number;\n prices: readonly (readonly [string, ModelsDevModelMatch])[];\n};\ntype UnpricedUsage = Pick<TokenStatsAttempt, 'model' | 'input_tokens' | 'output_tokens' | 'cache_read_tokens' | 'cache_write_tokens'> & {\n bucketStartMs: number | null;\n};\nconst PRICEABLE_USAGE = `cost_usd IS NULL AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL AND model <> 'unknown'`;\n\nexport class SQLiteTokenStatsMetering implements TokenStatsMeteringStorage {\n constructor(private readonly observation: PluginObservationStorage) {}\n\n async recordAttempt(row: TokenStatsAttempt, deadlineAt?: number): Promise<void> {\n row = { ...row };\n let remainingMs: () => number;\n if (deadlineAt === undefined) {\n const directDeadline = performance.now() + 50;\n remainingMs = () => directDeadline - performance.now();\n } else {\n if (!Number.isSafeInteger(deadlineAt)) throw new Error('invalid token-stats write deadline');\n const budget = this.observation.writeBudgetMs?.(deadlineAt);\n if (!budget) throw new Error('token-stats write deadline clock unavailable');\n remainingMs = budget;\n }\n const requireWriteBudget = () => {\n if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS) throw new Error('token-stats write deadline expired');\n };\n requireWriteBudget();\n const maxAttempts = deadlineAt === undefined ? 8 : Infinity;\n for (let attempt = 1; ; attempt++) {\n const busy = await this.observation.withDatabase((db) => {\n validateTokenStatsAttempt(row);\n const transaction = db.transaction(() => {\n if (deadlineAt !== undefined) requireWriteBudget();\n db.query(`\n INSERT OR IGNORE INTO token_stats_attempts (\n attempt_id, request_id, finished_at_ms, route_id, upstream_id, provider, outcome, model, key_id,\n input_tokens, output_tokens, input_source, output_source,\n cache_read_tokens, cache_write_tokens, cost_usd, observation_incomplete\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n row.attempt_id, row.request_id, row.finished_at_ms, row.route_id, row.upstream_id, row.provider,\n row.outcome, row.model, row.key_id ?? null, row.input_tokens, row.output_tokens, row.input_source, row.output_source,\n row.cache_read_tokens, row.cache_write_tokens, row.cost_usd, row.observation_incomplete ? 1 : 0,\n );\n // A fixed one-batch cleanup keeps the write transaction bounded.\n db.query(`\n DELETE FROM token_stats_attempts WHERE attempt_id IN (\n SELECT attempt_id FROM token_stats_attempts INDEXED BY idx_token_stats_attempts_finished\n WHERE finished_at_ms < ? ORDER BY finished_at_ms LIMIT 500\n )\n `).run(Date.now() - TOKEN_STATS_RETENTION_MS);\n if (deadlineAt !== undefined) requireWriteBudget();\n });\n return withReportingWriteTimeout(db, () => {\n try { transaction.immediate(); }\n catch (error) {\n if (error instanceof Error && error.name === 'SQLiteError' && 'code' in error\n && error.code === 'SQLITE_BUSY' && db.inTransaction === false) return error;\n throw error;\n }\n });\n });\n if (!busy) return;\n if (attempt === maxAttempts || remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS) throw busy;\n await new Promise<void>(resolve => setTimeout(resolve, 0));\n if (remainingMs() < TOKEN_STATS_BUSY_TIMEOUT_MS) throw busy;\n }\n }\n\n async queryPricingModels(input: WindowQuery): Promise<{ models: string[]; throughRow: number }> {\n const window = queryBounds(input);\n return this.observation.withDatabase((db) => db.transaction(() => {\n // Do not include newly inserted rows between the model lookup and the priced query.\n const { throughRow } = db.query<{ throughRow: number }, []>(\n 'SELECT COALESCE(MAX(rowid), 0) AS throughRow FROM token_stats_attempts',\n ).get()!;\n const { index, where, params } = attemptWindow({ ...window, throughRow });\n const rows = db.query<{ model: string }, (number | string)[]>(`\n SELECT DISTINCT model FROM token_stats_attempts INDEXED BY ${index}\n WHERE ${where} AND ${PRICEABLE_USAGE}\n `).all(...params);\n return { models: rows.map(row => row.model), throughRow };\n }).deferred());\n }\n\n async queryWindowSnapshot(input: WindowQuery & { pricing?: QueryPricing }): Promise<{\n all: TokenStatsSnapshotMetrics;\n data: Array<{ dimension: string; bucketStartMs?: number; metrics: TokenStatsSnapshotMetrics }>;\n bucketMs?: number;\n bucketStarts?: number[];\n bucketEndMs?: number;\n present: boolean;\n }> {\n const window = queryBounds(input);\n const { bucketMs, bucketStarts, bucketEndMs } = window;\n const pricing = input.pricing;\n const { sql, params, missingSql } = buildTokenStatsWindowSnapshotQuery({ ...window, throughRow: pricing?.throughRow });\n return this.observation.withDatabase((db) => {\n const read = () => {\n const rows = db.query<Record<string, number | string | null>, (number | string)[]>(sql).all(...params);\n if (!pricing?.prices.length) return rows;\n const prices = new Map(pricing.prices);\n const missing = db.query<UnpricedUsage, (number | string)[]>(missingSql)\n .iterate(...params, JSON.stringify([...prices.keys()]));\n const byGroup = new Map<string, number>();\n let total: number | undefined;\n for (const row of missing) {\n const nano = costNanoUsdOf(costOf(prices.get(row.model)!, {\n inputTokens: row.input_tokens ?? undefined, outputTokens: row.output_tokens ?? undefined,\n cacheReadTokens: row.cache_read_tokens ?? undefined, cacheWriteTokens: row.cache_write_tokens ?? undefined,\n }));\n if (nano === null) continue;\n const cost = nano / 1e9;\n total = (total ?? 0) + cost;\n const key = JSON.stringify([row.model, row.bucketStartMs]);\n byGroup.set(key, (byGroup.get(key) ?? 0) + cost);\n }\n for (const row of rows) {\n const extra = row.kind === 'all' ? total : byGroup.get(JSON.stringify([row.dimension, row.bucketStartMs]));\n if (extra !== undefined) row.estimatedCostUsd = Number(row.estimatedCostUsd ?? 0) + extra;\n }\n return rows;\n };\n const rows = pricing?.prices.length ? db.transaction(read).deferred() : read();\n const allRow = rows.find((row) => row.kind === 'all');\n const dataRows = rows.filter((row) => row.kind === 'data');\n const metrics = (row: Record<string, number | string | null> | undefined): TokenStatsSnapshotMetrics => {\n const base = !row ? { ...EMPTY_METRICS } : Object.fromEntries(TOKEN_STATS_METRICS.map((key) => {\n const value = Number(row[key] ?? 0);\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`invalid token-stats aggregate: ${key}`);\n return [key, value];\n })) as Record<TokenStatsMetricName, number>;\n const rawCost = row?.estimatedCostUsd;\n const estimatedCostUsd = rawCost === undefined || rawCost === null ? null : Number(rawCost);\n if (estimatedCostUsd !== null && (!Number.isFinite(estimatedCostUsd) || estimatedCostUsd < 0)) {\n throw new RangeError('invalid token-stats aggregate: estimatedCostUsd');\n }\n return { ...base, estimatedCostUsd };\n };\n return {\n all: metrics(allRow),\n data: dataRows.map((row) => ({\n dimension: String(row.dimension),\n ...(input.groupBy === 'time' ? { bucketStartMs: Number(row.bucketStartMs) } : {}),\n metrics: metrics(row),\n })),\n ...(bucketMs === undefined ? {} : { bucketMs }),\n ...(bucketStarts === undefined ? {} : { bucketStarts }),\n ...(bucketEndMs === undefined ? {} : { bucketEndMs }),\n present: Number(allRow?.present ?? 0) === 1,\n };\n });\n }\n async listClientModels(input: {page?:number;pageSize?:number;keyword?:string}) {\n const page=input.page ?? 1,pageSize=input.pageSize ?? 20,keyword=input.keyword;\n if(!Number.isSafeInteger(page)||page<1||page>400||!Number.isSafeInteger(pageSize)||pageSize<1||pageSize>100\n || keyword!==undefined&&(typeof keyword!=='string'||keyword.length>256))throw new Error('invalid token-stats client models page');\n const since=Date.now()-TOKEN_STATS_RETENTION_MS;\n const search=keyword ? `%${keyword.replace(/[\\\\%_]/g, character=>`\\\\${character}`)}%` : null;\n return this.observation.withDatabase(db=>{\n const filter=search ? \" AND model LIKE ? ESCAPE '\\\\'\" : '';\n const params:(string|number)[]=search ? [since,search] : [since];\n const total=Number(db.query<{total:number},(string|number)[]>(`SELECT COUNT(DISTINCT model) AS total FROM token_stats_attempts WHERE finished_at_ms >= ?${filter}`).get(...params)?.total ?? 0);\n const rows=db.query<{model:string},(string|number)[]>(`SELECT DISTINCT model FROM token_stats_attempts WHERE finished_at_ms >= ?${filter} ORDER BY model ASC LIMIT ? OFFSET ?`).all(...params,pageSize,(page-1)*pageSize);\n return {models:rows.map(row=>String(row.model)),total:Number.isSafeInteger(total)&&total>=0 ? total : 0,page,pageSize};\n });\n }\n\n}\n\nfunction queryBounds(input: WindowQuery) {\n validateTokenStatsTimestamp(input.asOfMs, 'asOfMs');\n if (!(TOKEN_STATS_RANGES as readonly string[]).includes(input.range)) throw new Error('invalid token-stats range');\n if (!['model', 'time'].includes(input.groupBy)) throw new Error('invalid token-stats groupBy');\n const window = tokenStatsWindow(input.range, input.asOfMs, input.timeZone);\n return {\n ...window,\n startMs: Math.max(window.startMs, Date.now() - TOKEN_STATS_RETENTION_MS),\n groupBy: input.groupBy,\n bucketMs: input.groupBy === 'time' ? window.bucketMs : undefined,\n bucketStarts: input.groupBy === 'time' ? window.bucketStarts : undefined,\n bucketEndMs: input.groupBy === 'time' ? window.bucketEndMs : undefined,\n keyId: input.keyId,\n };\n}\n\nfunction attemptWindow(input: { startMs: number; endMs: number; keyId?: string; throughRow?: number }) {\n const { startMs, endMs, keyId, throughRow } = input;\n if (keyId !== undefined && (typeof keyId !== 'string' || !keyId || keyId.length > 128)) throw new Error('invalid token-stats keyId');\n if (throughRow !== undefined && (!Number.isSafeInteger(throughRow) || throughRow < 0)) throw new Error('invalid token-stats row boundary');\n const keyFilter = keyId === undefined ? '' : keyId === '__unattributed__' ? ' AND key_id IS NULL' : ' AND key_id = ?';\n return {\n index: keyId === undefined ? 'idx_token_stats_attempts_finished' : 'idx_token_stats_attempts_key_finished',\n where: `finished_at_ms >= ? AND finished_at_ms < ?${keyFilter}${throughRow === undefined ? '' : ' AND rowid <= ?'}`,\n params: [startMs, endMs, ...(keyId !== undefined && keyId !== '__unattributed__' ? [keyId] : []), ...(throughRow === undefined ? [] : [throughRow])],\n };\n}\n\nexport function buildTokenStatsWindowSnapshotQuery(input: {\n startMs: number;\n endMs: number;\n groupBy: TokenStatsGroupBy;\n bucketMs?: number;\n bucketStarts?: readonly number[];\n keyId?: string;\n throughRow?: number;\n}): { sql: string; missingSql: string; params: (number | string)[] } {\n const metrics = (alias: string) => `\n COALESCE(SUM(CASE WHEN ${alias}.input_source = 'usage' THEN ${alias}.input_tokens ELSE 0 END), 0) AS officialInputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source = 'usage' THEN ${alias}.output_tokens ELSE 0 END), 0) AS officialOutputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.input_source IN ('estimated', 'partial') THEN ${alias}.input_tokens ELSE 0 END), 0) AS estimatedInputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source IN ('estimated', 'partial') THEN ${alias}.output_tokens ELSE 0 END), 0) AS estimatedOutputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.input_source IN ('usage', 'estimated', 'partial') THEN ${alias}.input_tokens ELSE 0 END), 0) AS inputTokens,\n COALESCE(SUM(CASE WHEN ${alias}.output_source IN ('usage', 'estimated', 'partial') THEN ${alias}.output_tokens ELSE 0 END), 0) AS outputTokens,\n COALESCE(SUM(${alias}.cache_read_tokens), 0) AS cacheReadTokens,\n COALESCE(SUM(${alias}.cache_write_tokens), 0) AS cacheWriteTokens,\n SUM(${alias}.cost_usd) AS estimatedCostUsd,\n SUM(CASE WHEN ${alias}.observation_incomplete = 1 AND ${alias}.output_source = 'usage' THEN 1 ELSE 0 END) AS partialOutputs,\n COUNT(DISTINCT ${alias}.request_id) AS logicalRequests,\n COUNT(*) AS upstreamAttempts,\n SUM(${alias}.observation_incomplete) AS observationIncompleteAttempts,\n SUM(${alias}.input_source = 'usage') AS inputAuthorityOfficial,\n 0 AS inputAuthorityLocal, SUM(${alias}.input_source = 'estimated') AS inputAuthorityHeuristic,\n SUM(${alias}.input_source = 'partial') AS inputAuthorityPartial, SUM(${alias}.input_source = 'unknown') AS inputAuthorityNone,\n SUM(${alias}.output_source = 'usage') AS outputAuthorityOfficial,\n 0 AS outputAuthorityLocal, SUM(${alias}.output_source = 'estimated') AS outputAuthorityHeuristic,\n SUM(${alias}.output_source = 'partial') AS outputAuthorityPartial, SUM(${alias}.output_source = 'unknown') AS outputAuthorityNone`;\n if (input.groupBy === 'time' && (!Number.isSafeInteger(input.bucketMs) || input.bucketMs! <= 0)) {\n throw new Error('invalid token-stats bucketMs');\n }\n if (input.bucketStarts && (!input.bucketStarts.length || input.bucketStarts.length > 31\n || input.bucketStarts.some((start, i, starts) => !Number.isSafeInteger(start) || start < 0 || i > 0 && start <= starts[i - 1]!))) {\n throw new Error('invalid token-stats bucketStarts');\n }\n const { index, where, params } = attemptWindow(input);\n const origin = input.bucketStarts?.[0] ?? 0;\n const uniform = !input.bucketStarts || input.bucketStarts.every((start, i) => start === origin + i * input.bucketMs!);\n const bucketStart = input.groupBy !== 'time' ? 'NULL' : uniform\n ? `CAST((attempt.finished_at_ms - ${origin}) / ${input.bucketMs} AS INTEGER) * ${input.bucketMs} + ${origin}`\n : `CASE ${[...input.bucketStarts!].reverse().map(start => `WHEN attempt.finished_at_ms >= ${start} THEN ${start}`).join(' ')} END`;\n const groupColumns = input.groupBy === 'time' ? `attempt.model, bucketStartMs` : 'attempt.model';\n const grouped = `\n UNION ALL\n SELECT 'data' AS kind, attempt.model AS dimension, ${bucketStart} AS bucketStartMs, ${metrics('attempt')}, 0 AS present\n FROM window_rows AS attempt GROUP BY ${groupColumns}`;\n return {\n sql: `\n WITH window_rows AS MATERIALIZED (\n SELECT * FROM token_stats_attempts INDEXED BY ${index}\n WHERE ${where}\n )\n SELECT 'all' AS kind, 'all' AS dimension, NULL AS bucketStartMs, ${metrics('attempt')}, (COUNT(*) > 0) AS present\n FROM window_rows AS attempt\n ${grouped}\n ORDER BY kind, bucketStartMs, dimension\n `,\n missingSql: `\n SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, ${bucketStart} AS bucketStartMs\n FROM token_stats_attempts AS attempt INDEXED BY ${index}\n WHERE ${where} AND ${PRICEABLE_USAGE} AND model IN (SELECT value FROM json_each(?))\n `,\n params,\n };\n}\n\nfunction validateTokenStatsAttempt(row: TokenStatsAttempt): void {\n if (!row || typeof row !== 'object' || Array.isArray(row)) throw new Error('invalid token-stats attempt');\n for (const key of ['attempt_id', 'request_id', 'route_id', 'upstream_id', 'provider', 'outcome', 'model'] as const) {\n if (typeof row[key] !== 'string' || row[key].length === 0) throw new Error(`invalid token-stats ${key}`);\n }\n if (row.key_id != null && (typeof row.key_id !== 'string' || !row.key_id || row.key_id.length > 128)) throw new Error('invalid token-stats key_id');\n validateTokenStatsTimestamp(row.finished_at_ms, 'finished_at_ms');\n for (const [key, value] of [\n ['input_tokens', row.input_tokens], ['output_tokens', row.output_tokens],\n ['cache_read_tokens', row.cache_read_tokens], ['cache_write_tokens', row.cache_write_tokens],\n ] as const) {\n if (value !== null && (!Number.isSafeInteger(value) || value < 0)) throw new Error(`invalid token-stats ${key}`);\n }\n if (row.cost_usd !== null && (!Number.isFinite(row.cost_usd) || row.cost_usd < 0)) throw new Error('invalid token-stats cost_usd');\n if (!isTokenStatsSource(row.input_source) || !isTokenStatsSource(row.output_source)) throw new Error('invalid token-stats value source');\n if (typeof row.observation_incomplete !== 'boolean') throw new Error('invalid token-stats observation_incomplete');\n if ((row.input_source === 'unknown') !== (row.input_tokens === null)\n || (row.output_source === 'unknown') !== (row.output_tokens === null)) throw new Error('token-stats value/source mismatch');\n}\n\nfunction isTokenStatsSource(value: unknown): value is TokenStatsValueSource {\n return value === 'usage' || value === 'estimated' || value === 'partial' || value === 'unknown';\n}\n\nfunction validateTokenStatsTimestamp(value: number, name: string): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error(`invalid token-stats ${name}`);\n const now = Date.now();\n if (value < now - TOKEN_STATS_RETENTION_MS) throw new RangeError(`token-stats ${name} exceeds 31-day retention`);\n if (value > now + TOKEN_STATS_MAX_FUTURE_SKEW_MS) throw new RangeError(`token-stats ${name} is too far in the future`);\n}\n\n\n/** Reporting writes have a short lock deadline and never retain a changed connection pragma. */\nexport function withReportingWriteTimeout<T>(db: Database, operation: () => T): T {\n const busyTimeout = db.query<{ timeout: number }, []>('PRAGMA busy_timeout').get()?.timeout;\n if (!Number.isSafeInteger(busyTimeout) || busyTimeout! < 0) throw new Error('unable to read SQLite busy_timeout');\n try {\n db.run(`PRAGMA busy_timeout = ${TOKEN_STATS_BUSY_TIMEOUT_MS}`);\n return operation();\n } finally {\n db.run(`PRAGMA busy_timeout = ${busyTimeout}`);\n }\n}\n",
21
21
  "import type { PluginStorage } from '@jeffusion/bungee-core/plugin';\n\n/** Pricing aliases never rewrite a request or the recorded model name. */\nexport interface PriceModelMapping { source: string; provider: string; model: string }\nexport interface PriceModelOption { provider: string; providerName: string; model: string; name: string }\nexport const PRICE_MODEL_MAPPINGS_KEY = 'pricing:model-mappings:v1';\nexport const MAX_PRICE_MODEL_MAPPINGS = 100;\n\n/** SQLite KV get() is best-effort and hides failures; pricing aliases need strict reads. */\nexport async function readPriceModelMappings(storage: PluginStorage): Promise<PriceModelMapping[]> {\n if (!storage.readStrict) throw new Error('token-stats strict storage capability is required');\n const result = await storage.readStrict(PRICE_MODEL_MAPPINGS_KEY);\n return parsePriceModelMappings(result.found ? result.value : []);\n}\n\nexport function isUnchangedPriceModelMapping(mapping: PriceModelMapping, existing: readonly PriceModelMapping[]): boolean {\n return existing.some(item => item.source === mapping.source && item.provider === mapping.provider && item.model === mapping.model);\n}\n\nexport function parsePriceModelMappings(value: unknown): PriceModelMapping[] {\n if (!Array.isArray(value) || value.length > MAX_PRICE_MODEL_MAPPINGS) throw new Error('invalid_input');\n const sources = new Set<string>();\n return value.map(item => {\n if (!item || typeof item !== 'object' || Array.isArray(item)\n || Object.keys(item).some(key => !['source', 'provider', 'model'].includes(key))) throw new Error('invalid_input');\n const { source, provider, model } = item;\n for (const [text, limit] of [[source, 256], [provider, 128], [model, 256]] as const) {\n if (typeof text !== 'string' || !text.trim() || text !== text.trim() || text.length > limit\n || /[\\u0000-\\u001f\\u007f]/.test(text)) throw new Error('invalid_input');\n }\n if (sources.has(source)) throw new Error('invalid_input');\n sources.add(source);\n return { source, provider, model };\n });\n}\n",
22
- "import type {\n PluginStorage,\n TokenStatsAttempt,\n TokenStatsMetricName,\n TokenStatsMeteringStorage,\n TokenStatsSnapshotMetrics,\n TokenStatsRange,\n} from '@jeffusion/bungee-core/plugin';\nimport type { CanonicalTokenAccountingEventV2 } from '@jeffusion/bungee-llms/plugin-api';\nimport type { ModelsDevCatalogService, ModelsDevModelMatch } from '../../models-dev/contract';\n// The control artifact needs only authority names, not the worker conversion runtime.\nconst TOKEN_ACCOUNTING_AUTHORITIES = ['official', 'local', 'heuristic', 'partial', 'none'] as const satisfies readonly CanonicalTokenAccountingEventV2['inputAuthority'][];\nimport { SQLiteTokenStatsMetering } from './storage';\nimport { TOKEN_STATS_RANGES, TOKEN_STATS_RETENTION_MS } from '@jeffusion/bungee-core/plugin';\nimport { PRICE_MODEL_MAPPINGS_KEY, readPriceModelMappings, type PriceModelMapping } from './model-mappings';\n\nexport type GroupByDimension = 'model' | 'time';\ntype TokenAccountingAuthority = typeof TOKEN_ACCOUNTING_AUTHORITIES[number];\nexport type CanonicalEvent = CanonicalTokenAccountingEventV2;\n\nexport interface AuthorityBreakdownDto {\n input: Record<TokenAccountingAuthority, number>;\n output: Record<TokenAccountingAuthority, number>;\n}\n\nexport interface GroupedAggregateDto {\n dimension: string;\n bucketStartMs?: number;\n inputTokens: number;\n outputTokens: number;\n officialInputTokens: number;\n officialOutputTokens: number;\n estimatedInputTokens: number;\n estimatedOutputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n partialOutputs: number;\n logicalRequests: number;\n upstreamAttempts: number;\n observationIncompleteAttempts: number;\n estimatedCostUsd: number | null;\n authorityBreakdown: AuthorityBreakdownDto;\n}\n\nexport interface AggregateDto extends Omit<GroupedAggregateDto, 'dimension' | 'bucketStartMs' | 'inputTokens' | 'outputTokens'> {\n /** Sticky evidence of dropped or failed reporting, shared across worker/control processes. */\n reportingIncomplete: boolean;\n groupBy: GroupByDimension;\n asOfMs: number;\n bucketMs?: number;\n bucketStarts?: number[];\n bucketEndMs?: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n data: GroupedAggregateDto[];\n}\n\nexport class TokenStatsRepositoryError extends Error {\n constructor(message: string) { super(message); this.name = 'TokenStatsRepositoryError'; }\n}\n\nexport class TokenStatsRepositoryLimitError extends TokenStatsRepositoryError {}\n\nexport interface ClientModelPage {\n /** Distinct raw client/attempt model names, exactly as recorded (original case). */\n models: string[];\n total: number;\n page: number;\n pageSize: number;\n}\n\nexport const MAX_CLIENT_MODEL_PAGE_SIZE = 100;\nexport const MAX_CLIENT_MODEL_PAGE = 400;\nconst CLIENT_MODEL_KEYWORD_MAX = 256;\n\nexport const REPORTING_INCOMPLETE_KEY = 'reporting:incomplete';\n\ntype MeteringLogger = { onFailure?(): void; warn(message: string, metadata?: object): void; error(message: string, metadata?: object): void };\ntype AttemptTask = () => TokenStatsAttempt | undefined | Promise<TokenStatsAttempt | undefined>;\ntype QueuedAttempt = { metering: TokenStatsMeteringStorage; task: AttemptTask; logger: MeteringLogger };\n\nconst MAX_PENDING_ATTEMPTS = 256;\nconst LOG_INTERVAL_MS = 60_000;\nconst pendingAttempts: QueuedAttempt[] = [];\nlet pendingCount = 0;\nlet drainTimer: ReturnType<typeof setTimeout> | undefined;\nlet draining = false;\nlet lastDropLogAt = 0;\nlet lastFailureLogAt = 0;\n\nfunction logRateLimited(logger: MeteringLogger, kind: 'drop' | 'failure', error?: unknown): void {\n try { logger.onFailure?.(); } catch { /* failure reporting must not affect proxy flow */ }\n const now = Date.now();\n if (kind === 'drop') {\n if (now - lastDropLogAt < LOG_INTERVAL_MS) return;\n lastDropLogAt = now;\n try { logger.warn('Token stats attempt queue full; dropping metering rows', { capacity: MAX_PENDING_ATTEMPTS }); } catch { /* logging must not affect proxy flow */ }\n return;\n }\n if (now - lastFailureLogAt < LOG_INTERVAL_MS) return;\n lastFailureLogAt = now;\n try {\n logger.error('Token stats attempt processing failed; dropping metering row', {\n error: error instanceof Error ? error.message : error === undefined ? 'attempt task returned no row' : String(error),\n });\n } catch { /* logging must not affect proxy flow */ }\n}\n\nfunction scheduleDrain(): void {\n if (drainTimer !== undefined || draining) return;\n drainTimer = setTimeout(() => { drainTimer = undefined; void drainOneAttempt(); }, 0);\n}\n\nasync function drainOneAttempt(): Promise<void> {\n if (draining) return;\n const item = pendingAttempts.shift();\n if (!item) return;\n draining = true;\n try {\n try {\n const row = await item.task();\n if (row === undefined) {\n logRateLimited(item.logger, 'failure');\n } else {\n await item.metering.recordAttempt(row);\n }\n } catch (error) {\n logRateLimited(item.logger, 'failure', error);\n }\n } finally {\n pendingCount--;\n draining = false;\n if (pendingAttempts.length) scheduleDrain();\n }\n}\n\nconst METRIC_FIELDS: readonly TokenStatsMetricName[] = [\n 'inputTokens', 'outputTokens', 'officialInputTokens', 'officialOutputTokens',\n 'estimatedInputTokens', 'estimatedOutputTokens', 'cacheReadTokens', 'cacheWriteTokens',\n 'partialOutputs', 'logicalRequests', 'upstreamAttempts', 'observationIncompleteAttempts',\n 'inputAuthorityOfficial', 'inputAuthorityLocal', 'inputAuthorityHeuristic', 'inputAuthorityPartial', 'inputAuthorityNone',\n 'outputAuthorityOfficial', 'outputAuthorityLocal', 'outputAuthorityHeuristic', 'outputAuthorityPartial', 'outputAuthorityNone',\n];\n\nfunction emptyMetrics(): TokenStatsSnapshotMetrics {\n return { ...Object.fromEntries(METRIC_FIELDS.map((key) => [key, 0])) as Record<TokenStatsMetricName, number>, estimatedCostUsd: null };\n}\n\nfunction emptyAuthorityBreakdown(): AuthorityBreakdownDto {\n const empty = () => Object.fromEntries(TOKEN_ACCOUNTING_AUTHORITIES.map((authority) => [authority, 0])) as Record<TokenAccountingAuthority, number>;\n return { input: empty(), output: empty() };\n}\n\nfunction metricsToDto(metrics: TokenStatsSnapshotMetrics): Omit<GroupedAggregateDto, 'dimension'> {\n const authorityBreakdown = emptyAuthorityBreakdown();\n for (const authority of TOKEN_ACCOUNTING_AUTHORITIES) {\n authorityBreakdown.input[authority] = metrics[`inputAuthority${authority[0]!.toUpperCase()}${authority.slice(1)}` as TokenStatsMetricName];\n authorityBreakdown.output[authority] = metrics[`outputAuthority${authority[0]!.toUpperCase()}${authority.slice(1)}` as TokenStatsMetricName];\n }\n return {\n inputTokens: metrics.inputTokens,\n outputTokens: metrics.outputTokens,\n officialInputTokens: metrics.officialInputTokens,\n officialOutputTokens: metrics.officialOutputTokens,\n estimatedInputTokens: metrics.estimatedInputTokens,\n estimatedOutputTokens: metrics.estimatedOutputTokens,\n cacheReadTokens: metrics.cacheReadTokens,\n cacheWriteTokens: metrics.cacheWriteTokens,\n partialOutputs: metrics.partialOutputs,\n logicalRequests: metrics.logicalRequests,\n upstreamAttempts: metrics.upstreamAttempts,\n observationIncompleteAttempts: metrics.observationIncompleteAttempts,\n estimatedCostUsd: metrics.estimatedCostUsd,\n authorityBreakdown,\n };\n}\n\nfunction sourceFor(value: number | undefined, authority: CanonicalTokenAccountingEventV2['inputAuthority']): TokenStatsAttempt['input_source'] {\n if (!Number.isSafeInteger(value) || value! < 0) return 'unknown';\n if (authority === 'official') return 'usage';\n if (authority === 'partial') return 'partial';\n return authority === 'none' ? 'unknown' : 'estimated';\n}\n\nexport function attemptRowFromEvent(\n event: CanonicalEvent,\n finishedAtMs: number,\n observationIncomplete: boolean,\n model: string,\n): TokenStatsAttempt {\n const inputSource = sourceFor(event.inputTokens, event.inputAuthority);\n const outputSource = sourceFor(event.outputTokens, event.outputAuthority);\n return {\n attempt_id: event.attemptId,\n request_id: event.requestId,\n finished_at_ms: finishedAtMs,\n route_id: event.routeId || 'unknown',\n upstream_id: event.upstreamId || 'unknown',\n provider: event.provider || 'unknown',\n outcome: event.outcome,\n model,\n input_tokens: inputSource === 'unknown' ? null : event.inputTokens!,\n output_tokens: outputSource === 'unknown' ? null : event.outputTokens!,\n input_source: inputSource,\n output_source: outputSource,\n cache_read_tokens: Number.isSafeInteger(event.cacheReadTokens) && event.cacheReadTokens! >= 0 ? event.cacheReadTokens! : null,\n cache_write_tokens: Number.isSafeInteger(event.cacheWriteTokens) && event.cacheWriteTokens! >= 0 ? event.cacheWriteTokens! : null,\n cost_usd: null,\n observation_incomplete: observationIncomplete,\n };\n}\n\nexport class TokenStatsRepository {\n private readonly metering: TokenStatsMeteringStorage & Partial<Pick<SQLiteTokenStatsMetering, 'queryPricingModels'>>;\n\n constructor(private readonly storage: PluginStorage) {\n if (!storage.metering && !storage.observation) throw new TokenStatsRepositoryError('token-stats metering storage is required');\n this.metering = storage.metering ?? new SQLiteTokenStatsMetering(storage.observation!);\n }\n\n /** Defers synchronous task work to drain; a task can still occupy the EventLoop. */\n enqueueAttempt(task: AttemptTask, logger: MeteringLogger): boolean {\n if (pendingCount >= MAX_PENDING_ATTEMPTS) {\n logRateLimited(logger, 'drop');\n return false;\n }\n pendingAttempts.push({ metering: this.metering, task, logger });\n pendingCount++;\n scheduleDrain();\n return true;\n }\n\n async query(range: string, groupBy: GroupByDimension, asOfMs = Date.now(), timeZone?: string, keyId?: string, catalog?: ModelsDevCatalogService): Promise<AggregateDto> {\n if (!(TOKEN_STATS_RANGES as readonly string[]).includes(range)) throw new TokenStatsRepositoryError('invalid token-stats range');\n if (groupBy !== 'model' && groupBy !== 'time') {\n throw new TokenStatsRepositoryError('invalid token-stats groupBy');\n }\n if (!Number.isSafeInteger(asOfMs) || asOfMs < 0) throw new TokenStatsRepositoryError('invalid token-stats asOfMs');\n const window = { asOfMs, range: range as TokenStatsRange, groupBy, timeZone, keyId };\n let input: Parameters<SQLiteTokenStatsMetering['queryWindowSnapshot']>[0] = window;\n if (catalog && this.metering.queryPricingModels) {\n const mappings = await this.mappings().catch(() => undefined);\n if (mappings) {\n const { models, throughRow } = await this.metering.queryPricingModels(window);\n const bySource = new Map(mappings.map(mapping => [mapping.source, mapping]));\n const prices: Array<[string, ModelsDevModelMatch]> = [];\n for (const model of models) {\n const mapped = bySource.get(model);\n // Stored wire protocol is not a pricing provider. Only resolve explicit mappings or exact catalog matches.\n const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });\n if (price !== null) prices.push([model, price]);\n }\n input = { ...window, pricing: { throughRow, prices } };\n }\n }\n const snapshot = await this.metering.queryWindowSnapshot(input);\n const total = metricsToDto(snapshot.all);\n const { inputTokens, outputTokens, ...summary } = total;\n return {\n reportingIncomplete: await (this.storage.uncached?.() ?? this.storage).get(REPORTING_INCOMPLETE_KEY) === true,\n groupBy,\n asOfMs,\n ...summary,\n totalInputTokens: inputTokens,\n totalOutputTokens: outputTokens,\n ...(snapshot.bucketMs === undefined ? {} : { bucketMs: snapshot.bucketMs }),\n ...(snapshot.bucketStarts === undefined ? {} : { bucketStarts: snapshot.bucketStarts }),\n ...(snapshot.bucketEndMs === undefined ? {} : { bucketEndMs: snapshot.bucketEndMs }),\n data: snapshot.data.map((row) => ({\n dimension: row.dimension,\n ...(row.bucketStartMs === undefined ? {} : { bucketStartMs: row.bucketStartMs }),\n ...metricsToDto(row.metrics),\n })).sort(groupBy === 'model'\n ? (a, b) => b.inputTokens + b.outputTokens - a.inputTokens - a.outputTokens\n || b.upstreamAttempts - a.upstreamAttempts || a.dimension.localeCompare(b.dimension)\n : (a, b) => a.bucketStartMs! - b.bucketStartMs! || a.dimension.localeCompare(b.dimension)),\n };\n }\n\n /**\n * Distinct real client model names within the retention window, independent of\n * the dashboard's current time-range filter or Top-N truncation. No synthetic\n * rows are inserted; a storage failure propagates instead of returning an empty\n * page. Bounded and fully reachable through paging.\n */\n async listClientModels(input: { keyword?: string; page?: number; pageSize?: number } = {}): Promise<ClientModelPage> {\n const pageSize = Math.max(1, Math.min(MAX_CLIENT_MODEL_PAGE_SIZE, Math.trunc(input.pageSize ?? 50)));\n const page = Math.max(1, Math.trunc(input.page ?? 1));\n if (!Number.isSafeInteger(page) || page > MAX_CLIENT_MODEL_PAGE) throw new TokenStatsRepositoryError('invalid token-stats page');\n const keyword = input.keyword;\n if (keyword !== undefined && (typeof keyword !== 'string' || keyword.length > CLIENT_MODEL_KEYWORD_MAX)) {\n throw new TokenStatsRepositoryError('invalid token-stats keyword');\n }\n if (this.metering.listClientModels) return this.metering.listClientModels({page,pageSize,keyword});\n throw new TokenStatsRepositoryError('token-stats client models capability is required');\n }\n\n /** Price aliases are token-stats business state, read/written through this repository. */\n async mappings(): Promise<PriceModelMapping[]> {\n return readPriceModelMappings(this.storage);\n }\n\n async configureMappings(mappings: PriceModelMapping[]): Promise<void> {\n await this.storage.set(PRICE_MODEL_MAPPINGS_KEY, mappings);\n }\n}\n",
22
+ "import type {\n PluginStorage,\n TokenStatsAttempt,\n TokenStatsMetricName,\n TokenStatsMeteringStorage,\n TokenStatsSnapshotMetrics,\n TokenStatsRange,\n} from '@jeffusion/bungee-core/plugin';\nimport type { CanonicalTokenAccountingEventV2 } from '@jeffusion/bungee-llms/plugin-api';\nimport type { ModelsDevCatalogService, ModelsDevModelMatch } from '../../models-dev/contract';\n// The control artifact needs only authority names, not the worker conversion runtime.\nconst TOKEN_ACCOUNTING_AUTHORITIES = ['official', 'local', 'heuristic', 'partial', 'none'] as const satisfies readonly CanonicalTokenAccountingEventV2['inputAuthority'][];\nimport { SQLiteTokenStatsMetering } from './storage';\nimport { TOKEN_STATS_RANGES, TOKEN_STATS_RETENTION_MS } from '@jeffusion/bungee-core/plugin';\nimport { PRICE_MODEL_MAPPINGS_KEY, readPriceModelMappings, type PriceModelMapping } from './model-mappings';\n\nexport type GroupByDimension = 'model' | 'time';\ntype TokenAccountingAuthority = typeof TOKEN_ACCOUNTING_AUTHORITIES[number];\nexport type CanonicalEvent = CanonicalTokenAccountingEventV2;\n\nexport interface AuthorityBreakdownDto {\n input: Record<TokenAccountingAuthority, number>;\n output: Record<TokenAccountingAuthority, number>;\n}\n\nexport interface GroupedAggregateDto {\n dimension: string;\n bucketStartMs?: number;\n inputTokens: number;\n outputTokens: number;\n officialInputTokens: number;\n officialOutputTokens: number;\n estimatedInputTokens: number;\n estimatedOutputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n partialOutputs: number;\n logicalRequests: number;\n upstreamAttempts: number;\n observationIncompleteAttempts: number;\n estimatedCostUsd: number | null;\n authorityBreakdown: AuthorityBreakdownDto;\n}\n\nexport interface AggregateDto extends Omit<GroupedAggregateDto, 'dimension' | 'bucketStartMs' | 'inputTokens' | 'outputTokens'> {\n /** Sticky evidence of dropped or failed reporting, shared across worker/control processes. */\n reportingIncomplete: boolean;\n groupBy: GroupByDimension;\n asOfMs: number;\n bucketMs?: number;\n bucketStarts?: number[];\n bucketEndMs?: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n data: GroupedAggregateDto[];\n}\n\nexport class TokenStatsRepositoryError extends Error {\n constructor(message: string) { super(message); this.name = 'TokenStatsRepositoryError'; }\n}\n\nexport class TokenStatsRepositoryLimitError extends TokenStatsRepositoryError {}\n\nexport interface ClientModelPage {\n /** Distinct raw client/attempt model names, exactly as recorded (original case). */\n models: string[];\n total: number;\n page: number;\n pageSize: number;\n}\n\nexport const MAX_CLIENT_MODEL_PAGE_SIZE = 100;\nexport const MAX_CLIENT_MODEL_PAGE = 400;\nconst CLIENT_MODEL_KEYWORD_MAX = 256;\n\nexport const REPORTING_INCOMPLETE_KEY = 'reporting:incomplete';\n\ntype MeteringLogger = { onFailure?(): void; warn(message: string, metadata?: object): void; error(message: string, metadata?: object): void };\ntype AttemptTask = () => TokenStatsAttempt | undefined | Promise<TokenStatsAttempt | undefined>;\ntype QueuedAttempt = { metering: TokenStatsMeteringStorage; task: AttemptTask; logger: MeteringLogger };\ntype FailureStage = 'prepare' | 'missing_row' | 'write';\n\nconst MAX_PENDING_ATTEMPTS = 256;\nconst LOG_INTERVAL_MS = 60_000;\nconst pendingAttempts: QueuedAttempt[] = [];\nlet pendingCount = 0;\nlet drainTimer: ReturnType<typeof setTimeout> | undefined;\nlet draining = false;\nlet lastDropLogAt = 0;\nconst lastFailureLogAt = new Map<string, number>();\n\nfunction failureCode(error: unknown): string {\n if (error instanceof DOMException && error.name === 'TimeoutError') return 'rpc_timeout';\n if (error instanceof Error && error.name === 'DataAdmissionError' && 'code' in error) {\n switch (error.code) {\n case 'invalid_worker_rpc':\n case 'worker_not_admitted':\n case 'rpc_busy':\n case 'rpc_capacity': return error.code;\n default: return 'rpc_rejected';\n }\n }\n return 'unclassified';\n}\n\nfunction logRateLimited(logger: MeteringLogger, stage: 'drop' | FailureStage, error?: unknown): void {\n try { logger.onFailure?.(); } catch { /* failure reporting must not affect proxy flow */ }\n const now = Date.now();\n if (stage === 'drop') {\n if (now - lastDropLogAt < LOG_INTERVAL_MS) return;\n lastDropLogAt = now;\n try { logger.warn('Token stats attempt queue full; dropping metering rows', { capacity: MAX_PENDING_ATTEMPTS }); } catch { /* logging must not affect proxy flow */ }\n return;\n }\n try {\n const failure = `${stage}/${failureCode(error)}`;\n if (now - (lastFailureLogAt.get(failure) ?? 0) < LOG_INTERVAL_MS) return;\n lastFailureLogAt.set(failure, now);\n logger.error(`Token stats attempt processing failed; dropping metering row [${failure}]`);\n } catch { /* logging must not affect proxy flow */ }\n}\n\nfunction scheduleDrain(): void {\n if (drainTimer !== undefined || draining) return;\n drainTimer = setTimeout(() => { drainTimer = undefined; void drainOneAttempt(); }, 0);\n}\n\nasync function drainOneAttempt(): Promise<void> {\n if (draining) return;\n const item = pendingAttempts.shift();\n if (!item) return;\n draining = true;\n let stage: FailureStage = 'prepare';\n try {\n const row = await item.task();\n if (row === undefined) return logRateLimited(item.logger, 'missing_row');\n stage = 'write';\n await item.metering.recordAttempt(row);\n } catch (error) {\n logRateLimited(item.logger, stage, error);\n } finally {\n pendingCount--;\n draining = false;\n if (pendingAttempts.length) scheduleDrain();\n }\n}\n\nconst METRIC_FIELDS: readonly TokenStatsMetricName[] = [\n 'inputTokens', 'outputTokens', 'officialInputTokens', 'officialOutputTokens',\n 'estimatedInputTokens', 'estimatedOutputTokens', 'cacheReadTokens', 'cacheWriteTokens',\n 'partialOutputs', 'logicalRequests', 'upstreamAttempts', 'observationIncompleteAttempts',\n 'inputAuthorityOfficial', 'inputAuthorityLocal', 'inputAuthorityHeuristic', 'inputAuthorityPartial', 'inputAuthorityNone',\n 'outputAuthorityOfficial', 'outputAuthorityLocal', 'outputAuthorityHeuristic', 'outputAuthorityPartial', 'outputAuthorityNone',\n];\n\nfunction emptyMetrics(): TokenStatsSnapshotMetrics {\n return { ...Object.fromEntries(METRIC_FIELDS.map((key) => [key, 0])) as Record<TokenStatsMetricName, number>, estimatedCostUsd: null };\n}\n\nfunction emptyAuthorityBreakdown(): AuthorityBreakdownDto {\n const empty = () => Object.fromEntries(TOKEN_ACCOUNTING_AUTHORITIES.map((authority) => [authority, 0])) as Record<TokenAccountingAuthority, number>;\n return { input: empty(), output: empty() };\n}\n\nfunction metricsToDto(metrics: TokenStatsSnapshotMetrics): Omit<GroupedAggregateDto, 'dimension'> {\n const authorityBreakdown = emptyAuthorityBreakdown();\n for (const authority of TOKEN_ACCOUNTING_AUTHORITIES) {\n authorityBreakdown.input[authority] = metrics[`inputAuthority${authority[0]!.toUpperCase()}${authority.slice(1)}` as TokenStatsMetricName];\n authorityBreakdown.output[authority] = metrics[`outputAuthority${authority[0]!.toUpperCase()}${authority.slice(1)}` as TokenStatsMetricName];\n }\n return {\n inputTokens: metrics.inputTokens,\n outputTokens: metrics.outputTokens,\n officialInputTokens: metrics.officialInputTokens,\n officialOutputTokens: metrics.officialOutputTokens,\n estimatedInputTokens: metrics.estimatedInputTokens,\n estimatedOutputTokens: metrics.estimatedOutputTokens,\n cacheReadTokens: metrics.cacheReadTokens,\n cacheWriteTokens: metrics.cacheWriteTokens,\n partialOutputs: metrics.partialOutputs,\n logicalRequests: metrics.logicalRequests,\n upstreamAttempts: metrics.upstreamAttempts,\n observationIncompleteAttempts: metrics.observationIncompleteAttempts,\n estimatedCostUsd: metrics.estimatedCostUsd,\n authorityBreakdown,\n };\n}\n\nfunction sourceFor(value: number | undefined, authority: CanonicalTokenAccountingEventV2['inputAuthority']): TokenStatsAttempt['input_source'] {\n if (!Number.isSafeInteger(value) || value! < 0) return 'unknown';\n if (authority === 'official') return 'usage';\n if (authority === 'partial') return 'partial';\n return authority === 'none' ? 'unknown' : 'estimated';\n}\n\nexport function attemptRowFromEvent(\n event: CanonicalEvent,\n finishedAtMs: number,\n observationIncomplete: boolean,\n model: string,\n): TokenStatsAttempt {\n const inputSource = sourceFor(event.inputTokens, event.inputAuthority);\n const outputSource = sourceFor(event.outputTokens, event.outputAuthority);\n return {\n attempt_id: event.attemptId,\n request_id: event.requestId,\n finished_at_ms: finishedAtMs,\n route_id: event.routeId || 'unknown',\n upstream_id: event.upstreamId || 'unknown',\n provider: event.provider || 'unknown',\n outcome: event.outcome,\n model,\n input_tokens: inputSource === 'unknown' ? null : event.inputTokens!,\n output_tokens: outputSource === 'unknown' ? null : event.outputTokens!,\n input_source: inputSource,\n output_source: outputSource,\n cache_read_tokens: Number.isSafeInteger(event.cacheReadTokens) && event.cacheReadTokens! >= 0 ? event.cacheReadTokens! : null,\n cache_write_tokens: Number.isSafeInteger(event.cacheWriteTokens) && event.cacheWriteTokens! >= 0 ? event.cacheWriteTokens! : null,\n cost_usd: null,\n observation_incomplete: observationIncomplete,\n };\n}\n\nexport class TokenStatsRepository {\n private readonly metering: TokenStatsMeteringStorage & Partial<Pick<SQLiteTokenStatsMetering, 'queryPricingModels'>>;\n\n constructor(private readonly storage: PluginStorage) {\n if (!storage.metering && !storage.observation) throw new TokenStatsRepositoryError('token-stats metering storage is required');\n this.metering = storage.metering ?? new SQLiteTokenStatsMetering(storage.observation!);\n }\n\n /** Defers synchronous task work to drain; a task can still occupy the EventLoop. */\n enqueueAttempt(task: AttemptTask, logger: MeteringLogger): boolean {\n if (pendingCount >= MAX_PENDING_ATTEMPTS) {\n logRateLimited(logger, 'drop');\n return false;\n }\n pendingAttempts.push({ metering: this.metering, task, logger });\n pendingCount++;\n scheduleDrain();\n return true;\n }\n\n async query(range: string, groupBy: GroupByDimension, asOfMs = Date.now(), timeZone?: string, keyId?: string, catalog?: ModelsDevCatalogService): Promise<AggregateDto> {\n if (!(TOKEN_STATS_RANGES as readonly string[]).includes(range)) throw new TokenStatsRepositoryError('invalid token-stats range');\n if (groupBy !== 'model' && groupBy !== 'time') {\n throw new TokenStatsRepositoryError('invalid token-stats groupBy');\n }\n if (!Number.isSafeInteger(asOfMs) || asOfMs < 0) throw new TokenStatsRepositoryError('invalid token-stats asOfMs');\n const window = { asOfMs, range: range as TokenStatsRange, groupBy, timeZone, keyId };\n let input: Parameters<SQLiteTokenStatsMetering['queryWindowSnapshot']>[0] = window;\n if (catalog && this.metering.queryPricingModels) {\n const mappings = await this.mappings().catch(() => undefined);\n if (mappings) {\n const { models, throughRow } = await this.metering.queryPricingModels(window);\n const bySource = new Map(mappings.map(mapping => [mapping.source, mapping]));\n const prices: Array<[string, ModelsDevModelMatch]> = [];\n for (const model of models) {\n const mapped = bySource.get(model);\n // Stored wire protocol is not a pricing provider. Only resolve explicit mappings or exact catalog matches.\n const price = catalog.resolveModel(mapped ? { model: mapped.model, pricingProvider: mapped.provider } : { model });\n if (price !== null) prices.push([model, price]);\n }\n input = { ...window, pricing: { throughRow, prices } };\n }\n }\n const snapshot = await this.metering.queryWindowSnapshot(input);\n const total = metricsToDto(snapshot.all);\n const { inputTokens, outputTokens, ...summary } = total;\n return {\n reportingIncomplete: await (this.storage.uncached?.() ?? this.storage).get(REPORTING_INCOMPLETE_KEY) === true,\n groupBy,\n asOfMs,\n ...summary,\n totalInputTokens: inputTokens,\n totalOutputTokens: outputTokens,\n ...(snapshot.bucketMs === undefined ? {} : { bucketMs: snapshot.bucketMs }),\n ...(snapshot.bucketStarts === undefined ? {} : { bucketStarts: snapshot.bucketStarts }),\n ...(snapshot.bucketEndMs === undefined ? {} : { bucketEndMs: snapshot.bucketEndMs }),\n data: snapshot.data.map((row) => ({\n dimension: row.dimension,\n ...(row.bucketStartMs === undefined ? {} : { bucketStartMs: row.bucketStartMs }),\n ...metricsToDto(row.metrics),\n })).sort(groupBy === 'model'\n ? (a, b) => b.inputTokens + b.outputTokens - a.inputTokens - a.outputTokens\n || b.upstreamAttempts - a.upstreamAttempts || a.dimension.localeCompare(b.dimension)\n : (a, b) => a.bucketStartMs! - b.bucketStartMs! || a.dimension.localeCompare(b.dimension)),\n };\n }\n\n /**\n * Distinct real client model names within the retention window, independent of\n * the dashboard's current time-range filter or Top-N truncation. No synthetic\n * rows are inserted; a storage failure propagates instead of returning an empty\n * page. Bounded and fully reachable through paging.\n */\n async listClientModels(input: { keyword?: string; page?: number; pageSize?: number } = {}): Promise<ClientModelPage> {\n const pageSize = Math.max(1, Math.min(MAX_CLIENT_MODEL_PAGE_SIZE, Math.trunc(input.pageSize ?? 50)));\n const page = Math.max(1, Math.trunc(input.page ?? 1));\n if (!Number.isSafeInteger(page) || page > MAX_CLIENT_MODEL_PAGE) throw new TokenStatsRepositoryError('invalid token-stats page');\n const keyword = input.keyword;\n if (keyword !== undefined && (typeof keyword !== 'string' || keyword.length > CLIENT_MODEL_KEYWORD_MAX)) {\n throw new TokenStatsRepositoryError('invalid token-stats keyword');\n }\n if (this.metering.listClientModels) return this.metering.listClientModels({page,pageSize,keyword});\n throw new TokenStatsRepositoryError('token-stats client models capability is required');\n }\n\n /** Price aliases are token-stats business state, read/written through this repository. */\n async mappings(): Promise<PriceModelMapping[]> {\n return readPriceModelMappings(this.storage);\n }\n\n async configureMappings(mappings: PriceModelMapping[]): Promise<void> {\n await this.storage.set(PRICE_MODEL_MAPPINGS_KEY, mappings);\n }\n}\n",
23
23
  "/**\n * Public contract of the models-dev catalog provider.\n *\n * This is the ONLY file other plugins may import from models-dev. It contains the\n * declared service identity, the wire-contract snapshot literal and the data types\n * of the read surface; it never exposes the downloader, the private storage keys or\n * the internal catalog representation.\n *\n * Consumers must declare a real dependency on `models-dev` and consume the local\n * service for their own process. The service methods are synchronous and read an\n * already-loaded in-memory view: no per-request network or SQL is performed.\n */\n\n/** Provider plugin name. Must match the manifest. */\nexport const MODELS_DEV_PLUGIN_NAME = 'models-dev';\n\n/** Explicit catalog identity, independent from the provider's wire model name. */\nexport interface CatalogModelReference {\n readonly provider: string;\n readonly model: string;\n}\nexport interface ModelIdentityDeclaration {\n readonly wireModel: string;\n readonly catalogModel: CatalogModelReference;\n}\nexport const MODEL_IDENTITY_ANNOTATION_KEY = 'models-dev.model-identity';\n\n/** The single upstream source; models-dev is the only component allowed to fetch it. */\nexport const MODELS_DEV_SOURCE_URL = 'https://models.dev/api.json';\n\n/** Same-process local read service, published in both the control and worker processes. */\nexport const MODELS_DEV_CATALOG_SERVICE_ID = 'models-dev.catalog.v1';\nexport const MODELS_DEV_CATALOG_CONTRACT_VERSION = 1;\n\n/** Versioned immutable snapshot of the full catalog, published by the control writer. */\nexport const MODELS_DEV_CATALOG_SNAPSHOT_ID = 'models-dev.catalog.snapshot.v1';\nexport const MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT_VERSION = 1;\n/**\n * One atomic record keeps fetchedAt and the immutable catalog with its version.\n * The catalog remains unrestricted JSON so every upstream field is preserved.\n */\nexport const MODELS_DEV_CATALOG_SNAPSHOT_SCHEMA = Object.freeze({\n type: 'object', properties: {\n version: { type: 'number', integer: true, minimum: 1 },\n fetchedAt: { type: 'number', minimum: 0 },\n catalog: { type: 'json', maxBytes: 32 * 1024 * 1024 },\n },\n} as const);\nexport const MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT = Object.freeze({\n id: MODELS_DEV_CATALOG_SNAPSHOT_ID,\n version: MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT_VERSION,\n content: MODELS_DEV_CATALOG_SNAPSHOT_SCHEMA,\n});\n\n/** Catalog availability is separate from whether the service is published. */\nexport type ModelsDevCatalogState = 'empty' | 'ready' | 'stale' | 'failed';\n\nexport interface ModelsDevCatalogStatus {\n readonly state: ModelsDevCatalogState;\n /** Monotonic published data version; `null` before the first successful load. */\n readonly version: number | null;\n readonly fetchedAt: number | null;\n readonly providerCount: number;\n readonly modelCount: number;\n /** Last failure reason; `null` after a fully successful load. */\n readonly error: string | null;\n}\n\nexport interface ModelsDevProviderSummary {\n readonly provider: string;\n readonly name: string;\n /** Normalized upstream API base (`provider.api`), or `null` when models.dev declares none. */\n readonly api: string | null;\n readonly modelCount: number;\n}\n\n/** One selectable catalog model. `provider` is the pricing provider, never the protocol. */\nexport interface ModelsDevModelOption {\n readonly provider: string;\n readonly providerName: string;\n readonly model: string;\n readonly name: string;\n}\n\nexport interface ModelsDevModelPage {\n readonly models: readonly ModelsDevModelOption[];\n readonly total: number;\n /** 1-based page actually returned. */\n readonly page: number;\n readonly pageSize: number;\n}\n\n/** USD per million tokens, applied to the whole request at this input threshold. */\nexport interface ModelsDevContextTier {\n readonly minimumInputTokens: number;\n readonly input: number;\n readonly output: number;\n readonly cacheRead: number | null;\n readonly cacheWrite: number | null;\n}\n\n/** A resolved catalog entry with optional ascending context price bands. */\nexport interface ModelsDevModelMatch {\n readonly provider: string;\n readonly model: string;\n readonly input: number;\n readonly output: number;\n readonly cacheRead: number | null;\n readonly cacheWrite: number | null;\n readonly tiered: boolean;\n readonly contextTiers?: readonly ModelsDevContextTier[];\n}\n\nexport interface ModelsDevProviderMatch {\n readonly provider: string;\n}\n\n/**\n * The declared local read surface. Implementations must be side-effect free and\n * must never throw for a miss/corruption of the current view: an unavailable\n * catalog returns an `empty`/`failed` status instead of a fabricated price.\n */\nexport interface ModelsDevCatalogService {\n status(): ModelsDevCatalogStatus;\n providers(): readonly ModelsDevProviderSummary[];\n modelOptions(input?: { readonly provider?: string; readonly search?: string; readonly page?: number; readonly pageSize?: number }): ModelsDevModelPage;\n /**\n * Resolve exactly one catalog entry for a client model name.\n *\n * `url` (when supplied) is canonicalized to host + path and matched against the\n * full catalog's `provider.api`; more than one candidate is ambiguous and returns\n * null. `pricingProvider` is a catalog provider id and takes priority over URL and\n * prefix inference. A model id present under several providers without an explicit\n * provider is ambiguous. Matching defaults to exact and case-sensitive.\n * `estimate` additionally permits normalized names, original-lab prices and\n * dated members of the same family. Explicit provider IDs remain binding;\n * an unresolved URL is only a hint in estimate mode.\n */\n resolveModel(input: { readonly model: string; readonly pricingProvider?: string; readonly url?: string; readonly mode?: 'exact' | 'estimate' }): ModelsDevModelMatch | null;\n /** Resolve one provider from a real upstream URL via `provider.api`; ambiguous/none => null. */\n resolveProvider(input: { readonly url: string }): ModelsDevProviderMatch | null;\n}\n\n/** Capability reads are additive; existing catalog.v1 consumers stay unchanged. */\nexport const MODELS_DEV_CAPABILITIES_SERVICE_ID = 'models-dev.capabilities.v1';\nexport const MODELS_DEV_CAPABILITIES_CONTRACT_VERSION = 1;\n/** Upstream control values; null/default do not name a concrete effort level. */\nexport type ModelsDevReasoningEffortValue = null | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'default';\n/** Validated models.dev reasoning_options, without inferred controls or levels. */\nexport type ModelsDevReasoningOption =\n | { readonly type: 'effort'; readonly values: readonly ModelsDevReasoningEffortValue[] }\n | { readonly type: 'toggle' }\n | { readonly type: 'budget_tokens'; readonly min?: number; readonly max?: number };\nexport type ModelsDevReasoningOptionsStatus = 'known' | 'missing' | 'invalid';\nexport interface ModelsDevCapabilities {\n readonly provider: string;\n readonly model: string;\n readonly name: string;\n readonly contextWindow: number | null;\n readonly outputLimit: number | null;\n readonly toolCall: boolean;\n readonly reasoning: boolean;\n /** null for missing/invalid metadata; a validated empty list remains known. */\n readonly reasoningOptions: readonly ModelsDevReasoningOption[] | null;\n readonly reasoningOptionsStatus: ModelsDevReasoningOptionsStatus;\n /** Version of the same complete snapshot that supplied all fields of this result. */\n readonly catalogVersion: number;\n readonly inputModalities: readonly string[];\n}\nexport interface ModelsDevCapabilitiesService {\n status(): ModelsDevCatalogStatus;\n /** Without a provider, require a unique exact model or a declared API URL match. */\n model(input: { readonly provider?: string; readonly model: string; readonly url?: string }): ModelsDevCapabilities | null;\n}\n",
24
24
  "import type { PluginStorage, Plugin, TokenStatsAttempt } from '@jeffusion/bungee-core/plugin';\nimport { definePlugin } from '@jeffusion/bungee-core/plugin';\nimport type { PluginHooks, PluginInitContext, PluginLogger } from '@jeffusion/bungee-core/plugin';\nimport {\n TOKEN_METERING_SERVICE_ID, TOKEN_METERING_CONTRACT_VERSION, type TokenMeteringService, type TokenMeteringResult,\n TOKEN_PRICING_SERVICE_ID, TOKEN_PRICING_CONTRACT_VERSION, type TokenPricingService,\n} from '@jeffusion/bungee-core/plugin';\nimport { withReportingWriteTimeout } from './storage';\nimport { TokenStatsRepository, REPORTING_INCOMPLETE_KEY } from './repository';\nimport { costNanoUsdOf, TokenStatsPricing } from './pricing';\nimport type { PriceModelMapping } from './model-mappings';\nimport { MODELS_DEV_CATALOG_CONTRACT_VERSION, MODELS_DEV_CATALOG_SERVICE_ID, type ModelsDevCatalogService } from '../../models-dev/contract';\n\nconst MAPPING_REFRESH_INTERVAL_MS = 10_000;\n\nfunction rowFromResult(result: TokenMeteringResult): TokenStatsAttempt {\n // Preserve reporting's historical official-only policy for interrupted attempts.\n const inputKnown = result.outcome === 'completed' || result.inputSource === 'official';\n const outputKnown = result.outcome === 'completed' || result.outputSource === 'official';\n const source = (value: TokenMeteringResult['inputSource']): TokenStatsAttempt['input_source'] =>\n value === 'official' ? 'usage' : value === 'none' ? 'unknown' : value;\n return {\n key_id: result.keyId ?? null, attempt_id: result.attemptId, request_id: result.requestId, finished_at_ms: result.finishedAtMs,\n route_id: result.routeId || 'unknown', upstream_id: result.upstreamId || 'unknown', provider: result.provider,\n outcome: result.observationIncomplete && result.outcome === 'completed' ? 'failed' : result.outcome, model: result.model || 'unknown',\n input_tokens: inputKnown ? result.inputTokens ?? null : null, output_tokens: outputKnown ? result.outputTokens ?? null : null,\n input_source: inputKnown ? source(result.inputSource) : 'unknown', output_source: outputKnown ? source(result.outputSource) : 'unknown',\n cache_read_tokens: result.cacheReadTokens ?? null, cache_write_tokens: result.cacheWriteTokens ?? null,\n cost_usd: null, observation_incomplete: result.observationIncomplete,\n };\n}\n\n/** One bounded result cache shared by reporting and required budget consumers. */\nexport class TokenStatsPricingService implements TokenPricingService {\n private readonly results = new Map<string, ReturnType<TokenPricingService['price']>>();\n constructor(private readonly pricing: TokenStatsPricing) {}\n readonly canPrice: TokenPricingService['canPrice'] = async input => {\n return this.pricing.estimate({ model: input.model, provider: input.pricingProvider, inputTokens: 0, outputTokens: 0 }) !== null;\n };\n readonly price: TokenPricingService['price'] = result => {\n // Include settlement revision and all pricing inputs; revised usage must be priced again.\n const row = rowFromResult(result);\n const key = JSON.stringify([result.requestId, result.attemptId, result.settlementVersion, result.model, result.pricingProvider,\n row.input_tokens, row.output_tokens, row.cache_read_tokens, row.cache_write_tokens]);\n const existing = this.results.get(key);\n if (existing) return existing;\n const pending = Promise.resolve().then(async () => {\n const raw = this.pricing.estimate({\n model: result.model, provider: result.pricingProvider,\n inputTokens: row.input_tokens ?? undefined, outputTokens: row.output_tokens ?? undefined,\n cacheReadTokens: result.cacheReadTokens, cacheWriteTokens: result.cacheWriteTokens,\n });\n const costNanoUsd = costNanoUsdOf(raw);\n return Object.freeze({ costNanoUsd, costUsd: costNanoUsd === null ? null : costNanoUsd / 1e9 });\n });\n this.results.set(key, pending);\n if (this.results.size > 2048) this.results.delete(this.results.keys().next().value!);\n return pending;\n };\n}\n\n/** In-memory alias view with a bounded background refresh: never SQL per request. */\nclass MappingCache {\n private mappings: PriceModelMapping[] | undefined = undefined;\n private loadedAt = 0;\n private inFlight = false;\n\n constructor(private readonly load: () => Promise<PriceModelMapping[]>) {}\n\n current(): PriceModelMapping[] | undefined { return this.mappings; }\n\n async refresh(now = Date.now()): Promise<void> {\n if (this.inFlight) return;\n this.inFlight = true;\n try {\n this.mappings = await this.load();\n this.loadedAt = now;\n } catch {\n // A read/parse failure must keep pricing unknown, never select a fallback.\n this.mappings = undefined;\n } finally {\n this.inFlight = false;\n }\n }\n\n maybeRefresh(now = Date.now()): void {\n if (this.inFlight || now - this.loadedAt < MAPPING_REFRESH_INTERVAL_MS) return;\n void this.refresh(now);\n }\n}\n\nexport const TokenStatsPlugin = definePlugin(\n class implements Plugin {\n static readonly name = 'token-stats';\n static readonly version = '4.0.0';\n storage!: PluginStorage;\n logger!: PluginLogger;\n repository!: TokenStatsRepository;\n pricing!: TokenStatsPricing;\n reportingIncomplete = false;\n private unsubscribe?: () => void;\n private mappingRefresh?: ReturnType<typeof setInterval>;\n\n private markReportingIncomplete(): void {\n if (this.reportingIncomplete) return;\n this.reportingIncomplete = true;\n setTimeout(() => {\n const reportFailure = (error: unknown) => {\n try { this.logger.error('Unable to persist reporting incomplete status', { error: String(error) }); } catch {}\n };\n try {\n const persist = () => this.storage.set(REPORTING_INCOMPLETE_KEY, true);\n const pending = this.storage.observation\n ? this.storage.observation.withDatabase(db => withReportingWriteTimeout(db, persist))\n : persist();\n void pending.catch(reportFailure);\n } catch (error) { reportFailure(error); }\n }, 0);\n }\n\n constructor(_config: Record<string, unknown> = {}, private readonly pricingFactory?: () => TokenStatsPricing) {}\n\n private applyMappings(mappings: PriceModelMapping[] | undefined): void {\n // Fixture doubles may not implement the extended surface; the real class does.\n if (typeof this.pricing.setMappings === 'function') this.pricing.setMappings(mappings);\n }\n\n async init(context: PluginInitContext): Promise<void> {\n if (!context.services) throw new Error('token-stats requires token-metering service');\n const metering = context.services.consume<TokenMeteringService>('token-metering', TOKEN_METERING_SERVICE_ID, TOKEN_METERING_CONTRACT_VERSION);\n // The catalog is optional for metering: without it token-stats still records\n // usage, but costs stay unknown instead of being blocked on a catalog.\n let catalog: ModelsDevCatalogService | null = null;\n try {\n catalog = context.services.consume<ModelsDevCatalogService>(\n 'models-dev', MODELS_DEV_CATALOG_SERVICE_ID, MODELS_DEV_CATALOG_CONTRACT_VERSION,\n );\n } catch { catalog = null; }\n this.storage = context.storage.uncached?.() ?? context.storage;\n this.logger = context.logger;\n this.repository = new TokenStatsRepository(context.storage);\n this.pricing = this.pricingFactory?.() ?? new TokenStatsPricing(catalog);\n const mappings = new MappingCache(() => this.repository.mappings());\n await mappings.refresh();\n this.applyMappings(mappings.current());\n const pricingService = new TokenStatsPricingService(this.pricing);\n context.services.publish(TOKEN_PRICING_SERVICE_ID, TOKEN_PRICING_CONTRACT_VERSION, { canPrice: pricingService.canPrice, price: pricingService.price });\n this.unsubscribe = metering.subscribe({\n onResult: result => {\n const row = rowFromResult(result);\n // Pick up alias edits without paying SQL per request.\n mappings.maybeRefresh();\n this.applyMappings(mappings.current());\n const price = pricingService.price(result);\n void price.catch(() => {});\n const accepted = this.repository.enqueueAttempt(async () => {\n try {\n return { ...row, cost_usd: (await price).costUsd };\n } catch (error) { this.markReportingIncomplete(); throw error; }\n }, {\n onFailure: () => this.markReportingIncomplete(),\n warn: (message, metadata) => { this.markReportingIncomplete(); this.logger.warn(message, metadata); },\n error: (message, metadata) => { this.markReportingIncomplete(); this.logger.error(message, metadata); },\n });\n if (!accepted) this.markReportingIncomplete();\n },\n onFailure: () => { this.markReportingIncomplete(); },\n });\n this.mappingRefresh = setInterval(() => { void mappings.refresh().then(() => this.applyMappings(mappings.current())); }, MAPPING_REFRESH_INTERVAL_MS);\n if (typeof this.mappingRefresh.unref === 'function') this.mappingRefresh.unref();\n context.services.onDispose(() => { this.unsubscribe?.(); this.unsubscribe = undefined; });\n this.logger.info('TokenStatsPlugin initialized');\n }\n\n bodyRequirements(): import('@jeffusion/bungee-core/plugin').PluginBodyRequirements { return { request: 'none' }; }\n\n register(_hooks: PluginHooks): void {}\n\n async onDestroy(): Promise<void> {\n this.unsubscribe?.(); this.unsubscribe = undefined;\n if (this.mappingRefresh !== undefined) clearInterval(this.mappingRefresh);\n this.mappingRefresh = undefined;\n this.logger?.info('TokenStatsPlugin destroyed');\n }\n },\n);\nexport default TokenStatsPlugin;\n"
25
25
  ],
26
- "mappings": ";;AAOA,IAAM,UAAU,OAAO,IAAI,mCAAmC;AAI9D,SAAS,YAAY,CAAC,WAAoB,CAAC,GAAkB;AAAA,EAC3D,MAAM,SAAS,CAAC,UACd,CAAC,OAAyB,YAAqB;AAAA,IAC7C,MAAM,OAAQ,WAAuC;AAAA,IACrD,IAAI,MAAM;AAAA,MACR,IAAI,OAAO,UAAU;AAAA,QAAU,KAAK,OAAO,UAAU,KAAK;AAAA,MACrD;AAAA,aAAK,OAAO,KAAI,aAAa,MAAK,GAAG,OAAO;AAAA,IACnD,EAAO,SAAI,UAAU,WAAW,QAAQ,IAAI,cAAc,SAAS;AAAA,MACjE,MAAM,QAAQ,UAAU,UAAU,QAAQ,QA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