@jeffusion/bungee-core 5.26.0 → 6.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/config-storage-worker.js +455 -223
  2. package/dist/main.js +803 -437
  3. package/dist/observability-worker.js +0 -10
  4. package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
  5. package/dist/plugins/anthropic-request-sanitizer/manifest.json +1 -1
  6. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
  7. package/dist/plugins/anthropic-tool-name-transformer/manifest.json +1 -1
  8. package/dist/plugins/chatgpt-oauth/control.js.map +1 -1
  9. package/dist/plugins/chatgpt-oauth/index.js.map +2 -2
  10. package/dist/plugins/chatgpt-oauth/manifest.json +1 -1
  11. package/dist/plugins/codex-router/control.js.map +1 -1
  12. package/dist/plugins/codex-router/index.js +2 -2
  13. package/dist/plugins/codex-router/index.js.map +3 -3
  14. package/dist/plugins/codex-router/manifest.json +1 -1
  15. package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
  16. package/dist/plugins/deepseek-reasoning-fix/manifest.json +1 -1
  17. package/dist/plugins/key-access/control.js.map +1 -1
  18. package/dist/plugins/key-access/index.js.map +2 -2
  19. package/dist/plugins/key-access/ingress.js.map +1 -1
  20. package/dist/plugins/key-access/manifest.json +1 -1
  21. package/dist/plugins/key-rate-limit/index.js.map +2 -2
  22. package/dist/plugins/key-rate-limit/manifest.json +1 -1
  23. package/dist/plugins/llm-protocol-adapter/control.js +2 -2
  24. package/dist/plugins/llm-protocol-adapter/control.js.map +4 -4
  25. package/dist/plugins/llm-protocol-adapter/index.js +2 -2
  26. package/dist/plugins/llm-protocol-adapter/index.js.map +3 -3
  27. package/dist/plugins/llm-protocol-adapter/manifest.json +1 -1
  28. package/dist/plugins/model-mapping/index.js.map +2 -2
  29. package/dist/plugins/model-mapping/manifest.json +1 -1
  30. package/dist/plugins/models-dev/index.js.map +2 -2
  31. package/dist/plugins/models-dev/manifest.json +1 -1
  32. package/dist/plugins/signature-repair/index.js.map +2 -2
  33. package/dist/plugins/signature-repair/manifest.json +1 -1
  34. package/dist/plugins/token-budget/control.js.map +1 -1
  35. package/dist/plugins/token-budget/index.js.map +2 -2
  36. package/dist/plugins/token-budget/manifest.json +1 -1
  37. package/dist/plugins/token-metering/index.js.map +2 -2
  38. package/dist/plugins/token-metering/manifest.json +1 -1
  39. package/dist/plugins/token-stats/control.js.map +1 -1
  40. package/dist/plugins/token-stats/index.js.map +2 -2
  41. package/dist/plugins/token-stats/manifest.json +1 -1
  42. package/dist/plugins/user-auth/control.js +3911 -0
  43. package/dist/plugins/{local-accounts → user-auth}/control.js.map +8 -5
  44. package/dist/plugins/{local-accounts → user-auth}/index.js +6 -6
  45. package/dist/plugins/{local-accounts → user-auth}/index.js.map +6 -6
  46. package/dist/plugins/user-auth/manifest.json +735 -0
  47. package/dist/plugins/user-auth/ui/ConnectionEditor.svelte +137 -0
  48. package/dist/plugins/user-auth/ui/Login.svelte +87 -0
  49. package/dist/plugins/user-auth/ui/LoginProviderIcon.svelte +19 -0
  50. package/dist/plugins/user-auth/ui/LoginSettings.svelte +141 -0
  51. package/dist/plugins/user-auth/ui/Profile.svelte +185 -0
  52. package/dist/plugins/{local-accounts → user-auth}/ui/RecoveryHelp.svelte +3 -3
  53. package/dist/plugins/user-auth/ui/SessionPolicy.svelte +104 -0
  54. package/dist/plugins/user-auth/ui/Settings.svelte +14 -0
  55. package/dist/plugins/user-auth/ui/SettingsSection.svelte +32 -0
  56. package/dist/plugins/user-auth/ui/Setup.svelte +38 -0
  57. package/dist/plugins/user-auth/ui/TurnstileChallenge.svelte +26 -0
  58. package/dist/plugins/user-auth/ui/TurnstileSettings.svelte +81 -0
  59. package/dist/plugins/user-auth/ui/Users.svelte +95 -0
  60. package/dist/plugins/user-auth/ui/assets/LICENSE.txt +30 -0
  61. package/dist/plugins/user-auth/ui/assets/github.svg +1 -0
  62. package/dist/plugins/user-auth/ui/assets/google.svg +1 -0
  63. package/dist/plugins/user-auth/ui/assets/microsoft.svg +1 -0
  64. package/dist/plugins/user-auth/ui/contracts.ts +16 -0
  65. package/dist/plugins/{local-accounts → user-auth}/ui/login-errors.ts +4 -1
  66. package/dist/plugins/user-auth/ui/turnstile.ts +21 -0
  67. package/package.json +2 -2
  68. package/dist/plugins/local-accounts/control.js +0 -715
  69. package/dist/plugins/local-accounts/manifest.json +0 -223
  70. package/dist/plugins/local-accounts/ui/Login.svelte +0 -47
  71. package/dist/plugins/local-accounts/ui/Settings.svelte +0 -117
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "uiExtensionMode": "none",
14
14
  "engines": {
15
- "bungee": "^4.2.0 || ^5.0.0"
15
+ "bungee": "^6.0.0"
16
16
  },
17
17
  "control": {
18
18
  "entry": "control.js",
@@ -4,8 +4,8 @@
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 };\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 }>;\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 /** 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 }>;\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
- "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 authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): Promise<boolean>;\n login(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): 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): 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",
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 }>;\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 /** 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 }>;\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
+ "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): 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): 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",
11
11
  "/**\n * Plugin service RPC data contract (P1/P4): a dependency-free schema DSL, a\n * bounded strict-JSON codec, and service/method contract validation.\n *\n * Scope boundary: this module validates *data shapes only*. It deliberately\n * grants no wire authorization — host identity, generation, scope/lease, call\n * context, and permissions must be enforced by the host RPC adapter, never by a\n * schema check here. In particular `command.deduplication` is a declared intent;\n * real local transactions and any cross-system exactly-once behavior belong to\n * the host and to the external contract, not to this file.\n *\n * Everything that reaches validation is first cloned from own property\n * descriptors into bounded pure JSON, so no getter, proxy trap, or `toJSON` is\n * ever invoked and no non-JSON shape is silently accepted.\n */\nimport { isProxy } from 'node:util/types';\n\nexport type RpcCallKind = 'query' | 'command';\nexport type RpcCallPurpose = 'bootstrap' | 'background' | 'management' | 'request' | 'attempt';\nexport type RpcCommandDeduplication = 'local-transaction' | 'external-contract' | 'none';\n\n/** Declared intent only; the host owns the actual transaction and retention. */\nexport interface RpcCommandPolicy {\n readonly deduplication: RpcCommandDeduplication;\n /**\n * `null` means the result is retained permanently and durably: it survives a\n * restart and is never recomputed. A positive number is a retention window in\n * milliseconds. Retention is a host/storage concern; this is declaration only.\n */\n readonly resultRetentionMs: number | null;\n readonly quotaBytes: number;\n readonly maxResultBytes: number;\n}\n\n/** Pure JSON: null, boolean, finite number, string, arrays, and plain records. */\nexport type RpcJson =\n | null\n | boolean\n | number\n | string\n | readonly RpcJson[]\n | { readonly [key: string]: RpcJson };\n\n/**\n * Data schema DSL. `object` rejects unknown fields, `optional` lists real\n * optional keys, and `json` carries an optional explicit byte bound (default:\n * the RPC envelope).\n */\nexport type RpcDataSchema =\n | { readonly type: 'string'; readonly minLength?: number; readonly maxLength?: number }\n | { readonly type: 'number'; readonly integer?: boolean; readonly minimum?: number; readonly maximum?: number }\n | { readonly type: 'boolean' }\n | { readonly type: 'null' }\n | { readonly type: 'literal'; readonly value: RpcJson }\n | { readonly type: 'array'; readonly items: RpcDataSchema; readonly maxItems?: number }\n | {\n readonly type: 'object';\n readonly properties: { readonly [key: string]: RpcDataSchema };\n readonly optional?: readonly string[];\n }\n | { readonly type: 'record'; readonly values: RpcDataSchema; readonly maxEntries?: number }\n | { readonly type: 'union'; readonly variants: readonly RpcDataSchema[] }\n | { readonly type: 'json'; readonly maxBytes?: number };\n\n/** Flattens intersections so optional modifiers survive as real optional keys. */\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype OptionalNames<S> = S extends { readonly optional: readonly (infer K extends string)[] } ? K : never;\n\ntype InferObject<P extends Record<string, RpcDataSchema>, O extends string> = Simplify<\n { [K in keyof P as K extends O ? never : K]: InferRpcData<P[K]> } &\n { [K in Extract<keyof P, O>]?: InferRpcData<P[K]> }\n>;\n\n/** Derives the TypeScript type described by a `RpcDataSchema`. */\nexport type InferRpcData<S> =\n RpcDataSchema extends S ? RpcJson : S extends { readonly type: 'string' }\n ? string\n : S extends { readonly type: 'number' }\n ? number\n : S extends { readonly type: 'boolean' }\n ? boolean\n : S extends { readonly type: 'null' }\n ? null\n : S extends { readonly type: 'literal'; readonly value: infer V extends RpcJson }\n ? V\n : S extends { readonly type: 'json' }\n ? RpcJson\n : S extends { readonly type: 'array'; readonly items: infer I extends RpcDataSchema }\n ? InferRpcData<I>[]\n : S extends { readonly type: 'record'; readonly values: infer V extends RpcDataSchema }\n ? { [key: string]: InferRpcData<V> }\n : S extends { readonly type: 'union'; readonly variants: infer VS }\n ? VS extends readonly (infer V extends RpcDataSchema)[]\n ? InferRpcData<V>\n : never\n : S extends { readonly type: 'object'; readonly properties: infer P extends Record<string, RpcDataSchema> }\n ? InferObject<P, OptionalNames<S>>\n : never;\n\nexport interface RpcMethodDefinition {\n readonly kind: RpcCallKind;\n readonly input: RpcDataSchema;\n readonly output: RpcDataSchema;\n readonly purposes: readonly RpcCallPurpose[];\n readonly timeoutMs?: number;\n readonly maxInputBytes?: number;\n readonly maxOutputBytes?: number;\n readonly command?: RpcCommandPolicy;\n}\n\nexport interface RpcServiceContract<\n M extends Record<string, RpcMethodDefinition> = Record<string, RpcMethodDefinition>,\n> {\n readonly id: string;\n readonly version: number;\n readonly methods: M;\n}\n\nexport const RPC_JSON_MAX_BYTES = 64 * 1024;\n/** Metadata contract/schema inputs are pure JSON and bounded well below the envelope. */\nexport const RPC_CONTRACT_MAX_BYTES = 256 * 1024;\n\nconst JSON_MAX_DEPTH = 64;\nconst SCHEMA_MAX_DEPTH = 64;\nconst RPC_MAX_TIMEOUT_MS = 300_000;\nconst RPC_MAX_METHODS = 128;\nconst RPC_SERVICE_ID = /^[a-z][a-z0-9.-]{0,127}$/;\nconst RPC_METHOD_NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/;\nconst RPC_CALL_PURPOSES = new Set<RpcCallPurpose>(['bootstrap', 'background', 'management', 'request', 'attempt']);\nconst RPC_COMMAND_DEDUPLICATION = new Set<RpcCommandDeduplication>(['local-transaction', 'external-contract', 'none']);\nconst RPC_COMMAND_POLICY_KEYS = new Set(['deduplication', 'resultRetentionMs', 'quotaBytes', 'maxResultBytes']);\nconst CONTRACT_KEYS = ['id', 'version', 'methods'] as const;\nconst METHOD_KEYS = [\n 'kind',\n 'input',\n 'output',\n 'purposes',\n 'timeoutMs',\n 'maxInputBytes',\n 'maxOutputBytes',\n 'command',\n] as const;\n\nexport type RpcProtocolErrorCode = 'invalid_data' | 'size_limit' | 'invalid_contract';\n\n/** Fixed-code error. It never carries payload, secrets, keys, or arbitrary objects. */\nexport class RpcProtocolError extends Error {\n readonly name = 'RpcProtocolError';\n\n constructor(\n readonly code: RpcProtocolErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\n/** Reports a fixed schema category only — never a user property name or value. */\nfunction failData(category: string): never {\n throw new RpcProtocolError('invalid_data', `invalid_data in ${category}`);\n}\n\nfunction failSize(): never {\n throw new RpcProtocolError('size_limit', 'size_limit: JSON value exceeds the byte limit');\n}\n\nfunction failContract(reason: string): never {\n throw new RpcProtocolError('invalid_contract', `invalid_contract: ${reason}`);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n if (isProxy(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction hasLoneSurrogate(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n if (index + 1 >= value.length) return true;\n const next = value.charCodeAt(index + 1);\n if (next < 0xdc00 || next > 0xdfff) return true;\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArrayIndex(key: string, length: number): boolean {\n if (!/^(?:0|[1-9]\\d*)$/.test(key)) return false;\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n\nfunction assertKnownKeys(input: Record<string, unknown>, allowed: readonly string[], category: string): void {\n for (const key of Object.keys(input)) {\n if (!allowed.includes(key)) failContract(`unknown ${category} field`);\n }\n}\n\n/**\n * Running lower bound of the JSON byte size, used to reject oversized input\n * before it is fully cloned or stringified. Every accounting term is an\n * underestimate (escapes only ever add bytes), so a positive budget never\n * rejects a value that would actually fit.\n */\ninterface SnapshotBudget {\n left: number;\n}\n\nfunction spend(budget: SnapshotBudget, bytes: number): void {\n budget.left -= bytes;\n if (budget.left < 0) failSize();\n}\n\n/**\n * Validates and deep-clones a value into a plain pure-JSON graph. Object\n * descriptors are inspected before any value is read, so accessors and `toJSON`\n * are never invoked. Cycles, holes, non-plain objects, non-enumerable or symbol\n * keys, non-finite numbers, lone surrogates, and over-deep nesting are rejected;\n * the budget rejects oversized values early.\n */\nfunction snapshot(value: unknown, depth: number, ancestors: Set<object>, budget: SnapshotBudget): RpcJson {\n if (value === null) {\n spend(budget, 4);\n return null;\n }\n if (typeof value === 'boolean') {\n spend(budget, value ? 4 : 5);\n return value;\n }\n if (typeof value === 'string') {\n if (hasLoneSurrogate(value)) failData('string');\n spend(budget, Buffer.byteLength(value, 'utf8') + 2);\n return value;\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) failData('number');\n spend(budget, 1);\n return value;\n }\n if (typeof value !== 'object') failData('json');\n const object = value as object;\n if (isProxy(object)) failData('json');\n if (ancestors.has(object)) failData('json');\n const nextDepth = depth + 1;\n if (nextDepth > JSON_MAX_DEPTH) failData('json');\n if (Array.isArray(object)) {\n if (Object.getPrototypeOf(object) !== Array.prototype) failData('array');\n const lengthDescriptor = Object.getOwnPropertyDescriptor(object, 'length');\n if (!lengthDescriptor || !('value' in lengthDescriptor) || typeof lengthDescriptor.value !== 'number') {\n failData('array');\n }\n const length = lengthDescriptor.value;\n if (!Number.isSafeInteger(length) || length < 0) failData('array');\n if (length > budget.left) failSize();\n spend(budget, 2);\n if (length > 1) spend(budget, length - 1);\n ancestors.add(object);\n const items: RpcJson[] = new Array(length);\n let count = 0;\n for (const key of Reflect.ownKeys(object)) {\n if (key === 'length') continue;\n if (typeof key !== 'string' || !isArrayIndex(key, length)) failData('array');\n const descriptor = Object.getOwnPropertyDescriptor(object, key);\n if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) failData('array');\n items[Number(key)] = snapshot(descriptor.value, nextDepth, ancestors, budget);\n count += 1;\n }\n if (count !== length) failData('array');\n ancestors.delete(object);\n return items;\n }\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) failData('object');\n const keys = Reflect.ownKeys(object);\n if (keys.length > budget.left) failSize();\n spend(budget, 2);\n if (keys.length > 1) spend(budget, keys.length - 1);\n ancestors.add(object);\n const result: Record<string, RpcJson> = {};\n for (const key of keys) {\n if (typeof key !== 'string') failData('object');\n if (hasLoneSurrogate(key)) failData('object');\n const descriptor = Object.getOwnPropertyDescriptor(object, key);\n if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) failData('object');\n spend(budget, Buffer.byteLength(key, 'utf8') + 3);\n // defineProperty keeps a literal `__proto__` key an own data property instead of polluting the prototype.\n Object.defineProperty(result, key, {\n value: snapshot(descriptor.value, nextDepth, ancestors, budget),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n ancestors.delete(object);\n return result;\n}\n\n/** Clones a contract/schema input as bounded pure JSON, mapping pure-JSON errors to invalid_contract. */\nfunction snapshotPureInput(input: unknown): RpcJson {\n try {\n const pure = snapshot(input, 0, new Set(), { left: RPC_CONTRACT_MAX_BYTES });\n if (Buffer.byteLength(JSON.stringify(pure), 'utf8') > RPC_CONTRACT_MAX_BYTES) failContract('input must be bounded pure JSON data');\n return pure;\n } catch (error) {\n if (error instanceof RpcProtocolError && (error.code === 'invalid_data' || error.code === 'size_limit')) {\n failContract('input must be bounded pure JSON data');\n }\n throw error;\n }\n}\n\n/** Strict scanner: rejects duplicate keys, trailing content, and deep nesting. */\nfunction scanJson(text: string): void {\n let index = 0;\n const numberPattern = /-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y;\n const fail = (): never => {\n throw new RpcProtocolError('invalid_data', 'invalid JSON text');\n };\n const whitespace = (): void => {\n while (index < text.length) {\n const character = text[index];\n if (character === ' ' || character === '\\t' || character === '\\n' || character === '\\r') index += 1;\n else break;\n }\n };\n const string = (): string => {\n if (text[index] !== '\"') return fail();\n const start = index;\n index += 1;\n while (index < text.length) {\n const character = text[index];\n if (character === '\"') {\n index += 1;\n try {\n const value: unknown = JSON.parse(text.slice(start, index));\n if (typeof value !== 'string') return fail();\n return value;\n } catch (error) {\n if (error instanceof RpcProtocolError) throw error;\n return fail();\n }\n }\n if (character === undefined) return fail();\n if (character.charCodeAt(0) < 0x20) return fail();\n if (character === '\\\\') {\n index += 1;\n const escape = text[index];\n if (escape === 'u') {\n if (!/^[0-9a-fA-F]{4}$/.test(text.slice(index + 1, index + 5))) return fail();\n index += 5;\n continue;\n }\n if (escape === undefined || !'\"\\\\/bfnrt'.includes(escape)) return fail();\n index += 1;\n continue;\n }\n index += 1;\n }\n return fail();\n };\n const value = (depth: number): void => {\n whitespace();\n const character = text[index];\n if (character === '{') {\n if (depth >= JSON_MAX_DEPTH) return fail();\n index += 1;\n whitespace();\n const keys = new Set<string>();\n if (text[index] === '}') {\n index += 1;\n return;\n }\n while (true) {\n whitespace();\n const key = string();\n if (keys.has(key)) return fail();\n keys.add(key);\n whitespace();\n if (text[index] !== ':') return fail();\n index += 1;\n value(depth + 1);\n whitespace();\n if (text[index] === '}') {\n index += 1;\n return;\n }\n if (text[index] !== ',') return fail();\n index += 1;\n }\n }\n if (character === '[') {\n if (depth >= JSON_MAX_DEPTH) return fail();\n index += 1;\n whitespace();\n if (text[index] === ']') {\n index += 1;\n return;\n }\n while (true) {\n value(depth + 1);\n whitespace();\n if (text[index] === ']') {\n index += 1;\n return;\n }\n if (text[index] !== ',') return fail();\n index += 1;\n }\n }\n if (character === '\"') {\n string();\n return;\n }\n if (text.startsWith('true', index)) {\n index += 4;\n return;\n }\n if (text.startsWith('false', index)) {\n index += 5;\n return;\n }\n if (text.startsWith('null', index)) {\n index += 4;\n return;\n }\n numberPattern.lastIndex = index;\n const match = numberPattern.exec(text);\n if (match === null) return fail();\n index = numberPattern.lastIndex;\n };\n value(0);\n whitespace();\n if (index !== text.length) fail();\n}\n\n/** Rejects numbers that overflowed to Infinity and lone surrogates after parsing. */\nfunction assertJsonGraph(value: unknown): void {\n const stack: unknown[] = [value];\n while (stack.length > 0) {\n const current = stack.pop();\n if (typeof current === 'number') {\n if (!Number.isFinite(current)) failData('json');\n continue;\n }\n if (typeof current === 'string') {\n if (hasLoneSurrogate(current)) failData('string');\n continue;\n }\n if (Array.isArray(current)) {\n for (const item of current) stack.push(item);\n continue;\n }\n if (current !== null && typeof current === 'object') {\n for (const key of Object.keys(current)) {\n if (hasLoneSurrogate(key)) failData('object');\n stack.push((current as Record<string, unknown>)[key]);\n }\n }\n }\n}\n\n/**\n * Serializes a pure-JSON value under a UTF-8 byte bound. Oversized values are\n * rejected by the running budget before a large clone is built. `maxBytes` may\n * be raised for independent, larger data channels; the default stays the control\n * envelope limit.\n */\nexport function encodeRpcJson(value: unknown, maxBytes: number = RPC_JSON_MAX_BYTES): string {\n assertByteLimit(maxBytes);\n const clone = snapshot(value, 0, new Set(), { left: maxBytes });\n const text = JSON.stringify(clone);\n if (typeof text !== 'string') failData('json');\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n return text;\n}\n\n/** Deterministic encoding for signed RPC metadata, retaining every legal JSON key. */\nexport function encodeCanonicalRpcJson(value: unknown, maxBytes: number = RPC_JSON_MAX_BYTES): string {\n assertByteLimit(maxBytes);\n const clone = snapshot(value, 0, new Set(), { left: maxBytes });\n const canonical = (item: RpcJson): string => {\n if (item === null || typeof item !== 'object') return JSON.stringify(item);\n if (Array.isArray(item)) return `[${item.map(canonical).join(',')}]`;\n const record = item as Readonly<Record<string, RpcJson>>;\n return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonical(record[key])}`).join(',')}}`;\n };\n const text = canonical(clone);\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n return text;\n}\n\n/** Parses strict, bounded pure JSON. Non-finite numbers and lone surrogates are rejected. */\nexport function decodeRpcJson(text: string, maxBytes: number = RPC_JSON_MAX_BYTES): RpcJson {\n assertByteLimit(maxBytes);\n if (typeof text !== 'string') failData('json');\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n scanJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new RpcProtocolError('invalid_data', 'invalid JSON text');\n }\n assertJsonGraph(parsed);\n return parsed as RpcJson;\n}\n\nfunction jsonEquals(left: RpcJson, right: RpcJson): boolean {\n if (left === right) return true;\n if (typeof left !== typeof right) return false;\n if (Array.isArray(left) !== Array.isArray(right)) return false;\n if (Array.isArray(left)) {\n if (!Array.isArray(right) || left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1) {\n if (!jsonEquals(left[index], right[index])) return false;\n }\n return true;\n }\n if (typeof left === 'object' && left !== null && right !== null && typeof right === 'object') {\n const leftRecord = left as Record<string, RpcJson>;\n const rightRecord = right as Record<string, RpcJson>;\n const keys = Object.keys(leftRecord);\n if (keys.length !== Object.keys(rightRecord).length) return false;\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(rightRecord, key)) return false;\n if (!jsonEquals(leftRecord[key], rightRecord[key])) return false;\n }\n return true;\n }\n return false;\n}\n\nfunction checkOptionalNonNegative(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!isNonNegativeSafeInteger(value)) failContract(`${field} must be a non-negative safe integer`);\n return value;\n}\n\nfunction checkOptionalFinite(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) failContract(`${field} must be a finite number`);\n return value;\n}\n\nfunction checkSchema(input: unknown, depth: number, seen: Set<object>): void {\n if (depth > SCHEMA_MAX_DEPTH) failContract('schema nesting exceeds the limit');\n if (!isPlainObject(input)) failContract('schema must be a plain object');\n if (seen.has(input)) failContract('schema must not contain cycles');\n seen.add(input);\n const type = input.type;\n if (type === 'string') {\n assertKnownKeys(input, ['type', 'minLength', 'maxLength'], 'schema');\n const min = checkOptionalNonNegative(input.minLength, 'minLength');\n const max = checkOptionalNonNegative(input.maxLength, 'maxLength');\n if (min !== undefined && max !== undefined && min > max) failContract('string minLength must not exceed maxLength');\n } else if (type === 'number') {\n assertKnownKeys(input, ['type', 'integer', 'minimum', 'maximum'], 'schema');\n if (input.integer !== undefined && typeof input.integer !== 'boolean') failContract('number integer flag must be boolean');\n const min = checkOptionalFinite(input.minimum, 'minimum');\n const max = checkOptionalFinite(input.maximum, 'maximum');\n if (min !== undefined && max !== undefined && min > max) failContract('number minimum must not exceed maximum');\n } else if (type === 'boolean') {\n assertKnownKeys(input, ['type'], 'schema');\n } else if (type === 'null') {\n assertKnownKeys(input, ['type'], 'schema');\n } else if (type === 'literal') {\n assertKnownKeys(input, ['type', 'value'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'value')) failContract('literal schema requires a value');\n try {\n snapshot(input.value, 0, new Set(), { left: Infinity });\n } catch (error) {\n if (error instanceof RpcProtocolError && error.code === 'invalid_data') {\n failContract('literal value must be pure JSON');\n }\n throw error;\n }\n } else if (type === 'array') {\n assertKnownKeys(input, ['type', 'items', 'maxItems'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'items')) failContract('array schema requires items');\n checkSchema(input.items, depth + 1, seen);\n checkOptionalNonNegative(input.maxItems, 'maxItems');\n } else if (type === 'object') {\n assertKnownKeys(input, ['type', 'properties', 'optional'], 'schema');\n const properties = input.properties;\n if (!isPlainObject(properties)) failContract('object schema requires a properties record');\n for (const key of Object.keys(properties)) checkSchema(properties[key], depth + 1, seen);\n const optional = input.optional;\n if (optional !== undefined) {\n if (!Array.isArray(optional)) failContract('object optional must be an array of field names');\n const names = new Set<string>();\n for (const name of optional) {\n if (typeof name !== 'string') failContract('object optional entries must be strings');\n if (names.has(name)) failContract('object optional entries must be unique');\n names.add(name);\n if (!Object.prototype.hasOwnProperty.call(properties, name)) {\n failContract('object optional names must exist in properties');\n }\n }\n }\n } else if (type === 'record') {\n assertKnownKeys(input, ['type', 'values', 'maxEntries'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'values')) failContract('record schema requires values');\n checkSchema(input.values, depth + 1, seen);\n checkOptionalNonNegative(input.maxEntries, 'maxEntries');\n } else if (type === 'union') {\n assertKnownKeys(input, ['type', 'variants'], 'schema');\n const variants = input.variants;\n if (!Array.isArray(variants) || variants.length === 0) {\n failContract('union schema requires a non-empty variants array');\n }\n for (const variant of variants) checkSchema(variant, depth + 1, seen);\n } else if (type === 'json') {\n assertKnownKeys(input, ['type', 'maxBytes'], 'schema');\n if (input.maxBytes !== undefined && !isPositiveSafeInteger(input.maxBytes)) {\n failContract('json schema maxBytes must be a positive safe integer');\n }\n } else {\n failContract('unknown schema type');\n }\n seen.delete(input);\n}\n\nfunction validateValue(schema: RpcDataSchema, value: unknown): void {\n switch (schema.type) {\n case 'string': {\n if (typeof value !== 'string') failData('string');\n if (schema.minLength !== undefined && value.length < schema.minLength) failData('string');\n if (schema.maxLength !== undefined && value.length > schema.maxLength) failData('string');\n return;\n }\n case 'number': {\n if (typeof value !== 'number' || !Number.isFinite(value)) failData('number');\n if (schema.integer === true && !Number.isInteger(value)) failData('number');\n if (schema.minimum !== undefined && value < schema.minimum) failData('number');\n if (schema.maximum !== undefined && value > schema.maximum) failData('number');\n return;\n }\n case 'boolean': {\n if (typeof value !== 'boolean') failData('boolean');\n return;\n }\n case 'null': {\n if (value !== null) failData('null');\n return;\n }\n case 'literal': {\n if (!jsonEquals(schema.value, value as RpcJson)) failData('literal');\n return;\n }\n case 'array': {\n if (!Array.isArray(value)) failData('array');\n if (schema.maxItems !== undefined && value.length > schema.maxItems) failData('array');\n for (const item of value) validateValue(schema.items, item);\n return;\n }\n case 'object': {\n if (!isPlainObject(value)) failData('object');\n const optional = new Set(schema.optional ?? []);\n for (const key of Object.keys(value)) {\n if (!Object.prototype.hasOwnProperty.call(schema.properties, key)) failData('object');\n }\n for (const key of Object.keys(schema.properties)) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n if (!optional.has(key)) failData('object');\n continue;\n }\n validateValue(schema.properties[key], value[key]);\n }\n return;\n }\n case 'record': {\n if (!isPlainObject(value)) failData('record');\n const keys = Object.keys(value);\n if (schema.maxEntries !== undefined && keys.length > schema.maxEntries) failData('record');\n for (const key of keys) validateValue(schema.values, value[key]);\n return;\n }\n case 'union': {\n for (const variant of schema.variants) {\n try {\n validateValue(variant, value);\n return;\n } catch (error) {\n if (!(error instanceof RpcProtocolError) || error.code !== 'invalid_data') throw error;\n }\n }\n failData('union');\n }\n case 'json': {\n const maxBytes = schema.maxBytes ?? RPC_JSON_MAX_BYTES;\n const text = JSON.stringify(value);\n if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > maxBytes) failData('json');\n return;\n }\n }\n}\n\n/**\n * Asserts a runtime value matches the schema. The whole value is first cloned\n * into bounded pure JSON without invoking accessors, then validated. Throws\n * `RpcProtocolError` with `invalid_data` (value) or `invalid_contract` (malformed\n * schema).\n */\n/** Validates a standalone data schema (lane contract registration) without a value. */\nexport function assertRpcDataSchema(schema: RpcDataSchema): void {\n const pure = snapshotPureInput(schema);\n checkSchema(pure, 0, new Set());\n}\n\nexport function assertRpcData<S extends RpcDataSchema>(\n schema: S,\n value: unknown,\n maxBytes?: number,\n): asserts value is InferRpcData<S> { const pureSchema = snapshotPureInput(schema);\n checkSchema(pureSchema, 0, new Set());\n const checkedSchema = pureSchema as unknown as RpcDataSchema;\n const limit = maxBytes ?? (checkedSchema.type === 'json' ? checkedSchema.maxBytes ?? RPC_JSON_MAX_BYTES : RPC_JSON_MAX_BYTES);\n assertByteLimit(limit);\n let pureValue: RpcJson;\n try { pureValue = snapshot(value, 0, new Set(), { left: limit }); }\n catch (error) {\n if (error instanceof RpcProtocolError && error.code === 'size_limit') failData('json');\n throw error;\n }\n if (Buffer.byteLength(JSON.stringify(pureValue), 'utf8') > limit) failData('json');\n validateValue(checkedSchema, pureValue);\n}\n\nfunction assertByteLimit(maxBytes: number): void {\n if (!isPositiveSafeInteger(maxBytes)) failContract('maxBytes must be a positive safe integer');\n}\n\nfunction checkByteLimit(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!isPositiveSafeInteger(value) || value > RPC_JSON_MAX_BYTES) {\n failContract(`${field} must be a positive integer no larger than the RPC envelope`);\n }\n return value;\n}\n\nfunction checkCommandPolicy(policy: Record<string, unknown>, maxOutputBytes: number): void {\n const keys = Object.keys(policy);\n if (keys.length !== RPC_COMMAND_POLICY_KEYS.size || keys.some((key) => !RPC_COMMAND_POLICY_KEYS.has(key))) {\n failContract('command policy fields are fixed');\n }\n const deduplication = policy.deduplication;\n if (typeof deduplication !== 'string' || !RPC_COMMAND_DEDUPLICATION.has(deduplication as RpcCommandDeduplication)) {\n failContract('invalid command deduplication');\n }\n const retention = policy.resultRetentionMs;\n if (retention !== null && !isPositiveSafeInteger(retention)) {\n failContract('resultRetentionMs must be a positive integer or null');\n }\n const maxResultBytes = policy.maxResultBytes;\n if (!isPositiveSafeInteger(maxResultBytes)) failContract('maxResultBytes must be a positive safe integer');\n if (maxResultBytes > maxOutputBytes) failContract('maxResultBytes must not exceed maxOutputBytes');\n const quotaBytes = policy.quotaBytes;\n if (!isPositiveSafeInteger(quotaBytes)) failContract('quotaBytes must be a positive safe integer');\n if (quotaBytes < maxResultBytes) failContract('quotaBytes must be able to hold maxResultBytes');\n}\n\nfunction checkMethod(definition: Record<string, unknown>): void {\n assertKnownKeys(definition, METHOD_KEYS, 'method');\n const kind = definition.kind;\n if (kind !== 'query' && kind !== 'command') failContract('method kind must be query or command');\n checkSchema(definition.input, 0, new Set());\n checkSchema(definition.output, 0, new Set());\n const purposes = definition.purposes;\n if (!Array.isArray(purposes) || purposes.length === 0) failContract('purposes must be a non-empty array');\n const seenPurposes = new Set<string>();\n for (const purpose of purposes) {\n if (typeof purpose !== 'string' || !RPC_CALL_PURPOSES.has(purpose as RpcCallPurpose)) failContract('invalid purpose');\n if (seenPurposes.has(purpose)) failContract('purposes must be unique');\n seenPurposes.add(purpose);\n }\n if (definition.timeoutMs !== undefined) {\n if (!isPositiveSafeInteger(definition.timeoutMs) || definition.timeoutMs > RPC_MAX_TIMEOUT_MS) {\n failContract('timeoutMs must be a positive integer no larger than the timeout bound');\n }\n }\n checkByteLimit(definition.maxInputBytes, 'maxInputBytes');\n const maxOutputBytes = checkByteLimit(definition.maxOutputBytes, 'maxOutputBytes');\n const command = definition.command;\n if (kind === 'command') {\n if (!isPlainObject(command)) failContract('command methods require an explicit command policy');\n checkCommandPolicy(command, maxOutputBytes ?? RPC_JSON_MAX_BYTES);\n } else if (command !== undefined) {\n failContract('query methods must not declare a command policy');\n }\n}\n\nfunction checkContract(contract: unknown): void {\n if (!isPlainObject(contract)) failContract('contract must be a plain object');\n assertKnownKeys(contract, CONTRACT_KEYS, 'contract');\n if (typeof contract.id !== 'string' || !RPC_SERVICE_ID.test(contract.id)) failContract('invalid service id');\n if (!isPositiveSafeInteger(contract.version)) failContract('service version must be a positive safe integer');\n const methods = contract.methods;\n if (!isPlainObject(methods)) failContract('methods must be a plain object');\n const names = Object.keys(methods);\n if (names.length === 0) failContract('service must declare at least one method');\n if (names.length > RPC_MAX_METHODS) failContract('service declares too many methods');\n for (const name of names) {\n if (!RPC_METHOD_NAME.test(name)) failContract('invalid method name');\n const definition = methods[name];\n if (!isPlainObject(definition)) failContract('method definition must be a plain object');\n checkMethod(definition);\n }\n}\n\nfunction deepFreeze(value: unknown): unknown {\n if (Array.isArray(value)) {\n for (const item of value) deepFreeze(item);\n return Object.freeze(value);\n }\n if (isPlainObject(value)) {\n for (const key of Object.keys(value)) deepFreeze(value[key]);\n return Object.freeze(value);\n }\n return value;\n}\n\n/**\n * Validates a service contract and returns a deep-frozen pure clone. The caller's\n * objects are never read through accessors, never frozen, and never modified;\n * `methods` keeps its literal types so clients can derive call signatures.\n */\nexport function defineRpcService<const M extends Record<string, RpcMethodDefinition>>(contract: {\n readonly id: string;\n readonly version: number;\n readonly methods: M;\n}): RpcServiceContract<M> {\n const pure = snapshotPureInput(contract);\n checkContract(pure);\n return deepFreeze(pure) as unknown as RpcServiceContract<M>;\n}\n",
@@ -10,7 +10,7 @@
10
10
  ],
11
11
  "uiExtensionMode": "none",
12
12
  "engines": {
13
- "bungee": "^4.2.0 || ^5.0.0"
13
+ "bungee": "^6.0.0"
14
14
  },
15
15
  "builtin": true,
16
16
  "contributes": {},