@jeffusion/bungee-core 5.16.0 → 5.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config-publication/worker-runtime-contract.d.ts +1 -1
- package/dist/config-storage/gateway-target-validation.d.ts +5 -0
- package/dist/config-worker/lifecycle.d.ts +6 -0
- package/dist/data-admission/worker.d.ts +1 -0
- package/dist/gateway/contracts.d.ts +1 -1
- package/dist/gateway/plugin.d.ts +1 -0
- package/dist/gateway/plugin.js +15 -1
- package/dist/gateway/runtime.d.ts +2 -0
- package/dist/gateway/websocket-contracts.d.ts +62 -0
- package/dist/gateway/websocket-credential.d.ts +3 -0
- package/dist/gateway/websocket-plugin.d.ts +9 -0
- package/dist/hooks/plugin-hooks.d.ts +8 -0
- package/dist/logger/access-log-writer.d.ts +1 -1
- package/dist/main.js +4326 -128
- package/dist/plugin.types.d.ts +1 -1
- package/dist/plugins/ai-transformer/index.js.map +2 -2
- package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
- package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
- package/dist/plugins/chatgpt-oauth/index.js +12 -4
- package/dist/plugins/chatgpt-oauth/index.js.map +5 -5
- package/dist/plugins/chatgpt-oauth/manifest.json +41 -0
- package/dist/plugins/codex-router/control.js +49 -0
- package/dist/plugins/codex-router/control.js.map +11 -0
- package/dist/plugins/codex-router/index.js +318 -0
- package/dist/plugins/codex-router/index.js.map +27 -0
- package/dist/plugins/codex-router/manifest.json +149 -0
- package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
- package/dist/plugins/key-access/index.js.map +2 -2
- package/dist/plugins/key-rate-limit/index.js.map +2 -2
- package/dist/plugins/local-accounts/index.js.map +2 -2
- package/dist/plugins/model-mapping/control.js.map +1 -1
- package/dist/plugins/model-mapping/index.js.map +3 -3
- package/dist/plugins/models-dev/control.js +24 -1
- package/dist/plugins/models-dev/control.js.map +5 -5
- package/dist/plugins/models-dev/index.js +24 -1
- package/dist/plugins/models-dev/index.js.map +6 -6
- package/dist/plugins/models-dev/manifest.json +12 -0
- package/dist/plugins/openai-messages-to-chat/index.js.map +2 -2
- package/dist/plugins/signature-repair/index.js.map +2 -2
- package/dist/plugins/token-budget/index.js.map +2 -2
- package/dist/plugins/token-metering/index.js +225 -3
- package/dist/plugins/token-metering/index.js.map +6 -5
- package/dist/plugins/token-stats/control.js.map +1 -1
- package/dist/plugins/token-stats/index.js.map +3 -3
- package/dist/public-listener/websocket.d.ts +4 -0
- package/dist/scoped-plugin-registry.d.ts +12 -0
- package/dist/websocket/headers.d.ts +9 -0
- package/dist/websocket/index.d.ts +3 -0
- package/dist/websocket/message.d.ts +3 -0
- package/dist/websocket/observation.d.ts +17 -0
- package/dist/websocket/transport.d.ts +77 -0
- package/package.json +4 -2
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/plugin-logger.ts", "../../../src/hooks/impl.ts", "../../../src/plugin.types.ts", "../../../src/plugin-extensions.ts", "../../../src/plugin-durable-state.ts", "../../../src/plugin-services/host-rpc.ts", "../../../src/plugin-services/wire-contract.ts", "../../../src/plugin-services/rpc-runtime.ts", "../../../src/plugin-services/peer-channel-protocol.ts", "../../../src/plugin-services/peer-channel-hub.ts", "../../../src/plugin-services/snapshot-store.ts", "../../../src/plugin-services.ts", "../../../src/gateway/retry-action.ts", "../../../src/token-stats-window.ts", "../../../../../plugins/models-dev/contract.ts", "../../../../../plugins/codex-router/server/config.ts", "../../../../../plugins/codex-router/server/catalog.ts", "../../../../../plugins/codex-router/server/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
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
|
+
"/**\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
|
+
"/**\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 plugins run once for all routes whenever activated; defaults to scoped bindings. */\n runtimeScope?: 'global' | 'scoped';\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\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 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): boolean;\n login(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): boolean;\n revokeSessions(): 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): string | undefined;\n}\nexport interface AdmissionTarget {\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 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
|
+
"import type { Database } from 'bun:sqlite';\nimport { createHash } from 'node:crypto';\n\n/** Configuration migration owns this DDL; constructors never modify schema. */\nexport const PLUGIN_DURABLE_STATE_SCHEMA_SQL = `\nCREATE TABLE 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;\nCREATE TABLE plugin_durable_commands (\n namespace TEXT NOT NULL, command_id TEXT NOT NULL, fingerprint TEXT NOT NULL,\n result_json TEXT NOT NULL, PRIMARY KEY(namespace, command_id)\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 }\nexport interface DurableCommand { commandId: string; mutations: readonly DurableMutation[] }\n/**\n * Host-only execution options. `extend` runs inside the SAME immediate\n * transaction, after the record mutations and the command row: it is the\n * outbox seam that commits a communication record atomically with the business\n * state. A throw from `extend` rolls back the whole command, and an idempotent\n * replay never runs it again (the first committed run already wrote its rows).\n */\nexport interface DurableCommandOptions { readonly extend?: () => void }\nexport interface PluginDurableState {\n get(key: string): DurableRecord | null;\n list(): readonly DurableRecord[];\n execute(command: DurableCommand, options?: DurableCommandOptions): 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}\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 and historical command IDs 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 forNamespace(namespace: string): PluginDurableState {\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 execute: (command: DurableCommand, options?: DurableCommandOptions): readonly DurableRecord[] => {\n identifier(command.commandId);\n if (!Array.isArray(command.mutations) || command.mutations.length === 0 || command.mutations.length > 256) throw new Error('Invalid durable state command');\n if (options !== undefined && options !== null && typeof options.extend !== 'undefined' && typeof options.extend !== 'function') throw new Error('Invalid durable state options');\n const keys = new Set<string>();\n const mutations = command.mutations.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 const fingerprint = createHash('sha256').update(commandJson).digest('hex');\n return db.transaction(() => {\n const prior = db.query<{ fingerprint: string; result_json: string }, [string, string]>('SELECT fingerprint,result_json FROM plugin_durable_commands WHERE namespace = ? AND command_id = ?').get(namespace, command.commandId);\n if (prior) {\n if (prior.fingerprint !== fingerprint) throw new Error('Durable state command ID already used');\n return Object.freeze((JSON.parse(prior.result_json) as DurableRecord[]).map(item => Object.freeze(item)));\n }\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 db.query('INSERT INTO plugin_durable_commands(namespace,command_id,fingerprint,result_json) VALUES (?,?,?,?)').run(namespace, command.commandId, fingerprint, JSON.stringify(results));\n // Outbox seam: same transaction, same connection, first execution only.\n options?.extend?.();\n return Object.freeze(results);\n }).immediate();\n },\n });\n }\n}\n",
|
|
10
|
+
"/**\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 {\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 /** 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 readonly external?: CommandExternalExecutor;\n}\n\n/** Host-owned durable journal factory; `null` refuses commands for this key. */\nexport type HostRpcJournalResolver = (request: HostRpcJournalRequest) => 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 HostRpcAdapterOptions {\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 external: CommandExternalExecutor | undefined;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || (key !== 'atomic' && 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 === '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; external?: CommandExternalExecutor } = {};\n if (atomic !== undefined) record.atomic = atomic;\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 return 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 };\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 ): 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?.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
|
+
"/**\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",
|
|
12
|
+
"/**\n * Host-only generic RPC execution kernel (P4): publication validation, admission-gated\n * dispatch, bounded concurrency, cancellation/deadline bookkeeping, retirement, drain, and\n * disposal. It owns NO security policy — the host supplies a required synchronous `admit`\n * callback that resolves a logical target to an exact registered opaque endpoint, a trusted\n * callee context, and a real lease release. No default allow, no retry, no invented context.\n *\n * Hardening guarantees:\n * - The outer invoke request (and its target/caller) is snapshotted through own property\n * descriptors: accessors, proxies, symbol/unknown keys are rejected and never invoked, so\n * authorization and dispatch observe the same immutable metadata.\n * - Commands track the REAL business promise, not only the executor promise: fire-and-forget\n * executors cannot release a task early, and a late `executeBusiness` closure after the\n * executor is terminal is refused without running user code.\n * - Public rejections are always rebuilt fixed-code errors: provider/admit messages, causes,\n * and operation ids never leak or spoof the wire error.\n * - Released endpoints drop the full record (handler/contract/runtime) and keep only a\n * lightweight revoked identity; drain/dispose waiter slots are bounded.\n *\n * Command execution is NOT implemented here: it must go through the host `RpcCommandExecutor`.\n * Durable deduplication, transactions, and cross-system exactly-once guarantees belong to the\n * still-pending P4 journal integration; a declared `command.deduplication` intent is never\n * upgraded into a delivered guarantee.\n */\nimport { isProxy } from 'node:util/types';\nimport type { PluginServiceProcess, PluginServiceScope } from './contracts';\nimport {\n RPC_JSON_MAX_BYTES,\n RpcProtocolError,\n assertRpcData,\n decodeRpcJson,\n defineRpcService,\n encodeRpcJson,\n type InferRpcData,\n type RpcCallKind,\n type RpcCallPurpose,\n type RpcDataSchema,\n type RpcJson,\n type RpcMethodDefinition,\n type RpcServiceContract,\n} from './wire-contract';\n\nconst OPERATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\nconst PROCESSES = new Set<string>(['control', 'worker', 'ingress']);\nconst SCOPES = new Set<string>(['global', 'binding']);\nconst PURPOSES = new Set<string>(['bootstrap', 'background', 'management', 'request', 'attempt']);\nconst DEFAULT_GLOBAL_MAX_IN_FLIGHT = 256;\nconst DEFAULT_ENDPOINT_MAX_IN_FLIGHT = 64;\nconst DEFAULT_CALLER_MAX_IN_FLIGHT = 64;\nconst DEFAULT_MAX_WAITERS = 256;\nconst DEFAULT_HARD_DEADLINE_MS = 300_000;\nconst DEFAULT_DRAIN_TIMEOUT_MS = 30_000;\n/** Node clamps setTimeout delays above this to 1ms; reject instead of silently degrading. */\nconst MAX_TIMER_MS = 2_147_483_647;\nconst REQUEST_KEYS = ['target', 'caller', 'callerToken', 'purpose', 'input', 'operationId', 'signal', 'timeoutMs', 'deadlineAt', 'maxInputBytes', 'commandAction'] as const;\nconst TARGET_KEYS = ['provider', 'service', 'major', 'method'] as const;\nconst CALLER_KEYS = ['subject', 'scope'] as const;\n\n/** Deployment identity bound by the external host verifier's endpoint ref. */\nexport interface RpcEndpointBinding {\n readonly endpoint: string;\n readonly process: PluginServiceProcess;\n readonly instance: string;\n readonly generation: number;\n readonly catalog: string;\n readonly scope: PluginServiceScope;\n readonly subject: string;\n}\n/** Logical call target, independent of the physical address and generation. */\nexport interface RpcInvokeTarget {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly method: string;\n}\n/** Stable caller identity; the host admission callback decides authorization. */\nexport interface RpcCaller {\n readonly subject: string;\n readonly scope?: PluginServiceScope;\n}\n/** Opaque frozen capability minted by `register`; only a WeakMap-registered handle is accepted. */\nexport interface RpcEndpointHandle {\n readonly __rpcEndpoint?: never;\n}\n/** Immutable admission input; the runtime snapshots and freezes these before calling `admit`. */\nexport interface RpcAdmissionRequest {\n readonly target: RpcInvokeTarget;\n readonly caller: RpcCaller;\n /** Host-private concrete caller identity; never supplied by JSON or SDK call options. */\n readonly callerToken?: object;\n readonly purpose: RpcCallPurpose;\n readonly operationId: string | null;\n readonly commandAction?: RpcCommandAction;\n}\nexport interface RpcAdmissionGrant<TCallee = unknown> {\n readonly endpoint: RpcEndpointHandle;\n readonly callee: TCallee;\n /** Releases the real host lease; called exactly once per accepted or rejected attempt. */\n readonly release: () => void;\n /** Admission-owned lifetime identity also covers legacy internal calls without an input token. */\n readonly callerToken?: object;\n /** Trusted host permission for a bootstrap call to a registered-but-not-ready endpoint. */\n readonly allowUnready?: boolean;\n /** Host-verified existing request lease only; never enables new background work. */\n readonly allowRetired?: boolean;\n}\n/** Must be synchronous: admission is atomic and checked on every request. */\nexport type RpcAdmission<TCallee = unknown> = (request: RpcAdmissionRequest) => RpcAdmissionGrant<TCallee> | null;\n/** Process-local handler context; the signal is never serialized onto the wire. */\nexport interface RpcHandlerContext<TCallee = unknown> {\n readonly endpoint: Readonly<RpcEndpointBinding & { readonly service: string; readonly version: number }>;\n readonly caller: Readonly<RpcCaller>;\n readonly method: string;\n readonly kind: RpcCallKind;\n readonly purpose: RpcCallPurpose;\n readonly operationId: string | null;\n readonly signal: AbortSignal;\n readonly callee: TCallee;\n /** Actual bounded invocation deadline, including caller and runtime limits. */\n readonly deadlineAt?: number;\n}\n/** Derives typed handler signatures from a literal contract. */\nexport type RpcHandlerMap<M extends Record<string, RpcMethodDefinition>, TCallee = unknown> = {\n readonly [K in keyof M]: (\n input: InferRpcData<M[K]['input']>,\n context: RpcHandlerContext<TCallee>,\n ) => InferRpcData<M[K]['output']> | Promise<InferRpcData<M[K]['output']>>;\n};\nexport interface RpcCommandExecution<TCallee = unknown> {\n readonly contract: RpcServiceContract;\n readonly method: string;\n readonly definition: RpcMethodDefinition;\n readonly context: RpcHandlerContext<TCallee>;\n readonly operationId: string;\n readonly input: RpcJson;\n /** Starts the real provider logic once; a repeated call returns the same promise. */\n readonly executeBusiness: () => Promise<RpcJson>;\n}\n/**\n * Host capability and the ONLY execution path for commands. This kernel invokes `execute` once\n * and never retries. Durable deduplication, transactions, and cross-system exactly-once behavior\n * are NOT implemented here: the P4 journal/CommandExecutor integration is still pending wiring.\n */\nexport interface RpcCommandExecutor<TCallee = unknown> {\n execute(execution: RpcCommandExecution<TCallee>): Promise<unknown>;\n queryResult?(execution: Omit<RpcCommandExecution<TCallee>, 'executeBusiness'>): Promise<unknown>;\n reconcile?(execution: Omit<RpcCommandExecution<TCallee>, 'executeBusiness'>): Promise<unknown>;\n}\nexport type RpcCommandAction = 'execute' | 'query-result' | 'reconcile';\nexport type RpcInvocationErrorCode =\n | 'unauthorized' | 'not_ready' | 'retired' | 'revoked' | 'unsupported_method' | 'wrong_purpose'\n | 'invalid_input' | 'invalid_output' | 'invalid_operation_id' | 'overloaded' | 'cancelled'\n | 'timeout' | 'unknown' | 'capability_unavailable' | 'closed' | 'failed'\n | 'conflict' | 'expired' | 'pending' | 'rejected' | 'missing' | 'storage_failure'\n | 'deadlock' | 'call_depth_exceeded';\nconst ERROR_MESSAGES: Record<RpcInvocationErrorCode, 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};\n/**\n * Fixed-code error. It never stores a provider/admit cause, message, or payload: the code and\n * the validated invocation's operation id are the only external data. Hosts log the original\n * exception separately.\n */\nexport class RpcInvocationError extends Error {\n readonly name = 'RpcInvocationError';\n readonly code: RpcInvocationErrorCode;\n readonly operationId: string | null;\n constructor(code: RpcInvocationErrorCode, operationId: string | null = null) {\n super(ERROR_MESSAGES[code]);\n this.code = code;\n this.operationId = operationId;\n }\n}\nexport interface RpcRuntimeLimits {\n readonly maxEndpoints?: number;\n readonly globalMaxInFlight?: number;\n readonly endpointMaxInFlight?: number;\n readonly callerMaxInFlight?: number;\n readonly maxWaiters?: number;\n readonly hardDeadlineMs?: number;\n readonly drainTimeoutMs?: number;\n}\ninterface ResolvedLimits {\n readonly maxEndpoints: number;\n readonly globalMaxInFlight: number;\n readonly endpointMaxInFlight: number;\n readonly callerMaxInFlight: number;\n readonly maxWaiters: number;\n readonly hardDeadlineMs: number;\n readonly drainTimeoutMs: number;\n}\nexport interface RpcInvokeRequest {\n readonly target: RpcInvokeTarget;\n readonly caller: RpcCaller;\n /** Host-private lifetime identity, separate from the journal's stable logical caller. */\n readonly callerToken?: object;\n readonly purpose: RpcCallPurpose;\n readonly input: unknown;\n readonly operationId?: string | null;\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n /** Host-owned absolute upper bound; never recomputed from a remaining duration. */\n readonly deadlineAt?: number;\n /** Narrower caller/parent header budget, combined with the method input limit. */\n readonly maxInputBytes?: number;\n /** Command control actions use the same target authorization, lease and deadline. */\n readonly commandAction?: RpcCommandAction;\n}\nexport interface RpcRuntimeStatus {\n readonly closed: boolean;\n readonly active: number;\n readonly endpoints: number;\n readonly waiters: number;\n}\nexport interface RpcDrainResult {\n readonly drained: boolean;\n readonly active: number;\n}\nexport interface RpcDisposeResult {\n readonly disposed: boolean;\n readonly active: number;\n}\nexport interface RpcRuntimeOptions<TCallee = unknown> {\n readonly admit: RpcAdmission<TCallee>;\n readonly commandExecutor?: RpcCommandExecutor<TCallee>;\n readonly hostLifetime?: AbortSignal;\n readonly limits?: RpcRuntimeLimits;\n}\n/** Host transport only. A rejected terminal promise never proves remote work ended. */\nexport interface RpcProxyExecution {\n readonly result: Promise<unknown>;\n readonly terminal: Promise<void>;\n}\nexport interface RpcProxyRequest<TCallee = unknown> {\n readonly method: string;\n readonly input: RpcJson;\n readonly context: RpcHandlerContext<TCallee>;\n readonly commandAction?: RpcCommandAction;\n}\nexport type RpcProxyExecutor<TCallee = unknown> = (request: RpcProxyRequest<TCallee>) => RpcProxyExecution;\ntype Handler = (input: RpcJson, context: RpcHandlerContext<unknown>) => unknown;\ninterface InvocationTracking { started: () => void; terminal: () => void }\ninterface EndpointRecord {\n readonly handle: RpcEndpointHandle;\n readonly runtime: object;\n readonly provider: string;\n readonly contract: RpcServiceContract;\n readonly methods: ReadonlyMap<string, RpcMethodDefinition>;\n readonly handler: ReadonlyMap<string, Handler>;\n readonly proxy: RpcProxyExecutor<unknown> | null;\n readonly binding: Readonly<RpcEndpointBinding>;\n ready: boolean;\n retiring: boolean;\n revoked: boolean;\n readonly active: Set<CallTask>;\n}\ntype AbortReason = 'cancelled' | 'timeout' | 'closed' | 'revoked' | 'retired';\ninterface CallTask {\n readonly record: EndpointRecord;\n readonly caller: RpcCaller;\n readonly callerKey: string;\n readonly callerToken?: object;\n readonly kind: RpcCallKind;\n readonly purpose: RpcCallPurpose;\n readonly deadlineAt: number;\n readonly allowRetired: boolean;\n readonly operationId: string | null;\n readonly release: () => void;\n readonly controller: AbortController;\n readonly cleanups: Array<() => void>;\n abortReason: AbortReason | null;\n callerSettled: boolean;\n finished: boolean;\n delivered: boolean;\n proxyTerminal: boolean;\n onTerminal?: () => void;\n resolve: (value: RpcJson) => void;\n reject: (error: unknown) => void;\n}\ninterface Waiter {\n check: () => boolean;\n settle: () => void;\n}\nconst ENDPOINTS = new WeakMap<object, EndpointRecord>();\n/** Revoked identity only: handle -> the runtime token that owned it. Never retains the record. */\nconst REVOKED = new WeakMap<object, object>();\n\nfunction positiveLimit(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new RpcProtocolError('invalid_contract', `invalid_contract: invalid ${label}`);\n }\n return value;\n}\nfunction timeoutLimit(value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_MS) {\n throw new RpcProtocolError('invalid_contract', 'invalid_contract: invalid timeout bound');\n }\n return value;\n}\nfunction resolveLimits(limits: RpcRuntimeLimits = {}): ResolvedLimits {\n return Object.freeze({\n maxEndpoints: positiveLimit(limits.maxEndpoints, 1024, 'endpoint limit'),\n globalMaxInFlight: positiveLimit(limits.globalMaxInFlight, DEFAULT_GLOBAL_MAX_IN_FLIGHT, 'global capacity'),\n endpointMaxInFlight: positiveLimit(limits.endpointMaxInFlight, DEFAULT_ENDPOINT_MAX_IN_FLIGHT, 'endpoint capacity'),\n callerMaxInFlight: positiveLimit(limits.callerMaxInFlight, DEFAULT_CALLER_MAX_IN_FLIGHT, 'caller capacity'),\n maxWaiters: positiveLimit(limits.maxWaiters, DEFAULT_MAX_WAITERS, 'waiter capacity'),\n hardDeadlineMs: timeoutLimit(limits.hardDeadlineMs, DEFAULT_HARD_DEADLINE_MS),\n drainTimeoutMs: timeoutLimit(limits.drainTimeoutMs, DEFAULT_DRAIN_TIMEOUT_MS),\n });\n}\nfunction once(action: () => void): () => void {\n let done = false;\n return () => { if (done) return; done = true; action(); };\n}\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n if (value === null) return false;\n const type = typeof value;\n if (type !== 'object' && type !== 'function') return false;\n try { return typeof (value as { then?: unknown }).then === 'function'; } catch { return false; }\n}\nfunction invalidRegistration(): RpcProtocolError {\n return new RpcProtocolError('invalid_contract', 'invalid_contract: invalid RPC endpoint registration');\n}\nfunction invalidInput(): RpcInvocationError {\n return new RpcInvocationError('invalid_input');\n}\n/** Never reuses a provider error, cause, message or spoofed operation id. */\nfunction invocationFailure(error: unknown, operationId: string | null): RpcInvocationError {\n if (error !== null && typeof error === 'object' && !isProxy(error)) {\n const descriptor = Object.getOwnPropertyDescriptor(error, 'code');\n const code = descriptor && 'value' in descriptor ? descriptor.value : null;\n if (typeof code === 'string' && Object.hasOwn(ERROR_MESSAGES, code)) {\n return new RpcInvocationError(code as RpcInvocationErrorCode, operationId);\n }\n }\n return new RpcInvocationError('failed', operationId);\n}\nfunction freezeBinding(binding: RpcEndpointBinding): Readonly<RpcEndpointBinding> {\n if (binding === null || typeof binding !== 'object') throw invalidRegistration();\n const record = binding as unknown as Record<string, unknown>;\n const endpoint = record.endpoint;\n const process = record.process;\n const instance = record.instance;\n const generation = record.generation;\n const catalog = record.catalog;\n const scope = record.scope;\n const subject = record.subject;\n if (typeof endpoint !== 'string' || !endpoint) throw invalidRegistration();\n if (typeof process !== 'string' || !PROCESSES.has(process)) throw invalidRegistration();\n if (typeof instance !== 'string' || !instance) throw invalidRegistration();\n if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 1) throw invalidRegistration();\n if (typeof catalog !== 'string') throw invalidRegistration();\n if (typeof scope !== 'string' || !SCOPES.has(scope)) throw invalidRegistration();\n if (typeof subject !== 'string' || !subject) throw invalidRegistration();\n return Object.freeze({\n endpoint, process: process as PluginServiceProcess, instance, generation, catalog,\n scope: scope as PluginServiceScope, subject,\n });\n}\n/**\n * Requires an exact own data-function for every declared method and nothing else: no prototype\n * fallback, accessor, symbol key, or `toJSON` path. A provider class may publish bound plain\n * functions as own properties.\n */\nfunction validateHandler(methods: Record<string, RpcMethodDefinition>, handler: unknown): ReadonlyMap<string, Handler> {\n if (handler === null || typeof handler !== 'object') throw invalidRegistration();\n const prototype = Object.getPrototypeOf(handler);\n if (prototype !== Object.prototype && prototype !== null) throw invalidRegistration();\n const declared = Object.keys(methods);\n const allowed = new Set(declared);\n const collected = new Map<string, Handler>();\n for (const key of Reflect.ownKeys(handler)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw invalidRegistration();\n const descriptor = Object.getOwnPropertyDescriptor(handler, key);\n if (!descriptor || !('value' in descriptor) || typeof descriptor.value !== 'function') throw invalidRegistration();\n collected.set(key, descriptor.value as Handler);\n }\n for (const name of declared) if (!collected.has(name)) throw invalidRegistration();\n return collected;\n}\n/**\n * Copies own enumerable data properties without ever invoking accessors or proxy traps. Unknown\n * keys, symbols, non-enumerable properties, and non-plain objects are rejected.\n */\nfunction snapshotPlain(source: unknown, allowedKeys: readonly string[]): Record<string, unknown> {\n if (source === null || typeof source !== 'object' || isProxy(source)) throw invalidInput();\n const prototype = Object.getPrototypeOf(source);\n if (prototype !== Object.prototype && prototype !== null) throw invalidInput();\n const allowed = new Set(allowedKeys);\n const result: Record<string, unknown> = {};\n for (const key of Reflect.ownKeys(source)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw invalidInput();\n const descriptor = Object.getOwnPropertyDescriptor(source, key);\n if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) throw invalidInput();\n result[key] = descriptor.value;\n }\n return result;\n}\nfunction requireString(value: unknown): string {\n if (typeof value !== 'string' || !value) throw invalidInput();\n return value;\n}\nfunction requireId(value: unknown): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) throw invalidInput();\n return value;\n}\n/** Snapshots the outer invoke request and its target/caller into frozen, getter-free metadata. */\nfunction snapshotInvokeRequest(request: unknown): RpcInvokeRequest {\n const fields = snapshotPlain(request, REQUEST_KEYS);\n const targetFields = snapshotPlain(fields.target, TARGET_KEYS);\n const target: RpcInvokeTarget = Object.freeze({\n provider: requireString(targetFields.provider),\n service: requireString(targetFields.service),\n major: requireId(targetFields.major),\n method: requireString(targetFields.method),\n });\n const callerFields = snapshotPlain(fields.caller, CALLER_KEYS);\n const subject = requireString(callerFields.subject);\n const rawScope = callerFields.scope;\n if (rawScope !== undefined && (typeof rawScope !== 'string' || !SCOPES.has(rawScope))) throw invalidInput();\n const caller: RpcCaller = Object.freeze(rawScope === undefined\n ? { subject }\n : { subject, scope: rawScope as PluginServiceScope });\n const callerToken = fields.callerToken;\n if (callerToken !== undefined && (callerToken === null || typeof callerToken !== 'object' || isProxy(callerToken))) throw invalidInput();\n const rawPurpose = fields.purpose;\n if (typeof rawPurpose !== 'string' || !PURPOSES.has(rawPurpose)) throw invalidInput();\n if (!Object.prototype.hasOwnProperty.call(fields, 'input')) throw invalidInput();\n const rawOperationId = fields.operationId;\n let operationId: string | null = null;\n if (rawOperationId !== undefined && rawOperationId !== null) {\n if (typeof rawOperationId !== 'string' || !OPERATION_ID.test(rawOperationId)) throw new RpcInvocationError('invalid_operation_id');\n operationId = rawOperationId;\n }\n const rawTimeout = fields.timeoutMs;\n if (rawTimeout !== undefined && (typeof rawTimeout !== 'number' || !Number.isSafeInteger(rawTimeout) || rawTimeout < 0)) {\n throw invalidInput();\n }\n const rawDeadline = fields.deadlineAt;\n if (rawDeadline !== undefined && (typeof rawDeadline !== 'number' || !Number.isSafeInteger(rawDeadline) || rawDeadline <= 0)) throw invalidInput();\n const rawMaxInput = fields.maxInputBytes;\n if (rawMaxInput !== undefined\n && (typeof rawMaxInput !== 'number' || !Number.isSafeInteger(rawMaxInput) || rawMaxInput <= 0 || rawMaxInput > RPC_JSON_MAX_BYTES)) {\n throw invalidInput();\n }\n const rawSignal = fields.signal;\n if (rawSignal !== undefined && !(rawSignal instanceof AbortSignal)) throw invalidInput();\n const commandAction = fields.commandAction;\n if (commandAction !== undefined && commandAction !== 'execute'\n && commandAction !== 'query-result' && commandAction !== 'reconcile') throw invalidInput();\n return Object.freeze({\n target, caller, callerToken: callerToken as object | undefined, purpose: rawPurpose as RpcCallPurpose, input: fields.input, operationId,\n signal: rawSignal as AbortSignal | undefined,\n timeoutMs: rawTimeout as number | undefined,\n deadlineAt: rawDeadline as number | undefined,\n maxInputBytes: rawMaxInput as number | undefined,\n commandAction: commandAction as RpcCommandAction | undefined,\n });\n}\n\nexport class RpcServiceRuntime<TCallee = unknown> {\n readonly #admit: RpcAdmission<TCallee>;\n readonly #commandExecutor: RpcCommandExecutor<TCallee> | undefined;\n readonly #hostLifetime: AbortSignal | undefined;\n readonly #limits: ResolvedLimits;\n readonly #identity: object = Object.freeze({});\n readonly #endpoints = new Set<EndpointRecord>();\n readonly #tasks = new Set<CallTask>();\n readonly #callerCounts = new Map<string, number>();\n readonly #waiters = new Set<Waiter>();\n #closed = false;\n\n constructor(options: RpcRuntimeOptions<TCallee>) {\n if (options === null || typeof options !== 'object' || typeof options.admit !== 'function') {\n throw new RpcProtocolError('invalid_contract', 'invalid_contract: a host admission callback is required');\n }\n this.#admit = options.admit;\n this.#commandExecutor = options.commandExecutor;\n this.#hostLifetime = options.hostLifetime;\n this.#limits = resolveLimits(options.limits);\n }\n\n /** Validates contract+handler, binds deployment identity, returns the opaque host-owned capability. */\n register<const M extends Record<string, RpcMethodDefinition>>(options: {\n readonly provider: string;\n readonly binding: RpcEndpointBinding;\n readonly contract: { readonly id: string; readonly version: number; readonly methods: M };\n readonly handler: RpcHandlerMap<M, TCallee>;\n }): RpcEndpointHandle {\n return this.#register(options, methods => ({ handler: validateHandler(methods, options.handler), proxy: null }));\n }\n\n /** Remote commands execute their journal at the provider, never again at this proxy. */\n registerProxy<const M extends Record<string, RpcMethodDefinition>>(options: {\n readonly provider: string;\n readonly binding: RpcEndpointBinding;\n readonly contract: { readonly id: string; readonly version: number; readonly methods: M };\n readonly execute: RpcProxyExecutor<TCallee>;\n }): RpcEndpointHandle {\n return this.#register(options, () => {\n const execute = options.execute;\n if (typeof execute !== 'function') throw invalidRegistration();\n return { handler: new Map(), proxy: execute as unknown as RpcProxyExecutor<unknown> };\n });\n }\n\n #register(options: { readonly provider: string; readonly binding: RpcEndpointBinding; readonly contract: RpcServiceContract },\n implementation: (methods: Record<string, RpcMethodDefinition>) => { handler: ReadonlyMap<string, Handler>; proxy: RpcProxyExecutor<unknown> | null }): RpcEndpointHandle {\n if (this.#closed || this.#hostLifetime?.aborted) throw new RpcInvocationError('closed');\n if (this.#endpoints.size >= this.#limits.maxEndpoints) throw new RpcInvocationError('overloaded');\n if (options === null || typeof options !== 'object') throw invalidRegistration();\n if (typeof options.provider !== 'string' || !options.provider) throw invalidRegistration();\n const contract = defineRpcService(options.contract);\n const methodTable = contract.methods as Record<string, RpcMethodDefinition>;\n const methods = new Map<string, RpcMethodDefinition>();\n for (const name of Object.keys(methodTable)) methods.set(name, methodTable[name]);\n const binding = freezeBinding(options.binding);\n const { handler, proxy } = implementation(methodTable);\n const handle: RpcEndpointHandle = Object.freeze({});\n const record: EndpointRecord = {\n handle, runtime: this, provider: options.provider, contract, methods, handler, proxy, binding,\n ready: false, retiring: false, revoked: false, active: new Set(),\n };\n ENDPOINTS.set(handle, record);\n this.#endpoints.add(record);\n return handle;\n }\n\n markReady(handle: RpcEndpointHandle): boolean {\n const record = this.#lookup(handle);\n if (!record || record.revoked || record.retiring) return false;\n record.ready = true;\n return true;\n }\n\n /** Stops new admissions immediately; already-accepted calls keep their lease until they finish. */\n retire(handle: RpcEndpointHandle): boolean {\n const record = this.#lookup(handle);\n if (!record || record.revoked) return false;\n record.retiring = true;\n return true;\n }\n\n /** Rejects the old reference and settles in-flight callers; late replies are never delivered. */\n revoke(handle: RpcEndpointHandle): boolean {\n const record = this.#lookup(handle);\n if (!record || record.revoked) return false;\n record.revoked = true;\n record.retiring = true;\n for (const task of [...record.active]) this.#abortTask(task, 'revoked');\n if (record.active.size === 0) this.#releaseRecord(record);\n return true;\n }\n\n /** Host-only entire-endpoint drain/verified peer exit proof. A single-call ACK must NOT use this. */\n confirmProxyEndpointStopped(handle: RpcEndpointHandle): boolean {\n const record = this.#lookup(handle);\n if (!record?.proxy) return false;\n this.revoke(handle);\n for (const task of [...record.active]) {\n task.proxyTerminal = true;\n if (task.callerSettled) this.#finishTask(task);\n }\n return true;\n }\n\n /** Small internal status; never exposed through a handler context. */\n status(): RpcRuntimeStatus {\n return Object.freeze({\n closed: this.#closed,\n active: this.#tasks.size,\n endpoints: this.#endpoints.size,\n waiters: this.#waiters.size,\n });\n }\n\n /**\n * Read-only registered metadata for an endpoint handle owned by this runtime. It exposes\n * only the immutable provider/binding/contract clone and never the handler, owner resource, or\n * caller context. Foreign, forged, and released handles return null. Revoked but still-active\n * records retain metadata until real work drains; admission still rejects their revocation.\n */\n endpointInfo(handle: RpcEndpointHandle): Readonly<{\n readonly provider: string;\n readonly binding: Readonly<RpcEndpointBinding>;\n readonly contract: RpcServiceContract;\n }> | null {\n const record = this.#lookup(handle);\n if (!record) return null;\n return Object.freeze({ provider: record.provider, binding: record.binding, contract: record.contract });\n }\n\n /** Bounded wait; a timeout reports the real active count and never claims disposal. */\n async drain(handle: RpcEndpointHandle, options: { readonly timeoutMs?: number } = {}): Promise<RpcDrainResult> {\n const record = this.#lookup(handle);\n if (!record) return Object.freeze({ drained: true, active: 0 });\n record.retiring = true;\n const timeoutMs = this.#resolveTimeout(options.timeoutMs, this.#limits.drainTimeoutMs);\n const drained = await this.#waitFor(() => record.active.size === 0, timeoutMs);\n return Object.freeze({ drained, active: record.active.size });\n }\n\n /** Canonical owner disposal also joins calls issued by owners without publications. */\n async drainOwner(callerSubject: string, handles: readonly RpcEndpointHandle[], options: { readonly timeoutMs?: number; readonly callerToken?: object } = {}): Promise<RpcDrainResult> {\n const records = new Set(handles.map(handle => this.#lookup(handle)).filter((record): record is EndpointRecord => record !== null));\n const ownedTasks = () => [...this.#tasks].filter(task => (task.callerKey === callerSubject\n && (options.callerToken === undefined || task.callerToken === options.callerToken)) || records.has(task.record));\n const timeoutMs = this.#resolveTimeout(options.timeoutMs, this.#limits.drainTimeoutMs);\n const drained = await this.#waitFor(() => ownedTasks().length === 0, timeoutMs);\n return Object.freeze({ drained, active: ownedTasks().length });\n }\n\n /** Revocation settles callers but still retains actual work, capacity and leases. */\n revokeCaller(callerSubject: string, callerToken?: object): void {\n for (const task of this.#tasks) if (task.callerKey === callerSubject\n && (callerToken === undefined || task.callerToken === callerToken)) this.#abortTask(task, 'revoked');\n }\n\n /** Closes admission, aborts callers, and bounded-joins real work without faking success. */\n async dispose(options: { readonly timeoutMs?: number } = {}): Promise<RpcDisposeResult> {\n this.#closed = true;\n for (const record of [...this.#endpoints]) {\n record.retiring = true;\n record.revoked = true;\n }\n for (const task of [...this.#tasks]) this.#abortTask(task, 'closed');\n for (const record of [...this.#endpoints]) if (record.active.size === 0) this.#releaseRecord(record);\n const timeoutMs = this.#resolveTimeout(options.timeoutMs, this.#limits.drainTimeoutMs);\n const disposed = await this.#waitFor(() => this.#tasks.size === 0, timeoutMs);\n return Object.freeze({ disposed, active: this.#tasks.size });\n }\n\n async invoke(request: RpcInvokeRequest): Promise<RpcJson> {\n return this.#invoke(request);\n }\n\n /** Host receiver obtains actual completion evidence, not merely the caller reply. */\n invokeTracked(request: RpcInvokeRequest): RpcProxyExecution {\n let started = false;\n let resolveTerminal!: () => void;\n const terminal = new Promise<void>(resolve => { resolveTerminal = resolve; });\n const result = this.#invoke(request, { started: () => { started = true; }, terminal: resolveTerminal });\n // A pre-admission rejection has no task or side effect to wait for.\n void result.then(() => { if (!started) resolveTerminal(); }, () => { if (!started) resolveTerminal(); });\n return Object.freeze({ result, terminal });\n }\n\n async #invoke(request: RpcInvokeRequest, tracking?: InvocationTracking): Promise<RpcJson> {\n if (this.#closed) throw new RpcInvocationError('closed');\n const snapshot = snapshotInvokeRequest(request);\n const { target, caller, purpose } = snapshot;\n const operationIdInput = snapshot.operationId ?? null;\n // Pre-admission cancellation must never consume admission or a host lease.\n if (snapshot.signal?.aborted) throw new RpcInvocationError('cancelled');\n if (this.#hostLifetime?.aborted) throw new RpcInvocationError('closed');\n if (snapshot.timeoutMs !== undefined && snapshot.timeoutMs <= 0) throw new RpcInvocationError('timeout');\n if (snapshot.deadlineAt !== undefined && snapshot.deadlineAt <= Date.now()) throw new RpcInvocationError('timeout');\n\n let grant: RpcAdmissionGrant<TCallee> | null;\n try {\n grant = this.#admit({ target, caller, callerToken: snapshot.callerToken, purpose, operationId: operationIdInput, commandAction: snapshot.commandAction });\n } catch {\n throw new RpcInvocationError('unauthorized');\n }\n if (grant === null || grant === undefined || typeof grant !== 'object'\n || typeof (grant as { release?: unknown }).release !== 'function') {\n throw new RpcInvocationError('unauthorized');\n }\n const release = once(() => {\n try { grant!.release(); } catch { /* the host lease is host-owned */ }\n });\n try {\n const resolved = this.#resolveAdmissionEndpoint(grant.endpoint);\n if (resolved === null) throw new RpcInvocationError('unauthorized');\n if (resolved === 'revoked') throw new RpcInvocationError('revoked');\n const record = resolved;\n if (record.provider !== target.provider\n || record.contract.id !== target.service\n || record.contract.version !== target.major) {\n throw new RpcInvocationError('unauthorized');\n }\n if (record.revoked) throw new RpcInvocationError('revoked');\n const allowRetired = grant.allowRetired === true && (purpose === 'request' || purpose === 'attempt');\n if (record.retiring && !allowRetired) throw new RpcInvocationError('retired');\n if (!record.ready && !(grant.allowUnready === true && purpose === 'bootstrap')) {\n throw new RpcInvocationError('not_ready');\n }\n const definition = record.methods.get(target.method);\n if (!definition) throw new RpcInvocationError('unsupported_method');\n if (!definition.purposes.includes(purpose)) throw new RpcInvocationError('wrong_purpose');\n if (snapshot.commandAction !== undefined && definition.kind !== 'command') throw new RpcInvocationError('invalid_input');\n if (definition.kind === 'command' && operationIdInput === null) throw new RpcInvocationError('invalid_operation_id');\n const grantToken = grant.callerToken;\n if (grantToken !== undefined && (grantToken === null || typeof grantToken !== 'object' || isProxy(grantToken))) throw new RpcInvocationError('unauthorized');\n const callerToken = grantToken === undefined ? snapshot.callerToken : grantToken;\n this.#assertCapacity(record, caller.subject);\n return this.#execute(record, target.method, definition, snapshot, operationIdInput, grant, release, callerToken, tracking);\n } catch (error) {\n release();\n if (error instanceof RpcInvocationError) throw error;\n throw new RpcInvocationError('failed');\n }\n }\n\n #execute(\n record: EndpointRecord,\n method: string,\n definition: RpcMethodDefinition,\n request: RpcInvokeRequest,\n operationIdInput: string | null,\n grant: RpcAdmissionGrant<TCallee>,\n release: () => void,\n callerToken: object | undefined,\n tracking?: InvocationTracking,\n ): Promise<RpcJson> {\n return new Promise<RpcJson>((resolve, reject) => {\n const task: CallTask = {\n record, caller: request.caller, callerKey: request.caller.subject, callerToken,\n kind: request.commandAction === 'query-result' ? 'query' : definition.kind,\n purpose: request.purpose, operationId: definition.kind === 'command' ? operationIdInput : null,\n deadlineAt: Math.min(request.deadlineAt ?? Infinity, Date.now() + Math.min(definition.timeoutMs ?? Infinity, request.timeoutMs ?? Infinity, this.#limits.hardDeadlineMs)),\n allowRetired: grant.allowRetired === true && (request.purpose === 'request' || request.purpose === 'attempt'),\n release, controller: new AbortController(), cleanups: [], abortReason: null, callerSettled: false,\n finished: false, delivered: false, proxyTerminal: false, onTerminal: tracking?.terminal, resolve, reject,\n };\n record.active.add(task);\n this.#tasks.add(task);\n this.#addCallerCount(task.callerKey, 1);\n tracking?.started();\n try {\n this.#attachCancellation(task, request);\n } catch {\n this.#finishTask(task);\n reject(new RpcInvocationError('failed'));\n return;\n }\n if (task.finished) return;\n if (this.#closed || this.#hostLifetime?.aborted) return this.#abortTask(task, 'closed');\n if (record.revoked) return this.#abortTask(task, 'revoked');\n if (record.retiring && !task.allowRetired) return this.#abortTask(task, 'retired');\n if (request.signal?.aborted) return this.#abortTask(task, 'cancelled');\n\n let input: RpcJson;\n try {\n input = request.commandAction === 'query-result' ? null\n : this.#validateData(definition.input, request.input, definition.maxInputBytes ?? RPC_JSON_MAX_BYTES, request.maxInputBytes);\n } catch (error) {\n task.callerSettled = true;\n reject(error instanceof RpcInvocationError ? error : new RpcInvocationError('invalid_input'));\n this.#finishTask(task);\n return;\n }\n // Re-confirm immediately before dispatch; never launch if the task was invalidated or the\n // absolute deadline already passed while this synchronous path ran.\n if (task.finished) return;\n if (this.#closed || this.#hostLifetime?.aborted) return this.#abortTask(task, 'closed');\n if (record.revoked) return this.#abortTask(task, 'revoked');\n if (record.retiring && !task.allowRetired) return this.#abortTask(task, 'retired');\n if (request.signal?.aborted) return this.#abortTask(task, 'cancelled');\n if (Date.now() >= task.deadlineAt) return this.#abortTask(task, 'timeout');\n\n task.delivered = true;\n if (record.proxy !== null) {\n this.#runProxy(record, method, definition, task, input, grant.callee, request.commandAction);\n return;\n }\n const actual = definition.kind === 'command'\n ? this.#runCommand(record, method, definition, task, input, task.operationId!, grant.callee, request.commandAction ?? 'execute')\n : this.#runQuery(record, method, definition, task, input, grant.callee);\n // The deadline timer cannot preempt synchronous work, so terminal delivery re-checks the\n // absolute deadline: a result that only settles past it is refused instead of delivered.\n actual.then(\n (output) => {\n if (task.callerSettled) return;\n task.callerSettled = true;\n if (Date.now() >= task.deadlineAt) task.reject(this.#deadlineError(task));\n else task.resolve(output);\n },\n (error) => {\n if (task.callerSettled) return;\n task.callerSettled = true;\n if (Date.now() >= task.deadlineAt) task.reject(this.#deadlineError(task));\n else task.reject(error);\n },\n ).finally(() => {\n try { this.#finishTask(task); } catch { /* teardown is best-effort */ }\n });\n });\n }\n\n #attachCancellation(task: CallTask, request: RpcInvokeRequest): void {\n const sources: ReadonlyArray<{ signal: AbortSignal | undefined; reason: AbortReason }> = [\n { signal: request.signal, reason: 'cancelled' },\n { signal: this.#hostLifetime, reason: 'closed' },\n ];\n for (const source of sources) {\n const signal = source.signal;\n if (!signal || signal.aborted) continue;\n const listener = () => { this.#abortTask(task, source.reason); };\n signal.addEventListener('abort', listener, { once: true });\n task.cleanups.push(() => signal.removeEventListener('abort', listener));\n }\n const deadlineMs = task.deadlineAt - Date.now();\n if (Number.isFinite(deadlineMs)) {\n const timer = setTimeout(() => { this.#abortTask(task, 'timeout'); }, Math.max(0, deadlineMs));\n task.cleanups.push(() => clearTimeout(timer));\n }\n }\n\n #runProxy(record: EndpointRecord, method: string, definition: RpcMethodDefinition, task: CallTask,\n input: RpcJson, callee: TCallee, commandAction?: RpcCommandAction): void {\n const failUnconfirmed = (): void => {\n if (!task.callerSettled) {\n task.callerSettled = true;\n task.reject(new RpcInvocationError(task.kind === 'command' ? 'unknown' : 'failed', task.operationId));\n }\n if (!task.controller.signal.aborted) task.controller.abort('proxy_terminal_unconfirmed');\n // Transport failure is not remote terminal evidence. Capacity and lease stay held.\n };\n let resultPromise: Promise<unknown> | undefined;\n let terminalPromise: Promise<void> | undefined;\n try {\n const execution = record.proxy!({ method, input, context: this.#handlerContext(record, task, method, definition, callee),\n ...(definition.kind === 'command' ? { commandAction: commandAction ?? 'execute' } : {}) });\n const result = execution.result;\n if (result instanceof Promise) { resultPromise = result; void result.catch(() => undefined); }\n const terminal = execution.terminal;\n if (terminal instanceof Promise) { terminalPromise = terminal; void terminal.catch(() => undefined); }\n if (resultPromise === undefined || terminalPromise === undefined) throw invalidRegistration();\n } catch {\n failUnconfirmed();\n return;\n }\n void resultPromise.then(\n value => {\n if (task.callerSettled) return;\n let result: RpcJson;\n try { result = this.#validateOutput(definition, value); }\n catch (error) { task.callerSettled = true; task.reject(Date.now() >= task.deadlineAt ? this.#deadlineError(task) : error); return; }\n task.callerSettled = true;\n if (Date.now() >= task.deadlineAt) task.reject(this.#deadlineError(task));\n else task.resolve(result);\n },\n error => {\n if (task.callerSettled) return;\n task.callerSettled = true;\n const failure = error instanceof RpcInvocationError ? invocationFailure(error, task.operationId)\n : new RpcInvocationError(task.kind === 'command' ? 'unknown' : 'failed', task.operationId);\n task.reject(Date.now() >= task.deadlineAt ? this.#deadlineError(task) : failure);\n },\n ).finally(() => { if (task.proxyTerminal) this.#finishTask(task); });\n void terminalPromise.then(() => {\n task.proxyTerminal = true;\n if (task.callerSettled) this.#finishTask(task);\n }, failUnconfirmed);\n }\n\n async #runQuery(\n record: EndpointRecord,\n method: string,\n definition: RpcMethodDefinition,\n task: CallTask,\n input: RpcJson,\n callee: TCallee,\n ): Promise<RpcJson> {\n const handler = record.handler.get(method);\n if (!handler) throw new RpcInvocationError('unsupported_method', task.operationId);\n const context = this.#handlerContext(record, task, method, definition, callee);\n let raw: unknown;\n try {\n raw = handler(input, context);\n if (isThenable(raw)) raw = await raw;\n } catch {\n // Query handlers are provider code; they cannot forge host error codes.\n throw new RpcInvocationError('failed', task.operationId);\n }\n return this.#validateOutput(definition, raw);\n }\n\n async #runCommand(\n record: EndpointRecord,\n method: string,\n definition: RpcMethodDefinition,\n task: CallTask,\n input: RpcJson,\n operationId: string,\n callee: TCallee,\n action: RpcCommandAction,\n ): Promise<RpcJson> {\n const executor = this.#commandExecutor;\n if (!executor) throw new RpcInvocationError('capability_unavailable', operationId);\n const handler = record.handler.get(method);\n if (!handler) throw new RpcInvocationError('unsupported_method', operationId);\n const context = this.#handlerContext(record, task, method, definition, callee);\n if (action !== 'execute') {\n const control = action === 'query-result' ? executor.queryResult : executor.reconcile;\n if (typeof control !== 'function') throw new RpcInvocationError('capability_unavailable', operationId);\n const execution = Object.freeze({ contract: record.contract, method, definition, context, operationId, input });\n let result: unknown;\n try { result = await control.call(executor, execution); }\n catch (error) { throw invocationFailure(error, operationId); }\n return this.#validateOutput(definition, result);\n }\n let executorSettled = false;\n let businessStarted = false;\n let business: Promise<RpcJson> | undefined;\n\n const executeBusiness = (): Promise<RpcJson> => {\n if (businessStarted) return business!;\n // The first business dispatch re-checks the absolute deadline: a synchronous executor can\n // outlive the deadline timer, so an expired closure must never run provider code.\n const expired = Date.now() >= task.deadlineAt;\n if (executorSettled || task.finished || task.controller.signal.aborted || expired) {\n const reason: RpcInvocationErrorCode = task.abortReason === 'revoked' ? 'revoked'\n : (task.abortReason === 'closed' || this.#closed ? 'closed'\n : (expired ? this.#deadlineCode(task) : 'unknown'));\n const refused: Promise<RpcJson> = Promise.reject(new RpcInvocationError(reason, operationId));\n void refused.catch(() => undefined);\n // Install the refusal as the business outcome so a fire-and-forget executor that returned\n // success is still surfaced as a failure instead of a forged success.\n businessStarted = true;\n business = refused;\n return refused;\n }\n businessStarted = true;\n let resolve!: (value: RpcJson) => void;\n let reject!: (error: unknown) => void;\n const started = new Promise<RpcJson>((accept, fail) => { resolve = accept; reject = fail; });\n business = started;\n void started.catch(() => undefined);\n void (async (): Promise<RpcJson> => {\n let raw: unknown;\n try {\n raw = await handler(input, context);\n } catch {\n // Provider handler code is untrusted: its error, cause, message, and any forged code are\n // dropped; only the fixed `failed` code and the current operation id survive.\n throw new RpcInvocationError('failed', operationId);\n }\n // Kernel output validation stays outside the provider catch so `invalid_output` is never\n // masked as a business failure.\n return this.#validateOutput(definition, raw);\n })().then(resolve, reject);\n return started;\n };\n\n const execution: RpcCommandExecution<TCallee> = Object.freeze({\n contract: record.contract, method, definition, context, operationId, input, executeBusiness,\n });\n const executorPromise: Promise<unknown> = (async () => {\n try {\n return await executor.execute(execution);\n } finally {\n executorSettled = true;\n }\n })();\n\n let executorOutput: unknown = undefined;\n let failure: RpcInvocationError | null = null;\n try {\n executorOutput = await executorPromise;\n } catch (error) {\n failure = invocationFailure(error, operationId);\n }\n // The task may only finish after any real business work it started has reached terminal.\n if (businessStarted) {\n try {\n await business;\n } catch (error) {\n if (failure === null) failure = invocationFailure(error, operationId);\n }\n }\n if (failure !== null) throw failure;\n return this.#validateOutput(definition, executorOutput);\n }\n\n #handlerContext(\n record: EndpointRecord,\n task: CallTask,\n method: string,\n definition: RpcMethodDefinition,\n callee: TCallee,\n ): RpcHandlerContext<TCallee> {\n return Object.freeze({\n endpoint: Object.freeze({ ...record.binding, service: record.contract.id, version: record.contract.version }),\n caller: Object.freeze({ subject: task.caller.subject, scope: task.caller.scope }),\n method, kind: definition.kind, purpose: task.purpose, operationId: task.operationId,\n signal: task.controller.signal, callee,\n deadlineAt: task.deadlineAt,\n });\n }\n\n #validateData(schema: RpcDataSchema, value: unknown, methodLimit: number, callerLimit?: number): RpcJson {\n const limit = Math.min(methodLimit, callerLimit ?? RPC_JSON_MAX_BYTES);\n try {\n const clone = decodeRpcJson(encodeRpcJson(value, limit), limit);\n assertRpcData(schema, clone);\n return clone;\n } catch {\n throw new RpcInvocationError('invalid_input');\n }\n }\n\n #validateOutput(definition: RpcMethodDefinition, raw: unknown): RpcJson {\n const limit = definition.maxOutputBytes ?? RPC_JSON_MAX_BYTES;\n try {\n const clone = decodeRpcJson(encodeRpcJson(raw, limit), limit);\n assertRpcData(definition.output, clone);\n return clone;\n } catch {\n throw new RpcInvocationError('invalid_output');\n }\n }\n\n #abortTask(task: CallTask, reason: AbortReason): void {\n if (task.finished) return;\n if (task.abortReason === null) task.abortReason = reason;\n if (!task.controller.signal.aborted) task.controller.abort(reason);\n if (!task.callerSettled) {\n task.callerSettled = true;\n task.reject(this.#abortError(task, reason));\n }\n // The real task (if any) keeps its count and lease until it reaches terminal.\n if (!task.delivered) this.#finishTask(task);\n else if (task.record.proxy !== null && task.proxyTerminal) this.#finishTask(task);\n }\n\n #abortError(task: CallTask, reason: AbortReason): RpcInvocationError {\n if (task.kind === 'command' && task.delivered) return new RpcInvocationError('unknown', task.operationId);\n switch (reason) {\n case 'timeout': return new RpcInvocationError('timeout', task.operationId);\n case 'closed': return new RpcInvocationError('closed', task.operationId);\n case 'revoked': return new RpcInvocationError('revoked', task.operationId);\n case 'retired': return new RpcInvocationError('retired', task.operationId);\n default: return new RpcInvocationError('cancelled', task.operationId);\n }\n }\n\n /** Deadline failure keeps the already-delivered command `unknown` contract; otherwise `timeout`. */\n #deadlineCode(task: CallTask): RpcInvocationErrorCode {\n return task.kind === 'command' && task.delivered ? 'unknown' : 'timeout';\n }\n\n #deadlineError(task: CallTask): RpcInvocationError {\n return new RpcInvocationError(this.#deadlineCode(task), task.operationId);\n }\n\n /** Deletes the full record (handler, contract, runtime reference) and keeps revoked identity only. */\n #releaseRecord(record: EndpointRecord): void {\n if (!this.#endpoints.delete(record)) return;\n ENDPOINTS.delete(record.handle);\n REVOKED.set(record.handle, this.#identity);\n }\n\n #finishTask(task: CallTask): void {\n if (task.finished) return;\n task.finished = true;\n for (const cleanup of task.cleanups.splice(0)) {\n try { cleanup(); } catch { /* teardown is best-effort */ }\n }\n task.record.active.delete(task);\n if (task.record.revoked && task.record.active.size === 0) this.#releaseRecord(task.record);\n this.#tasks.delete(task);\n this.#addCallerCount(task.callerKey, -1);\n try { task.release(); } catch { /* the host lease is host-owned */ }\n this.#notifyWaiters();\n task.onTerminal?.();\n }\n\n #assertCapacity(record: EndpointRecord, callerKey: string): void {\n if (this.#tasks.size >= this.#limits.globalMaxInFlight) throw new RpcInvocationError('overloaded');\n if (record.active.size >= this.#limits.endpointMaxInFlight) throw new RpcInvocationError('overloaded');\n if ((this.#callerCounts.get(callerKey) ?? 0) >= this.#limits.callerMaxInFlight) throw new RpcInvocationError('overloaded');\n }\n\n #addCallerCount(callerKey: string, delta: number): void {\n const next = (this.#callerCounts.get(callerKey) ?? 0) + delta;\n if (next <= 0) this.#callerCounts.delete(callerKey);\n else this.#callerCounts.set(callerKey, next);\n }\n\n /** Resolves an admitted handle; released handles only report revoked for their owning runtime. */\n #resolveAdmissionEndpoint(handle: RpcEndpointHandle): EndpointRecord | 'revoked' | null {\n if (handle === null || typeof handle !== 'object') return null;\n const record = ENDPOINTS.get(handle as object);\n if (record) return record.runtime === this ? record : null;\n const token = REVOKED.get(handle as object);\n if (!token) return null;\n return token === this.#identity ? 'revoked' : null;\n }\n\n #lookup(handle: RpcEndpointHandle): EndpointRecord | null {\n if (handle === null || typeof handle !== 'object') return null;\n const record = ENDPOINTS.get(handle as object);\n if (!record || record.runtime !== this) return null;\n return record;\n }\n\n #resolveTimeout(value: number | undefined, fallback: number): number {\n return timeoutLimit(value, fallback);\n }\n\n #waitFor(check: () => boolean, timeoutMs: number): Promise<boolean> {\n if (check()) return Promise.resolve(true);\n if (this.#waiters.size >= this.#limits.maxWaiters) {\n return Promise.reject(new RpcInvocationError('overloaded'));\n }\n return new Promise<boolean>((resolve) => {\n const waiter: Waiter = { check, settle: () => undefined };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const settle = (value: boolean): void => {\n if (timer !== undefined) clearTimeout(timer);\n this.#waiters.delete(waiter);\n resolve(value);\n };\n waiter.settle = () => settle(true);\n this.#waiters.add(waiter);\n timer = setTimeout(() => settle(false), timeoutMs);\n });\n }\n\n #notifyWaiters(): void {\n if (this.#waiters.size === 0) return;\n for (const waiter of [...this.#waiters]) {\n if (waiter.check()) waiter.settle();\n }\n }\n}\n",
|
|
13
|
+
"/**\n * Host communication lane protocol (P5): strict, bounded codecs for the three\n * non-RPC lanes — `event`, `snapshot`, `stream`.\n *\n * Scope boundary: this module only defines shapes and constants. It opens no\n * transport, keeps no state, and grants no authority: every request/response is\n * authenticated and correlated by the peer link (`peer-rpc-link.ts`), and every\n * authorization decision belongs to the host adapter (`channels.ts`).\n *\n * Design rules:\n * - A lane request rides the link's existing request/response machinery; only the\n * lane payload is lane-specific. Bulk bytes never ride a request envelope: they\n * travel as `emit` frames (stream chunks) or as bounded chunk responses\n * (snapshot bodies), never by enlarging the 64 KiB RPC message.\n * - Every codec is strict: exact key sets, bounded strings/numbers, and a byte\n * bound. A malformed lane payload is refused, never partially trusted.\n * - Every request carries the host-minted `caller` + `callerScope`, so the\n * receiving host correlates an inbound frame to the exact original owner it was\n * authorized for (never to a bare plugin name).\n * - Result bodies are pure JSON `{ ok: true, ... } | { ok: false, code, detail? }`,\n * so a lane can report `gap`/`conflict`/`unauthorized` without widening the\n * link's own fixed wire-error vocabulary.\n */\n\nimport { decodeRpcJson, encodeRpcJson, type RpcCallPurpose, type RpcJson } from './wire-contract';\nimport type { PluginPeerRpcRequestExecution } from './peer-rpc-link';\n\nexport const PLUGIN_CHANNEL_VERSION = 1 as const;\n\n/** A lane request context stays far below the 8 KiB peer header cap. */\nexport const CHANNEL_REQUEST_MAX_BYTES = 4 * 1024;\n/** A JSON result payload (event body / snapshot descriptor) stays below the frame cap. */\nexport const CHANNEL_RESULT_MAX_BYTES = 60 * 1024;\n/** Largest single chunk body that fits one peer frame with the emit wrapper. */\nexport const CHANNEL_MAX_CHUNK_BYTES = 60 * 1024;\n\nexport type PluginChannelLane = 'event' | 'snapshot' | 'stream';\n\n/**\n * The exact transport surface a lane engine needs. `PluginPeerRpcLink` satisfies\n * it structurally; a same-process route uses the hub's in-process loopback port,\n * so local and remote transfers share one implementation and one set of limits.\n */\nexport interface PluginChannelLinkPort {\n /**\n * Exact transport admission state. `true` once this link has retired: NEW\n * open/subscribe/read work is refused by the hub, while frames belonging to an\n * already-accepted transfer/subscription/session keep flowing.\n */\n readonly retired?: boolean;\n requestOnLane(\n lane: PluginChannelLane,\n context: RpcJson,\n body: Uint8Array,\n options: { readonly deadlineAt: number; readonly signal?: AbortSignal },\n ): PluginPeerRpcRequestExecution;\n emitLane(\n lane: PluginChannelLane,\n kind: 'chunk' | 'notification',\n requestId: string,\n deadlineAt: number,\n context: RpcJson,\n body: Uint8Array,\n priority?: 'data' | 'control',\n ): boolean;\n}\n\nexport type PluginChannelErrorCode =\n | 'unavailable'\n | 'ambiguous'\n | 'unauthorized'\n | 'invalid'\n | 'overloaded'\n | 'expired'\n | 'conflict'\n | 'gap'\n | 'truncated'\n | 'rejected'\n | 'cancelled'\n | 'closed'\n | 'unknown'\n | 'failed';\n\nexport const PLUGIN_CHANNEL_LANES: readonly PluginChannelLane[] = Object.freeze(['event', 'snapshot', 'stream']);\n\n/** Fixed-code channel error. It never carries a cause, path, or payload. */\nexport class PluginChannelError extends Error {\n readonly name = 'PluginChannelError';\n constructor(readonly code: PluginChannelErrorCode, message: string) {\n super(message);\n }\n}\n\nexport function failChannel(code: PluginChannelErrorCode, message: string): never {\n throw new PluginChannelError(code, message);\n}\n\n/** Logical target of one lane request; the physical identity is never a plugin concern. */\nexport interface PluginChannelTarget {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n}\n\nconst NAME = /^[a-zA-Z0-9][a-zA-Z0-9._@/-]{0,127}$/;\nconst SERVICE = /^[a-z][a-z0-9.-]{0,127}$/;\n/** Event ids are lowercase hex; they are minted per durable sequence. */\nconst EVENT_ID = /^[0-9a-f]{16,64}$/;\nconst DIGEST = /^sha256:[0-9a-f]{64}$/;\nconst OBJECT_ID = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,127}$/;\n/** Canonical contract hash: lowercase hex, 32 or 64 chars. */\nconst CONTRACT_HASH = /^[0-9a-f]{32,64}$/;\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction exactKeys(record: Record<string, unknown>, keys: readonly string[]): boolean {\n const actual = Object.keys(record);\n return actual.length === keys.length && keys.every(key => Object.prototype.hasOwnProperty.call(record, key));\n}\n\nfunction isSafeInt(value: unknown, minimum = 0): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isName(value: unknown): value is string {\n return typeof value === 'string' && NAME.test(value);\n}\n\nfunction isServiceId(value: unknown): value is string {\n return typeof value === 'string' && SERVICE.test(value);\n}\n\nfunction decodeTarget(value: unknown): PluginChannelTarget | null {\n if (!isPlainRecord(value) || !exactKeys(value, ['provider', 'service', 'major'])) return null;\n if (!isName(value.provider) || !isServiceId(value.service) || !isSafeInt(value.major, 1)) return null;\n return Object.freeze({ provider: value.provider, service: value.service, major: value.major });\n}\n\nfunction maybeDigest(value: unknown): value is `sha256:${string}` | null {\n return value === null || (typeof value === 'string' && DIGEST.test(value));\n}\n\n/** Encodes one lane request payload into the link's bounded JSON envelope. */\nfunction encodePayload(value: unknown): RpcJson {\n try { return JSON.parse(encodeRpcJson(value, CHANNEL_REQUEST_MAX_BYTES)) as RpcJson; }\n catch { return failChannel('invalid', 'channel request payload is not valid bounded JSON'); }\n}\n\n/** Decodes one lane request payload; `null` means \"refuse, never dispatch\". */\nfunction decodePayload(value: unknown): Record<string, unknown> | null {\n if (!isPlainRecord(value)) return null;\n try {\n const text = encodeRpcJson(value, CHANNEL_REQUEST_MAX_BYTES);\n const parsed = decodeRpcJson(text, CHANNEL_REQUEST_MAX_BYTES);\n return isPlainRecord(parsed) ? parsed as Record<string, unknown> : null;\n } catch { return null; }\n}\n\nexport function encodeChannelResult(\n value:\n | { readonly ok: true; readonly [key: string]: unknown }\n | { readonly ok: false; readonly code: PluginChannelErrorCode; readonly detail?: Record<string, unknown> },\n): Uint8Array {\n const encoded = encodePayload(value);\n return new TextEncoder().encode(JSON.stringify(encoded));\n}\n\nexport type PluginChannelResult =\n | { readonly ok: true; readonly value: Record<string, unknown> }\n | { readonly ok: false; readonly code: PluginChannelErrorCode; readonly detail?: Record<string, unknown> };\n\nconst ERROR_CODES = new Set<PluginChannelErrorCode>([\n 'unavailable', 'ambiguous', 'unauthorized', 'invalid', 'overloaded', 'expired',\n 'conflict', 'gap', 'truncated', 'rejected', 'cancelled', 'closed', 'unknown', 'failed',\n]);\n\n/** Strict decode of a JSON lane result body; `null` is a protocol failure. */\nexport function decodeChannelResult(bytes: Uint8Array): PluginChannelResult | null {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > CHANNEL_RESULT_MAX_BYTES) return null;\n let text: string;\n try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { return null; }\n let parsed: unknown;\n try { parsed = decodeRpcJson(text, CHANNEL_RESULT_MAX_BYTES); } catch { return null; }\n if (!isPlainRecord(parsed) || typeof parsed.ok !== 'boolean') return null;\n if (parsed.ok === false) {\n const keys = Object.keys(parsed);\n if (keys.length === 2) {\n if (!exactKeys(parsed, ['ok', 'code'])) return null;\n if (typeof parsed.code !== 'string' || !ERROR_CODES.has(parsed.code as PluginChannelErrorCode)) return null;\n return Object.freeze({ ok: false, code: parsed.code as PluginChannelErrorCode });\n }\n if (!exactKeys(parsed, ['ok', 'code', 'detail'])) return null;\n if (typeof parsed.code !== 'string' || !ERROR_CODES.has(parsed.code as PluginChannelErrorCode)) return null;\n if (!isPlainRecord(parsed.detail)) return null;\n return Object.freeze({ ok: false, code: parsed.code as PluginChannelErrorCode, detail: Object.freeze({ ...parsed.detail }) });\n }\n const { ok: _ok, ...value } = parsed;\n return Object.freeze({ ok: true, value: Object.freeze(value) });\n}\n\n/** Raw chunk response body: bytes carried by a snapshot/stream chunk call. */\nexport function encodeChannelBytes(bytes: Uint8Array): Uint8Array {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength > CHANNEL_MAX_CHUNK_BYTES) {\n return failChannel('invalid', 'channel chunk exceeds the frame body budget');\n }\n return new Uint8Array(bytes);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Lane request envelopes */\n/* -------------------------------------------------------------------------- */\n\n/** Common envelope: target + host-minted caller identity + lane-specific request. */\nconst RPC_CALL_PURPOSES = new Set<RpcCallPurpose>(['bootstrap', 'background', 'management', 'request', 'attempt']);\n\ninterface LaneRequestBase {\n readonly v: typeof PLUGIN_CHANNEL_VERSION;\n readonly target: PluginChannelTarget;\n /** Consumer plugin name; host-minted, never payload-claimed. */\n readonly caller: string;\n /** Consumer owner scope key; host-minted (`global` or a binding scope). */\n readonly callerScope: string;\n /**\n * Host-minted invocation purpose shared across the peer boundary, so the\n * providing host can keep the original request/attempt/management context\n * instead of re-interpreting the call as an unauthenticated background task.\n */\n readonly purpose: RpcCallPurpose;\n /**\n * Canonical hash of the consumer's declared lane contract (id + version + the\n * `wire-contract` data schema). The provider refuses a request that does not\n * hash to its own contract, so the two sides cannot silently disagree about\n * the payload type.\n */\n readonly contract: string;\n readonly kind: string;\n}\n\nexport interface ChannelStreamOpenRequest extends LaneRequestBase {\n readonly kind: 'stream.open' | 'stream.open-write';\n readonly request: {\n /** Consumer-minted correlation id; becomes the transfer id for every later frame. */\n readonly clientId: string;\n readonly objectId: string;\n readonly version: number;\n readonly offset: number;\n readonly size: number | null;\n readonly digest: `sha256:${string}` | null;\n readonly creditBytes: number;\n readonly idleMs: number;\n };\n}\n\n/**\n * One duplex session negotiation: a SINGLE transfer id carries both a provider ->\n * consumer read flow and a consumer -> provider write flow, each with its own\n * independent absolute credit window, over one shared terminal.\n */\nexport interface ChannelStreamOpenDuplexRequest extends LaneRequestBase {\n readonly kind: 'stream.open-duplex';\n readonly request: {\n readonly clientId: string;\n readonly objectId: string;\n readonly version: number;\n readonly readOffset: number;\n readonly readSize: number | null;\n readonly readDigest: `sha256:${string}` | null;\n readonly writeSize: number | null;\n readonly writeDigest: `sha256:${string}` | null;\n readonly readCreditBytes: number;\n readonly writeCreditBytes: number;\n readonly idleMs: number;\n };\n}\n\nexport interface ChannelStreamFinishRequest extends LaneRequestBase {\n readonly kind: 'stream.finish';\n readonly request: {\n readonly transferId: string;\n readonly size: number;\n readonly digest: `sha256:${string}`;\n };\n}\n\nexport interface ChannelEventSubscribeRequest extends LaneRequestBase {\n readonly kind: 'event.subscribe';\n readonly request: {\n readonly clientId: string;\n readonly delivery: 'transient' | 'reliable';\n readonly consumerId: string;\n readonly from: number | null;\n };\n}\n\nexport interface ChannelEventAckRequest extends LaneRequestBase {\n readonly kind: 'event.ack';\n readonly request: { readonly subscriptionId: string; readonly sequence: number };\n}\n\nexport interface ChannelSnapshotDescribeRequest extends LaneRequestBase {\n readonly kind: 'snapshot.describe';\n readonly request: { readonly version: number | null };\n}\n\n/**\n * Pins one immutable version for a WHOLE read: the provider retains the exact\n * source until `snapshot.release` (or its bounded idle expiry), so a refresh or a\n * version eviction can never swap or free the body mid-read.\n */\nexport interface ChannelSnapshotOpenRequest extends LaneRequestBase {\n readonly kind: 'snapshot.open';\n readonly request: { readonly version: number | null };\n}\n\nexport interface ChannelSnapshotChunkRequest extends LaneRequestBase {\n readonly kind: 'snapshot.chunk';\n readonly request: { readonly sessionId: string; readonly offset: number; readonly length: number };\n}\n\nexport interface ChannelSnapshotReleaseRequest extends LaneRequestBase {\n readonly kind: 'snapshot.release';\n readonly request: { readonly sessionId: string };\n}\n\nfunction laneEnvelope(record: Record<string, unknown>): Omit<LaneRequestBase, 'kind'> | null {\n if (!exactKeys(record, ['v', 'kind', 'target', 'caller', 'callerScope', 'purpose', 'contract', 'request'])) return null;\n if (record.v !== PLUGIN_CHANNEL_VERSION) return null;\n const target = decodeTarget(record.target);\n if (target === null || !isName(record.caller) || typeof record.callerScope !== 'string' || !NAME.test(record.callerScope)) return null;\n if (typeof record.purpose !== 'string' || !RPC_CALL_PURPOSES.has(record.purpose as RpcCallPurpose)) return null;\n if (typeof record.contract !== 'string' || !CONTRACT_HASH.test(record.contract)) return null;\n return { v: PLUGIN_CHANNEL_VERSION, target, caller: record.caller, callerScope: record.callerScope, purpose: record.purpose as RpcCallPurpose, contract: record.contract };\n}\n\nexport function encodeStreamOpenRequest(\n kind: 'stream.open' | 'stream.open-write',\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n request: ChannelStreamOpenRequest['request'],\n purpose: RpcCallPurpose = 'background',\n): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind, target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeStreamOpenRequest(payload: unknown): ChannelStreamOpenRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || (record.kind !== 'stream.open' && record.kind !== 'stream.open-write')) return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['clientId', 'objectId', 'version', 'offset', 'size', 'digest', 'creditBytes', 'idleMs'])) return null;\n if (typeof request.clientId !== 'string' || !NAME.test(request.clientId)) return null;\n if (typeof request.objectId !== 'string' || !OBJECT_ID.test(request.objectId)) return null;\n if (!isSafeInt(request.version, 1) || !isSafeInt(request.offset)) return null;\n if (request.size !== null && !isSafeInt(request.size, 1)) return null;\n if (!maybeDigest(request.digest)) return null;\n if (!isSafeInt(request.creditBytes, 1) || !isSafeInt(request.idleMs, 1)) return null;\n return Object.freeze({\n ...base, kind: record.kind,\n request: Object.freeze({\n clientId: request.clientId, objectId: request.objectId, version: request.version, offset: request.offset,\n size: request.size, digest: request.digest as `sha256:${string}` | null,\n creditBytes: request.creditBytes, idleMs: request.idleMs,\n }),\n });\n}\n\nexport function encodeStreamOpenDuplexRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelStreamOpenDuplexRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'stream.open-duplex', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeStreamOpenDuplexRequest(payload: unknown): ChannelStreamOpenDuplexRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'stream.open-duplex') return null;\n const request = record.request;\n if (!isPlainRecord(request)) return null;\n if (!exactKeys(request, ['clientId', 'objectId', 'version', 'readOffset', 'readSize', 'readDigest', 'writeSize', 'writeDigest', 'readCreditBytes', 'writeCreditBytes', 'idleMs'])) return null;\n if (typeof request.clientId !== 'string' || !NAME.test(request.clientId)) return null;\n if (typeof request.objectId !== 'string' || !OBJECT_ID.test(request.objectId)) return null;\n if (!isSafeInt(request.version, 1) || !isSafeInt(request.readOffset)) return null;\n if (request.readSize !== null && !isSafeInt(request.readSize, 1)) return null;\n if (!maybeDigest(request.readDigest)) return null;\n if (request.writeSize !== null && !isSafeInt(request.writeSize, 1)) return null;\n if (!maybeDigest(request.writeDigest)) return null;\n if (!isSafeInt(request.readCreditBytes, 1) || !isSafeInt(request.writeCreditBytes, 1) || !isSafeInt(request.idleMs, 1)) return null;\n return Object.freeze({\n ...base, kind: 'stream.open-duplex',\n request: Object.freeze({\n clientId: request.clientId, objectId: request.objectId, version: request.version,\n readOffset: request.readOffset, readSize: request.readSize,\n readDigest: request.readDigest as `sha256:${string}` | null,\n writeSize: request.writeSize, writeDigest: request.writeDigest as `sha256:${string}` | null,\n readCreditBytes: request.readCreditBytes, writeCreditBytes: request.writeCreditBytes, idleMs: request.idleMs,\n }),\n });\n}\n\nexport function encodeStreamFinishRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelStreamFinishRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'stream.finish', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeStreamFinishRequest(payload: unknown): ChannelStreamFinishRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'stream.finish') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['transferId', 'size', 'digest'])) return null;\n if (typeof request.transferId !== 'string' || !NAME.test(request.transferId)) return null;\n if (!isSafeInt(request.size, 1)) return null;\n if (typeof request.digest !== 'string' || !DIGEST.test(request.digest)) return null;\n return Object.freeze({\n ...base, kind: 'stream.finish',\n request: Object.freeze({ transferId: request.transferId, size: request.size, digest: request.digest as `sha256:${string}` }),\n });\n}\n\nexport function encodeEventSubscribeRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelEventSubscribeRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'event.subscribe', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeEventSubscribeRequest(payload: unknown): ChannelEventSubscribeRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'event.subscribe') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['clientId', 'delivery', 'consumerId', 'from'])) return null;\n if (typeof request.clientId !== 'string' || !NAME.test(request.clientId)) return null;\n if (request.delivery !== 'transient' && request.delivery !== 'reliable') return null;\n if (typeof request.consumerId !== 'string' || !NAME.test(request.consumerId)) return null;\n if (request.from !== null && !isSafeInt(request.from, 1)) return null;\n return Object.freeze({\n ...base, kind: 'event.subscribe',\n request: Object.freeze({ clientId: request.clientId, delivery: request.delivery, consumerId: request.consumerId, from: request.from }),\n });\n}\n\nexport function encodeEventAckRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelEventAckRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'event.ack', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeEventAckRequest(payload: unknown): ChannelEventAckRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'event.ack') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['subscriptionId', 'sequence'])) return null;\n if (typeof request.subscriptionId !== 'string' || !NAME.test(request.subscriptionId)) return null;\n if (!isSafeInt(request.sequence, 1)) return null;\n return Object.freeze({ ...base, kind: 'event.ack', request: Object.freeze({ subscriptionId: request.subscriptionId, sequence: request.sequence }) });\n}\n\nexport function encodeSnapshotDescribeRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelSnapshotDescribeRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'snapshot.describe', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeSnapshotDescribeRequest(payload: unknown): ChannelSnapshotDescribeRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'snapshot.describe') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['version'])) return null;\n if (request.version !== null && !isSafeInt(request.version, 1)) return null;\n return Object.freeze({ ...base, kind: 'snapshot.describe', request: Object.freeze({ version: request.version }) });\n}\n\nexport function encodeSnapshotOpenRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelSnapshotOpenRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'snapshot.open', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeSnapshotOpenRequest(payload: unknown): ChannelSnapshotOpenRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'snapshot.open') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['version'])) return null;\n if (request.version !== null && !isSafeInt(request.version, 1)) return null;\n return Object.freeze({ ...base, kind: 'snapshot.open', request: Object.freeze({ version: request.version }) });\n}\n\nexport function encodeSnapshotChunkRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelSnapshotChunkRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'snapshot.chunk', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeSnapshotChunkRequest(payload: unknown): ChannelSnapshotChunkRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'snapshot.chunk') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['sessionId', 'offset', 'length'])) return null;\n if (typeof request.sessionId !== 'string' || !NAME.test(request.sessionId)) return null;\n if (!isSafeInt(request.offset) || !isSafeInt(request.length, 1) || request.length > CHANNEL_MAX_CHUNK_BYTES) return null;\n return Object.freeze({\n ...base, kind: 'snapshot.chunk',\n request: Object.freeze({ sessionId: request.sessionId, offset: request.offset, length: request.length }),\n });\n}\n\nexport function encodeSnapshotReleaseRequest(target: PluginChannelTarget, caller: string, callerScope: string, contract: string, request: ChannelSnapshotReleaseRequest['request'], purpose: RpcCallPurpose = 'background'): RpcJson {\n return encodePayload({ v: PLUGIN_CHANNEL_VERSION, kind: 'snapshot.release', target, caller, callerScope, purpose, contract, request });\n}\n\nexport function decodeSnapshotReleaseRequest(payload: unknown): ChannelSnapshotReleaseRequest | null {\n const record = decodePayload(payload);\n if (record === null) return null;\n const base = laneEnvelope(record);\n if (base === null || record.kind !== 'snapshot.release') return null;\n const request = record.request;\n if (!isPlainRecord(request) || !exactKeys(request, ['sessionId'])) return null;\n if (typeof request.sessionId !== 'string' || !NAME.test(request.sessionId)) return null;\n return Object.freeze({ ...base, kind: 'snapshot.release', request: Object.freeze({ sessionId: request.sessionId }) });\n}\n\n/* -------------------------------------------------------------------------- */\n/* Emit frame payloads */\n/* -------------------------------------------------------------------------- */\n\nexport interface ChannelStreamChunkEmit {\n readonly kind: 'stream.chunk';\n readonly transferId: string;\n readonly offset: number;\n readonly last: boolean;\n}\n\nexport interface ChannelStreamDataEmit {\n readonly kind: 'stream.data';\n readonly transferId: string;\n readonly offset: number;\n readonly last: boolean;\n}\n\n/**\n * Consumer half-close of the READ direction of a duplex session: it will accept\n * no further read chunks (and stops granting read credit), while the WRITE\n * direction of the same session keeps running.\n */\nexport interface ChannelStreamEndReadEmit {\n readonly kind: 'stream.end-read';\n readonly transferId: string;\n}\n\n/**\n * Provider -> consumer end of the READ direction: the producer has emitted every\n * byte of this immutable version (including a zero-byte body). It is ordered on\n * the same link AFTER the final data frame, so the receiver can settle the read\n * with a real protocol end instead of a timing guess.\n */\nexport interface ChannelStreamEndEmit {\n readonly kind: 'stream.end';\n readonly transferId: string;\n}\n\nexport interface ChannelStreamCreditEmit {\n readonly kind: 'stream.credit';\n readonly transferId: string;\n /**\n * Which window this grant governs, so one duplex session can carry two fully\n * independent credit windows on the SAME transfer id:\n * - `read`: the provider -> consumer flow (granted by the consumer);\n * - `write`: the consumer -> provider flow (granted by the provider).\n */\n readonly direction: 'read' | 'write';\n /**\n * ABSOLUTE credit window: the total byte count the receiver currently allows\n * from offset 0. Absolute (never a delta) because a window is idempotent: a\n * retried or repeated grant can never double-count, and a lost frame heals as\n * soon as the sender re-emits the current window.\n */\n readonly window: number;\n}\n\nexport interface ChannelEventNotifyEmit {\n readonly kind: 'event.notify';\n readonly subscriptionId: string;\n readonly sequence: number;\n readonly eventId: string;\n readonly delivery: 'transient' | 'reliable';\n}\n\n/**\n * Provider -> consumer reliable-event gap/failure notice: the ordered delivery\n * can no longer continue (a refused emit while disconnected, a bounded queue\n * overflow, an unreadable replay). The consumer must observe a REAL failure\n * instead of a silent close, and re-subscribe from its durable checkpoint.\n */\nexport interface ChannelEventGapEmit {\n readonly kind: 'event.gap';\n readonly subscriptionId: string;\n readonly code: PluginChannelErrorCode;\n}\n\nexport type ChannelEmitPayload = ChannelStreamChunkEmit | ChannelStreamDataEmit | ChannelStreamCreditEmit | ChannelStreamEndReadEmit | ChannelStreamEndEmit | ChannelEventNotifyEmit | ChannelEventGapEmit;\n\nexport function encodeChannelEmit(payload: ChannelEmitPayload): RpcJson {\n return encodePayload(payload);\n}\n\nexport function decodeChannelEmit(payload: unknown): ChannelEmitPayload | null {\n const record = decodePayload(payload);\n if (record === null || typeof record.kind !== 'string') return null;\n switch (record.kind) {\n case 'stream.chunk':\n case 'stream.data': {\n if (!exactKeys(record, ['kind', 'transferId', 'offset', 'last'])) return null;\n if (typeof record.transferId !== 'string' || !NAME.test(record.transferId)) return null;\n if (!isSafeInt(record.offset) || typeof record.last !== 'boolean') return null;\n return Object.freeze({\n kind: record.kind as 'stream.chunk' | 'stream.data',\n transferId: record.transferId, offset: record.offset, last: record.last as boolean,\n });\n }\n case 'stream.credit': {\n if (!exactKeys(record, ['kind', 'transferId', 'direction', 'window'])) return null;\n if (typeof record.transferId !== 'string' || !NAME.test(record.transferId)) return null;\n if (record.direction !== 'read' && record.direction !== 'write') return null;\n if (!isSafeInt(record.window)) return null;\n return Object.freeze({\n kind: 'stream.credit', transferId: record.transferId,\n direction: record.direction as 'read' | 'write', window: record.window,\n });\n }\n case 'stream.end-read': {\n if (!exactKeys(record, ['kind', 'transferId'])) return null;\n if (typeof record.transferId !== 'string' || !NAME.test(record.transferId)) return null;\n return Object.freeze({ kind: 'stream.end-read', transferId: record.transferId });\n }\n case 'stream.end': {\n if (!exactKeys(record, ['kind', 'transferId'])) return null;\n if (typeof record.transferId !== 'string' || !NAME.test(record.transferId)) return null;\n return Object.freeze({ kind: 'stream.end', transferId: record.transferId });\n }\n case 'event.notify': {\n if (!exactKeys(record, ['kind', 'subscriptionId', 'sequence', 'eventId', 'delivery'])) return null;\n if (typeof record.subscriptionId !== 'string' || !NAME.test(record.subscriptionId)) return null;\n // Transient notifications carry sequence 0 (they are not an ordered log).\n if (!isSafeInt(record.sequence, 0)) return null;\n if (typeof record.eventId !== 'string' || !EVENT_ID.test(record.eventId)) return null;\n if (record.delivery !== 'transient' && record.delivery !== 'reliable') return null;\n return Object.freeze({\n kind: 'event.notify', subscriptionId: record.subscriptionId, sequence: record.sequence,\n eventId: record.eventId, delivery: record.delivery,\n });\n }\n case 'event.gap': {\n if (!exactKeys(record, ['kind', 'subscriptionId', 'code'])) return null;\n if (typeof record.subscriptionId !== 'string' || !NAME.test(record.subscriptionId)) return null;\n if (typeof record.code !== 'string' || !ERROR_CODES.has(record.code as PluginChannelErrorCode)) return null;\n return Object.freeze({\n kind: 'event.gap', subscriptionId: record.subscriptionId, code: record.code as PluginChannelErrorCode,\n });\n }\n default:\n return null;\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Result payloads */\n/* -------------------------------------------------------------------------- */\n\nexport interface ChannelStreamOpenResult {\n readonly transferId: string;\n readonly size: number | null;\n readonly digest: `sha256:${string}` | null;\n readonly frameBytes: number;\n readonly creditBytes: number;\n}\n\nexport function decodeStreamOpenResult(result: PluginChannelResult): ChannelStreamOpenResult | null {\n if (!result.ok) return null;\n const value = result.value;\n if (!exactKeys(value, ['transferId', 'size', 'digest', 'frameBytes', 'creditBytes'])) return null;\n if (typeof value.transferId !== 'string' || !NAME.test(value.transferId)) return null;\n if (value.size !== null && !isSafeInt(value.size, 1)) return null;\n if (!maybeDigest(value.digest)) return null;\n if (!isSafeInt(value.frameBytes, 1) || !isSafeInt(value.creditBytes, 1)) return null;\n return Object.freeze({\n transferId: value.transferId, size: value.size,\n digest: value.digest as `sha256:${string}` | null,\n frameBytes: value.frameBytes, creditBytes: value.creditBytes,\n });\n}\n\nexport interface ChannelStreamOpenDuplexResult {\n readonly transferId: string;\n readonly readSize: number | null;\n readonly readDigest: `sha256:${string}` | null;\n readonly readFrameBytes: number;\n readonly readCreditBytes: number;\n readonly writeCreditBytes: number;\n}\n\nexport function decodeStreamOpenDuplexResult(result: PluginChannelResult): ChannelStreamOpenDuplexResult | null {\n if (!result.ok) return null;\n const value = result.value;\n if (!exactKeys(value, ['transferId', 'readSize', 'readDigest', 'readFrameBytes', 'readCreditBytes', 'writeCreditBytes'])) return null;\n if (typeof value.transferId !== 'string' || !NAME.test(value.transferId)) return null;\n if (value.readSize !== null && !isSafeInt(value.readSize, 1)) return null;\n if (!maybeDigest(value.readDigest)) return null;\n if (!isSafeInt(value.readFrameBytes, 1) || !isSafeInt(value.readCreditBytes, 1) || !isSafeInt(value.writeCreditBytes, 1)) return null;\n return Object.freeze({\n transferId: value.transferId, readSize: value.readSize,\n readDigest: value.readDigest as `sha256:${string}` | null,\n readFrameBytes: value.readFrameBytes, readCreditBytes: value.readCreditBytes, writeCreditBytes: value.writeCreditBytes,\n });\n}\n\nexport interface ChannelSnapshotOpenResult {\n readonly sessionId: string;\n readonly descriptor: ChannelSnapshotDescriptor;\n}\n\nexport function decodeSnapshotOpenResult(result: PluginChannelResult): ChannelSnapshotOpenResult | null {\n if (!result.ok) return null;\n const value = result.value;\n if (!exactKeys(value, ['sessionId', 'descriptor'])) return null;\n if (typeof value.sessionId !== 'string' || !NAME.test(value.sessionId)) return null;\n if (!isPlainRecord(value.descriptor)) return null;\n const descriptor = decodeDescriptorRecord(value.descriptor);\n if (descriptor === null) return null;\n return Object.freeze({ sessionId: value.sessionId, descriptor });\n}\n\nfunction decodeDescriptorRecord(value: Record<string, unknown>): ChannelSnapshotDescriptor | null {\n if (!exactKeys(value, ['owner', 'epoch', 'version', 'schemaVersion', 'digest', 'size', 'chunkBytes'])) return null;\n if (typeof value.owner !== 'string' || !NAME.test(value.owner)) return null;\n if (!isSafeInt(value.epoch, 1) || !isSafeInt(value.version, 1) || !isSafeInt(value.schemaVersion, 1)) return null;\n if (typeof value.digest !== 'string' || !DIGEST.test(value.digest)) return null;\n if (!isSafeInt(value.size, 1) || !isSafeInt(value.chunkBytes, 1) || value.chunkBytes > CHANNEL_MAX_CHUNK_BYTES) return null;\n return Object.freeze({\n owner: value.owner, epoch: value.epoch, version: value.version, schemaVersion: value.schemaVersion,\n digest: value.digest as `sha256:${string}`, size: value.size, chunkBytes: value.chunkBytes,\n });\n}\n\nexport interface ChannelEventSubscribeResult {\n readonly subscriptionId: string;\n readonly delivery: 'transient' | 'reliable';\n readonly fromSequence: number;\n readonly oldestSequence: number | null;\n readonly prunedThrough: number;\n}\n\nexport function decodeEventSubscribeResult(result: PluginChannelResult): ChannelEventSubscribeResult | null {\n if (!result.ok) return null;\n const value = result.value;\n if (!exactKeys(value, ['subscriptionId', 'delivery', 'fromSequence', 'oldestSequence', 'prunedThrough'])) return null;\n if (typeof value.subscriptionId !== 'string' || !NAME.test(value.subscriptionId)) return null;\n if (value.delivery !== 'transient' && value.delivery !== 'reliable') return null;\n if (!isSafeInt(value.fromSequence, 1)) return null;\n if (value.oldestSequence !== null && !isSafeInt(value.oldestSequence, 1)) return null;\n if (!isSafeInt(value.prunedThrough)) return null;\n return Object.freeze({\n subscriptionId: value.subscriptionId, delivery: value.delivery,\n fromSequence: value.fromSequence, oldestSequence: value.oldestSequence, prunedThrough: value.prunedThrough,\n });\n}\n\nexport interface ChannelEventAckResult {\n readonly acked: number;\n}\n\nexport function decodeEventAckResult(result: PluginChannelResult): ChannelEventAckResult | null {\n if (!result.ok) return null;\n const value = result.value;\n if (!exactKeys(value, ['acked'])) return null;\n if (!isSafeInt(value.acked, 1)) return null;\n return Object.freeze({ acked: value.acked });\n}\n\nexport interface ChannelSnapshotDescriptor {\n readonly owner: string;\n readonly epoch: number;\n readonly version: number;\n readonly schemaVersion: number;\n readonly digest: `sha256:${string}`;\n readonly size: number;\n readonly chunkBytes: number;\n}\n\nexport function decodeSnapshotDescriptor(result: PluginChannelResult): ChannelSnapshotDescriptor | null {\n if (!result.ok) return null;\n return decodeDescriptorRecord(result.value);\n}\n\n/** Encoding helpers for the lane success/error bodies, kept in one place. */\nexport function streamOpenResultBody(result: ChannelStreamOpenResult): Uint8Array {\n return encodeChannelResult({ ok: true, ...result });\n}\n\nexport function streamOpenDuplexResultBody(result: ChannelStreamOpenDuplexResult): Uint8Array {\n return encodeChannelResult({ ok: true, ...result });\n}\n\nexport function snapshotOpenResultBody(result: ChannelSnapshotOpenResult): Uint8Array {\n return encodeChannelResult({ ok: true, sessionId: result.sessionId, descriptor: { ...result.descriptor } });\n}\n\nexport function eventSubscribeResultBody(result: ChannelEventSubscribeResult): Uint8Array {\n return encodeChannelResult({ ok: true, ...result });\n}\n\nexport function eventAckResultBody(result: ChannelEventAckResult): Uint8Array {\n return encodeChannelResult({ ok: true, ...result });\n}\n\nexport function successBody(value: Record<string, unknown> = {}): Uint8Array {\n return encodeChannelResult({ ok: true, ...value });\n}\n\nexport function errorBody(code: PluginChannelErrorCode, detail?: Record<string, unknown>): Uint8Array {\n return detail === undefined ? encodeChannelResult({ ok: false, code }) : encodeChannelResult({ ok: false, code, detail });\n}\n",
|
|
14
|
+
"/**\n * Host communication lane engines (P5): stream (read + write) / event / snapshot\n * over one authenticated peer link, or in-process for a same-process provider.\n *\n * This module is the transport-and-semantics layer only. It never decides which\n * plugin may speak: every inbound lane frame is authorized by the host adapter\n * (`channels.ts`) through {@link PluginPeerChannelHubOptions.authorizeInbound},\n * and every provider registration is created by that adapter. The hub owns:\n *\n * - bounded state machines for each lane, always failing closed with a fixed\n * {@link PluginChannelErrorCode};\n * - real backpressure (credit windows for read and write streams, bounded\n * per-consumer windows for events, bounded chunk call sizes for snapshots);\n * - honest terminal states: `complete | failed | cancelled | truncated` — a\n * written buffer, a resolved result producer, or a resolved terminal is never\n * treated as proof that the peer consumed the bytes;\n * - provider-side Host leases: admitting a lane request takes the exact providing\n * plugin's Host lease and holds it until the real source/sink task settles, so\n * owner disposal can never race a live provider task.\n *\n * Reuse, not a second framework: requests ride the link's existing\n * authentication/correlation/deadline/cancellation/ACK machinery\n * (`requestOnLane`), and bulk bytes ride `emitLane` frames or bounded chunk\n * responses. A same-process route uses the in-process loopback port, so local and\n * remote transfers share exactly one implementation and one set of limits.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\nimport type { PluginServiceProcess } from './contracts';\nimport type { PluginPeerLaneEmit, PluginPeerLaneHandler, PluginPeerRpcRequestExecution } from './peer-rpc-link';\nimport type { RpcCallPurpose, RpcJson } from './wire-contract';\nimport {\n CHANNEL_MAX_CHUNK_BYTES,\n decodeChannelEmit,\n decodeChannelResult,\n decodeEventAckRequest,\n decodeEventAckResult,\n decodeEventSubscribeRequest,\n decodeEventSubscribeResult,\n decodeSnapshotChunkRequest,\n decodeSnapshotDescriptor,\n decodeSnapshotDescribeRequest,\n decodeSnapshotOpenRequest,\n decodeSnapshotOpenResult,\n decodeSnapshotReleaseRequest,\n decodeStreamFinishRequest,\n decodeStreamOpenDuplexRequest,\n decodeStreamOpenDuplexResult,\n decodeStreamOpenRequest,\n decodeStreamOpenResult,\n encodeChannelEmit,\n encodeEventAckRequest,\n encodeEventSubscribeRequest,\n encodeSnapshotChunkRequest,\n encodeSnapshotDescribeRequest,\n encodeSnapshotOpenRequest,\n encodeSnapshotReleaseRequest,\n encodeStreamFinishRequest,\n encodeStreamOpenDuplexRequest,\n encodeStreamOpenRequest,\n errorBody,\n eventAckResultBody,\n eventSubscribeResultBody,\n snapshotOpenResultBody,\n streamOpenDuplexResultBody,\n streamOpenResultBody,\n successBody,\n type ChannelSnapshotDescriptor,\n type PluginChannelErrorCode,\n type PluginChannelLane,\n type PluginChannelLinkPort,\n type PluginChannelResult,\n type PluginChannelTarget,\n} from './peer-channel-protocol';\n\n/* -------------------------------------------------------------------------- */\n/* Limits (bounded by contract, never by unbounded queues) */\n/* -------------------------------------------------------------------------- */\n\nexport const CHANNEL_MAX_ACTIVE_TRANSFERS = 32;\nexport const CHANNEL_MAX_SUBSCRIPTIONS = 64;\n/** Per-transfer buffered bytes a consumer may hold before it must consume. */\nexport const CHANNEL_MAX_TRANSFER_BUFFER_BYTES = 4 * CHANNEL_MAX_CHUNK_BYTES;\n/** Process-wide buffered bytes across every outbound transfer. */\nexport const CHANNEL_MAX_TOTAL_BUFFER_BYTES = 16 * CHANNEL_MAX_CHUNK_BYTES;\n/** Absolute byte ceiling for one stream object / snapshot body. */\nexport const CHANNEL_STREAM_MAX_TOTAL_BYTES = 64 * 1024 * 1024;\n/** Outstanding credit a receiver may grant for one transfer. */\nexport const CHANNEL_STREAM_MAX_CREDIT_BYTES = 8 * CHANNEL_MAX_CHUNK_BYTES;\n/** A lost credit window heals: its owner re-announces it this often. */\nexport const CHANNEL_CREDIT_HEARTBEAT_MS = 1_000;\nexport const CHANNEL_STREAM_DEFAULT_CREDIT_BYTES = 4 * CHANNEL_MAX_CHUNK_BYTES;\nexport const CHANNEL_STREAM_DEFAULT_IDLE_MS = 30_000;\nexport const CHANNEL_STREAM_DEFAULT_DEADLINE_MS = 120_000;\nexport const CHANNEL_STREAM_EMIT_RETRIES = 256;\n/** Bounded wait for an in-flight sink write to settle after cancellation. */\nexport const CHANNEL_STREAM_ABORT_DRAIN_MS = 30_000;\n/**\n * Grace for already-in-flight duplex read frames after the peer session ends.\n * Frames are delivered in order within milliseconds of being emitted, so this\n * only has to cover a queue that is already on the wire — never a long wait.\n */\nexport const CHANNEL_DUPLEX_TERMINAL_GRACE_MS = 1_000;\n/** Credit frames must never be dropped: a much longer bounded retry window. */\nexport const CHANNEL_STREAM_CREDIT_RETRIES = 512;\nexport const CHANNEL_SNAPSHOT_MAX_BYTES = 64 * 1024 * 1024;\nexport const CHANNEL_SNAPSHOT_CHUNK_CONCURRENCY = 4;\n/** A pinned snapshot read session is released after this idle bound. */\nexport const CHANNEL_SNAPSHOT_SESSION_IDLE_MS = 60_000;\n/** Concurrent pinned snapshot read sessions per hub. */\nexport const CHANNEL_SNAPSHOT_MAX_SESSIONS = 32;\nexport const CHANNEL_EVENT_QUEUE_MAX = 256;\nexport const CHANNEL_EVENT_REPLAY_BATCH = 64;\nexport const CHANNEL_EVENT_MAX_PAYLOAD_BYTES = 60 * 1024;\nexport const CHANNEL_SNAPSHOT_CHUNK_BYTES = CHANNEL_MAX_CHUNK_BYTES;\n\nconst EMPTY = new Uint8Array(0);\n\n/* -------------------------------------------------------------------------- */\n/* Provider implementation contracts */\n/* -------------------------------------------------------------------------- */\n\nexport interface PluginChannelStreamSource {\n readonly size: number;\n readonly digest: `sha256:${string}`;\n /** Reads `length` bytes at `offset` of this immutable version. */\n read(offset: number, length: number): Promise<Uint8Array>;\n}\n\nexport interface PluginChannelStreamSink {\n /** Consumes one chunk at `offset`; resolves once the sink accepted it. */\n write(offset: number, bytes: Uint8Array): Promise<void>;\n /** Final commit of the complete body; must verify the size/digest contract. */\n finish(size: number, digest: `sha256:${string}`): Promise<void>;\n /** Reclaims an unfinished transfer; never called after `finish` resolved. */\n abort?(reason: 'cancelled' | 'failed' | 'closed'): void;\n}\n\nexport interface PluginChannelStreamProvider {\n /** Read side: the immutable version to serve, or `null` when unavailable. */\n open?(input: { readonly caller: string; readonly callerScope: string; readonly objectId: string; readonly version: number }): PluginChannelStreamSource | null;\n /** Write side: the sink that will receive the consumer's bytes, or `null`. */\n accept?(input: { readonly caller: string; readonly callerScope: string; readonly objectId: string; readonly version: number }): PluginChannelStreamSink | null;\n /**\n * Duplex session: ONE negotiation for both directions over one transfer id and\n * one shared terminal. A read-only or write-only side is expressed by omitting\n * the other half; returning `null` refuses the whole session.\n */\n duplex?(input: { readonly caller: string; readonly callerScope: string; readonly objectId: string; readonly version: number }): {\n readonly source?: PluginChannelStreamSource;\n readonly sink?: PluginChannelStreamSink;\n } | null;\n}\n\nexport interface PluginChannelSnapshotSource {\n readonly descriptor: ChannelSnapshotDescriptor;\n read(offset: number, length: number): Promise<Uint8Array>;\n /**\n * Retains exactly this immutable version for one whole-body read. Called by the\n * hub when it pins the source for a session, before any chunk is read.\n */\n retain?(): void;\n /**\n * Releases the provider-side retention of exactly this immutable version. The\n * hub calls it once when the read session (which pinned this source for the\n * WHOLE body) ends; a bound store uses it to keep an in-use version alive.\n */\n release?(): void;\n}\n\nexport interface PluginChannelSnapshotProvider {\n /** Current immutable descriptor + reader, or `null` when no valid snapshot exists. */\n current(): PluginChannelSnapshotSource | null;\n /** One explicitly named still-retained version, or `null` once it was evicted. */\n version(version: number): PluginChannelSnapshotSource | null;\n}\n\nexport interface PluginChannelEventEntry {\n readonly sequence: number;\n readonly eventId: string;\n readonly payload: Uint8Array;\n}\n\nexport interface PluginChannelEventAck {\n /** The consumer's durable checkpoint after this ack (never lower than before). */\n readonly acked: number;\n}\n\nexport interface PluginChannelReliableEventLog {\n /** Oldest still-replayable sequence, or `null` when the log holds no events. */\n oldestSequence(): number | null;\n latestSequence(): number;\n /** Highest sequence already pruned; a `from` at or below it is an explicit gap. */\n prunedThrough(): number;\n /** Bounded replay from `from`; a contiguous run, never sparse. */\n list(fromSequence: number, limit: number): Promise<readonly PluginChannelEventEntry[]>;\n /** Highest durable checkpoint for this consumer (0 when none). */\n checkpoint(consumerId: string): number;\n /** Monotonic durable ack: an older sequence never lowers the stored checkpoint. */\n ack(consumerId: string, sequence: number): PluginChannelEventAck;\n /** Durable append; the returned sequence and event id are stable and unique. */\n append(payload: Uint8Array): { readonly sequence: number; readonly eventId: string };\n /**\n * Outbox primitive: writes ONLY the event row on the caller's already-open\n * transaction (the provider's business-state transaction on the same\n * connection), so both commit or both roll back. Never opens its own. When a\n * `receiptId` is given, a durable (sequence, eventId, payloadHash) receipt is\n * written in the same transaction, so an idempotent replay can return the FIRST\n * result instead of appending a second event.\n */\n appendWithinTransaction?(payload: Uint8Array, receiptId?: string): { readonly sequence: number; readonly eventId: string };\n /** Durable outbox receipt for `receiptId`, or `null` when none exists. */\n receipt?(receiptId: string): { readonly sequence: number; readonly eventId: string; readonly payloadHash: string } | null;\n}\n\nexport interface PluginChannelEventProvider {\n readonly delivery: 'transient' | 'reliable';\n /** Present exactly for a reliable topic; absence is refused, never guessed. */\n readonly log?: PluginChannelReliableEventLog;\n}\n\nexport interface PluginChannelEventDelivery {\n readonly sequence: number;\n readonly eventId: string;\n readonly payload: Uint8Array;\n readonly delivery: 'transient' | 'reliable';\n}\n\n/* -------------------------------------------------------------------------- */\n/* Hub */\n/* -------------------------------------------------------------------------- */\n\nexport interface PluginChannelRegistrationInput {\n readonly lane: PluginChannelLane;\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly process: PluginServiceProcess;\n /** Canonical hash of the provider's declared lane contract. */\n readonly contract: string;\n}\n\ninterface Registration {\n readonly key: string;\n readonly lane: PluginChannelLane;\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly process: PluginServiceProcess;\n readonly contract: string;\n readonly stream?: PluginChannelStreamProvider;\n readonly snapshot?: PluginChannelSnapshotProvider;\n readonly event?: PluginChannelEventProvider;\n ready: boolean;\n retiring: boolean;\n}\n\nexport interface PluginChannelProviderHandle {\n markReady(): void;\n retire(): void;\n dispose(): void;\n}\n\nexport type PluginChannelRouteResolution =\n | { readonly kind: 'local' }\n | { readonly kind: 'remote'; readonly link: PluginChannelLinkPort }\n | { readonly kind: 'ambiguous' }\n | { readonly kind: 'unavailable' };\n\n/** Host-minted invocation context for one provider-side lane task. */\nexport interface PluginChannelProviderContext {\n readonly purpose: RpcCallPurpose;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface PluginPeerChannelHubOptions {\n readonly process: PluginServiceProcess;\n /** The only peer process this hub can reach over a link. */\n readonly peerProcess: PluginServiceProcess;\n /**\n * Host-owned route resolution for one target. The hub prefers a local\n * registration when the host says so, otherwise exactly one remote link, and\n * reports `ambiguous`/`unavailable` instead of guessing.\n */\n readonly resolveRoute: (target: PluginChannelTarget, lane: PluginChannelLane) => PluginChannelRouteResolution;\n /** Trusted host decision for one inbound lane request. */\n readonly authorizeInbound: (request: {\n readonly lane: PluginChannelLane;\n readonly target: PluginChannelTarget;\n readonly caller: string;\n readonly callerScope: string;\n readonly providerProcess: PluginServiceProcess;\n readonly local: boolean;\n readonly link: PluginChannelLinkPort | null;\n /**\n * `true` for a frame that belongs to an ALREADY-accepted transfer,\n * subscription or snapshot session (finish/ACK/chunk/release), `false` for a\n * NEW open/subscribe/describe. A draining peer may still admit continuations\n * by exact identity while it refuses every new lane request.\n */\n readonly continuation: boolean;\n }) => boolean;\n /**\n * Host-only provider lease for the exact providing plugin; the hub holds it\n * from admission until the real provider task settles. `null` refuses the work.\n * The host-minted invocation context (purpose + absolute deadline + signal)\n * rides along, so a peer-originated lane task keeps the caller's real purpose\n * and cancellation instead of being downgraded to a background task.\n */\n readonly beginProviderOperation?: (plugin: string, context: PluginChannelProviderContext) => (() => void) | null;\n readonly onDiagnostic?: (event: { readonly kind: string; readonly lane: PluginChannelLane; readonly code: PluginChannelErrorCode | 'invalid' }) => void;\n}\n\nfunction callTargetKey(lane: PluginChannelLane, target: PluginChannelTarget): string {\n return [lane, target.provider, target.service, String(target.major)].join('\\0');\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise<void>((resolve) => { const timer = setTimeout(resolve, ms); timer.unref?.(); });\n}\n\ninterface Deferred<T> {\n readonly promise: Promise<T>;\n /** True once settled; lets callers avoid acting on an already-finished transfer. */\n readonly settled: boolean;\n resolve(value: T): void;\n reject(error: unknown): void;\n}\n\nfunction createDeferred<T>(): Deferred<T> {\n let settleResolve!: (value: T) => void;\n let settleReject!: (error: unknown) => void;\n let settled = false;\n const promise = new Promise<T>((accept, decline) => { settleResolve = accept; settleReject = decline; });\n void promise.catch(() => undefined);\n return {\n promise,\n get settled() { return settled; },\n resolve(value) { if (settled) return; settled = true; settleResolve(value); },\n reject(error) { if (settled) return; settled = true; settleReject(error); },\n };\n}\n\nfunction decodeResultOrError(bytes: Uint8Array): PluginChannelResult {\n return decodeChannelResult(bytes) ?? Object.freeze({ ok: false as const, code: 'failed' as const });\n}\n\nfunction safeSha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n}\n\nclass ChannelError extends Error {\n readonly name = 'ChannelError';\n constructor(readonly code: PluginChannelErrorCode, message: string) {\n super(message);\n }\n}\n\n/* Stream state ------------------------------------------------------------- */\n\ninterface StreamInbound {\n readonly link: PluginChannelLinkPort;\n readonly providerKey: string;\n readonly transferId: string;\n readonly caller: string;\n readonly callerScope: string;\n readonly deadlineAt: number;\n readonly frameBytes: number;\n readonly idleMs: number;\n readonly release: (() => void) | null;\n /** Duplex: abort the sibling write half when this read half fails. */\n readonly abortSibling?: (reason: 'cancelled' | 'failed') => void;\n /** Absolute credit window: the highest byte offset this producer may send to. */\n window: number;\n creditWaiters: Array<() => void>;\n idleTimer: ReturnType<typeof setTimeout> | null;\n aborted: boolean;\n finished: boolean;\n}\n\ninterface StreamOutbound {\n readonly link: PluginChannelLinkPort;\n readonly providerKey: string;\n readonly transferId: string;\n readonly deadlineAt: number;\n readonly idleMs: number;\n readonly baseOffset: number;\n /** Adopted from the provider's open result when the caller left it open. */\n expectedSize: number | null;\n expectedDigest: `sha256:${string}` | null;\n readonly hash: ReturnType<typeof createHash> | null;\n readonly chunks: Uint8Array[];\n queuedBytes: number;\n receivedBytes: number;\n /** Bytes the caller already consumed (the window base). */\n consumedBytes: number;\n /** Allowance granted but not yet consumed. */\n slack: number;\n heartbeat: ReturnType<typeof setInterval> | null;\n lastSeen: boolean;\n /** The consumer half-closed this read direction (duplex): iteration must end. */\n halfClosed: boolean;\n completed: boolean;\n failure: Error | null;\n waiters: Array<() => void>;\n readonly completion: Deferred<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n idleTimer: ReturnType<typeof setTimeout> | null;\n readonly controller: AbortController;\n /** Released when the transfer settles (Host owner lease, if any). */\n readonly release: (() => void) | null;\n /** Present when this read flow is one half of a duplex session. */\n duplex?: DuplexOutbound;\n}\n\ninterface WriteInbound {\n readonly link: PluginChannelLinkPort;\n readonly providerKey: string;\n readonly transferId: string;\n readonly caller: string;\n readonly callerScope: string;\n readonly deadlineAt: number;\n readonly idleMs: number;\n readonly release: (() => void) | null;\n readonly expectedSize: number | null;\n readonly expectedDigest: `sha256:${string}` | null;\n readonly hash: ReturnType<typeof createHash>;\n readonly sink: PluginChannelStreamSink;\n readonly finishedWait: Deferred<void>;\n /** Duplex: abort the sibling read half when this write half fails. */\n readonly abortSibling?: (reason: 'cancelled' | 'failed') => void;\n /** Serializes sink.write calls: one sink is never written concurrently. */\n writeTail: Promise<void>;\n offset: number;\n /** Allowance the sink already accepted but the consumer has not used yet. */\n slack: number;\n /** Highest absolute window announced to the consumer. */\n window: number;\n heartbeat: ReturnType<typeof setInterval> | null;\n idleTimer: ReturnType<typeof setTimeout> | null;\n finished: boolean;\n aborting: boolean;\n /** A finish request is committing: late data frames are refused, not written. */\n finishing: boolean;\n}\n\ninterface WriteOutbound {\n readonly link: PluginChannelLinkPort;\n readonly transferId: string;\n readonly deadlineAt: number;\n readonly idleMs: number;\n readonly purpose: RpcCallPurpose;\n readonly controller: AbortController;\n readonly completion: Deferred<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n /** Absolute window announced by the provider: this consumer may send up to here. */\n window: number;\n hash: ReturnType<typeof createHash>;\n bytes: number;\n creditWaiters: Array<() => void>;\n idleTimer: ReturnType<typeof setTimeout> | null;\n failure: Error | null;\n /** A finish request is in flight: its result, not the terminal, settles this. */\n finishing: boolean;\n writeTail: Promise<void>;\n queuedWriteBytes: number;\n release: (() => void) | null;\n /** Present when this write flow is one half of a duplex session. */\n duplex?: DuplexOutbound;\n}\n\n/**\n * One consumer-side duplex session: the read and write flows of the SAME transfer\n * id, with the shared completion that settles only when both real halves have\n * settled (a half-closed direction contributes `null`).\n */\ninterface DuplexOutbound {\n readonly transferId: string;\n readonly read: StreamOutbound;\n readonly write: WriteOutbound;\n readonly completion: Deferred<PluginChannelDuplexResult>;\n readSettled: boolean;\n writeSettled: boolean;\n readValue: { readonly bytes: number; readonly digest: `sha256:${string}` } | null;\n writeValue: { readonly bytes: number; readonly digest: `sha256:${string}` } | null;\n failure: Error | null;\n settled: boolean;\n /** True once the consumer half-closed the read direction (a legal end, not a failure). */\n readHalfClosed: boolean;\n /** The one Host operation lease for the whole session, released on drain. */\n readonly release: (() => void) | null;\n /** Session-level request controller (aborted only when the whole session ends). */\n readonly controller: AbortController;\n}\n\n/** One provider-side pinned snapshot read session (whole-body retention). */\ninterface SnapshotSession {\n readonly link: PluginChannelLinkPort;\n readonly providerKey: string;\n readonly sessionId: string;\n readonly caller: string;\n readonly callerScope: string;\n readonly deadlineAt: number;\n readonly source: PluginChannelSnapshotSource;\n readonly release: (() => void) | null;\n idleTimer: ReturnType<typeof setTimeout> | null;\n closed: boolean;\n /** Real `source.read` calls still in flight; release waits for these. */\n activeReads: number;\n released: boolean;\n /** Callers of a release waiting for every active read to drain. */\n drainWaiters: Array<() => void>;\n}\n\n/* Event state -------------------------------------------------------------- */\n\ninterface QueuedEvent {\n readonly sequence: number;\n readonly eventId: string;\n readonly payload: Uint8Array;\n}\n\ninterface EventSubscription {\n readonly link: PluginChannelLinkPort;\n readonly providerKey: string;\n readonly subscriptionId: string;\n readonly caller: string;\n readonly callerScope: string;\n readonly consumerId: string;\n readonly delivery: 'transient' | 'reliable';\n readonly deadlineAt: number;\n readonly release: (() => void) | null;\n pending: QueuedEvent[];\n dropped: number;\n lastAcked: number;\n /** Highest CONTIGUOUS sequence delivered (the true ACK ceiling). */\n lastDelivered: number;\n /** One real task reads the durable log for both history and live delivery. */\n replaying: boolean;\n closed: boolean;\n /** A reliable delivery gap that must be signalled once the transport is up. */\n gapPending: boolean;\n gapCode: PluginChannelErrorCode | null;\n waiters: Array<() => void>;\n workWaiters: Array<() => void>;\n wakeVersion: number;\n}\n\ninterface EventOutbound {\n readonly link: PluginChannelLinkPort;\n readonly subscriptionId: string;\n readonly deadlineAt: number;\n readonly delivery: 'transient' | 'reliable';\n readonly purpose: RpcCallPurpose;\n readonly handler: (event: PluginChannelEventDelivery) => void;\n queue: QueuedEvent[];\n dropped: number;\n scheduled: boolean;\n ready: boolean;\n closed: boolean;\n /** Highest sequence whose callback actually RAN, contiguous from `fromSequence`. */\n delivered: number;\n readonly terminal: Deferred<'closed' | 'failed'>;\n readonly controller: AbortController;\n release: (() => void) | null;\n}\n\n/** One consumer-visible live read stream. */\nexport interface PluginChannelStream {\n readonly transferId: string;\n readonly size: number | null;\n readonly digest: `sha256:${string}` | null;\n /** Resolves only after the consumer fully consumed and verified the body. */\n readonly completed: Promise<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n chunks(): AsyncGenerator<Uint8Array, void, void>;\n /** Drains the whole body and resolves the verified result. */\n collect(): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}`; readonly body: Uint8Array }>;\n cancel(): void;\n}\n\n/** Combined result of one duplex session; a half-closed direction is `null`. */\nexport interface PluginChannelDuplexResult {\n readonly read: { readonly bytes: number; readonly digest: `sha256:${string}` } | null;\n readonly write: { readonly bytes: number; readonly digest: `sha256:${string}` } | null;\n}\n\n/**\n * One consumer-visible duplex session: a single transfer id with an independent\n * read flow and write flow (each with its own credit window), a shared terminal,\n * and per-direction half-close. The session drains only when BOTH real halves\n * have settled.\n */\nexport interface PluginChannelDuplexSession {\n readonly transferId: string;\n readonly readSize: number | null;\n readonly readDigest: `sha256:${string}` | null;\n readonly completed: Promise<PluginChannelDuplexResult>;\n chunks(): AsyncGenerator<Uint8Array, void, void>;\n collect(): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}`; readonly body: Uint8Array }>;\n write(chunk: Uint8Array): Promise<void>;\n /** Commits the write direction; the read direction keeps running. */\n finishWrite(): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n /** Half-closes the read direction; the write direction keeps running. */\n endRead(): void;\n abort(): void;\n}\n\n/** One consumer-visible write stream. */\nexport interface PluginChannelWriteStream {\n readonly transferId: string;\n /** Resolves after the provider durably accepted and verified the whole body. */\n readonly completed: Promise<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n write(chunk: Uint8Array): Promise<void>;\n finish(): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}` }>;\n abort(): void;\n}\n\n/** One consumer-visible event subscription. */\nexport interface PluginChannelEventSubscription {\n readonly subscriptionId: string;\n readonly delivery: 'transient' | 'reliable';\n readonly fromSequence: number;\n readonly oldestSequence: number | null;\n readonly prunedThrough: number;\n readonly dropped: () => number;\n /**\n * Settles exactly once: `'closed'` on an orderly close, `'failed'` when the\n * ordered reliable delivery can no longer continue (a real gap/overflow/\n * refusal). It never resolves silently as a success, so a consumer can\n * re-subscribe from its durable checkpoint instead of waiting forever.\n */\n readonly terminal: Promise<'closed' | 'failed'>;\n ack(sequence: number): Promise<number>;\n close(): void;\n}\n\nexport interface PluginChannelSnapshotRead {\n readonly descriptor: ChannelSnapshotDescriptor;\n readonly bytes: Uint8Array;\n}\n\n/** Module-private handle brand: only the hub can mint or read it. */\nconst HANDLE_REGISTRATIONS = new WeakMap<object, Registration>();\n\nexport class PluginPeerChannelHub {\n readonly #options: PluginPeerChannelHubOptions;\n readonly #registrations = new Map<string, Registration>();\n readonly #streamInbound = new Map<string, StreamInbound>();\n readonly #streamOutbound = new Map<string, StreamOutbound>();\n readonly #writeInbound = new Map<string, WriteInbound>();\n readonly #writeOutbound = new Map<string, WriteOutbound>();\n readonly #eventInbound = new Map<string, EventSubscription>();\n readonly #eventOutbound = new Map<string, EventOutbound>();\n /** Pinned whole-body snapshot read sessions (provider side). */\n readonly #snapshotSessions = new Map<string, SnapshotSession>();\n #bufferedBytes = 0;\n #disposed = false;\n #loopback: PluginChannelLinkPort | null = null;\n\n constructor(options: PluginPeerChannelHubOptions) {\n this.#options = options;\n }\n\n get process(): PluginServiceProcess { return this.#options.process; }\n\n /** A lane handler bound to one concrete link (or to the in-process loopback). */\n handlerFor(link: PluginChannelLinkPort): PluginPeerLaneHandler {\n const handler: PluginPeerLaneHandler = {\n onRequest: (call, signal) => this.#onRequest(link, call.metadata, call.deadlineAt, signal),\n onEmit: (frame) => this.#onEmit(link, frame),\n onTransportReady: () => this.#onTransportReady(link),\n onTransportEnd: (reason) => this.#onTransportEnd(link, reason),\n };\n return Object.freeze(handler);\n }\n\n /** Host-only directory view of this hub's real registrations (for the peer directory). */\n publicationView(): readonly {\n readonly provider: string; readonly service: string; readonly major: number;\n readonly scope: 'global'; readonly scopeKey: 'global'; readonly ready: boolean;\n readonly lane: PluginChannelLane;\n }[] {\n const view = [];\n for (const registration of this.#registrations.values()) {\n view.push(Object.freeze({\n provider: registration.provider, service: registration.service, major: registration.major,\n scope: 'global' as const, scopeKey: 'global',\n ready: registration.ready && !registration.retiring, lane: registration.lane,\n }));\n }\n view.sort((left, right) => left.provider.localeCompare(right.provider)\n || left.service.localeCompare(right.service) || left.major - right.major || left.lane.localeCompare(right.lane));\n return Object.freeze(view);\n }\n\n /** In-process port for a same-process route; one instance per hub. */\n loopbackPort(): PluginChannelLinkPort {\n if (this.#loopback === null) {\n const port: PluginChannelLinkPort = {\n retired: false,\n requestOnLane: (lane, context, body, options) => this.#loopbackRequest(port, lane, context, body, options),\n emitLane: (lane, kind, requestId, deadlineAt, context, body) => {\n if (this.#disposed) return false;\n if (kind !== 'chunk' && kind !== 'notification') return false;\n try {\n this.#onEmit(port, Object.freeze({\n lane, kind, requestId, deadlineAt, context, body: new Uint8Array(body), sequence: 0,\n }));\n return true;\n } catch { return false; }\n },\n };\n this.#loopback = port;\n }\n return this.#loopback;\n }\n\n registerStream(input: PluginChannelRegistrationInput, provider: PluginChannelStreamProvider): PluginChannelProviderHandle {\n if (provider.open === undefined && provider.accept === undefined && provider.duplex === undefined) {\n throw new ChannelError('invalid', 'a stream provider must offer a read, write or duplex side');\n }\n return this.#register(input, { stream: provider });\n }\n\n registerSnapshot(input: PluginChannelRegistrationInput, provider: PluginChannelSnapshotProvider): PluginChannelProviderHandle {\n return this.#register(input, { snapshot: provider });\n }\n\n registerEvent(input: PluginChannelRegistrationInput, provider: PluginChannelEventProvider): PluginChannelProviderHandle {\n if (provider.delivery === 'reliable' && provider.log === undefined) {\n throw new ChannelError('invalid', 'a reliable event topic requires a durable log');\n }\n return this.#register(input, { event: provider });\n }\n\n #register(\n input: PluginChannelRegistrationInput,\n impl: { readonly stream?: PluginChannelStreamProvider; readonly snapshot?: PluginChannelSnapshotProvider; readonly event?: PluginChannelEventProvider },\n ): PluginChannelProviderHandle {\n const key = callTargetKey(input.lane, { provider: input.provider, service: input.service, major: input.major });\n if (this.#registrations.has(key)) throw new ChannelError('conflict', 'channel provider is already registered');\n if (typeof input.contract !== 'string' || input.contract.length === 0) throw new ChannelError('invalid', 'channel registration requires a contract hash');\n const registration: Registration = {\n key, lane: input.lane, provider: input.provider, service: input.service,\n major: input.major, process: input.process, contract: input.contract,\n stream: impl.stream, snapshot: impl.snapshot, event: impl.event,\n ready: false, retiring: false,\n };\n this.#registrations.set(key, registration);\n let released = false;\n const handle: PluginChannelProviderHandle = Object.freeze({\n markReady: () => { if (!released) registration.ready = true; },\n retire: () => { registration.retiring = true; },\n dispose: () => {\n if (released) return;\n released = true;\n registration.ready = false;\n registration.retiring = true;\n if (this.#registrations.get(key) === registration) this.#registrations.delete(key);\n // Accepted inbound work keeps draining through its own Host lease.\n },\n });\n HANDLE_REGISTRATIONS.set(handle, registration);\n return handle;\n }\n\n #registrationOf(handle: PluginChannelProviderHandle): Registration {\n const registration = HANDLE_REGISTRATIONS.get(handle as object);\n if (registration === undefined) throw new ChannelError('unauthorized', 'channel provider handle is not host-issued');\n return registration;\n }\n\n /**\n * Appends one reliable event and fans it out to every current subscriber.\n * Capacity/quota failure propagates so the publishing plugin sees an explicit\n * refusal instead of a silent drop. `extend` (when given) commits the provider's\n * business state in the same durable transaction as the event.\n */\n async publishReliable(\n handle: PluginChannelProviderHandle,\n payload: Uint8Array,\n appendPlan?: (payload: Uint8Array) => { readonly sequence: number; readonly eventId: string },\n ): Promise<number> {\n const registration = this.#registrationOf(handle);\n const log = registration.event?.log;\n if (log === undefined) throw new ChannelError('unavailable', 'channel reliable event log is unavailable');\n if (payload.byteLength > CHANNEL_EVENT_MAX_PAYLOAD_BYTES) throw new ChannelError('invalid', 'channel event payload exceeds the frame budget');\n // `appendPlan` lets the host commit the event inside the provider's own\n // business-state transaction; the fan-out happens only after that commit.\n const appended = appendPlan === undefined ? log.append(payload) : appendPlan(payload);\n this.#fanOut(registration, { sequence: appended.sequence, eventId: appended.eventId, payload: new Uint8Array(payload) }, 'reliable');\n return appended.sequence;\n }\n\n /** Fans one transient notification out to every current subscriber. */\n publishTransient(handle: PluginChannelProviderHandle, payload: Uint8Array): void {\n const registration = this.#registrationOf(handle);\n if (registration.event === undefined || registration.event.delivery !== 'transient') {\n throw new ChannelError('unavailable', 'channel transient event topic is unavailable');\n }\n if (payload.byteLength > CHANNEL_EVENT_MAX_PAYLOAD_BYTES) throw new ChannelError('invalid', 'channel event payload exceeds the frame budget');\n this.#fanOut(registration, { sequence: 0, eventId: randomUUID().replace(/-/g, ''), payload: new Uint8Array(payload) }, 'transient');\n }\n\n /* ------------------------------------------------------------------ */\n /* Route resolution */\n /* ------------------------------------------------------------------ */\n\n #route(target: PluginChannelTarget, lane: PluginChannelLane): { readonly link: PluginChannelLinkPort; readonly providerKey: string } {\n const localKey = callTargetKey(lane, target);\n const local = this.#registrations.get(localKey);\n if (local !== undefined && local.ready && !local.retiring && local.process === this.#options.process) {\n return { link: this.loopbackPort(), providerKey: localKey };\n }\n const resolution = this.#options.resolveRoute(target, lane);\n if (resolution.kind === 'remote') return { link: resolution.link, providerKey: localKey };\n if (resolution.kind === 'ambiguous') throw new ChannelError('ambiguous', 'peer channel target is ambiguous');\n throw new ChannelError('unavailable', 'peer channel target is unavailable');\n }\n\n /**\n * Refuses NEW consumer work on an exactly-retired link. Frames that belong to\n * an already-accepted transfer/subscription/session are NOT routed through\n * here; they keep flowing (finish/ACK/chunk/release/credit).\n */\n #assertLinkAdmitsNewWork(link: PluginChannelLinkPort): void {\n if (link.retired === true) throw new ChannelError('closed', 'peer channel link is retiring');\n }\n\n /* ------------------------------------------------------------------ */\n /* Consumer operations */\n /* ------------------------------------------------------------------ */\n\n openStream(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n request: {\n readonly objectId: string;\n readonly version: number;\n readonly offset: number;\n readonly size: number | null;\n readonly digest: `sha256:${string}` | null;\n readonly creditBytes?: number;\n readonly idleMs?: number;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n readonly purpose?: RpcCallPurpose;\n readonly release?: () => void;\n },\n ): PluginChannelStream {\n const { link, providerKey } = this.#route(target, 'stream');\n this.#assertLinkAdmitsNewWork(link);\n if (this.#streamOutbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) throw new ChannelError('overloaded', 'peer channel stream capacity is exhausted');\n if (!Number.isSafeInteger(request.offset) || request.offset < 0) throw new ChannelError('invalid', 'peer channel stream offset is invalid');\n if (request.size !== null && (!Number.isSafeInteger(request.size) || request.size < 1)) throw new ChannelError('invalid', 'peer channel stream size is invalid');\n if (request.size !== null && request.size > CHANNEL_STREAM_MAX_TOTAL_BYTES) throw new ChannelError('overloaded', 'peer channel stream exceeds the total byte ceiling');\n const creditBytes = request.creditBytes ?? CHANNEL_STREAM_DEFAULT_CREDIT_BYTES;\n const idleMs = request.idleMs ?? CHANNEL_STREAM_DEFAULT_IDLE_MS;\n if (!Number.isSafeInteger(creditBytes) || creditBytes < 1 || creditBytes > CHANNEL_STREAM_MAX_CREDIT_BYTES) throw new ChannelError('invalid', 'peer channel stream credit is invalid');\n if (!Number.isSafeInteger(idleMs) || idleMs < 1) throw new ChannelError('invalid', 'peer channel stream idle deadline is invalid');\n const deadlineAt = request.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n\n const transferId = randomUUID();\n const controller = new AbortController();\n const removeOuterAbort = linkExternalSignal(request.signal, controller);\n const drainingLease = terminalGatedRelease(request.release);\n const state: StreamOutbound = {\n link, providerKey, transferId, deadlineAt, idleMs,\n baseOffset: request.offset,\n expectedSize: request.size,\n expectedDigest: request.offset === 0 ? request.digest : null,\n hash: request.offset === 0 ? createHash('sha256') : null,\n chunks: [], queuedBytes: 0, receivedBytes: 0, consumedBytes: 0, slack: creditBytes, heartbeat: null,\n lastSeen: false, halfClosed: false, completed: false, failure: null, waiters: [],\n completion: createDeferred(), idleTimer: null, controller,\n release: drainingLease.release,\n };\n this.#streamOutbound.set(transferId, state);\n this.#armStreamIdle(state);\n this.#armStreamHeartbeat(state);\n\n const openCall = link.requestOnLane(\n 'stream',\n encodeStreamOpenRequest('stream.open', target, caller, callerScope, contract, {\n clientId: transferId, objectId: request.objectId, version: request.version,\n offset: request.offset, size: request.size, digest: request.digest,\n creditBytes, idleMs,\n }, request.purpose),\n EMPTY,\n { deadlineAt, signal: controller.signal },\n );\n drainingLease.observe(openCall.terminal);\n void openCall.terminal.then(\n () => { removeOuterAbort(); this.#onStreamTerminal(state); },\n () => { removeOuterAbort(); this.#failStream(state, 'truncated'); },\n );\n void openCall.result.then(\n (bytes) => {\n const result = decodeResultOrError(bytes);\n if (!result.ok) { this.#failStream(state, result.code === 'unavailable' ? 'unavailable' : 'failed'); return; }\n const open = decodeStreamOpenResult(result);\n if (open === null || open.transferId !== transferId) { this.#failStream(state, 'invalid'); return; }\n if (request.size !== null && open.size !== null && open.size !== request.size) { this.#failStream(state, 'conflict'); return; }\n // The provider's own size/digest are authoritative: adopt them when the\n // caller left them open, so the stream is still fully verified.\n if (state.expectedSize === null && open.size !== null) state.expectedSize = open.size;\n if (state.expectedDigest === null && request.offset === 0 && open.digest !== null) state.expectedDigest = open.digest;\n if (open.size !== null && open.size > CHANNEL_STREAM_MAX_TOTAL_BYTES) this.#failStream(state, 'overloaded');\n },\n (error) => { this.#failStream(state, errorCodeOf(error)); },\n );\n\n return Object.freeze({\n transferId,\n size: request.size,\n digest: request.digest,\n completed: state.completion.promise,\n chunks: () => this.#iterateStream(state),\n collect: () => this.#collectStream(state),\n cancel: () => { this.#cancelStream(state); },\n });\n }\n\n /** Opens a write stream: the consumer sends the bytes, the provider commits them. */\n openWriteStream(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n request: {\n readonly objectId: string;\n readonly version: number;\n readonly size: number | null;\n readonly digest: `sha256:${string}` | null;\n readonly creditBytes?: number;\n readonly idleMs?: number;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n readonly purpose?: RpcCallPurpose;\n readonly release?: () => void;\n },\n ): PluginChannelWriteStream {\n const { link } = this.#route(target, 'stream');\n this.#assertLinkAdmitsNewWork(link);\n if (this.#writeOutbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) throw new ChannelError('overloaded', 'peer channel write capacity is exhausted');\n if (request.size !== null && (!Number.isSafeInteger(request.size) || request.size < 1 || request.size > CHANNEL_STREAM_MAX_TOTAL_BYTES)) {\n throw new ChannelError('invalid', 'peer channel write size is invalid');\n }\n const creditBytes = request.creditBytes ?? CHANNEL_STREAM_DEFAULT_CREDIT_BYTES;\n const idleMs = request.idleMs ?? CHANNEL_STREAM_DEFAULT_IDLE_MS;\n if (!Number.isSafeInteger(creditBytes) || creditBytes < 1 || creditBytes > CHANNEL_STREAM_MAX_CREDIT_BYTES) throw new ChannelError('invalid', 'peer channel write credit is invalid');\n const deadlineAt = request.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n const transferId = randomUUID();\n const controller = new AbortController();\n const removeOuterAbort = linkExternalSignal(request.signal, controller);\n const drainingLease = terminalGatedRelease(request.release);\n const state: WriteOutbound = {\n link, transferId, deadlineAt, idleMs, purpose: request.purpose ?? 'background', controller,\n completion: createDeferred(), window: 0, hash: createHash('sha256'), bytes: 0,\n creditWaiters: [], idleTimer: null, failure: null, finishing: false,\n writeTail: Promise.resolve(), queuedWriteBytes: 0, release: drainingLease.release,\n };\n this.#writeOutbound.set(transferId, state);\n this.#armWriteIdle(state);\n\n const openCall = link.requestOnLane(\n 'stream',\n encodeStreamOpenRequest('stream.open-write', target, caller, callerScope, contract, {\n clientId: transferId, objectId: request.objectId, version: request.version,\n offset: 0, size: request.size, digest: request.digest,\n creditBytes, idleMs,\n }, request.purpose),\n EMPTY,\n { deadlineAt, signal: controller.signal },\n );\n drainingLease.observe(openCall.terminal);\n void openCall.terminal.then(\n () => { removeOuterAbort(); if (state.failure === null && !isSettled(state.completion) && !state.finishing) this.#failWrite(state, 'truncated'); },\n () => { removeOuterAbort(); this.#failWrite(state, 'truncated'); },\n );\n void openCall.result.then(\n (bytes) => {\n const result = decodeResultOrError(bytes);\n if (!result.ok) { this.#failWrite(state, result.code === 'unavailable' ? 'unavailable' : 'failed'); return; }\n const open = decodeStreamOpenResult(result);\n if (open === null || open.transferId !== transferId) { this.#failWrite(state, 'invalid'); return; }\n state.window = Math.max(state.window, Math.min(open.creditBytes, CHANNEL_STREAM_MAX_CREDIT_BYTES));\n this.#wakeWrite(state);\n },\n (error) => { this.#failWrite(state, errorCodeOf(error)); },\n );\n\n return Object.freeze({\n transferId,\n completed: state.completion.promise,\n write: (chunk: Uint8Array) => this.#writeChunk(state, chunk),\n finish: () => this.#finishWrite(state, target, caller, callerScope, contract),\n abort: () => { this.#abortWrite(state, 'cancelled'); },\n });\n }\n\n /**\n * Opens a true duplex session: ONE negotiation creates a single transfer id\n * carrying an independent read flow and write flow with one shared terminal.\n */\n openDuplex(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n request: {\n readonly objectId: string;\n readonly version: number;\n readonly readOffset?: number;\n readonly readSize?: number | null;\n readonly readDigest?: `sha256:${string}` | null;\n readonly writeSize?: number | null;\n readonly writeDigest?: `sha256:${string}` | null;\n readonly readCreditBytes?: number;\n readonly writeCreditBytes?: number;\n readonly idleMs?: number;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n readonly purpose?: RpcCallPurpose;\n readonly release?: () => void;\n },\n ): PluginChannelDuplexSession {\n const { link } = this.#route(target, 'stream');\n this.#assertLinkAdmitsNewWork(link);\n if (this.#streamOutbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS || this.#writeOutbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) {\n throw new ChannelError('overloaded', 'peer channel duplex capacity is exhausted');\n }\n const readOffset = request.readOffset ?? 0;\n if (!Number.isSafeInteger(readOffset) || readOffset < 0) throw new ChannelError('invalid', 'peer channel duplex read offset is invalid');\n const readSize = request.readSize ?? null;\n if (readSize !== null && (!Number.isSafeInteger(readSize) || readSize < 1 || readSize > CHANNEL_STREAM_MAX_TOTAL_BYTES)) {\n throw new ChannelError('invalid', 'peer channel duplex read size is invalid');\n }\n const writeSize = request.writeSize ?? null;\n if (writeSize !== null && (!Number.isSafeInteger(writeSize) || writeSize < 1 || writeSize > CHANNEL_STREAM_MAX_TOTAL_BYTES)) {\n throw new ChannelError('invalid', 'peer channel duplex write size is invalid');\n }\n const readCreditBytes = request.readCreditBytes ?? CHANNEL_STREAM_DEFAULT_CREDIT_BYTES;\n const writeCreditBytes = request.writeCreditBytes ?? CHANNEL_STREAM_DEFAULT_CREDIT_BYTES;\n if (!Number.isSafeInteger(readCreditBytes) || readCreditBytes < 1 || readCreditBytes > CHANNEL_STREAM_MAX_CREDIT_BYTES\n || !Number.isSafeInteger(writeCreditBytes) || writeCreditBytes < 1 || writeCreditBytes > CHANNEL_STREAM_MAX_CREDIT_BYTES) {\n throw new ChannelError('invalid', 'peer channel duplex credit is invalid');\n }\n const idleMs = request.idleMs ?? CHANNEL_STREAM_DEFAULT_IDLE_MS;\n if (!Number.isSafeInteger(idleMs) || idleMs < 1) throw new ChannelError('invalid', 'peer channel duplex idle deadline is invalid');\n const deadlineAt = request.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n\n const transferId = randomUUID();\n // Three controllers: the SESSION controller owns the one open-duplex request\n // (so a read half-close cancels nothing), and each direction has its own so a\n // half-close of one direction never aborts the other's in-flight requests.\n const sessionController = new AbortController();\n const readController = new AbortController();\n const writeController = new AbortController();\n const removeSessionAbort = linkExternalSignal(request.signal, sessionController);\n const removeReadAbort = linkExternalSignal(request.signal, readController);\n const removeWriteAbort = linkExternalSignal(request.signal, writeController);\n const removeOuterAbort = () => { removeSessionAbort(); removeReadAbort(); removeWriteAbort(); };\n const drainingLease = terminalGatedRelease(request.release);\n const read: StreamOutbound = {\n link, providerKey: callTargetKey('stream', target), transferId, deadlineAt, idleMs,\n baseOffset: readOffset, expectedSize: readSize, expectedDigest: readOffset === 0 ? request.readDigest ?? null : null,\n hash: readOffset === 0 ? createHash('sha256') : null,\n chunks: [], queuedBytes: 0, receivedBytes: 0, consumedBytes: 0, slack: readCreditBytes, heartbeat: null,\n lastSeen: false, halfClosed: false, completed: false, failure: null, waiters: [],\n completion: createDeferred(), idleTimer: null, controller: readController, release: null,\n };\n const write: WriteOutbound = {\n link, transferId, deadlineAt, idleMs, purpose: request.purpose ?? 'background', controller: writeController,\n completion: createDeferred(), window: writeCreditBytes, hash: createHash('sha256'), bytes: 0,\n creditWaiters: [], idleTimer: null, failure: null, finishing: false,\n writeTail: Promise.resolve(), queuedWriteBytes: 0, release: null,\n };\n const duplex: DuplexOutbound = {\n transferId, read, write, completion: createDeferred(),\n readSettled: false, writeSettled: false, readValue: null, writeValue: null,\n failure: null, settled: false, readHalfClosed: false, release: drainingLease.release,\n controller: sessionController,\n };\n read.duplex = duplex;\n write.duplex = duplex;\n this.#streamOutbound.set(transferId, read);\n this.#writeOutbound.set(transferId, write);\n this.#armStreamIdle(read);\n this.#armWriteIdle(write);\n\n const openCall = link.requestOnLane(\n 'stream',\n encodeStreamOpenDuplexRequest(target, caller, callerScope, contract, {\n clientId: transferId, objectId: request.objectId, version: request.version,\n readOffset, readSize, readDigest: request.readDigest ?? null,\n writeSize, writeDigest: request.writeDigest ?? null,\n readCreditBytes, writeCreditBytes, idleMs,\n }, request.purpose),\n EMPTY,\n { deadlineAt, signal: sessionController.signal },\n );\n drainingLease.observe(openCall.terminal);\n void openCall.terminal.then(\n () => {\n removeOuterAbort();\n // The provider's session terminal resolves only after it emitted the\n // ordered `stream.end` for its read direction (or explicitly ended it).\n // A read half that never reached a real end is a truncation — never a\n // timer guess about an in-flight frame.\n if (duplex.settled || duplex.readSettled || read.lastSeen) return;\n this.#duplexFail(duplex, 'truncated');\n },\n () => { removeOuterAbort(); if (!duplex.settled) this.#duplexFail(duplex, 'closed'); },\n );\n void openCall.result.then(\n (bytes) => {\n const result = decodeResultOrError(bytes);\n if (!result.ok) { this.#duplexFail(duplex, result.code as PluginChannelErrorCode); return; }\n const open = decodeStreamOpenDuplexResult(result);\n if (open === null || open.transferId !== transferId) { this.#duplexFail(duplex, 'invalid'); return; }\n if (readSize !== null && open.readSize !== null && open.readSize !== readSize) { this.#duplexFail(duplex, 'conflict'); return; }\n if (read.expectedSize === null && open.readSize !== null) read.expectedSize = open.readSize;\n if (read.expectedDigest === null && readOffset === 0 && open.readDigest !== null) read.expectedDigest = open.readDigest;\n if (open.readSize !== null && open.readSize > CHANNEL_STREAM_MAX_TOTAL_BYTES) { this.#duplexFail(duplex, 'overloaded'); return; }\n write.window = Math.max(write.window, Math.min(open.writeCreditBytes, CHANNEL_STREAM_MAX_CREDIT_BYTES));\n this.#wakeWrite(write);\n if (open.readSize === null) {\n // The provider explicitly offered NO read direction (`readSize` is null\n // only when it has no source). The consumer must never wait for a half\n // that can never exist: settle the read half as a real `null` now, while\n // the write direction keeps running to its own terminal.\n this.#settleAbsentRead(read);\n this.#duplexSettle(duplex, 'read', null);\n }\n },\n (error) => { this.#duplexFail(duplex, errorCodeOf(error)); },\n );\n\n const session: PluginChannelDuplexSession = Object.freeze({\n transferId,\n get readSize(): number | null { return read.expectedSize; },\n get readDigest(): `sha256:${string}` | null { return read.expectedDigest; },\n completed: duplex.completion.promise,\n chunks: () => this.#iterateStream(read),\n collect: () => this.#collectStream(read),\n write: (chunk: Uint8Array) => this.#writeChunk(write, chunk),\n finishWrite: () => this.#finishWrite(write, target, caller, callerScope, contract),\n endRead: () => this.#endDuplexRead(read),\n abort: () => { this.#abortDuplex(duplex, 'cancelled'); },\n });\n return session;\n }\n\n /** Half-closes the read direction: the write direction keeps running. */\n #endDuplexRead(read: StreamOutbound): void {\n const duplex = read.duplex;\n if (duplex === undefined || duplex.readHalfClosed || read.completed || read.failure !== null) return;\n duplex.readHalfClosed = true;\n const payload = encodeChannelEmit({ kind: 'stream.end-read', transferId: read.transferId });\n void this.#emitLaneWithRetry(read.link, read.transferId, read.deadlineAt, payload).catch(() => undefined);\n read.completed = true;\n read.halfClosed = true;\n this.#clearStreamResources(read);\n for (const resolve of read.waiters.splice(0)) resolve();\n read.completion.resolve(Object.freeze({ bytes: read.receivedBytes, digest: `sha256:${(read.hash ?? createHash('sha256')).digest('hex')}` }));\n this.#duplexSettle(duplex, 'read', null);\n }\n\n #abortDuplex(duplex: DuplexOutbound, code: PluginChannelErrorCode): void {\n this.#duplexFail(duplex, code);\n }\n\n /** Ends a read half the provider never offered: a real `null`, not a hang. */\n #settleAbsentRead(read: StreamOutbound): void {\n if (read.completed || read.failure !== null) return;\n read.completed = true;\n read.halfClosed = true;\n this.#clearStreamResources(read);\n read.completion.resolve(Object.freeze({ bytes: read.receivedBytes, digest: `sha256:${(read.hash ?? createHash('sha256')).digest('hex')}` }));\n for (const resolve of read.waiters.splice(0)) resolve();\n }\n\n #duplexSettle(duplex: DuplexOutbound, half: 'read' | 'write', value: { readonly bytes: number; readonly digest: `sha256:${string}` } | null): void {\n if (half === 'read') { duplex.readSettled = true; duplex.readValue = value; }\n else { duplex.writeSettled = true; duplex.writeValue = value; }\n this.#duplexCheck(duplex);\n }\n\n #duplexFail(duplex: DuplexOutbound, code: PluginChannelErrorCode, half?: 'read' | 'write'): void {\n if (duplex.settled) return;\n // Tell the provider the whole session is over (its inbound request signal\n // aborts and both halves drain); a half-close never reaches this path.\n try { duplex.controller.abort('failed'); } catch { /* already aborted */ }\n // A failed direction IS settled: without this the shared terminal would wait\n // forever for a half that can never complete again.\n if (half === 'read') duplex.readSettled = true;\n if (half === 'write') duplex.writeSettled = true;\n if (duplex.failure === null) duplex.failure = new ChannelError(code, `peer channel duplex ${code}`);\n this.#duplexCheck(duplex);\n }\n\n #duplexCheck(duplex: DuplexOutbound): void {\n if (duplex.settled) return;\n if (duplex.failure !== null) {\n // A failure in either direction drains the whole session: force the other\n // half to settle before the shared terminal rejects.\n if (!duplex.readSettled) this.#failStream(duplex.read, 'failed');\n if (!duplex.writeSettled) this.#failWrite(duplex.write, 'failed');\n if (duplex.settled) return;\n }\n if (!duplex.readSettled || !duplex.writeSettled) return;\n duplex.settled = true;\n this.#releaseDuplex(duplex);\n if (duplex.failure !== null) duplex.completion.reject(duplex.failure);\n else duplex.completion.resolve(Object.freeze({ read: duplex.readValue, write: duplex.writeValue }));\n }\n\n #releaseDuplex(duplex: DuplexOutbound): void {\n try { duplex.controller.abort('settled'); } catch { /* already aborted */ }\n try { duplex.read.controller.abort('settled'); } catch { /* already aborted */ }\n try { duplex.write.controller.abort('settled'); } catch { /* already aborted */ }\n duplex.release?.();\n }\n\n #writeChunk(state: WriteOutbound, chunk: Uint8Array): Promise<void> {\n if (state.failure !== null) return Promise.reject(state.failure);\n if (state.finishing) return Promise.reject(new ChannelError('conflict', 'write direction is finishing'));\n if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0 || chunk.byteLength > CHANNEL_MAX_CHUNK_BYTES) {\n return Promise.reject(new ChannelError('invalid', 'peer channel write chunk is invalid'));\n }\n if (state.queuedWriteBytes + chunk.byteLength > CHANNEL_MAX_TRANSFER_BUFFER_BYTES) {\n return Promise.reject(new ChannelError('overloaded', 'peer channel pending writes exceed the buffer budget'));\n }\n const bytes = new Uint8Array(chunk);\n state.queuedWriteBytes += bytes.byteLength;\n const task = state.writeTail.then(() => this.#sendWriteChunk(state, bytes))\n .finally(() => { state.queuedWriteBytes -= bytes.byteLength; });\n state.writeTail = task;\n void task.catch(() => undefined);\n return task;\n }\n\n async #sendWriteChunk(state: WriteOutbound, chunk: Uint8Array): Promise<void> {\n if (state.failure !== null) throw state.failure;\n if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0) throw new ChannelError('invalid', 'peer channel write chunk is empty');\n if (chunk.byteLength > CHANNEL_MAX_CHUNK_BYTES) throw new ChannelError('invalid', 'peer channel write chunk exceeds the frame budget');\n const bytes = new Uint8Array(chunk);\n const offset = state.bytes;\n const payload = encodeChannelEmit({ kind: 'stream.data', transferId: state.transferId, offset, last: false });\n for (let attempt = 0; attempt < CHANNEL_STREAM_EMIT_RETRIES; attempt++) {\n if (state.failure !== null) throw state.failure;\n if (state.window - state.bytes >= bytes.byteLength) {\n if (state.link.emitLane('stream', 'chunk', state.transferId, state.deadlineAt, payload, bytes)) {\n state.hash.update(bytes);\n state.bytes += bytes.byteLength;\n this.#armWriteIdle(state);\n return;\n }\n // Credit and socket capacity are independent. A refused frame was not\n // queued, so yield to transport drain before retrying that same chunk.\n // Waiting for already-available credit would exhaust retries in microtasks.\n await delay(2);\n continue;\n }\n await this.#awaitWriteCredit(state, bytes.byteLength);\n }\n this.#abortWrite(state, 'overloaded');\n throw new ChannelError('overloaded', 'peer channel write was not accepted by the transport');\n }\n\n async #finishWrite(state: WriteOutbound, target: PluginChannelTarget, caller: string, callerScope: string, contract: string): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}` }> {\n if (state.failure !== null) throw state.failure;\n state.finishing = true;\n await state.writeTail;\n if (state.failure !== null) throw state.failure;\n const digest = `sha256:${state.hash.digest('hex')}` as `sha256:${string}`;\n const call = state.link.requestOnLane(\n 'stream',\n encodeStreamFinishRequest(target, caller, callerScope, contract, { transferId: state.transferId, size: state.bytes, digest }, state.purpose),\n EMPTY,\n { deadlineAt: state.deadlineAt, signal: state.controller.signal },\n );\n void call.terminal.catch(() => undefined);\n try {\n const body = await call.result;\n const result = decodeResultOrError(body);\n if (!result.ok) throw new ChannelError(result.code, `peer channel write finish failed: ${result.code}`);\n } catch (error) {\n // A definitive provider error body is that error; a LOST finish response is\n // `unknown` — the provider may already have committed, so a blind retry is\n // never implied. The finish request WAS dispatched before this point.\n const code = error instanceof ChannelError ? error.code : 'unknown';\n this.#failWrite(state, code);\n throw state.failure ?? error;\n }\n this.#settleWrite(state, state.bytes, digest);\n return Object.freeze({ bytes: state.bytes, digest });\n }\n\n /** Waits until the whole chunk fits the granted window (never a partial spin). */\n async #awaitWriteCredit(state: WriteOutbound, needed: number): Promise<void> {\n while (state.window - state.bytes < needed && state.failure === null) {\n await new Promise<void>((resolve) => { state.creditWaiters.push(resolve); });\n }\n }\n\n #wakeWrite(state: WriteOutbound): void {\n for (const resolve of state.creditWaiters.splice(0)) resolve();\n }\n\n #armWriteIdle(state: WriteOutbound): void {\n if (state.idleTimer !== null) clearTimeout(state.idleTimer);\n const timer = setTimeout(() => { this.#failWrite(state, 'truncated'); }, state.idleMs);\n timer.unref?.();\n state.idleTimer = timer;\n }\n\n #failWrite(state: WriteOutbound, code: PluginChannelErrorCode): void {\n if (state.failure !== null || isSettled(state.completion)) return;\n state.failure = new ChannelError(code, `peer channel write ${code}`);\n this.#clearWriteTimers(state);\n this.#writeOutbound.delete(state.transferId);\n try { state.controller.abort('failed'); } catch { /* already aborted */ }\n state.release?.();\n state.completion.reject(state.failure);\n this.#wakeWrite(state);\n if (state.duplex !== undefined) this.#duplexFail(state.duplex, code, 'write');\n }\n\n #abortWrite(state: WriteOutbound, code: PluginChannelErrorCode): void {\n this.#failWrite(state, code);\n }\n\n #settleWrite(state: WriteOutbound, bytes: number, digest: `sha256:${string}`): void {\n if (state.failure !== null || isSettled(state.completion)) return;\n this.#clearWriteTimers(state);\n this.#writeOutbound.delete(state.transferId);\n state.release?.();\n state.completion.resolve(Object.freeze({ bytes, digest }));\n this.#wakeWrite(state);\n if (state.duplex !== undefined) this.#duplexSettle(state.duplex, 'write', { bytes, digest });\n }\n\n #clearWriteTimers(state: WriteOutbound): void {\n if (state.idleTimer !== null) { clearTimeout(state.idleTimer); state.idleTimer = null; }\n }\n\n async * #iterateStream(state: StreamOutbound): AsyncGenerator<Uint8Array, void, void> {\n try {\n for (;;) {\n if (state.failure !== null) throw state.failure;\n if (state.chunks.length > 0) {\n const chunk = state.chunks.shift()!;\n state.queuedBytes -= chunk.byteLength;\n this.#bufferedBytes -= chunk.byteLength;\n yield chunk;\n // Real credit: every consumed byte is granted back to the producer.\n this.#grantCredit(state, chunk.byteLength);\n continue;\n }\n if (state.halfClosed || state.completed) return;\n if (state.lastSeen) { this.#verifyAndSettle(state); return; }\n await new Promise<void>((resolve) => { state.waiters.push(resolve); });\n }\n } finally {\n // An early `return`/`throw` from the caller must release the transfer, never\n // leave a live producer pumping into a discarded buffer. If every byte was\n // already received, verify it instead of discarding a complete body.\n if (!state.completed && state.failure === null) {\n if (state.lastSeen && state.chunks.length === 0) this.#verifyAndSettle(state);\n else this.#cancelStream(state);\n }\n }\n }\n\n async #collectStream(state: StreamOutbound): Promise<{ readonly bytes: number; readonly digest: `sha256:${string}`; readonly body: Uint8Array }> {\n const chunks: Uint8Array[] = [];\n for await (const chunk of this.#iterateStream(state)) chunks.push(chunk);\n const done = await state.completion.promise;\n return Object.freeze({ bytes: done.bytes, digest: done.digest, body: concat(chunks) });\n }\n\n #grantCredit(state: StreamOutbound, bytes: number): void {\n if (bytes <= 0 || state.lastSeen || state.failure !== null) return;\n state.consumedBytes += bytes;\n state.slack = Math.min(state.slack + bytes, CHANNEL_STREAM_MAX_CREDIT_BYTES);\n this.#announceStreamWindow(state);\n }\n\n /**\n * Absolute window = resume offset + consumed + still-granted allowance; never\n * a delta. Including the base offset is what makes a resumed read\n * (`offset > 0`, possibly beyond the initial credit) actually progress.\n */\n #announceStreamWindow(state: StreamOutbound): void {\n if (state.failure !== null) return;\n const window = state.baseOffset + state.consumedBytes + state.slack;\n const payload = encodeChannelEmit({ kind: 'stream.credit', transferId: state.transferId, direction: 'read', window });\n void this.#emitLaneWithRetry(state.link, state.transferId, state.deadlineAt, payload)\n .then((delivered) => { if (!delivered && state.failure === null) this.#failStream(state, 'overloaded'); });\n }\n\n /** Repeats the window so a refused frame heals instead of starving the producer. */\n #armStreamHeartbeat(state: StreamOutbound): void {\n if (state.heartbeat !== null) clearInterval(state.heartbeat);\n const timer = setInterval(() => { this.#announceStreamWindow(state); }, CHANNEL_CREDIT_HEARTBEAT_MS);\n timer.unref?.();\n state.heartbeat = timer;\n }\n\n /** Describes the peer's snapshot without transferring the body (reconciliation). */\n async describeSnapshot(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n options: { readonly version?: number | null; readonly deadlineAt?: number; readonly signal?: AbortSignal; readonly purpose?: RpcCallPurpose } = {},\n ): Promise<ChannelSnapshotDescriptor> {\n const { link } = this.#route(target, 'snapshot');\n this.#assertLinkAdmitsNewWork(link);\n const deadlineAt = options.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n const described = await this.#requestResult('snapshot', link, encodeSnapshotDescribeRequest(target, caller, callerScope, contract, { version: options.version ?? null }, options.purpose), deadlineAt, options.signal);\n if (!described.ok) throw new ChannelError(described.code, `snapshot describe failed: ${described.code}`);\n const descriptor = decodeSnapshotDescriptor(described);\n if (descriptor === null) throw new ChannelError('invalid', 'snapshot descriptor is invalid');\n if (descriptor.size > CHANNEL_SNAPSHOT_MAX_BYTES) throw new ChannelError('overloaded', 'snapshot exceeds the bounded receive budget');\n return descriptor;\n }\n\n async readSnapshot(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n options: { readonly version?: number | null; readonly deadlineAt?: number; readonly signal?: AbortSignal; readonly purpose?: RpcCallPurpose } = {},\n ): Promise<PluginChannelSnapshotRead> {\n const { link } = this.#route(target, 'snapshot');\n this.#assertLinkAdmitsNewWork(link);\n const deadlineAt = options.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n // Pin the WHOLE version first: the provider retains the exact source (and its\n // descriptor owner/epoch/version/schema/digest/size) until our release.\n const opened = await this.#requestResult('snapshot', link, encodeSnapshotOpenRequest(target, caller, callerScope, contract, { version: options.version ?? null }, options.purpose), deadlineAt, options.signal);\n if (!opened.ok) throw new ChannelError(opened.code, `snapshot open failed: ${opened.code}`);\n const session = decodeSnapshotOpenResult(opened);\n if (session === null) throw new ChannelError('invalid', 'snapshot session is invalid');\n const descriptor = session.descriptor;\n if (descriptor.size > CHANNEL_SNAPSHOT_MAX_BYTES) {\n await this.#releaseSnapshot(link, target, caller, callerScope, contract, session.sessionId, deadlineAt, options.signal, options.purpose);\n throw new ChannelError('overloaded', 'snapshot exceeds the bounded receive budget');\n }\n\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(descriptor.size);\n const chunkBytes = Math.min(descriptor.chunkBytes, CHANNEL_SNAPSHOT_CHUNK_BYTES);\n const total = Math.ceil(descriptor.size / chunkBytes);\n let next = 0;\n const workers = Array.from({ length: Math.min(CHANNEL_SNAPSHOT_CHUNK_CONCURRENCY, total) }, async () => {\n for (;;) {\n const index = next++;\n if (index >= total) return;\n const offset = index * chunkBytes;\n const length = Math.min(chunkBytes, descriptor.size - offset);\n const body = await this.#requestBytes(link, encodeSnapshotChunkRequest(target, caller, callerScope, contract, {\n sessionId: session.sessionId, offset, length,\n }, options.purpose), deadlineAt, options.signal);\n if (body.byteLength !== length) throw new ChannelError('truncated', 'snapshot chunk length mismatch');\n bytes.set(body, offset);\n }\n });\n // Wait for EVERY in-flight chunk read to settle before the pinned session is\n // released in `finally`: a fast rejection from one worker must never release\n // the provider retention/lease under another worker that is still reading.\n const results = await Promise.allSettled(workers);\n const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (failed !== undefined) throw failed.reason;\n if (safeSha256(bytes) !== descriptor.digest) throw new ChannelError('failed', 'snapshot digest mismatch');\n } finally {\n // The pinned session is released exactly once, on success or failure, so a\n // failed read can never keep an old version retained.\n await this.#releaseSnapshot(link, target, caller, callerScope, contract, session.sessionId, deadlineAt, options.signal, options.purpose);\n }\n return Object.freeze({ descriptor, bytes });\n }\n\n async #releaseSnapshot(link: PluginChannelLinkPort, target: PluginChannelTarget, caller: string, callerScope: string, contract: string, sessionId: string, deadlineAt: number, signal: AbortSignal | undefined, purpose: RpcCallPurpose | undefined): Promise<void> {\n try {\n await this.#requestResult('snapshot', link, encodeSnapshotReleaseRequest(target, caller, callerScope, contract, { sessionId }, purpose), deadlineAt, signal);\n } catch {\n // Best-effort: an unreleased session is bounded by the provider's idle expiry.\n }\n }\n\n async subscribeEvents(\n target: PluginChannelTarget,\n caller: string,\n callerScope: string,\n contract: string,\n request: {\n readonly delivery: 'transient' | 'reliable';\n readonly consumerId: string;\n readonly from?: number | null;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n readonly purpose?: RpcCallPurpose;\n readonly release?: () => void;\n readonly onEvent: (event: PluginChannelEventDelivery) => void;\n },\n ): Promise<PluginChannelEventSubscription> {\n const { link } = this.#route(target, 'event');\n this.#assertLinkAdmitsNewWork(link);\n if (this.#eventOutbound.size >= CHANNEL_MAX_SUBSCRIPTIONS) throw new ChannelError('overloaded', 'peer channel subscription capacity is exhausted');\n const deadlineAt = request.deadlineAt ?? Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS;\n const subscriptionId = randomUUID();\n const controller = new AbortController();\n const removeOuterAbort = linkExternalSignal(request.signal, controller);\n const drainingLease = terminalGatedRelease(request.release);\n const state: EventOutbound = {\n link, subscriptionId, deadlineAt, delivery: request.delivery, handler: request.onEvent, purpose: request.purpose ?? 'background',\n queue: [], dropped: 0, scheduled: false, ready: false, closed: false, delivered: 0,\n terminal: createDeferred<'closed' | 'failed'>(), controller, release: drainingLease.release,\n };\n this.#eventOutbound.set(subscriptionId, state);\n const call = link.requestOnLane('event', encodeEventSubscribeRequest(target, caller, callerScope, contract, {\n clientId: subscriptionId, delivery: request.delivery, consumerId: request.consumerId, from: request.from ?? null,\n }, request.purpose), EMPTY, { deadlineAt, signal: controller.signal });\n drainingLease.observe(call.terminal);\n // A provider-side end of the subscription must release the local slot too.\n void call.terminal.then(\n () => { removeOuterAbort(); this.#closeOutboundSubscription(state); },\n () => { removeOuterAbort(); this.#closeOutboundSubscription(state); },\n );\n let result: PluginChannelResult;\n try {\n result = decodeResultOrError(await call.result);\n } catch (error) {\n this.#closeOutboundSubscription(state);\n throw new ChannelError(errorCodeOf(error), 'event subscribe failed');\n }\n if (!result.ok) {\n this.#closeOutboundSubscription(state);\n const error = new ChannelError(result.code, `event subscribe failed: ${result.code}`) as ChannelError & { detail?: Record<string, unknown> };\n error.detail = result.detail ?? {};\n throw error;\n }\n const subscribed = decodeEventSubscribeResult(result);\n if (subscribed === null || subscribed.subscriptionId !== subscriptionId) {\n this.#closeOutboundSubscription(state);\n throw new ChannelError('invalid', 'event subscribe result is invalid');\n }\n // The contiguous callback-delivery ceiling starts at the first sequence the\n // provider will replay.\n state.delivered = subscribed.fromSequence - 1;\n state.ready = true;\n if (!state.closed && state.queue.length > 0 && !state.scheduled) {\n state.scheduled = true;\n queueMicrotask(() => this.#drainOutboundEvents(state));\n }\n return Object.freeze({\n subscriptionId,\n delivery: subscribed.delivery,\n fromSequence: subscribed.fromSequence,\n oldestSequence: subscribed.oldestSequence,\n prunedThrough: subscribed.prunedThrough,\n dropped: () => state.dropped,\n terminal: state.terminal.promise,\n ack: async (sequence: number): Promise<number> => {\n if (state.closed) throw new ChannelError('closed', 'event subscription is closed');\n if (subscribed.delivery !== 'reliable') throw new ChannelError('invalid', 'a transient subscription has no durable ack');\n if (!Number.isSafeInteger(sequence) || sequence < 1) throw new ChannelError('invalid', 'event ack sequence is invalid');\n // The durable checkpoint advances only over a CONTIGUOUS callback run: an\n // ACK past a real gap would silently skip an undelivered reliable event.\n if (sequence > state.delivered) throw new ChannelError('rejected', 'event ack exceeds contiguous callback delivery');\n const ackResult = await this.#requestResult(\n 'event', link,\n encodeEventAckRequest(target, caller, callerScope, contract, { subscriptionId, sequence }, state.purpose),\n Date.now() + CHANNEL_STREAM_DEFAULT_DEADLINE_MS,\n state.controller.signal,\n );\n if (!ackResult.ok) throw new ChannelError(ackResult.code, `event ack failed: ${ackResult.code}`);\n const acked = decodeEventAckResult(ackResult);\n if (acked === null) throw new ChannelError('invalid', 'event ack result is invalid');\n return acked.acked;\n },\n close: () => {\n this.#closeOutboundSubscription(state);\n removeOuterAbort();\n try { state.controller.abort('closed'); } catch { /* already aborted */ }\n },\n });\n }\n\n #closeOutboundSubscription(state: EventOutbound): void {\n if (state.closed) return;\n state.closed = true;\n this.#eventOutbound.delete(state.subscriptionId);\n state.queue.length = 0;\n state.release?.();\n state.terminal.resolve('closed');\n }\n\n /** A real reliable gap/failure: observable to the consumer, never a silent close. */\n #failOutboundSubscription(state: EventOutbound, code: PluginChannelErrorCode): void {\n if (state.closed) return;\n state.closed = true;\n this.#eventOutbound.delete(state.subscriptionId);\n state.queue.length = 0;\n state.release?.();\n try { state.controller.abort(code); } catch { /* already aborted */ }\n state.terminal.resolve('failed');\n }\n\n /** Request helpers ---------------------------------------------------- */\n\n #requestResult(\n lane: PluginChannelLane,\n link: PluginChannelLinkPort,\n context: RpcJson,\n deadlineAt: number,\n signal: AbortSignal | undefined,\n ): Promise<PluginChannelResult> {\n const call = link.requestOnLane(lane, context, EMPTY, { deadlineAt, ...(signal === undefined ? {} : { signal }) });\n void call.terminal.catch(() => undefined);\n return call.result.then(\n (bytes) => decodeResultOrError(bytes),\n () => Object.freeze({ ok: false as const, code: 'failed' as const }),\n );\n }\n\n async #requestBytes(\n link: PluginChannelLinkPort,\n context: RpcJson,\n deadlineAt: number,\n signal: AbortSignal | undefined,\n ): Promise<Uint8Array> {\n const call = link.requestOnLane('snapshot', context, EMPTY, { deadlineAt, ...(signal === undefined ? {} : { signal }) });\n void call.terminal.catch(() => undefined);\n return call.result;\n }\n\n /* ------------------------------------------------------------------ */\n /* Inbound dispatch */\n /* ------------------------------------------------------------------ */\n\n #onRequest(\n link: PluginChannelLinkPort,\n payload: unknown,\n deadlineAt: number,\n signal: AbortSignal,\n ): PluginPeerRpcRequestExecution | null {\n if (this.#disposed) return null;\n const kind = (payload as { kind?: unknown } | null)?.kind;\n switch (kind) {\n case 'stream.open': return this.#onStreamOpen(link, payload, deadlineAt, signal);\n case 'stream.open-write': return this.#onStreamOpenWrite(link, payload, deadlineAt, signal);\n case 'stream.open-duplex': return this.#onStreamOpenDuplex(link, payload, deadlineAt, signal);\n case 'stream.finish': return this.#onStreamFinish(link, payload);\n case 'snapshot.describe': return this.#onSnapshotDescribe(link, payload);\n case 'snapshot.open': return this.#onSnapshotOpen(link, payload, deadlineAt, signal);\n case 'snapshot.chunk': return this.#onSnapshotChunk(link, payload);\n case 'snapshot.release': return this.#onSnapshotRelease(link, payload);\n case 'event.subscribe': return this.#onEventSubscribe(link, payload, deadlineAt, signal);\n case 'event.ack': return this.#onEventAck(link, payload);\n default: return null;\n }\n }\n\n #authorized(link: PluginChannelLinkPort, lane: PluginChannelLane, target: PluginChannelTarget, caller: string, callerScope: string, process: PluginServiceProcess, continuation = false): boolean {\n // A same-process route carries no peer frame, but it is still authorized by\n // the host with the same trusted declaration check (`local: true`); the host\n // adapter's own consumption check is a second, not a substitute, gate.\n const local = link === this.#loopback;\n try {\n return this.#options.authorizeInbound({\n lane, target, caller, callerScope, providerProcess: process, local, link: local ? null : link, continuation,\n });\n } catch { return false; }\n }\n\n #registrationFor(lane: PluginChannelLane, target: PluginChannelTarget): Registration | null {\n const registration = this.#registrations.get(callTargetKey(lane, target));\n if (registration === undefined || !registration.ready || registration.retiring) return null;\n return registration;\n }\n\n /**\n * A retiring provider admits no NEW work, but an ALREADY-ACCEPTED transfer's\n * finish/ack must still complete on the original registration. This lookup\n * therefore ignores `retiring` (a disposed registration is removed from the\n * map entirely, so revoked providers are still refused).\n */\n #registrationIncludingRetiring(lane: PluginChannelLane, target: PluginChannelTarget): Registration | null {\n const registration = this.#registrations.get(callTargetKey(lane, target));\n if (registration === undefined || !registration.ready) return null;\n return registration;\n }\n\n #rejected(lane: PluginChannelLane, code: PluginChannelErrorCode | 'invalid'): void {\n try { this.#options.onDiagnostic?.({ kind: 'rejected', lane, code }); } catch { /* diagnostics never affect admission */ }\n }\n\n #immediate(body: Uint8Array): PluginPeerRpcRequestExecution {\n return Object.freeze({ result: Promise.resolve(body), terminal: Promise.resolve() });\n }\n\n /** Takes the provider owner's Host lease; `null` when the host refuses. */\n #beginProvider(plugin: string, context: { readonly purpose: RpcCallPurpose; readonly deadlineAt?: number; readonly signal?: AbortSignal }): (() => void) | null {\n if (this.#options.beginProviderOperation === undefined) return () => undefined;\n try { return this.#options.beginProviderOperation(plugin, context); } catch { return null; }\n }\n\n #onStreamOpen(link: PluginChannelLinkPort, payload: unknown, deadlineAt: number, signal: AbortSignal): PluginPeerRpcRequestExecution | null {\n const request = decodeStreamOpenRequest(payload);\n if (request === null || request.kind !== 'stream.open') { this.#rejected('stream', 'invalid'); return null; }\n const registration = this.#registrationFor('stream', request.target);\n if (registration === null || registration.stream?.open === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'stream', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('stream', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n let source: PluginChannelStreamSource | null;\n try { source = registration.stream.open({ caller: request.caller, callerScope: request.callerScope, objectId: request.request.objectId, version: request.request.version }); }\n catch { return this.#immediate(errorBody('failed')); }\n if (source === null) return this.#immediate(errorBody('unavailable'));\n const { offset, size, digest, creditBytes, idleMs, clientId } = request.request;\n if (size !== null && source.size !== size) return this.#immediate(errorBody('conflict'));\n if (digest !== null && source.digest !== digest) return this.#immediate(errorBody('conflict'));\n if (offset > source.size) return this.#immediate(errorBody('invalid'));\n if (source.size > CHANNEL_STREAM_MAX_TOTAL_BYTES) return this.#immediate(errorBody('overloaded'));\n if (this.#streamInbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) return this.#immediate(errorBody('overloaded'));\n if (clientId.length > 128 || this.#streamInbound.has(clientId)) return this.#immediate(errorBody('conflict'));\n const release = this.#beginProvider(registration.provider, { purpose: request.purpose, deadlineAt, signal });\n if (release === null) return this.#immediate(errorBody('overloaded'));\n\n const transfer: StreamInbound = {\n link, providerKey: registration.key, transferId: clientId,\n caller: request.caller, callerScope: request.callerScope, deadlineAt,\n frameBytes: Math.min(creditBytes, CHANNEL_MAX_CHUNK_BYTES),\n idleMs, release, window: creditBytes, creditWaiters: [], idleTimer: null, aborted: false, finished: false,\n };\n this.#streamInbound.set(transfer.transferId, transfer);\n this.#armInboundIdle(transfer);\n\n const onAbort = () => { this.#abortInboundStream(transfer); };\n try { signal.addEventListener('abort', onAbort, { once: true }); } catch { /* signal already aborted */ }\n if (signal.aborted) this.#abortInboundStream(transfer);\n\n const result = streamOpenResultBody({\n transferId: transfer.transferId, size: source.size, digest: source.digest,\n frameBytes: transfer.frameBytes, creditBytes,\n });\n const terminal = this.#pumpStream(transfer, source, offset);\n void terminal.catch(() => undefined);\n return Object.freeze({\n result: Promise.resolve(result),\n terminal: terminal.finally(() => {\n try { signal.removeEventListener('abort', onAbort); } catch { /* already removed */ }\n }),\n });\n }\n\n #onStreamOpenWrite(link: PluginChannelLinkPort, payload: unknown, deadlineAt: number, signal: AbortSignal): PluginPeerRpcRequestExecution | null {\n const request = decodeStreamOpenRequest(payload);\n if (request === null || request.kind !== 'stream.open-write') { this.#rejected('stream', 'invalid'); return null; }\n const registration = this.#registrationFor('stream', request.target);\n if (registration === null || registration.stream?.accept === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'stream', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('stream', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n let sink: PluginChannelStreamSink | null;\n try { sink = registration.stream.accept({ caller: request.caller, callerScope: request.callerScope, objectId: request.request.objectId, version: request.request.version }); }\n catch { return this.#immediate(errorBody('failed')); }\n if (sink === null) return this.#immediate(errorBody('unavailable'));\n const { size, digest, creditBytes, idleMs, clientId } = request.request;\n if (size !== null && size > CHANNEL_STREAM_MAX_TOTAL_BYTES) return this.#immediate(errorBody('overloaded'));\n if (this.#writeInbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) return this.#immediate(errorBody('overloaded'));\n if (clientId.length > 128 || this.#writeInbound.has(clientId)) return this.#immediate(errorBody('conflict'));\n const release = this.#beginProvider(registration.provider, { purpose: request.purpose, deadlineAt, signal });\n if (release === null) return this.#immediate(errorBody('overloaded'));\n\n const transfer: WriteInbound = {\n link, providerKey: registration.key, transferId: clientId,\n caller: request.caller, callerScope: request.callerScope, deadlineAt, idleMs, release,\n expectedSize: size, expectedDigest: digest, hash: createHash('sha256'),\n sink, finishedWait: createDeferred<void>(), writeTail: Promise.resolve(),\n offset: 0, slack: creditBytes, window: creditBytes,\n heartbeat: null, idleTimer: null, finished: false, aborting: false, finishing: false,\n };\n this.#writeInbound.set(transfer.transferId, transfer);\n this.#armWriteInboundIdle(transfer);\n this.#armWriteHeartbeat(transfer);\n const onAbort = () => { this.#abortInboundWrite(transfer, 'cancelled'); };\n try { signal.addEventListener('abort', onAbort, { once: true }); } catch { /* already aborted */ }\n if (signal.aborted) this.#abortInboundWrite(transfer, 'cancelled');\n\n const result = streamOpenResultBody({\n transferId: transfer.transferId, size, digest, frameBytes: CHANNEL_MAX_CHUNK_BYTES, creditBytes,\n });\n const terminal = this.#awaitWriteFinish(transfer, signal, onAbort);\n void terminal.catch(() => undefined);\n return Object.freeze({ result: Promise.resolve(result), terminal });\n }\n\n /**\n * Admits ONE duplex session: a single client id, one provider lease and one\n * shared terminal for both directions. A failure/cancel in either direction\n * aborts the sibling, so the session drains as a whole.\n */\n #onStreamOpenDuplex(link: PluginChannelLinkPort, payload: unknown, deadlineAt: number, signal: AbortSignal): PluginPeerRpcRequestExecution | null {\n const request = decodeStreamOpenDuplexRequest(payload);\n if (request === null) { this.#rejected('stream', 'invalid'); return null; }\n const registration = this.#registrationFor('stream', request.target);\n if (registration === null || registration.stream?.duplex === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'stream', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('stream', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n let impl: { readonly source?: PluginChannelStreamSource; readonly sink?: PluginChannelStreamSink } | null;\n try { impl = registration.stream.duplex({ caller: request.caller, callerScope: request.callerScope, objectId: request.request.objectId, version: request.request.version }); }\n catch { return this.#immediate(errorBody('failed')); }\n if (impl === null) return this.#immediate(errorBody('unavailable'));\n if (impl.source === undefined && impl.sink === undefined) return this.#immediate(errorBody('invalid'));\n const { readOffset, readSize, readDigest, writeSize, writeDigest, readCreditBytes, writeCreditBytes, idleMs, clientId } = request.request;\n if (impl.source !== undefined) {\n if (readSize !== null && impl.source.size !== readSize) return this.#immediate(errorBody('conflict'));\n if (readDigest !== null && impl.source.digest !== readDigest) return this.#immediate(errorBody('conflict'));\n if (readOffset > impl.source.size) return this.#immediate(errorBody('invalid'));\n if (impl.source.size > CHANNEL_STREAM_MAX_TOTAL_BYTES) return this.#immediate(errorBody('overloaded'));\n } else if (readSize !== null || readDigest !== null || readOffset !== 0) {\n // Requesting a read side the provider does not offer is a contract mismatch.\n return this.#immediate(errorBody('unavailable'));\n }\n if (writeSize !== null && writeSize > CHANNEL_STREAM_MAX_TOTAL_BYTES) return this.#immediate(errorBody('overloaded'));\n if (this.#streamInbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS || this.#writeInbound.size >= CHANNEL_MAX_ACTIVE_TRANSFERS) return this.#immediate(errorBody('overloaded'));\n if (clientId.length > 128 || this.#streamInbound.has(clientId) || this.#writeInbound.has(clientId)) return this.#immediate(errorBody('conflict'));\n const release = this.#beginProvider(registration.provider, { purpose: request.purpose, deadlineAt, signal });\n if (release === null) return this.#immediate(errorBody('overloaded'));\n\n let halves = (impl.source === undefined ? 0 : 1) + (impl.sink === undefined ? 0 : 1);\n const sessionDone = createDeferred<void>();\n const sharedRelease = (): void => {\n halves -= 1;\n if (halves > 0) return;\n try { release(); } finally { sessionDone.resolve(undefined); }\n };\n\n let readHalf: StreamInbound | null = null;\n let writeHalf: WriteInbound | null = null;\n\n if (impl.source !== undefined) {\n readHalf = {\n link, providerKey: registration.key, transferId: clientId,\n caller: request.caller, callerScope: request.callerScope, deadlineAt,\n frameBytes: Math.min(readCreditBytes, CHANNEL_MAX_CHUNK_BYTES),\n idleMs, release: sharedRelease, window: readCreditBytes, creditWaiters: [], idleTimer: null, aborted: false, finished: false,\n abortSibling: (reason) => { if (writeHalf !== null) this.#abortInboundWrite(writeHalf, reason); },\n };\n this.#streamInbound.set(clientId, readHalf);\n this.#armInboundIdle(readHalf);\n }\n if (impl.sink !== undefined) {\n writeHalf = {\n link, providerKey: registration.key, transferId: clientId,\n caller: request.caller, callerScope: request.callerScope, deadlineAt, idleMs, release: sharedRelease,\n expectedSize: writeSize, expectedDigest: writeDigest, hash: createHash('sha256'),\n sink: impl.sink, finishedWait: createDeferred<void>(), writeTail: Promise.resolve(),\n offset: 0, slack: writeCreditBytes, window: writeCreditBytes,\n heartbeat: null, idleTimer: null, finished: false, aborting: false, finishing: false,\n abortSibling: (reason) => { if (readHalf !== null) this.#abortInboundStreamWith(readHalf, reason); },\n };\n this.#writeInbound.set(clientId, writeHalf);\n this.#armWriteInboundIdle(writeHalf);\n this.#armWriteHeartbeat(writeHalf);\n }\n\n const onAbort = (): void => {\n if (readHalf !== null) this.#abortInboundStream(readHalf);\n if (writeHalf !== null) this.#abortInboundWrite(writeHalf, 'cancelled');\n };\n try { signal.addEventListener('abort', onAbort, { once: true }); } catch { /* signal already aborted */ }\n if (signal.aborted) onAbort();\n\n const result = streamOpenDuplexResultBody({\n transferId: clientId,\n readSize: impl.source?.size ?? null,\n readDigest: impl.source?.digest ?? null,\n readFrameBytes: readHalf?.frameBytes ?? CHANNEL_MAX_CHUNK_BYTES,\n readCreditBytes,\n writeCreditBytes,\n });\n if (readHalf !== null && impl.source !== undefined) {\n const pump = this.#pumpStream(readHalf, impl.source, readOffset);\n void pump.catch(() => undefined);\n }\n const terminal = sessionDone.promise.finally(() => {\n try { signal.removeEventListener('abort', onAbort); } catch { /* already removed */ }\n });\n void terminal.catch(() => undefined);\n return Object.freeze({ result: Promise.resolve(result), terminal });\n }\n\n /** Consumer half-closed the read direction of a duplex session. */\n #onStreamEndRead(link: PluginChannelLinkPort, payload: { readonly transferId: string }): void {\n const transfer = this.#streamInbound.get(payload.transferId);\n if (transfer === undefined || transfer.link !== link) return;\n this.#abortInboundStreamWith(transfer, 'cancelled');\n }\n\n /**\n * Provider finished the read direction (ordered after its final data frame, so\n * the receiver can settle honestly without a timer guess).\n */\n #onStreamEnd(link: PluginChannelLinkPort, payload: { readonly transferId: string }): void {\n const state = this.#streamOutbound.get(payload.transferId);\n if (state === undefined || state.link !== link) return;\n if (state.failure !== null || state.completed) return;\n state.lastSeen = true;\n for (const resolve of state.waiters.splice(0)) resolve();\n }\n\n /** Emits the ordered read-direction end frame; resolves after transport accept. */\n async #emitStreamEnd(transfer: StreamInbound): Promise<void> {\n const payload = encodeChannelEmit({ kind: 'stream.end', transferId: transfer.transferId });\n await this.#emitLaneWithRetry(transfer.link, transfer.transferId, transfer.deadlineAt, payload);\n }\n\n async #awaitWriteFinish(transfer: WriteInbound, signal: AbortSignal, onAbort: () => void): Promise<void> {\n try {\n await transfer.finishedWait.promise;\n } finally {\n try { signal.removeEventListener('abort', onAbort); } catch { /* already removed */ }\n }\n }\n\n #onStreamFinish(link: PluginChannelLinkPort, payload: unknown): PluginPeerRpcRequestExecution | null {\n const request = decodeStreamFinishRequest(payload);\n if (request === null) { this.#rejected('stream', 'invalid'); return null; }\n // An already-accepted write half (standalone OR one side of a duplex session)\n // must still be committable; the transfer lookup below is the real ownership\n // proof, so `accept` is not required here.\n const registration = this.#registrationIncludingRetiring('stream', request.target);\n if (registration === null) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'stream', request.target, request.caller, request.callerScope, registration.process, true)) {\n this.#rejected('stream', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n const transfer = this.#writeInbound.get(request.request.transferId);\n if (transfer === undefined || transfer.link !== link || transfer.providerKey !== registration.key) return this.#immediate(errorBody('expired'));\n if (transfer.caller !== request.caller || transfer.callerScope !== request.callerScope) return this.#immediate(errorBody('unauthorized'));\n if (transfer.finishing) return this.#immediate(errorBody('conflict'));\n if (transfer.expectedSize !== null && transfer.offset !== transfer.expectedSize) return this.#immediate(errorBody('truncated'));\n if (transfer.offset !== request.request.size) return this.#immediate(errorBody('truncated'));\n const actual = `sha256:${transfer.hash.digest('hex')}`;\n if (actual !== request.request.digest) return this.#immediate(errorBody('truncated'));\n if (transfer.expectedDigest !== null && transfer.expectedDigest !== actual) return this.#immediate(errorBody('conflict'));\n transfer.finishing = true;\n const committedOffset = transfer.offset;\n // Commit barrier: the sink's finish runs only after EVERY accepted write has\n // really settled, so the committed body can never be missing a write.\n const finishTask = transfer.writeTail.then(() => {\n if (transfer.aborting) throw new ChannelError('cancelled', 'write was aborted before commit');\n return transfer.sink.finish(committedOffset, actual);\n });\n // Cancellation must also wait for an already executing finish, not only the\n // writes that preceded it. A rejected write remains rejected in this chain.\n transfer.writeTail = finishTask;\n // The REAL terminal resolves only when the provider task truly ends: no timer\n // ever fabricates completion of an unfinished finish.\n const terminal = finishTask.then(\n () => { this.#settleInboundWrite(transfer); },\n () => { this.#abortInboundWrite(transfer, 'failed'); },\n );\n void terminal.catch(() => undefined);\n // Only the CALL result may time out into `unknown` (the provider may already\n // have committed, so a blind retry is never implied); the terminal and the\n // provider lease stay held until the real task settles.\n let timer: ReturnType<typeof setTimeout> | null = null;\n const bounded = new Promise<Uint8Array>((resolve) => {\n timer = setTimeout(() => resolve(errorBody('unknown')), CHANNEL_STREAM_ABORT_DRAIN_MS);\n timer.unref?.();\n });\n const result = Promise.race([\n finishTask.then(() => successBody({ digest: actual, size: committedOffset }), () => errorBody('failed')),\n bounded,\n ]).finally(() => { if (timer !== null) clearTimeout(timer); });\n return Object.freeze({ result, terminal });\n }\n\n #settleInboundWrite(transfer: WriteInbound): void {\n if (transfer.finished) return;\n transfer.finished = true;\n this.#clearWriteInboundTimer(transfer);\n this.#writeInbound.delete(transfer.transferId);\n transfer.release?.();\n transfer.finishedWait.resolve(undefined);\n }\n\n #abortInboundWrite(transfer: WriteInbound, reason: 'cancelled' | 'failed' | 'closed'): void {\n if (transfer.finished || transfer.aborting) return;\n transfer.aborting = true;\n transfer.finishing = true;\n this.#clearWriteInboundTimer(transfer);\n try { transfer.sink.abort?.(reason); } catch { /* sink-owned */ }\n // A failed/cancelled write half drains the sibling read half of a duplex.\n transfer.abortSibling?.(reason === 'failed' ? 'failed' : 'cancelled');\n // The provider lease, transfer slot and terminal stay held until the REAL\n // sink task (including any in-flight write) settles. There is deliberately NO\n // timer here: only the real task end (or process exit) confirms the terminal,\n // never a fabricated 30s \"settled\" while the provider is still writing.\n const settle = (): void => {\n if (transfer.finished) return;\n transfer.finished = true;\n this.#writeInbound.delete(transfer.transferId);\n transfer.release?.();\n transfer.finishedWait.resolve(undefined);\n };\n void transfer.writeTail.then(settle, settle);\n }\n\n #clearWriteInboundTimer(transfer: WriteInbound): void {\n if (transfer.idleTimer !== null) { clearTimeout(transfer.idleTimer); transfer.idleTimer = null; }\n if (transfer.heartbeat !== null) { clearInterval(transfer.heartbeat); transfer.heartbeat = null; }\n }\n\n #armWriteInboundIdle(transfer: WriteInbound): void {\n if (transfer.idleTimer !== null) clearTimeout(transfer.idleTimer);\n const timer = setTimeout(() => { this.#abortInboundWrite(transfer, 'failed'); }, transfer.idleMs);\n timer.unref?.();\n transfer.idleTimer = timer;\n }\n\n async #pumpStream(transfer: StreamInbound, source: PluginChannelStreamSource, startOffset: number): Promise<void> {\n let offset = startOffset;\n try {\n while (offset < source.size) {\n if (transfer.aborted) return;\n if (!await this.#awaitCredit(transfer, offset)) return;\n const length = Math.min(transfer.frameBytes, source.size - offset, transfer.window - offset);\n if (length <= 0) continue;\n const bytes = await source.read(offset, length);\n if (transfer.aborted) return;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > length) {\n throw new ChannelError('failed', 'channel stream source returned an invalid chunk');\n }\n const last = offset + bytes.byteLength >= source.size;\n if (!await this.#emitChunk(transfer, offset, bytes, last)) throw new ChannelError('truncated', 'channel stream frame was not accepted by the transport');\n offset += bytes.byteLength;\n }\n // The whole read direction is done: emit the ordered end marker BEFORE the\n // session terminal, so the receiver settles on a real protocol end (also\n // for a zero-byte body) instead of a timing guess.\n await this.#emitStreamEnd(transfer);\n } catch {\n // Fail closed: the link reports a fixed result/terminal failure; this\n // terminal resolution is the honest producer end. A duplex session drains\n // its sibling direction too.\n transfer.abortSibling?.('failed');\n } finally {\n this.#finishInboundStream(transfer);\n }\n }\n\n async #emitChunk(transfer: StreamInbound, offset: number, bytes: Uint8Array, last: boolean): Promise<boolean> {\n const payload = encodeChannelEmit({ kind: 'stream.chunk', transferId: transfer.transferId, offset, last });\n for (let attempt = 0; attempt < CHANNEL_STREAM_EMIT_RETRIES; attempt++) {\n if (transfer.aborted) return false;\n if (transfer.link.emitLane('stream', 'chunk', transfer.transferId, transfer.deadlineAt, payload, bytes)) return true;\n await delay(2);\n }\n return false;\n }\n\n async #awaitCredit(transfer: StreamInbound, offset: number): Promise<boolean> {\n while (transfer.window <= offset) {\n if (transfer.aborted || transfer.finished) return false;\n await new Promise<void>((resolve) => { transfer.creditWaiters.push(resolve); });\n }\n return !transfer.aborted;\n }\n\n #armInboundIdle(transfer: StreamInbound): void {\n if (transfer.idleTimer !== null) clearTimeout(transfer.idleTimer);\n const timer = setTimeout(() => { this.#abortInboundStream(transfer); }, transfer.idleMs);\n timer.unref?.();\n transfer.idleTimer = timer;\n }\n\n #abortInboundStream(transfer: StreamInbound): void {\n if (transfer.finished || transfer.aborted) return;\n transfer.aborted = true;\n this.#wakeCredit(transfer);\n // A failed/cancelled read half drains the sibling write half of a duplex.\n transfer.abortSibling?.('cancelled');\n }\n\n /** Half-close of the read direction: abort ONLY this half, keep the sibling. */\n #abortInboundStreamWith(transfer: StreamInbound, reason: 'cancelled' | 'failed'): void {\n if (transfer.finished || transfer.aborted) return;\n void reason;\n transfer.aborted = true;\n this.#wakeCredit(transfer);\n }\n\n #finishInboundStream(transfer: StreamInbound): void {\n if (transfer.finished) return;\n transfer.finished = true;\n if (transfer.idleTimer !== null) { clearTimeout(transfer.idleTimer); transfer.idleTimer = null; }\n this.#streamInbound.delete(transfer.transferId);\n transfer.release?.();\n this.#wakeCredit(transfer);\n }\n\n #wakeCredit(transfer: StreamInbound): void {\n for (const resolve of transfer.creditWaiters.splice(0)) resolve();\n }\n\n #onSnapshotDescribe(link: PluginChannelLinkPort, payload: unknown): PluginPeerRpcRequestExecution | null {\n const request = decodeSnapshotDescribeRequest(payload);\n if (request === null) { this.#rejected('snapshot', 'invalid'); return null; }\n const registration = this.#registrationFor('snapshot', request.target);\n if (registration === null || registration.snapshot === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'snapshot', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('snapshot', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n let source: PluginChannelSnapshotSource | null;\n try {\n source = request.request.version === null ? registration.snapshot.current() : registration.snapshot.version(request.request.version);\n } catch { return this.#immediate(errorBody('failed')); }\n if (source === null) return this.#immediate(errorBody(request.request.version === null ? 'unavailable' : 'conflict'));\n if (source.descriptor.size > CHANNEL_SNAPSHOT_MAX_BYTES) return this.#immediate(errorBody('overloaded'));\n return this.#immediate(successBody({ ...source.descriptor }));\n }\n\n /**\n * Pins one immutable version for a WHOLE read and returns its exact descriptor.\n * The provider lease and the source's own retention are held until the session\n * is released (or idle-expires), so a concurrent refresh or version eviction can\n * never swap or free the body mid-read.\n */\n #onSnapshotOpen(link: PluginChannelLinkPort, payload: unknown, deadlineAt: number, signal: AbortSignal): PluginPeerRpcRequestExecution | null {\n const request = decodeSnapshotOpenRequest(payload);\n if (request === null) { this.#rejected('snapshot', 'invalid'); return null; }\n const registration = this.#registrationFor('snapshot', request.target);\n if (registration === null || registration.snapshot === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'snapshot', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('snapshot', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n let source: PluginChannelSnapshotSource | null;\n try {\n source = request.request.version === null ? registration.snapshot.current() : registration.snapshot.version(request.request.version);\n } catch { return this.#immediate(errorBody('failed')); }\n if (source === null) return this.#immediate(errorBody(request.request.version === null ? 'unavailable' : 'conflict'));\n if (source.descriptor.size > CHANNEL_SNAPSHOT_MAX_BYTES) return this.#immediate(errorBody('overloaded'));\n if (this.#snapshotSessions.size >= CHANNEL_SNAPSHOT_MAX_SESSIONS) return this.#immediate(errorBody('overloaded'));\n // Retain the exact version BEFORE any byte is read, so a concurrent publish or\n // GC can never free/replace the body under this whole-body read.\n try { source.retain?.(); } catch { return this.#immediate(errorBody('failed')); }\n const release = this.#beginProvider(registration.provider, { purpose: request.purpose, deadlineAt, signal });\n if (release === null) {\n try { source.release?.(); } catch { /* provider-owned */ }\n return this.#immediate(errorBody('overloaded'));\n }\n const sessionId = randomUUID();\n const session: SnapshotSession = {\n link, providerKey: registration.key, sessionId,\n caller: request.caller, callerScope: request.callerScope, deadlineAt,\n source, release, idleTimer: null, closed: false,\n activeReads: 0, released: false, drainWaiters: [],\n };\n this.#snapshotSessions.set(sessionId, session);\n this.#armSnapshotIdle(session);\n const onAbort = () => { void this.#closeSnapshotSession(session); };\n try { signal.addEventListener('abort', onAbort, { once: true }); } catch { /* signal already aborted */ }\n if (signal.aborted) void this.#closeSnapshotSession(session);\n return this.#immediate(snapshotOpenResultBody({ sessionId, descriptor: source.descriptor }));\n }\n\n #armSnapshotIdle(session: SnapshotSession): void {\n if (session.closed) return;\n if (session.idleTimer !== null) clearTimeout(session.idleTimer);\n const timer = setTimeout(() => { void this.#closeSnapshotSession(session); }, CHANNEL_SNAPSHOT_SESSION_IDLE_MS);\n timer.unref?.();\n session.idleTimer = timer;\n }\n\n /**\n * Stops NEW reads immediately, then releases the provider retention and Host\n * lease only after EVERY in-flight `source.read` has really settled. The\n * returned promise is the real drain, so `snapshot.release` (or an idle expiry)\n * can wait for it instead of dropping retention under a live read. A new chunk\n * request is refused as `expired` the instant the session is closed.\n */\n #closeSnapshotSession(session: SnapshotSession): Promise<void> {\n if (!session.closed) {\n session.closed = true;\n if (session.idleTimer !== null) { clearTimeout(session.idleTimer); session.idleTimer = null; }\n this.#snapshotSessions.delete(session.sessionId);\n }\n return this.#releaseSnapshotSession(session);\n }\n\n #releaseSnapshotSession(session: SnapshotSession): Promise<void> {\n if (session.released) return Promise.resolve();\n if (session.activeReads > 0) {\n return new Promise<void>((resolve) => { session.drainWaiters.push(resolve); });\n }\n session.released = true;\n try { session.source.release?.(); } catch { /* provider-owned */ }\n session.release?.();\n for (const resolve of session.drainWaiters.splice(0)) resolve();\n return Promise.resolve();\n }\n\n #onSnapshotChunk(link: PluginChannelLinkPort, payload: unknown): PluginPeerRpcRequestExecution | null {\n const request = decodeSnapshotChunkRequest(payload);\n if (request === null) { this.#rejected('snapshot', 'invalid'); return null; }\n // The session (not the registration) owns the read: an already-accepted\n // session keeps working even after the provider retired.\n const registration = this.#registrationIncludingRetiring('snapshot', request.target);\n if (registration === null) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'snapshot', request.target, request.caller, request.callerScope, registration.process, true)) {\n this.#rejected('snapshot', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n const session = this.#snapshotSessions.get(request.request.sessionId);\n if (session === undefined || session.closed\n || session.link !== link || session.providerKey !== registration.key\n || session.caller !== request.caller || session.callerScope !== request.callerScope) {\n return this.#immediate(errorBody('expired'));\n }\n const { offset, length } = request.request;\n if (offset + length > session.source.descriptor.size) return this.#immediate(errorBody('invalid'));\n this.#armSnapshotIdle(session);\n // The terminal is the REAL end of the source read PLUS the drain bookkeeping,\n // never a pre-resolved stand-in: the caller's ACK barrier waits for the actual\n // task, and a concurrent close can only release after this read settles.\n session.activeReads += 1;\n const result = session.source.read(offset, length).then(\n (bytes) => {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength !== length) throw new ChannelError('failed', 'channel snapshot source returned an invalid chunk');\n return new Uint8Array(bytes);\n },\n () => { throw new ChannelError('failed', 'channel snapshot read failed'); },\n ).finally(() => {\n session.activeReads -= 1;\n if (session.closed && session.activeReads === 0) void this.#releaseSnapshotSession(session);\n });\n return Object.freeze({ result, terminal: result.then(() => undefined, () => undefined) });\n }\n\n #onSnapshotRelease(link: PluginChannelLinkPort, payload: unknown): PluginPeerRpcRequestExecution | null {\n const request = decodeSnapshotReleaseRequest(payload);\n if (request === null) { this.#rejected('snapshot', 'invalid'); return null; }\n const registration = this.#registrationIncludingRetiring('snapshot', request.target);\n if (registration === null) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'snapshot', request.target, request.caller, request.callerScope, registration.process, true)) {\n this.#rejected('snapshot', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n const session = this.#snapshotSessions.get(request.request.sessionId);\n if (session === undefined || session.closed\n || session.link !== link || session.providerKey !== registration.key\n || session.caller !== request.caller || session.callerScope !== request.callerScope) {\n return this.#immediate(errorBody('expired'));\n }\n // The release result resolves only after every in-flight read has drained, so\n // a caller that awaits it really waited for the retention/lease release.\n const drained = this.#closeSnapshotSession(session);\n return Object.freeze({ result: drained.then(() => successBody({})), terminal: drained });\n }\n\n #onEventSubscribe(link: PluginChannelLinkPort, payload: unknown, deadlineAt: number, signal: AbortSignal): PluginPeerRpcRequestExecution | null {\n const request = decodeEventSubscribeRequest(payload);\n if (request === null) { this.#rejected('event', 'invalid'); return null; }\n const registration = this.#registrationFor('event', request.target);\n if (registration === null || registration.event === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'event', request.target, request.caller, request.callerScope, registration.process)) {\n this.#rejected('event', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n const provider = registration.event;\n if (provider.delivery !== request.request.delivery) return this.#immediate(errorBody('invalid'));\n if (request.request.delivery === 'reliable' && provider.log === undefined) return this.#immediate(errorBody('unavailable'));\n if (this.#eventInbound.size >= CHANNEL_MAX_SUBSCRIPTIONS) return this.#immediate(errorBody('overloaded'));\n if (this.#eventInbound.has(request.request.clientId)) return this.#immediate(errorBody('conflict'));\n\n // A checkpoint is isolated per (caller plugin, caller scope, consumer id): two\n // plugins that happen to pick the same consumer id never share a cursor.\n const consumerKey = `${request.caller}\\0${request.callerScope}\\0${request.request.consumerId}`;\n let from = request.request.from;\n let oldest: number | null = null;\n let prunedThrough = 0;\n if (provider.delivery === 'reliable' && provider.log !== undefined) {\n const log = provider.log;\n try {\n oldest = log.oldestSequence();\n prunedThrough = log.prunedThrough();\n if (from === null) from = log.checkpoint(consumerKey) + 1;\n if (from < 1) from = 1;\n if ((oldest !== null && from < oldest) || from <= prunedThrough) {\n return this.#immediate(errorBody('gap', { oldestSequence: oldest, prunedThrough }));\n }\n } catch { return this.#immediate(errorBody('failed')); }\n } else {\n from = 1;\n }\n const subscriptionId = request.request.clientId;\n const release = this.#beginProvider(registration.provider, { purpose: request.purpose, deadlineAt, signal });\n if (release === null) return this.#immediate(errorBody('overloaded'));\n const subscription: EventSubscription = {\n link, providerKey: registration.key, subscriptionId, caller: request.caller, callerScope: request.callerScope,\n consumerId: consumerKey, delivery: request.request.delivery, deadlineAt, release,\n pending: [], dropped: 0, lastAcked: from - 1, lastDelivered: from - 1, replaying: false, closed: false,\n gapPending: false, gapCode: null, waiters: [], workWaiters: [], wakeVersion: 0,\n };\n this.#eventInbound.set(subscriptionId, subscription);\n\n const onAbort = () => { this.#closeInboundSubscription(subscription); };\n try { signal.addEventListener('abort', onAbort, { once: true }); } catch { /* already aborted */ }\n if (signal.aborted) this.#closeInboundSubscription(subscription);\n\n const result = eventSubscribeResultBody({\n subscriptionId, delivery: subscription.delivery,\n fromSequence: from, oldestSequence: oldest, prunedThrough,\n });\n const terminal = this.#replayReliable(provider, subscription, from)\n .then(() => this.#waitForClose(subscription))\n .finally(() => {\n try { signal.removeEventListener('abort', onAbort); } catch { /* already removed */ }\n });\n void terminal.catch(() => undefined);\n return Object.freeze({ result: Promise.resolve(result), terminal });\n }\n\n #waitForClose(subscription: EventSubscription): Promise<void> {\n if (subscription.closed) return Promise.resolve();\n return new Promise<void>((resolve) => { subscription.waiters.push(resolve); });\n }\n\n async #replayReliable(provider: PluginChannelEventProvider, subscription: EventSubscription, from: number): Promise<void> {\n if (provider.delivery !== 'reliable' || provider.log === undefined) return;\n const log = provider.log;\n subscription.replaying = true;\n try {\n let cursor = from;\n while (!subscription.closed) {\n if (subscription.gapPending || subscription.pending.length >= CHANNEL_EVENT_QUEUE_MAX) {\n await new Promise<void>(resolve => { subscription.workWaiters.push(resolve); });\n continue;\n }\n const wakeVersion = subscription.wakeVersion;\n const available = CHANNEL_EVENT_QUEUE_MAX - subscription.pending.length;\n let entries: readonly PluginChannelEventEntry[];\n try { entries = await log.list(cursor, Math.min(available, CHANNEL_EVENT_REPLAY_BATCH)); }\n catch {\n // A failed or partial replay is NOT an empty log: signal a real gap so\n // the consumer observes a failure instead of a silent short replay.\n this.#signalEventGap(subscription, 'failed');\n return;\n }\n if (subscription.closed) return;\n if (entries.length === 0) {\n // A publish during the asynchronous read must not be lost between an\n // empty result and installing the waiter. Later publishes/ACKs wake it.\n if (subscription.wakeVersion === wakeVersion) {\n await new Promise<void>(resolve => { subscription.workWaiters.push(resolve); });\n }\n continue;\n }\n for (const entry of entries) {\n if (subscription.closed) return;\n if (entry.sequence !== cursor) { this.#signalEventGap(subscription, 'gap'); break; }\n this.#emitEvent(subscription, { sequence: entry.sequence, eventId: entry.eventId, payload: entry.payload });\n if (subscription.gapPending || subscription.closed) break;\n cursor = entry.sequence + 1;\n }\n }\n } finally {\n subscription.replaying = false;\n if (subscription.closed) this.#finishInboundSubscription(subscription);\n }\n }\n\n #wakeEventDelivery(subscription: EventSubscription): void {\n subscription.wakeVersion += 1;\n for (const resolve of subscription.workWaiters.splice(0)) resolve();\n }\n\n #deliverEvent(subscription: EventSubscription, event: QueuedEvent): void {\n if (subscription.closed) return;\n if (subscription.delivery === 'reliable') {\n // The durable log is the only queue. One retained replay task delivers both\n // history and live facts in order; saturation waits for ACK, not for retry.\n this.#wakeEventDelivery(subscription);\n return;\n }\n this.#emitEvent(subscription, event);\n }\n\n #emitEvent(subscription: EventSubscription, event: QueuedEvent): void {\n if (subscription.closed) return;\n // A pending real gap must be signalled before any later event, or the\n // consumer's contiguous ACK window could advance over lost sequences.\n if (subscription.gapPending) { this.#flushEventGap(subscription); return; }\n const ordered = subscription.delivery !== 'reliable' || event.sequence <= 0\n ? true\n : event.sequence === subscription.lastDelivered + 1;\n if (subscription.pending.length >= CHANNEL_EVENT_QUEUE_MAX) {\n if (subscription.delivery === 'reliable') {\n // The bounded unacked window is full: surface a gap instead of silently\n // forgetting an unacked reliable event.\n this.#signalEventGap(subscription, 'overloaded');\n return;\n }\n subscription.pending.shift();\n subscription.dropped += 1;\n }\n const encoded = encodeChannelEmit({\n kind: 'event.notify', subscriptionId: subscription.subscriptionId,\n sequence: event.sequence, eventId: event.eventId, delivery: subscription.delivery,\n });\n const accepted = subscription.link.emitLane('event', 'notification', subscription.subscriptionId, subscription.deadlineAt, encoded, event.payload);\n if (!accepted) {\n subscription.dropped += 1;\n // A refused reliable frame is a real gap; it is signalled once the transport\n // is available again, never silently dropped.\n if (subscription.delivery === 'reliable' && event.sequence > 0) this.#signalEventGap(subscription, 'gap');\n return;\n }\n subscription.pending.push({ sequence: event.sequence, eventId: event.eventId, payload: event.payload });\n // The ACK ceiling advances only over a CONTIGUOUS run; a hole caps it, so a\n // consumer can never ACK past an undelivered sequence.\n if (ordered && event.sequence > subscription.lastDelivered) subscription.lastDelivered = event.sequence;\n }\n\n /** Marks a real reliable-delivery gap and tries to signal it immediately. */\n #signalEventGap(subscription: EventSubscription, code: PluginChannelErrorCode): void {\n if (subscription.gapPending) return;\n subscription.gapPending = true;\n subscription.gapCode = code;\n this.#flushEventGap(subscription);\n }\n\n #flushEventGap(subscription: EventSubscription): void {\n if (subscription.closed || !subscription.gapPending) return;\n const encoded = encodeChannelEmit({\n kind: 'event.gap', subscriptionId: subscription.subscriptionId,\n code: subscription.gapCode ?? 'gap',\n });\n if (!subscription.link.emitLane('event', 'notification', subscription.subscriptionId, subscription.deadlineAt, encoded, EMPTY)) {\n // Transport is down: keep the gap pending; it flushes on transport ready.\n return;\n }\n subscription.gapPending = false;\n this.#closeInboundSubscription(subscription);\n }\n\n /** A reconnect lets a lane re-signal a gap it could not send while detached. */\n #onTransportReady(link: PluginChannelLinkPort): void {\n for (const subscription of [...this.#eventInbound.values()]) {\n if (subscription.link === link && subscription.gapPending) this.#flushEventGap(subscription);\n }\n }\n\n #closeInboundSubscription(subscription: EventSubscription): void {\n if (subscription.closed) return;\n subscription.closed = true;\n this.#wakeEventDelivery(subscription);\n if (!subscription.replaying) this.#finishInboundSubscription(subscription);\n for (const resolve of subscription.waiters.splice(0)) resolve();\n }\n\n #finishInboundSubscription(subscription: EventSubscription): void {\n this.#eventInbound.delete(subscription.subscriptionId);\n subscription.release?.();\n }\n\n #onEventAck(link: PluginChannelLinkPort, payload: unknown): PluginPeerRpcRequestExecution | null {\n const request = decodeEventAckRequest(payload);\n if (request === null) { this.#rejected('event', 'invalid'); return null; }\n // An already-accepted subscription must keep ACKing after its provider retires.\n const registration = this.#registrationIncludingRetiring('event', request.target);\n if (registration === null || registration.event === undefined) return this.#immediate(errorBody('unavailable'));\n if (registration.contract !== request.contract) return this.#immediate(errorBody('conflict', { reason: 'contract' }));\n if (!this.#authorized(link, 'event', request.target, request.caller, request.callerScope, registration.process, true)) {\n this.#rejected('event', 'unauthorized');\n return this.#immediate(errorBody('unauthorized'));\n }\n const subscription = this.#eventInbound.get(request.request.subscriptionId);\n // Correlation is exact: same physical link, same target registration, same\n // original owner. A bare caller-string match could ACK another worker's or\n // another topic's subscription.\n if (subscription === undefined\n || subscription.link !== link\n || subscription.providerKey !== registration.key\n || subscription.caller !== request.caller\n || subscription.callerScope !== request.callerScope) {\n return this.#immediate(errorBody('expired'));\n }\n const sequence = request.request.sequence;\n if (sequence > subscription.lastDelivered) return this.#immediate(errorBody('rejected', { reason: 'undelivered' }));\n if (sequence <= subscription.lastAcked) return this.#immediate(errorBody('rejected', { reason: 'regressed' }));\n const log = registration.event.log;\n let acked = sequence;\n if (registration.event.delivery === 'reliable' && log !== undefined) {\n try { acked = log.ack(subscription.consumerId, sequence).acked; }\n catch { return this.#immediate(errorBody('failed')); }\n }\n subscription.lastAcked = Math.max(subscription.lastAcked, acked);\n subscription.pending = subscription.pending.filter(entry => entry.sequence > subscription.lastAcked);\n this.#wakeEventDelivery(subscription);\n return this.#immediate(eventAckResultBody({ acked: subscription.lastAcked }));\n }\n\n #fanOut(registration: Registration, event: QueuedEvent, delivery: 'transient' | 'reliable'): void {\n for (const subscription of [...this.#eventInbound.values()]) {\n if (subscription.closed || subscription.delivery !== delivery) continue;\n if (subscription.providerKey !== registration.key) continue;\n this.#deliverEvent(subscription, event);\n }\n }\n\n /* Emit + transport callbacks --------------------------------------- */\n\n #onEmit(link: PluginChannelLinkPort, frame: PluginPeerLaneEmit): void {\n if (this.#disposed) return;\n const lane = frame.lane;\n if (lane !== 'event' && lane !== 'snapshot' && lane !== 'stream') return;\n const payload = decodeChannelEmit(frame.context);\n if (payload === null) { this.#rejected(lane, 'invalid'); return; }\n switch (payload.kind) {\n case 'stream.chunk': return this.#onStreamChunk(link, frame.body, payload);\n case 'stream.data': return this.#onStreamData(link, frame.body, payload);\n case 'stream.credit': return this.#onStreamCredit(link, payload);\n case 'stream.end-read': return this.#onStreamEndRead(link, payload);\n case 'stream.end': return this.#onStreamEnd(link, payload);\n case 'event.notify': return this.#onEventNotify(link, frame.body, payload);\n case 'event.gap': return this.#onEventGap(link, payload);\n }\n }\n\n #onStreamChunk(link: PluginChannelLinkPort, body: Uint8Array, payload: { readonly transferId: string; readonly offset: number; readonly last: boolean }): void {\n const state = this.#streamOutbound.get(payload.transferId);\n if (state === undefined || state.link !== link) return;\n if (state.failure !== null || state.lastSeen) return;\n if (payload.offset !== state.baseOffset + state.receivedBytes) { this.#failStream(state, 'truncated'); return; }\n if (state.queuedBytes + body.byteLength > CHANNEL_MAX_TRANSFER_BUFFER_BYTES\n || this.#bufferedBytes + body.byteLength > CHANNEL_MAX_TOTAL_BUFFER_BYTES) {\n this.#failStream(state, 'overloaded');\n return;\n }\n const bytes = new Uint8Array(body);\n state.chunks.push(bytes);\n state.queuedBytes += bytes.byteLength;\n this.#bufferedBytes += bytes.byteLength;\n state.receivedBytes += bytes.byteLength;\n if (state.hash !== null) state.hash.update(bytes);\n this.#armStreamIdle(state);\n if (payload.last) state.lastSeen = true;\n for (const resolve of state.waiters.splice(0)) resolve();\n }\n\n #onStreamData(link: PluginChannelLinkPort, body: Uint8Array, payload: { readonly transferId: string; readonly offset: number; readonly last: boolean }): void {\n const transfer = this.#writeInbound.get(payload.transferId);\n if (transfer === undefined || transfer.link !== link || transfer.finished || transfer.aborting || transfer.finishing) return;\n if (payload.offset !== transfer.offset) { this.#abortInboundWrite(transfer, 'failed'); return; }\n if (body.byteLength === 0 || body.byteLength > CHANNEL_MAX_CHUNK_BYTES) { this.#abortInboundWrite(transfer, 'failed'); return; }\n if (transfer.offset + body.byteLength > transfer.window) { this.#abortInboundWrite(transfer, 'failed'); return; }\n if (transfer.expectedSize !== null && transfer.offset + body.byteLength > transfer.expectedSize) { this.#abortInboundWrite(transfer, 'failed'); return; }\n // The absolute ceiling also applies when the caller declared no size, so an\n // unknown-size write can never stream without bound.\n if (transfer.offset + body.byteLength > CHANNEL_STREAM_MAX_TOTAL_BYTES) { this.#abortInboundWrite(transfer, 'failed'); return; }\n const bytes = new Uint8Array(body);\n const offset = transfer.offset;\n transfer.slack -= bytes.byteLength;\n transfer.offset += bytes.byteLength;\n transfer.hash.update(bytes);\n this.#armWriteInboundIdle(transfer);\n // One sink is written SERIALLY: a later chunk waits for the earlier write to\n // settle instead of racing it, and credit is granted per CONSUMED byte (after\n // the real sink accepted it), never per received byte.\n const task = transfer.writeTail.then(() => {\n if (transfer.aborting) throw new ChannelError('cancelled', 'write direction was aborted');\n return transfer.sink.write(offset, bytes);\n }).then(() => { this.#grantWriteCredit(transfer, bytes.byteLength); });\n transfer.writeTail = task;\n void task.catch(() => { this.#abortInboundWrite(transfer, 'failed'); });\n }\n\n #grantWriteCredit(transfer: WriteInbound, bytes: number): void {\n if (transfer.finished || transfer.aborting) return;\n transfer.slack = Math.min(transfer.slack + bytes, CHANNEL_STREAM_MAX_CREDIT_BYTES);\n this.#announceWriteWindow(transfer);\n }\n\n /** Announces the ABSOLUTE window (received so far + still-unconsumed allowance). */\n #announceWriteWindow(transfer: WriteInbound): void {\n if (transfer.finished) return;\n transfer.window = Math.max(transfer.window, transfer.offset + transfer.slack);\n const payload = encodeChannelEmit({ kind: 'stream.credit', transferId: transfer.transferId, direction: 'write', window: transfer.window });\n void this.#emitLaneWithRetry(transfer.link, transfer.transferId, transfer.deadlineAt, payload)\n .then((delivered) => { if (!delivered && !transfer.finished) this.#abortInboundWrite(transfer, 'failed'); });\n }\n\n /** Repeats the window so a frame refused by the transport heals instead of stalling. */\n #armWriteHeartbeat(transfer: WriteInbound): void {\n if (transfer.heartbeat !== null) clearInterval(transfer.heartbeat);\n const timer = setInterval(() => { this.#announceWriteWindow(transfer); }, CHANNEL_CREDIT_HEARTBEAT_MS);\n timer.unref?.();\n transfer.heartbeat = timer;\n }\n\n /** Retries one lane emit until the transport accepts it, bounded and yielding. */\n async #emitLaneWithRetry(link: PluginChannelLinkPort, requestId: string, deadlineAt: number, payload: RpcJson): Promise<boolean> {\n for (let attempt = 0; attempt < CHANNEL_STREAM_CREDIT_RETRIES; attempt++) {\n if (link.emitLane('stream', 'notification', requestId, deadlineAt, payload, EMPTY)) return true;\n await delay(2);\n }\n return false;\n }\n\n #onStreamCredit(link: PluginChannelLinkPort, payload: { readonly transferId: string; readonly direction: 'read' | 'write'; readonly window: number }): void {\n // The direction selects the flow, so a duplex session can never cross its two\n // independent windows on the same transfer id.\n if (payload.direction === 'read') {\n const transfer = this.#streamInbound.get(payload.transferId);\n if (transfer === undefined || transfer.link !== link) return;\n // Absolute and monotonic: a repeated or reordered window can never inflate\n // the allowance, and a lost frame is corrected by the next announcement.\n transfer.window = Math.max(transfer.window, payload.window);\n this.#armInboundIdle(transfer);\n this.#wakeCredit(transfer);\n return;\n }\n const state = this.#writeOutbound.get(payload.transferId);\n if (state === undefined || state.link !== link) return;\n state.window = Math.max(state.window, payload.window);\n this.#armWriteIdle(state);\n this.#wakeWrite(state);\n }\n\n #onEventNotify(link: PluginChannelLinkPort, body: Uint8Array, payload: { readonly subscriptionId: string; readonly sequence: number; readonly eventId: string; readonly delivery: 'transient' | 'reliable' }): void {\n const state = this.#eventOutbound.get(payload.subscriptionId);\n if (state === undefined || state.link !== link || state.closed) return;\n if (payload.delivery !== state.delivery) { this.#failOutboundSubscription(state, 'invalid'); return; }\n if (state.queue.length >= CHANNEL_EVENT_QUEUE_MAX) {\n if (state.delivery === 'reliable' && payload.sequence > 0) {\n // A reliable event must NEVER be silently shifted away: surface the real\n // overflow so the consumer re-syncs from its durable checkpoint.\n this.#failOutboundSubscription(state, 'overloaded');\n return;\n }\n state.queue.shift();\n state.dropped += 1;\n }\n state.queue.push({ sequence: payload.sequence, eventId: payload.eventId, payload: new Uint8Array(body) });\n if (state.ready && !state.scheduled) {\n state.scheduled = true;\n queueMicrotask(() => this.#drainOutboundEvents(state));\n }\n }\n\n /** A provider-signalled real reliable gap: fail publicly, never close silently. */\n #onEventGap(link: PluginChannelLinkPort, payload: { readonly subscriptionId: string; readonly code: PluginChannelErrorCode }): void {\n const state = this.#eventOutbound.get(payload.subscriptionId);\n if (state === undefined || state.link !== link || state.closed) return;\n this.#failOutboundSubscription(state, payload.code);\n }\n\n #drainOutboundEvents(state: EventOutbound): void {\n state.scheduled = false;\n while (!state.closed && state.queue.length > 0) {\n const event = state.queue.shift()!;\n if (state.delivery === 'reliable' && event.sequence > 0 && event.sequence !== state.delivered + 1) {\n // A hole in the ordered run: never invoke a later callback as if the run\n // were contiguous, and never let an ACK cross the missing sequence.\n this.#failOutboundSubscription(state, 'gap');\n return;\n }\n // Advance the contiguous-delivery ceiling BEFORE the callback so an ACK\n // issued inside the callback sees exactly this delivered sequence.\n if (state.delivery === 'reliable' && event.sequence > 0) state.delivered = event.sequence;\n try { state.handler({ sequence: event.sequence, eventId: event.eventId, payload: event.payload, delivery: state.delivery }); }\n catch {\n this.#failOutboundSubscription(state, 'failed');\n return;\n }\n }\n }\n\n #onTransportEnd(link: PluginChannelLinkPort, reason: 'retired' | 'closed' | 'remote-stopped'): void {\n if (reason === 'retired') return;\n for (const state of [...this.#streamOutbound.values()]) {\n if (state.link === link) this.#failStream(state, reason === 'remote-stopped' ? 'truncated' : 'closed');\n }\n for (const state of [...this.#writeOutbound.values()]) {\n if (state.link === link) this.#failWrite(state, reason === 'remote-stopped' ? 'truncated' : 'closed');\n }\n for (const transfer of [...this.#streamInbound.values()]) {\n if (transfer.link === link) this.#abortInboundStream(transfer);\n }\n for (const transfer of [...this.#writeInbound.values()]) {\n if (transfer.link === link) this.#abortInboundWrite(transfer, 'closed');\n }\n for (const subscription of [...this.#eventInbound.values()]) {\n if (subscription.link === link) this.#closeInboundSubscription(subscription);\n }\n for (const state of [...this.#eventOutbound.values()]) {\n if (state.link !== link) continue;\n // A reliable subscription that ends without an orderly provider close is a\n // REAL failure, never a silent close.\n if (state.delivery === 'reliable') this.#failOutboundSubscription(state, 'closed');\n else this.#closeOutboundSubscription(state);\n }\n for (const session of [...this.#snapshotSessions.values()]) {\n if (session.link === link) void this.#closeSnapshotSession(session);\n }\n }\n\n /* Outbound stream settlement --------------------------------------- */\n\n #armStreamIdle(state: StreamOutbound): void {\n if (state.idleTimer !== null) clearTimeout(state.idleTimer);\n const timer = setTimeout(() => { this.#failStream(state, 'truncated'); }, state.idleMs);\n timer.unref?.();\n state.idleTimer = timer;\n }\n\n #onStreamTerminal(state: StreamOutbound): void {\n // The producer end is real evidence only once the consumer verified `last`.\n if (state.failure !== null || state.completed) return;\n if (state.lastSeen) return;\n this.#failStream(state, 'truncated');\n }\n\n /** Verifies size/digest and only then resolves the consumer's completion. */\n #verifyAndSettle(state: StreamOutbound): void {\n if (state.failure !== null || state.completed) return;\n if (state.expectedSize !== null && state.baseOffset + state.receivedBytes !== state.expectedSize) {\n return this.#failStream(state, 'truncated');\n }\n let digest: `sha256:${string}` | null = null;\n if (state.hash !== null) {\n digest = `sha256:${state.hash.digest('hex')}`;\n if (state.expectedDigest !== null && digest !== state.expectedDigest) return this.#failStream(state, 'truncated');\n }\n this.#settleStream(state, digest ?? `sha256:${(state.hash ?? createHash('sha256')).digest('hex')}`);\n }\n\n #failStream(state: StreamOutbound, code: PluginChannelErrorCode): void {\n if (state.failure !== null || state.completed) return;\n state.failure = new ChannelError(code, `peer channel stream ${code}`);\n this.#clearStreamResources(state);\n state.completion.reject(state.failure);\n for (const resolve of state.waiters.splice(0)) resolve();\n if (state.duplex !== undefined) this.#duplexFail(state.duplex, code, 'read');\n }\n\n #settleStream(state: StreamOutbound, digest: `sha256:${string}`): void {\n if (state.failure !== null || state.completed) return;\n state.completed = true;\n this.#clearStreamResources(state);\n state.completion.resolve(Object.freeze({ bytes: state.receivedBytes, digest }));\n for (const resolve of state.waiters.splice(0)) resolve();\n if (state.duplex !== undefined) this.#duplexSettle(state.duplex, 'read', { bytes: state.receivedBytes, digest });\n }\n\n #clearStreamResources(state: StreamOutbound): void {\n if (state.idleTimer !== null) { clearTimeout(state.idleTimer); state.idleTimer = null; }\n if (state.heartbeat !== null) { clearInterval(state.heartbeat); state.heartbeat = null; }\n this.#streamOutbound.delete(state.transferId);\n this.#bufferedBytes -= state.queuedBytes;\n state.queuedBytes = 0;\n state.chunks.length = 0;\n state.release?.();\n try { state.controller.abort('settled'); } catch { /* already aborted */ }\n }\n\n #cancelStream(state: StreamOutbound): void {\n this.#failStream(state, 'cancelled');\n try { state.controller.abort('cancelled'); } catch { /* already aborted */ }\n }\n\n /* In-process loopback -------------------------------------------------- */\n\n #loopbackRequest(\n port: PluginChannelLinkPort,\n _lane: PluginChannelLane,\n context: import('./wire-contract').RpcJson,\n _body: Uint8Array,\n options: { readonly deadlineAt: number; readonly signal?: AbortSignal },\n ): PluginPeerRpcRequestExecution {\n if (this.#disposed) {\n return Object.freeze({ result: Promise.reject(new ChannelError('closed', 'peer channel hub is disposed')), terminal: Promise.resolve() });\n }\n if (!Number.isSafeInteger(options.deadlineAt) || options.deadlineAt <= 0 || Date.now() >= options.deadlineAt) {\n return Object.freeze({ result: Promise.reject(new ChannelError('expired', 'peer channel request deadline expired')), terminal: Promise.resolve() });\n }\n const controller = new AbortController();\n const removeOuter = linkExternalSignal(options.signal, controller);\n const timer = setTimeout(() => { try { controller.abort('deadline'); } catch { /* already aborted */ } }, options.deadlineAt - Date.now());\n timer.unref?.();\n const execution = this.#onRequest(port, context, options.deadlineAt, controller.signal);\n if (execution === null) {\n clearTimeout(timer); removeOuter();\n return Object.freeze({\n result: Promise.reject(new ChannelError('unavailable', 'peer channel target is unavailable')),\n terminal: Promise.resolve(),\n });\n }\n return Object.freeze({\n result: execution.result,\n terminal: execution.terminal.finally(() => { clearTimeout(timer); removeOuter(); }),\n });\n }\n\n /* Lifecycle ---------------------------------------------------------- */\n\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n for (const state of [...this.#streamOutbound.values()]) this.#failStream(state, 'closed');\n for (const state of [...this.#writeOutbound.values()]) this.#failWrite(state, 'closed');\n for (const transfer of [...this.#streamInbound.values()]) this.#abortInboundStream(transfer);\n for (const transfer of [...this.#writeInbound.values()]) this.#abortInboundWrite(transfer, 'closed');\n for (const subscription of [...this.#eventInbound.values()]) this.#closeInboundSubscription(subscription);\n for (const state of [...this.#eventOutbound.values()]) this.#closeOutboundSubscription(state);\n for (const session of [...this.#snapshotSessions.values()]) void this.#closeSnapshotSession(session);\n this.#registrations.clear();\n this.#bufferedBytes = 0;\n }\n\n status(): {\n readonly registrations: number;\n readonly activeInboundTransfers: number;\n readonly activeOutboundTransfers: number;\n readonly subscriptions: number;\n readonly subscribers: number;\n readonly bufferedBytes: number;\n } {\n return Object.freeze({\n registrations: this.#registrations.size,\n activeInboundTransfers: this.#streamInbound.size + this.#writeInbound.size,\n activeOutboundTransfers: this.#streamOutbound.size + this.#writeOutbound.size,\n subscriptions: this.#eventInbound.size,\n subscribers: this.#eventOutbound.size,\n bufferedBytes: this.#bufferedBytes,\n });\n }\n}\n\n/** Result cancellation never substitutes for the authenticated task terminal. */\nfunction terminalGatedRelease(release: (() => void) | undefined): {\n readonly release: () => void;\n observe(terminal: Promise<void>): void;\n} {\n let requested = false;\n let ended = false;\n let released = false;\n const complete = (): void => {\n if (!requested || !ended || released) return;\n released = true;\n release?.();\n };\n return {\n release: () => { requested = true; complete(); },\n observe: (terminal) => {\n void terminal.then(() => { ended = true; complete(); }, () => {\n // An unobservable terminal is not proof that the task ended.\n });\n },\n };\n}\n\nfunction isSettled<T>(deferred: Deferred<T>): boolean {\n return deferred.settled;\n}\n\nfunction concat(chunks: readonly Uint8Array[]): Uint8Array {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const out = new Uint8Array(total);\n let at = 0;\n for (const chunk of chunks) { out.set(chunk, at); at += chunk.byteLength; }\n return out;\n}\n\n/** Links an external AbortSignal into a locally owned controller; returns a remover. */\nfunction linkExternalSignal(signal: AbortSignal | undefined, controller: AbortController): () => void {\n if (signal === undefined) return () => undefined;\n if (signal.aborted) { try { controller.abort('caller'); } catch { /* already aborted */ } return () => undefined; }\n const listener = () => { try { controller.abort('caller'); } catch { /* already aborted */ } };\n signal.addEventListener('abort', listener, { once: true });\n return () => signal.removeEventListener('abort', listener);\n}\n\nfunction errorCodeOf(error: unknown): PluginChannelErrorCode {\n const code = (error as { code?: unknown } | null)?.code;\n if (code === 'cancelled') return 'cancelled';\n if (code === 'timeout' || code === 'expired') return 'expired';\n if (code === 'closed' || code === 'disconnected') return 'closed';\n if (code === 'overloaded') return 'overloaded';\n return 'failed';\n}\n",
|
|
15
|
+
"/**\n * Host-managed persistent atomic snapshot version store.\n *\n * A provider plugin (e.g. the future models-dev directory) gets versioned,\n * immutable, digest-addressed snapshot bodies with bounded retention WITHOUT\n * inventing its own chunking or widening the 1 MiB durable-command limit: the\n * body is stored as bounded chunks in the host `plugin_communication_records`\n * table (the audited v14 schema; no new table, no runtime DDL), and the version\n * becomes visible atomically by flipping its meta + the current pointer.\n *\n * Durability/atomicity contract:\n * - chunks are written first; a version is INVISIBLE until its meta row exists,\n * so a crash mid-write leaves only unreachable chunks (reclaimed by `collect`);\n * - the current pointer is flipped last, so a reader never observes a half-written\n * body as current;\n * - a returned source keeps the exact descriptor fixed and can `retain()`/`release()`\n * the version; a retained version is never reclaimed, so an in-flight whole-body\n * read can never have its bytes swapped or freed underneath it;\n * - retention is explicit and bounded (`maxVersions`, `maxBytes`), and GC never\n * touches the current version, a retained version, or a version whose chunks\n * are still referenced.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ChannelSnapshotDescriptor } from './peer-channel-protocol';\nimport type { PluginChannelSnapshotSource } from './peer-channel-hub';\nimport { CHANNEL_MAX_CHUNK_BYTES } from './peer-channel-protocol';\nimport { CHANNEL_SNAPSHOT_MAX_BYTES } from './peer-channel-hub';\nimport type { CommunicationNamespaceStore } from './persistence';\nimport { encodeRpcJson } from './wire-contract';\n\nconst DEFAULT_MAX_VERSIONS = 3;\nconst DEFAULT_CHUNK_BYTES = 60 * 1024;\n\n/**\n * Retained-version refcounts shared by ALL store instances of one version family.\n * Two `store()` calls for the same (namespace, owner, family id) must share pin\n * management: otherwise one instance's GC could reclaim a version another instance\n * still has retained for an in-flight whole-body read.\n */\nconst SNAPSHOT_FAMILY_REFS = new Map<string, Map<number, number>>();\n\nfunction familyRefs(prefix: string): Map<number, number> {\n let refs = SNAPSHOT_FAMILY_REFS.get(prefix);\n if (refs === undefined) { refs = new Map(); SNAPSHOT_FAMILY_REFS.set(prefix, refs); }\n return refs;\n}\n\n/** Minimal read surface shared by the namespace store and its transaction mutator. */\ninterface SnapshotRecordReader {\n get(key: string): { readonly payload: Uint8Array } | null;\n}\n\nexport interface HostSnapshotStoreOptions {\n /** Descriptor owner identity (usually the providing plugin name). */\n readonly owner: string;\n /**\n * Immutable version-family id declared by the provider. Two `store()` calls\n * with the same id share ONE durable family (current pointer, version index,\n * retention, pins); a different id is a completely separate family. It is part\n * of the persistent identity, so the same family is readable again after a\n * process restart.\n */\n readonly id?: string;\n /** Runtime generation of the owner; part of the immutable descriptor. */\n readonly epoch?: number;\n readonly schemaVersion: number;\n readonly chunkBytes?: number;\n /** Retained versions, including the current one. */\n readonly maxVersions?: number;\n /** Bounded total retained body bytes. */\n readonly maxBytes?: number;\n}\n\ninterface VersionMeta {\n readonly owner: string;\n readonly epoch: number;\n readonly version: number;\n readonly schemaVersion: number;\n readonly digest: `sha256:${string}`;\n readonly size: number;\n readonly chunkBytes: number;\n readonly chunks: number;\n}\n\n/**\n * One namespace-isolated, atomically published version family. The store never\n * exposes its keys, connection, or any other namespace.\n */\nexport class HostSnapshotStore {\n readonly #store: CommunicationNamespaceStore;\n readonly #owner: string;\n readonly #epoch: number;\n readonly #schemaVersion: number;\n readonly #chunkBytes: number;\n readonly #maxVersions: number;\n readonly #maxBytes: number;\n readonly #prefix: string;\n #maintenanceError: string | null = null;\n\n constructor(store: CommunicationNamespaceStore, options: HostSnapshotStoreOptions) {\n const chunkBytes = options.chunkBytes ?? DEFAULT_CHUNK_BYTES;\n const maxVersions = options.maxVersions ?? DEFAULT_MAX_VERSIONS;\n const maxBytes = options.maxBytes ?? CHANNEL_SNAPSHOT_MAX_BYTES;\n if (typeof options.owner !== 'string' || options.owner.length === 0) throw new Error('snapshot store requires an owner identity');\n if (!Number.isSafeInteger(options.schemaVersion) || options.schemaVersion < 1) throw new Error('snapshot store schema version is invalid');\n if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1 || chunkBytes > CHANNEL_MAX_CHUNK_BYTES) throw new Error('snapshot store chunk size is invalid');\n if (!Number.isSafeInteger(maxVersions) || maxVersions < 1) throw new Error('snapshot store version retention is invalid');\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > CHANNEL_SNAPSHOT_MAX_BYTES) throw new Error('snapshot store byte retention is invalid');\n const familyId = options.id ?? '';\n if (options.id !== undefined && (typeof options.id !== 'string' || options.id.length === 0 || options.id.length > 256)) {\n throw new Error('snapshot store family id is invalid');\n }\n this.#store = store;\n this.#owner = options.owner;\n this.#epoch = options.epoch ?? 1;\n this.#schemaVersion = options.schemaVersion;\n this.#chunkBytes = chunkBytes;\n this.#maxVersions = maxVersions;\n this.#maxBytes = maxBytes;\n // The family id is part of the persistent identity: two declared families of\n // one provider never share a current pointer, version index or pins.\n const identity = familyId === '' ? `${store.namespace}/${options.owner}` : `${store.namespace}/${options.owner}/${familyId}`;\n this.#prefix = `hs:${createHash('sha256').update(identity).digest('hex').slice(0, 16)}`;\n }\n\n #chunkKey(version: number, index: number): string {\n return `${this.#prefix}:${version}:c${String(index).padStart(8, '0')}`;\n }\n\n #metaKey(version: number): string { return `${this.#prefix}:${version}:m`; }\n\n #currentKey(): string { return `${this.#prefix}:cur`; }\n\n #digest(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n }\n\n #readMeta(version: number, reader: SnapshotRecordReader = this.#store): VersionMeta | null {\n const record = reader.get(this.#metaKey(version));\n if (record === null) return null;\n let parsed: unknown;\n try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(record.payload)); }\n catch { throw new Error('snapshot store meta is unreadable'); }\n if (parsed === null || typeof parsed !== 'object') throw new Error('snapshot store meta is invalid');\n const meta = parsed as Partial<VersionMeta>;\n if (meta.owner !== this.#owner || meta.version !== version\n || !Number.isSafeInteger(meta.epoch) || !Number.isSafeInteger(meta.schemaVersion)\n || !Number.isSafeInteger(meta.size) || !Number.isSafeInteger(meta.chunkBytes)\n || !Number.isSafeInteger(meta.chunks) || typeof meta.digest !== 'string') {\n throw new Error('snapshot store meta is invalid');\n }\n return Object.freeze({\n owner: meta.owner, epoch: meta.epoch as number, version, schemaVersion: meta.schemaVersion as number,\n digest: meta.digest as `sha256:${string}`, size: meta.size as number,\n chunkBytes: meta.chunkBytes as number, chunks: meta.chunks as number,\n });\n }\n\n #descriptor(meta: VersionMeta): ChannelSnapshotDescriptor {\n return Object.freeze({\n owner: meta.owner, epoch: meta.epoch, version: meta.version, schemaVersion: meta.schemaVersion,\n digest: meta.digest, size: meta.size, chunkBytes: meta.chunkBytes,\n });\n }\n\n /**\n * Atomically publishes one immutable version. Returns the fixed descriptor, or\n * throws (quota/corruption) — a partially written version is never visible.\n */\n publish(version: number, body: unknown | Uint8Array): ChannelSnapshotDescriptor {\n if (!Number.isSafeInteger(version) || version < 1) throw new Error('snapshot store version is invalid');\n const bytes = body instanceof Uint8Array ? new Uint8Array(body) : new TextEncoder().encode(encodeRpcJson(body, this.#maxBytes));\n if (bytes.byteLength === 0 || bytes.byteLength > this.#maxBytes) throw new Error('snapshot store body exceeds the bounded retention budget');\n const chunks = Math.ceil(bytes.byteLength / this.#chunkBytes);\n const prior = this.#readMeta(version);\n if (prior !== null) {\n // Republishing the SAME immutable version must be idempotent; different\n // content under an existing version is refused.\n if (prior.digest !== this.#digest(bytes) || prior.size !== bytes.byteLength) throw new Error('snapshot store version already exists with different content');\n return this.#descriptor(prior);\n }\n const digest = this.#digest(bytes);\n const meta: VersionMeta = Object.freeze({\n owner: this.#owner, epoch: this.#epoch, version, schemaVersion: this.#schemaVersion,\n digest, size: bytes.byteLength, chunkBytes: this.#chunkBytes, chunks,\n });\n const versions = this.#publishedVersions(this.#store);\n const nextVersions = versions.includes(version) ? versions : [...versions, version].sort((left, right) => left - right);\n const encoder = new TextEncoder();\n // ONE immediate transaction for the whole version: chunks, meta, version index\n // and the visibility flip commit together. This both makes a partial version\n // impossible and pays exactly ONE durable commit instead of one per chunk\n // (per-chunk commits blocked the host event loop for seconds on a large body).\n this.#store.transact((mutator) => {\n for (let index = 0; index < chunks; index += 1) {\n const offset = index * this.#chunkBytes;\n const chunk = bytes.subarray(offset, Math.min(offset + this.#chunkBytes, bytes.byteLength));\n mutator.put(this.#chunkKey(version, index), chunk, { required: false, expiresAt: null });\n }\n mutator.put(this.#metaKey(version), encoder.encode(JSON.stringify(meta)), { required: false, expiresAt: null });\n mutator.put(this.#versionsKey(), encoder.encode(JSON.stringify({ versions: nextVersions })), { required: false, expiresAt: null });\n // Visibility flip is LAST, inside the same commit: a reader never observes a\n // half-written body as current, and a crash leaves only unreachable chunks.\n // A monotonic fence makes the flip safe under out-of-order publishes: a new\n // but LOWER version is still durable/retained, yet it can never move the\n // current pointer backwards. (Re-publishing an already-existing version\n // returned above without touching the pointer.)\n const current = this.#currentVersion(mutator);\n if (current === null || version > current) {\n mutator.put(this.#currentKey(), encoder.encode(String(version)), { required: false, expiresAt: null });\n }\n });\n this.maintain();\n return this.#descriptor(meta);\n }\n\n /** Post-commit GC failure cannot turn a durable publication into a failed publish. */\n maintain(): { readonly removed: number; readonly error: string | null } {\n try {\n const removed = this.collect();\n this.#maintenanceError = null;\n return Object.freeze({ removed, error: null });\n } catch {\n this.#maintenanceError = 'storage_failure';\n return Object.freeze({ removed: 0, error: this.#maintenanceError });\n }\n }\n\n maintenanceStatus(): { readonly pending: boolean; readonly error: string | null } {\n return Object.freeze({ pending: this.#maintenanceError !== null, error: this.#maintenanceError });\n }\n\n /** Source for the current version, or `null` when none was published. */\n current(): PluginChannelSnapshotSource | null {\n const pointer = this.#store.get(this.#currentKey());\n if (pointer === null) return null;\n let text: string;\n try { text = new TextDecoder('utf-8', { fatal: true }).decode(pointer.payload); }\n catch { throw new Error('snapshot store current pointer is unreadable'); }\n const version = Number(text);\n if (!Number.isSafeInteger(version) || version < 1) throw new Error('snapshot store current pointer is invalid');\n return this.version(version);\n }\n\n /** Source for one explicitly named, still-retained version. */\n version(version: number): PluginChannelSnapshotSource | null {\n if (!Number.isSafeInteger(version) || version < 1) return null;\n // A present-but-corrupt meta/version index record is CORRUPTION, not\n // \"absent\": reporting `null` would let a reader believe the version never\n // existed. `#readMeta` throws on corruption and is intentionally not caught.\n const meta = this.#readMeta(version);\n if (meta === null) return null;\n const store = this.#store;\n const digest = meta.digest;\n const size = meta.size;\n const chunkBytes = meta.chunkBytes;\n const chunks = meta.chunks;\n const prefix = this.#prefix;\n const refs = familyRefs(prefix);\n let retained = false;\n const source: PluginChannelSnapshotSource = {\n descriptor: this.#descriptor(meta),\n retain: () => {\n if (retained) return;\n retained = true;\n refs.set(version, (refs.get(version) ?? 0) + 1);\n },\n release: () => {\n if (!retained) return;\n retained = false;\n const count = (refs.get(version) ?? 1) - 1;\n if (count <= 0) refs.delete(version);\n else refs.set(version, count);\n },\n read: async (offset: number, length: number): Promise<Uint8Array> => {\n if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || offset + length > size) {\n throw new Error('snapshot store read is out of range');\n }\n const out = new Uint8Array(length);\n let at = offset;\n let written = 0;\n while (written < length) {\n const index = Math.floor(at / chunkBytes);\n if (index >= chunks) throw new Error('snapshot store chunk is missing');\n const record = store.get(`${prefix}:${version}:c${String(index).padStart(8, '0')}`);\n if (record === null) throw new Error('snapshot store chunk is missing');\n const chunk = record.payload;\n const within = at - index * chunkBytes;\n const take = Math.min(chunk.byteLength - within, length - written);\n if (take <= 0) throw new Error('snapshot store chunk is truncated');\n out.set(chunk.subarray(within, within + take), written);\n written += take;\n at += take;\n }\n // Integrity is re-verified on every read: a tampered chunk is refused.\n if (this.#digest(out) !== digest && length === size && offset === 0) {\n // Full-body reads re-check the whole digest; partial reads rely on the\n // chunked layout plus the session's whole-body verification.\n throw new Error('snapshot store digest mismatch');\n }\n return out;\n },\n };\n return Object.freeze(source);\n }\n\n #currentVersion(reader: SnapshotRecordReader = this.#store): number | null {\n const pointer = reader.get(this.#currentKey());\n if (pointer === null) return null;\n let text: string;\n try { text = new TextDecoder('utf-8', { fatal: true }).decode(pointer.payload); }\n catch { throw new Error('snapshot store current pointer is unreadable'); }\n const version = Number(text);\n if (!Number.isSafeInteger(version) || version < 1) throw new Error('snapshot store current pointer is invalid');\n return version;\n }\n\n #totalBytes(reader: SnapshotRecordReader): number {\n let total = 0;\n for (const version of this.#publishedVersions(reader)) {\n const meta = this.#readMeta(version, reader);\n if (meta !== null) total += meta.size;\n }\n return total;\n }\n\n /**\n * Durable published-version index. `list()` cannot be used here: it returns the\n * first N rows by key order, so a large body's chunk rows would push later\n * version metas out of view and GC would never run.\n */\n #versionsKey(): string { return `${this.#prefix}:versions`; }\n\n #publishedVersions(reader: SnapshotRecordReader): number[] {\n const record = reader.get(this.#versionsKey());\n if (record === null) return [];\n let parsed: unknown;\n try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(record.payload)); }\n catch { throw new Error('snapshot store version index is unreadable'); }\n if (parsed === null || typeof parsed !== 'object') throw new Error('snapshot store version index is invalid');\n const list = (parsed as { versions?: unknown }).versions;\n if (!Array.isArray(list)) throw new Error('snapshot store version index is invalid');\n return list.filter((value): value is number => Number.isSafeInteger(value) && value >= 1).sort((left, right) => left - right);\n }\n\n /**\n * Bounded GC in ONE transaction: drops the oldest unreferenced, non-current\n * versions until both the version count and the total byte budget fit. Never\n * touches a version a live read has retained, and never the current version.\n */\n collect(): number {\n const encoder = new TextEncoder();\n return this.#store.transact((mutator) => {\n let removed = 0;\n for (;;) {\n const versions = this.#publishedVersions(mutator);\n const total = this.#totalBytes(mutator);\n if (versions.length <= this.#maxVersions && total <= this.#maxBytes) break;\n const current = this.#currentVersion(mutator);\n const oldest = versions.find((version) => version !== current && (familyRefs(this.#prefix).get(version) ?? 0) === 0);\n if (oldest === undefined) break;\n const meta = this.#readMeta(oldest, mutator);\n if (meta === null) break;\n for (let index = 0; index < meta.chunks; index += 1) mutator.ack(this.#chunkKey(oldest, index));\n mutator.ack(this.#metaKey(oldest));\n mutator.put(this.#versionsKey(), encoder.encode(JSON.stringify({ versions: versions.filter((version) => version !== oldest) })), { required: false, expiresAt: null });\n removed += 1;\n }\n return removed;\n });\n }\n}\n",
|
|
16
|
+
"/** Public same-process plugin services. Cross-process callers require the host RPC adapter. */\nimport type { PluginServiceDeclarations, PluginServiceProcess } from './plugin-services/contracts';\nimport { assertSupportedServiceDeclarations, isCrossProcessSelfSnapshot } from './plugin-services/contracts';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { HostRpcAdapter, RpcServiceError, type HostRpcAdapterOptions, type HostRpcLifecycleIdentity, type HostRpcOwnerHandle, type HostRpcInvocationContext, type HostRpcLeaseRequest, type HostRpcLeaseGrant, type HostRpcHandlerFrame } from './plugin-services/host-rpc';\nimport type { RpcCallPurpose, RpcMethodDefinition } from './plugin-services/wire-contract';\nimport type { HostChannelOperation, HostChannelOwnerHandle, PluginChannelCapabilities, PluginChannelOwnerInput, PluginEventServices, PluginSnapshotServices, PluginStreamServices } from './plugin-services/channels';\nexport { defineRpcService } from './plugin-services/wire-contract';\nexport { RpcServiceError } from './plugin-services/host-rpc';\nexport { HostSnapshotStore, type HostSnapshotStoreOptions } from './plugin-services/snapshot-store';\nexport type { AsyncRpcClient, HostRpcCommandCapabilities, RpcCallOptions, RpcServiceErrorCode } from './plugin-services/host-rpc';\nexport type { RpcHandlerMap, RpcHandlerContext } from './plugin-services/rpc-runtime';\nexport type { RpcDataSchema, RpcMethodDefinition, InferRpcData } from './plugin-services/wire-contract';\nexport type { PluginServiceDeclarations, PluginServicePublication, PluginServiceConsumption, PluginServiceProcess, PluginServiceKind, PluginServiceScope } from './plugin-services/contracts';\nexport type {\n PluginStreamServices, PluginSnapshotServices, PluginEventServices, PluginStreamContract, PluginSnapshotContract,\n PluginEventContract, PluginChannelPublication, PluginStreamReadInput, PluginStreamWriteInput, PluginStreamDuplexInput,\n PluginSnapshotView, PluginSnapshotStatus, PluginEventPublisher, PluginChannelCapabilities, HostChannelPublicationView,\n PluginSnapshotVersionSource, HostSnapshotStoreOptionsView,\n} from './plugin-services/channels';\nexport type { PluginChannelDuplexSession, PluginChannelDuplexResult } from './plugin-services/peer-channel-hub';\n\nconst CHANNEL_KINDS = new Set(['events', 'snapshot', 'stream']);\n\nexport interface PluginServices {\n /** Explicit owner-bound background invocation; never inherits a stale/request frame. */\n runBackground?<T>(run: () => T): T;\n onDispose(cleanup: () => void): void;\n publish<T extends object>(serviceId: string, contractVersion: number, implementation: T): void;\n consume<T extends object>(provider: string, serviceId: string, contractVersion: number): Readonly<T>;\n /** Typed asynchronous data-only services, when the host communication runtime is configured. */\n readonly rpc?: Pick<HostRpcOwnerHandle, 'publish' | 'consume'>;\n /** Bounded, cancelable chunked byte channels over the authenticated peer link. */\n readonly stream?: PluginStreamServices;\n /** Transient notifications and durable at-least-once topics. */\n readonly events?: PluginEventServices;\n /** Versioned immutable snapshots with digest verification. */\n readonly snapshot?: PluginSnapshotServices;\n /** Explicit deployment capabilities for the channel lanes (checked before declaring work). */\n readonly channelCapabilities?: PluginChannelCapabilities;\n}\n\nexport interface PluginServiceCommunications extends Omit<HostRpcAdapterOptions, 'process' | 'enterHostHandlerFrame'> {\n /** Real process/owner identity supplied by the runtime, never invented by the plugin. */\n readonly identity: (plugin: string, scope: string) => HostRpcLifecycleIdentity;\n /**\n * Trusted host hook, called for one declared RPC consumption before the\n * adapter resolves its route. It lets the host register the native remote\n * proxy for the consumer's own contract so `resolvePlacement` can select it.\n * A host that does not implement remote routing simply omits it.\n */\n readonly ensureRemoteRoute?: (input: {\n readonly plugin: string;\n readonly scope: string;\n readonly provider: string;\n readonly contract: { readonly id: string; readonly version: number; readonly methods: Record<string, RpcMethodDefinition> };\n }) => void;\n /**\n * Host-owned event/snapshot/stream adapter. It is created by the same process\n * composition that owns the peer link, so channel work rides the one\n * authenticated transport and the canonical owner lifecycle.\n */\n readonly channels?: (input: PluginChannelOwnerInput) => HostChannelOwnerHandle;\n}\nexport interface PluginServiceInvocation {\n readonly purpose: RpcCallPurpose;\n /** Exact pre-admission lease returned by this host; request/attempt require it. */\n readonly lease?: () => void;\n readonly callee?: unknown;\n readonly signal?: AbortSignal;\n readonly deadlineAt?: number;\n}\ninterface LeaseProof { readonly retained: ReadonlySet<Owner>; released: boolean }\ninterface InvocationFrame extends HostRpcInvocationContext { readonly proof?: LeaseProof; readonly callee?: unknown; readonly ownerAuthority?: Owner; readonly peerAuthenticated?: boolean }\ninterface RpcReference { readonly owner: Owner }\n\ntype Owner = {\n plugin: string; scope: string; dependencies: Readonly<Record<string, string>>;\n ready: boolean; retiring: boolean; revoked: boolean; cleaning: boolean; leases: number;\n pending: Set<Promise<unknown>>; waiters: Array<() => void>; cleanups: Set<() => void>;\n consumed: Set<Owner>;\n rpcConsumed: Map<string, RpcReference>;\n rpc?: HostRpcOwnerHandle;\n channels?: HostChannelOwnerHandle;\n};\ntype Publication = { owner: Owner; id: string; version: number; kind: 'local' | 'rpc'; implementation?: object };\n\n/** Cleanup failed after the context was fully revoked; runtime teardown must still run. */\nexport class PluginServiceCleanupError extends AggregateError {\n constructor(failures: readonly unknown[]) { super(failures, 'Plugin service cleanup failed'); }\n}\n\nexport class PluginServiceHost {\n readonly rpc?: HostRpcAdapter;\n private readonly frames = new AsyncLocalStorage<InvocationFrame>();\n private readonly leaseProofs = new WeakMap<() => void, LeaseProof>();\n private readonly liveInvocations = new WeakSet<object>();\n private readonly ownerTokens = new WeakSet<object>();\n private readonly disposals = new WeakMap<Owner, Promise<void>>();\n private readonly communications?: PluginServiceCommunications;\n constructor(readonly process: PluginServiceProcess = 'worker', communications?: PluginServiceCommunications) {\n this.communications = communications;\n if (communications) this.rpc = new HostRpcAdapter({\n ...communications, process,\n enterHostHandlerFrame: (hostFrame, run) => this.runHostHandlerFrame(hostFrame, run),\n });\n }\n private contracts?: ReadonlyMap<string, PluginServiceDeclarations>;\n setDeclarations(contracts: ReadonlyMap<string, PluginServiceDeclarations>): void {\n for (const declarations of contracts.values()) assertSupportedServiceDeclarations(declarations);\n this.contracts = new Map(contracts);\n }\n /** Trusted host view of the declared service graph; never exposed to plugins. */\n serviceDeclarations(): ReadonlyMap<string, PluginServiceDeclarations> { return this.contracts ?? new Map(); }\n private owners = new Map<string, Owner>();\n private contexts = new WeakMap<PluginServices, Owner>();\n private publications = new Map<string, Publication>();\n private key(plugin: string, scope: string): string { return `${plugin}\\0${scope}`; }\n private publicationKey(plugin: string, scope: string, id: string, version: number): string {\n return `${plugin}\\0${scope}\\0${id}\\0${version}`;\n }\n isReady(plugin: string, scope = 'global'): boolean {\n const owner = this.owners.get(this.key(plugin, scope));\n return !!owner?.ready && !owner.retiring && !owner.revoked;\n }\n /** Trusted runtime entry; not exposed through PluginServices. */\n runInInvocation<T>(context: PluginServices, invocation: PluginServiceInvocation, run: () => T): T {\n const owner = this.contexts.get(context);\n if (!owner || owner.revoked || this.owners.get(this.key(owner.plugin, owner.scope)) !== owner) throw new RpcServiceError('unauthorized');\n const proof = invocation.lease === undefined ? undefined : this.leaseProofs.get(invocation.lease);\n if (invocation.purpose === 'request' || invocation.purpose === 'attempt') {\n if (!proof || proof.released || !proof.retained.has(owner)) throw new RpcServiceError('unauthorized');\n } else if (owner.retiring) throw new RpcServiceError('retired');\n const frame: InvocationFrame = Object.freeze({ ...invocation, proof, token: Object.freeze({}) });\n this.liveInvocations.add(frame.token);\n return this.frames.run(frame, () => {\n try {\n const result = run();\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as { then?: unknown }).then === 'function') {\n return Promise.resolve(result).finally(() => this.liveInvocations.delete(frame.token)) as T;\n }\n this.liveInvocations.delete(frame.token);\n return result;\n } catch (error) { this.liveInvocations.delete(frame.token); throw error; }\n });\n }\n /** Broker-only entry after physical-peer and per-call identity projection. */\n runPeerInvocation<T>(purpose: 'request' | 'attempt', callee: unknown, run: () => T): T {\n const frame: InvocationFrame = Object.freeze({purpose, callee, peerAuthenticated: true, token: Object.freeze({})});\n this.liveInvocations.add(frame.token);\n return this.frames.run(frame, () => {\n try {\n const result = run();\n if (result && typeof (result as any).then === 'function') return Promise.resolve(result).finally(() => this.liveInvocations.delete(frame.token)) as T;\n this.liveInvocations.delete(frame.token); return result;\n } catch (error) { this.liveInvocations.delete(frame.token); throw error; }\n });\n }\n /** Read by the trusted callee resolver to carry management/request authority. */\n currentInvocation(): Readonly<HostRpcInvocationContext & { readonly callee?: unknown }> | null {\n const frame = this.frames.getStore();\n return frame === undefined || !this.liveInvocations.has(frame.token) ? null : Object.freeze({ purpose: frame.purpose, token: frame.token, signal: frame.signal, deadlineAt: frame.deadlineAt, callee: frame.callee });\n }\n /**\n * Enters one live host-handler frame bound to the exact published owner, so a\n * native RPC handler shares the SAME trusted invocation store as local\n * dispatch. The frame is live only for the handler's real duration; a stale\n * (settled) frame is therefore never observable.\n */\n private runHostHandlerFrame(host: HostRpcHandlerFrame, run: () => unknown): unknown {\n const owner = host.ownerToken !== null && this.ownerTokens.has(host.ownerToken) ? host.ownerToken as Owner : undefined;\n const frame: InvocationFrame = Object.freeze({\n purpose: host.purpose,\n token: Object.freeze({}),\n ...(host.signal === undefined ? {} : { signal: host.signal }),\n ...(host.deadlineAt === undefined ? {} : { deadlineAt: host.deadlineAt }),\n ...(owner === undefined ? {} : { ownerAuthority: owner }),\n });\n this.liveInvocations.add(frame.token);\n const settle = (): void => { this.liveInvocations.delete(frame.token); };\n return this.frames.run(frame, () => {\n try {\n const result = run();\n if (result !== null && (typeof result === 'object' || typeof result === 'function') && typeof (result as { then?: unknown }).then === 'function') {\n return Promise.resolve(result).finally(settle);\n }\n settle();\n return result;\n } catch (error) { settle(); throw error; }\n });\n }\n createContext(plugin: string, scope = 'global', dependencies: Readonly<Record<string, string>> = {}): PluginServices {\n const key = this.key(plugin, scope);\n if (this.owners.has(key)) throw new Error(`Service context already exists: ${plugin}/${scope}`);\n const declarations = this.contracts?.get(plugin);\n if (!this.rpc && (declarations?.provides?.some(service => service.process === this.process && service.kind === 'rpc')\n || declarations?.consumes?.some(service => service.process === this.process && service.kind === 'rpc'))) {\n throw new RpcServiceError('capability_unavailable');\n }\n const channelProvider = declarations?.provides?.some(service => service.process === this.process && CHANNEL_KINDS.has(service.kind ?? 'local')) === true;\n const channelConsumer = declarations?.consumes?.some(service => service.process === this.process && CHANNEL_KINDS.has(service.kind ?? 'local')) === true;\n // A declared channel provider or required consumer without the host channel\n // adapter is refused here (capability_unavailable), never silently degraded.\n if ((channelProvider || channelConsumer) && this.communications?.channels === undefined) {\n throw new RpcServiceError('capability_unavailable');\n }\n const owner: Owner = { plugin, scope, dependencies: Object.freeze({ ...dependencies }), consumed: new Set(), rpcConsumed: new Map(), ready: false, retiring: false, revoked: false, cleaning: false, leases: 0, pending: new Set(), waiters: [], cleanups: new Set() };\n this.owners.set(key, owner);\n this.ownerTokens.add(owner);\n try {\n if (this.rpc) {\n owner.rpc = this.rpc.createOwner({\n token: owner, plugin, scope, dependencies: owner.dependencies,\n declarations: this.contracts?.get(plugin) ?? {}, lifecycle: this.communications!.identity(plugin, scope),\n getLifecycleState: () => ({ ready: owner.ready, retiring: owner.retiring, revoked: owner.revoked }),\n acquireLease: request => this.acquireRpcLease(owner, request),\n resolveInvocationContext: () => this.currentInvocation(),\n registerPublication: publication => {\n const publicationKey = this.publicationKey(plugin, scope, publication.id, publication.version);\n if (this.publications.has(publicationKey)) throw new RpcServiceError('invalid_registration');\n this.publications.set(publicationKey, { owner, id: publication.id, version: publication.version, kind: 'rpc' });\n },\n registerConsumption: (declaration, providerToken) => {\n const referenceKey = this.publicationKey(declaration.plugin, 'global', declaration.id, declaration.version);\n if (providerToken) {\n const provider = [...this.owners.values()].find(candidate => candidate === providerToken);\n if (!provider || provider.revoked) throw new RpcServiceError('unavailable');\n owner.rpcConsumed.set(referenceKey, { owner: provider });\n } else owner.rpcConsumed.delete(referenceKey);\n },\n });\n }\n if (this.communications?.channels !== undefined && (channelProvider || channelConsumer)) {\n owner.channels = this.communications.channels({\n plugin, scope, declarations: this.contracts?.get(plugin) ?? {},\n dependencies: owner.dependencies,\n lifecycle: this.communications.identity(plugin, scope),\n getLifecycleState: () => ({ ready: owner.ready, retiring: owner.retiring, revoked: owner.revoked }),\n trackPending: (pending: Promise<unknown>) => {\n owner.pending.add(pending);\n void pending.finally(() => { owner.pending.delete(pending); this.notify(owner); }).catch(() => {});\n },\n beginOperation: (options) => this.beginChannelOperation(plugin, scope, options),\n });\n }\n } catch (error) { this.owners.delete(key); throw error; }\n const assertActive = (target = owner) => {\n if (target.revoked || (target.retiring && !target.cleaning && !owner.cleaning && target.leases === 0 && target.pending.size === 0)) throw new Error(`Plugin service handle revoked: ${target.plugin}`);\n };\n const wrap = (value: unknown, provider: Owner, receiver?: object): any => {\n if (typeof value === 'function') return (...args: unknown[]) => {\n assertActive(); assertActive(provider);\n const guardArgument = (arg: unknown): unknown => {\n if (typeof arg === 'function') return (...callbackArgs: unknown[]) => {\n assertActive(); assertActive(provider);\n const result = Reflect.apply(arg, undefined, callbackArgs);\n if (result && typeof result.then === 'function') {\n const pending = Promise.resolve(result);\n owner.pending.add(pending); provider.pending.add(pending);\n void pending.finally(() => { owner.pending.delete(pending); provider.pending.delete(pending); this.notify(owner); this.notify(provider); }).catch(() => {});\n return pending;\n }\n return result;\n };\n if (Array.isArray(arg)) return Object.freeze(arg.map(guardArgument));\n if (arg && typeof arg === 'object') return Object.freeze(Object.fromEntries(Object.entries(arg).map(([key, value]) => [key, guardArgument(value)])));\n return arg;\n };\n const guarded = args.map(guardArgument);\n const result = Reflect.apply(value, receiver, guarded);\n if (result && typeof result.then === 'function') {\n const pending = Promise.resolve(result).then(output => { assertActive(); assertActive(provider); return wrap(output, provider); });\n owner.pending.add(pending); provider.pending.add(pending);\n void pending.finally(() => { owner.pending.delete(pending); provider.pending.delete(pending); this.notify(owner); this.notify(provider); }).catch(() => {});\n return pending;\n }\n return wrap(result, provider);\n };\n if (Array.isArray(value)) return Object.freeze(value.map(item => wrap(item, provider)));\n if (value && typeof value === 'object') {\n // A fresh facade prevents access to implementation identity or mutable provider fields.\n const facade: Record<string, unknown> = {};\n for (const key of Object.keys(value)) Object.defineProperty(facade, key, {\n enumerable: true, get: () => { assertActive(); assertActive(provider); return wrap((value as any)[key], provider, value as object); },\n });\n return Object.freeze(facade);\n }\n return value;\n };\n const consume = <T extends object>(provider: string, id: string, version: number): Readonly<T> => {\n assertActive();\n const declaration = this.contracts?.get(plugin)?.consumes?.find(value => value.plugin === provider && value.id === id && value.version === version && value.process === this.process);\n if (this.contracts && !declaration) throw new Error(`Undeclared plugin service consumption: ${plugin} -> ${provider}/${id}`);\n if (declaration?.kind && declaration.kind !== 'local') throw new Error('Non-local services require their asynchronous host adapter');\n if (provider === plugin || !Object.hasOwn(owner.dependencies, provider)) throw new Error(`Undeclared plugin service dependency: ${plugin} -> ${provider}`);\n const targetScope = 'global';\n const publication = this.publications.get(this.publicationKey(provider, targetScope, id, version));\n if (!publication || !publication.owner.ready || publication.owner.retiring || publication.owner.revoked) {\n if ([...this.publications.values()].some(value => value.owner.plugin === provider && value.owner.scope === targetScope && value.id === id && value.version !== version)) throw new Error(`Plugin service contract mismatch: ${provider}/${id}`);\n throw new Error(`Plugin service not ready: ${provider}/${id}`);\n }\n owner.consumed.add(publication.owner);\n return wrap(publication.implementation, publication.owner);\n };\n const context: PluginServices = Object.freeze({\n runBackground: <T>(run: () => T): T => {\n if (this.contexts.get(context) !== owner || this.owners.get(key) !== owner\n || !owner.ready || owner.retiring || owner.revoked) throw new RpcServiceError('retired');\n const release = this.acquireLease(plugin, scope);\n try {\n const result = this.runInInvocation(context, { purpose: 'background' }, run);\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as { then?: unknown }).then === 'function') {\n return Promise.resolve(result).finally(release) as T;\n }\n release();\n return result;\n } catch (error) { release(); throw error; }\n },\n onDispose: (cleanup: () => void) => { assertActive(); owner.cleanups.add(cleanup); },\n publish: <T extends object>(id: string, version: number, implementation: T) => {\n assertActive();\n const candidates = this.contracts?.get(plugin)?.provides?.filter(value => value.id === id && value.version === version && value.process === this.process);\n const declaration = candidates?.[0];\n if (this.contracts && !declaration) throw new Error(`Undeclared plugin service publication: ${plugin}/${id}`);\n if (declaration?.kind && declaration.kind !== 'local') throw new Error('Non-local services require their asynchronous host adapter');\n if (owner.scope !== 'global') throw new Error('Only global providers may publish global services');\n if (!Number.isSafeInteger(version) || version < 1) throw new Error('Invalid service contract version');\n const publicationKey = this.publicationKey(plugin, owner.scope, id, version);\n if (this.publications.has(publicationKey)) throw new Error(`Service already published: ${plugin}/${id}`);\n this.publications.set(publicationKey, { owner, id, version, implementation, kind: 'local' });\n },\n consume: <T extends object>(provider: string, id: string, version: number): Readonly<T> => consume<T>(provider, id, version),\n rpc: owner.rpc === undefined ? undefined : (() => {\n const ownerHandle = owner.rpc!;\n const prepare = (provider: string, contract: { readonly id: string; readonly version: number; readonly methods: Record<string, RpcMethodDefinition> }): void => {\n try { this.communications?.ensureRemoteRoute?.({ plugin, scope: owner.scope, provider, contract }); }\n catch { /* an unroutable remote declaration stays unavailable, never guessed */ }\n };\n return Object.freeze({\n publish: ownerHandle.publish,\n consume: <const M extends Record<string, RpcMethodDefinition>>(provider: string, contract: { readonly id: string; readonly version: number; readonly methods: M }) => {\n prepare(provider, contract);\n return ownerHandle.consume(provider, contract);\n },\n });\n })(),\n stream: owner.channels?.stream,\n events: owner.channels?.events,\n snapshot: owner.channels?.snapshot,\n channelCapabilities: owner.channels?.capabilities,\n });\n this.contexts.set(context, owner);\n return context;\n }\n markReady(plugin: string, scope = 'global', expectedContext?: PluginServices): void {\n const owner = this.requireOwner(plugin, scope, expectedContext);\n if (owner.retiring || owner.revoked) throw new Error(`Plugin service disposed: ${plugin}`);\n for (const publication of this.contracts?.get(plugin)?.provides ?? []) {\n if (publication.kind === 'rpc' && publication.process === this.process && (publication.scope ?? 'global') === (scope === 'global' ? 'global' : 'binding')\n && this.publications.get(this.publicationKey(plugin, scope, publication.id, publication.version))?.kind !== 'rpc') throw new RpcServiceError('not_ready');\n }\n owner.rpc?.markReady();\n owner.channels?.markReady();\n owner.ready = true;\n }\n retire(plugin: string, scope = 'global', expectedContext?: PluginServices): void {\n const owner = this.requireOwner(plugin, scope, expectedContext);\n owner.retiring = true;\n owner.rpc?.retire();\n try { owner.channels?.retire(); } catch { /* host-owned */ }\n }\n /**\n * Host-only: retires admission for EVERY live owner at once. It is wired to\n * the real drain admission point, so after it no new bootstrap/background work\n * is admitted while every already-accepted lease, result and terminal keeps\n * draining normally (nothing is revoked here).\n */\n retireAll(): void {\n for (const owner of this.owners.values()) {\n if (owner.revoked) continue;\n owner.retiring = true;\n try { owner.rpc?.retire(); } catch { /* host-owned */ }\n try { owner.channels?.retire(); } catch { /* host-owned */ }\n }\n }\n /**\n * Host-only: begins ONE channel operation for an owner. It applies the exact\n * same invocation-frame rules as an RPC call (management only from a\n * management frame, request/attempt only with a live retained lease proof, no\n * new work while retiring, bootstrap-only before ready) and holds a real\n * owner lease for the operation's whole lifetime, so owner disposal can never\n * race a live lane task. `null` refuses the operation.\n */\n beginChannelOperation(\n plugin: string,\n scope = 'global',\n incoming?: {\n readonly purpose?: RpcCallPurpose;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n readonly authenticated?: boolean;\n /**\n * Host-managed background work: the operation runs in an EXPLICIT\n * independent background context and deliberately ignores any frame the\n * caller happens to be inside (typically a closed bootstrap/init closure).\n */\n readonly background?: boolean;\n },\n ): HostChannelOperation | null {\n const owner = this.owners.get(this.key(plugin, scope));\n if (!owner || owner.revoked) return null;\n if (this.owners.get(this.key(plugin, scope)) !== owner) return null;\n const stored = this.frames.getStore();\n let frame: InvocationFrame | undefined;\n if (incoming?.background === true) {\n // Explicit Host background context: no inherited purpose/deadline/signal.\n frame = undefined;\n } else {\n // A stale (already settled) frame is REFUSED: a finished invocation must\n // never be reused as fresh authority nor laundered into another purpose.\n // Legitimate background work either runs outside a frame or asks for the\n // explicit Host background context above.\n if (stored !== undefined && !this.liveInvocations.has(stored.token)) return null;\n frame = stored;\n }\n const leaseBound = frame !== undefined\n && (frame.purpose === 'request' || frame.purpose === 'attempt')\n && ((frame.proof !== undefined && !frame.proof.released && frame.proof.retained.has(owner))\n || frame.ownerAuthority === owner);\n if (frame !== undefined && (frame.purpose === 'request' || frame.purpose === 'attempt') && !leaseBound) return null;\n // A peer-authenticated inbound channel request carries the caller host's real\n // purpose, but only request/attempt/background may cross that boundary: a peer\n // may never claim management or bootstrap authority for a provider lease.\n const peerPurpose = frame === undefined && incoming?.authenticated === true\n && (incoming.purpose === 'request' || incoming.purpose === 'attempt' || incoming.purpose === 'background')\n ? incoming.purpose\n : undefined;\n const purpose = frame?.purpose ?? peerPurpose ?? 'background';\n const requestBound = leaseBound || peerPurpose === 'request' || peerPurpose === 'attempt';\n // Retirement refuses NEW work; already-accepted request/attempt work finishes.\n if (owner.retiring && !requestBound) return null;\n if (!owner.ready && !requestBound && purpose !== 'bootstrap') return null;\n const deadlineAt = minDefined(frame?.deadlineAt, incoming?.deadlineAt);\n const signal = combineAbortSignals(frame?.signal, incoming?.signal);\n owner.leases += 1;\n let released = false;\n const release = () => { if (released) return; released = true; owner.leases -= 1; this.notify(owner); };\n return Object.freeze({\n purpose,\n ...(signal === undefined ? {} : { signal }),\n ...(deadlineAt === undefined ? {} : { deadlineAt }),\n release,\n });\n }\n\n /** Capture before admission; release only after all consumers finish old-request processing. */\n acquireLease(plugin: string, scope = 'global'): () => void {\n const owner = this.requireOwner(plugin, scope);\n if (!owner.ready || owner.retiring || owner.revoked) throw new Error(`Plugin service not ready: ${plugin}`);\n const retained = new Set<Owner>();\n const retain = (target: Owner): void => {\n if (retained.has(target)) return;\n if (!target.ready || target.retiring || target.revoked) throw new Error(`Plugin service not ready: ${target.plugin}`);\n retained.add(target);\n for (const provider of this.dependencyOwners(target)) retain(provider);\n for (const provider of target.consumed) if (provider.ready && !provider.retiring && !provider.revoked) retain(provider);\n // A declared in-process channel provider is an exact required\n // reference too, and its ready provider owner enters the lease proof so a\n // request/attempt frame can authorize real channel work on it.\n for (const provider of this.channelDependencyOwners(target)) {\n if (provider.ready && !provider.retiring && !provider.revoked) retain(provider);\n }\n for (const reference of target.rpcConsumed.values()) retain(reference.owner);\n };\n retain(owner);\n for (const target of retained) target.leases++;\n let released = false;\n const proof: LeaseProof = { retained, released: false };\n const release = () => { if (released) return; released = true; proof.released = true; for (const target of retained) { target.leases--; this.notify(target); } };\n this.leaseProofs.set(release, proof);\n return release;\n }\n\n references(plugin: string): ReadonlyArray<{ plugin: string; scope: string; leases: number }> {\n return [...this.owners.values()].filter(o => !o.revoked && (o.plugin === plugin || [...this.dependencyOwners(o), ...this.consumedOwners(o)].some(provider => provider.plugin === plugin)))\n .map(o => Object.freeze({ plugin: o.plugin, scope: o.scope, leases: o.leases }));\n }\n /** Stop admission immediately, preserve acquired handles until leases and calls drain. */\n dispose(plugin: string, scope = 'global', expectedContext?: PluginServices): Promise<void> {\n let owner: Owner;\n try { owner = this.requireOwner(plugin, scope, expectedContext); } catch (error) { return Promise.reject(error); }\n const existing = this.disposals.get(owner);\n if (existing) return existing;\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n const task = new Promise<void>((accept, fail) => { resolve = accept; reject = fail; });\n // Install before cleanup can synchronously re-enter disposal.\n this.disposals.set(owner, task);\n void this.disposeOwner(owner).then(() => {\n this.disposals.delete(owner); resolve();\n }, error => { this.disposals.delete(owner); reject(error); });\n return task;\n }\n private async disposeOwner(owner: Owner): Promise<void> {\n const { plugin, scope } = owner;\n const hasPublications = [...this.publications.values()].some(publication => publication.owner === owner);\n if (hasPublications) {\n const dependents = [...this.owners.values()].filter(candidate => candidate !== owner && !candidate.revoked && (this.dependencyOwners(candidate).includes(owner) || this.consumedOwners(candidate).includes(owner)));\n if (dependents.length) throw new Error(`Plugin service provider is referenced: ${plugin} <- ${dependents.map(candidate => `${candidate.plugin}/${candidate.scope}`).join(', ')}`);\n }\n owner.retiring = true;\n owner.rpc?.retire();\n try { owner.channels?.retire(); } catch { /* host-owned */ }\n if (owner.leases || owner.pending.size) await new Promise<void>(resolve => owner.waiters.push(resolve));\n if (owner.channels) {\n try { await owner.channels.dispose(); } catch { /* provider release is best-effort here */ }\n }\n if (owner.rpc) {\n const result = await owner.rpc.dispose();\n if (!result.drained) throw new RpcServiceError('timeout');\n }\n // Cleanup may invoke its cached unsubscribe handle after drain, before final revocation.\n owner.cleaning = true;\n const failures: unknown[] = [];\n try {\n for (const cleanup of owner.cleanups) { try { cleanup(); } catch (error) { failures.push(error); } }\n } finally {\n owner.cleanups.clear(); owner.consumed.clear(); owner.rpcConsumed.clear(); owner.cleaning = false;\n owner.revoked = true; owner.ready = false;\n for (const [key, publication] of this.publications) if (publication.owner === owner) this.publications.delete(key);\n if (this.owners.get(this.key(plugin, scope)) === owner) this.owners.delete(this.key(plugin, scope));\n }\n if (failures.length) throw new PluginServiceCleanupError(failures);\n }\n /** Actual local provider owners, not activation edges to another process/binding. */\n private dependencyOwners(owner: Owner): Owner[] {\n const result = new Set<Owner>();\n for (const dependency of Object.keys(owner.dependencies)) {\n const declarations = this.contracts?.get(owner.plugin)?.consumes?.filter(service => service.plugin === dependency && service.process === this.process);\n if (declarations?.length) {\n for (const service of declarations) {\n // RPC providers are retained through `rpcConsumed`/`acquireRpcLease`,\n // never here. A local channel provider (events/snapshot/stream) IS a\n // real provider owner, so a request/attempt lease must retain it too,\n // or `beginChannelOperation` would refuse exact in-process channel work.\n if ((service.kind ?? 'local') === 'rpc') continue;\n const provider = this.owners.get(this.key(dependency, 'global'));\n if (provider) result.add(provider);\n }\n } else {\n const provider = this.owners.get(this.key(dependency, 'global'));\n if (provider) result.add(provider);\n }\n }\n return [...result];\n }\n /** Local providers of this owner's declared channel consumptions. */\n private channelDependencyOwners(owner: Owner): Owner[] {\n const result = new Set<Owner>();\n for (const service of this.contracts?.get(owner.plugin)?.consumes ?? []) {\n if (service.process !== this.process) continue;\n if (!CHANNEL_KINDS.has(service.kind ?? 'local')) continue;\n if (typeof service.plugin !== 'string' || !service.plugin) continue;\n if (isCrossProcessSelfSnapshot(owner.plugin, service, this.contracts?.get(owner.plugin) ?? {})) continue;\n if (!Object.hasOwn(owner.dependencies, service.plugin)) continue;\n const provider = this.owners.get(this.key(service.plugin, 'global'));\n if (provider) result.add(provider);\n }\n return [...result];\n }\n /** Consumers release all actual references before providers. */\n disposalOrder(): ReadonlyArray<{ plugin: string; scope: string }> {\n const visited = new Set<Owner>(), visiting = new Set<Owner>(), ordered: Owner[] = [];\n const visit = (owner: Owner): void => {\n if (visited.has(owner)) return;\n if (visiting.has(owner)) throw new Error('Plugin service reference cycle during disposal');\n visiting.add(owner);\n for (const provider of [...this.dependencyOwners(owner), ...this.consumedOwners(owner)]) if (!provider.revoked) visit(provider);\n visiting.delete(owner); visited.add(owner); ordered.push(owner);\n };\n for (const owner of this.owners.values()) visit(owner);\n return ordered.reverse().map(owner => Object.freeze({ plugin: owner.plugin, scope: owner.scope }));\n }\n private requireOwner(plugin: string, scope: string, expectedContext?: PluginServices): Owner {\n const owner = this.owners.get(this.key(plugin, scope));\n if (!owner) throw new Error(`Missing plugin service context: ${plugin}/${scope}`);\n if (expectedContext && this.contexts.get(expectedContext) !== owner) throw new Error(`Stale plugin service context: ${plugin}/${scope}`);\n return owner;\n }\n private notify(owner: Owner): void {\n if (!owner.leases && !owner.pending.size) for (const resolve of owner.waiters.splice(0)) resolve();\n }\n private consumedOwners(owner: Owner): Owner[] {\n return [...new Set([...owner.consumed, ...[...owner.rpcConsumed.values()].map(reference => reference.owner)])];\n }\n /** Each real RPC task borrows the canonical owner until actual business work settles. */\n private acquireRpcLease(owner: Owner, request: HostRpcLeaseRequest): HostRpcLeaseGrant {\n if (owner.revoked || this.owners.get(this.key(owner.plugin, owner.scope)) !== owner) throw new RpcServiceError('revoked');\n const frame = this.frames.getStore();\n if (frame && !this.liveInvocations.has(frame.token)) throw new RpcServiceError('unauthorized');\n if (request.purpose === 'management' && frame?.purpose !== 'management') throw new RpcServiceError('unauthorized');\n const existing = (request.purpose === 'request' || request.purpose === 'attempt')\n && frame?.purpose === request.purpose && ((frame.proof !== undefined && !frame.proof.released && frame.proof.retained.has(owner)) || (request.role === 'callee' && frame.peerAuthenticated === true));\n if ((request.purpose === 'request' || request.purpose === 'attempt') && !existing) throw new RpcServiceError('unauthorized');\n if (owner.retiring && !existing) throw new RpcServiceError('retired');\n if (!owner.ready && request.purpose !== 'bootstrap') throw new RpcServiceError('not_ready');\n owner.leases++;\n let released = false;\n return { allowRetired: existing, release: () => { if (released) return; released = true; owner.leases--; this.notify(owner); } };\n }\n}\n\n/** Smallest defined deadline, or undefined when neither side has one. */\nfunction minDefined(left: number | undefined, right: number | undefined): number | undefined {\n if (left === undefined) return right;\n if (right === undefined) return left;\n return Math.min(left, right);\n}\n\n/** Combines local and peer-provided abort signals without dropping either. */\nfunction combineAbortSignals(...signals: ReadonlyArray<AbortSignal | undefined>): AbortSignal | undefined {\n const present = signals.filter((signal): signal is AbortSignal => signal !== undefined);\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n const any = (AbortSignal as unknown as { any?: (list: readonly AbortSignal[]) => AbortSignal }).any;\n if (typeof any === 'function') return any.call(AbortSignal, present);\n const controller = new AbortController();\n const abort = (signal: AbortSignal) => { if (!controller.signal.aborted) controller.abort(signal.reason); };\n for (const signal of present) {\n if (signal.aborted) { abort(signal); break; }\n signal.addEventListener('abort', () => abort(signal), { once: true });\n }\n return controller.signal;\n}\n\nexport const TOKEN_METERING_SERVICE_ID = 'token-metering.v1';\nexport const TOKEN_METERING_CONTRACT_VERSION = 1;\nexport type TokenMeteringSource = 'official' | 'estimated' | 'partial' | 'none';\nexport type TokenMeteringAuthority = 'official' | 'local' | 'heuristic' | 'partial' | 'none';\nexport interface TokenMeteringResult {\n readonly requestId: string; readonly attemptId: string; readonly routeId: string; readonly upstreamId: string;\n readonly keyId?: string | null;\n readonly provider: string; readonly model?: string; readonly pricingProvider?: string;\n readonly inputTokens?: number; readonly outputTokens?: number; readonly cacheReadTokens?: number; readonly cacheWriteTokens?: number;\n readonly inputSource: TokenMeteringSource; readonly outputSource: TokenMeteringSource;\n readonly inputAuthority: TokenMeteringAuthority; readonly outputAuthority: TokenMeteringAuthority;\n readonly complete: boolean; readonly observationIncomplete: boolean;\n readonly outcome: 'completed' | 'failed' | 'aborted'; readonly finishedAtMs: number; readonly settlementVersion: number;\n}\nexport interface TokenMeteringSubscription {\n /** Omit for degradable all-request reporting; required consumers bind their admitted request. */\n readonly requestId?: string;\n readonly required?: boolean;\n readonly onResult: (result: TokenMeteringResult) => void | Promise<void>;\n readonly onFailure?: (error: unknown, result: TokenMeteringResult) => void | Promise<void>;\n}\nexport interface TokenMeteringService {\n /** Final completion boundary: await this request's required settlement/failure callbacks before releasing its host lease. */\n drainRequest(requestId: string): Promise<void>;\n subscribe(subscription: TokenMeteringSubscription): () => void;\n prepareAttempt(input: Readonly<{ requestId: string; attemptId: string; routeId: string; upstreamId: string; url: string; body: unknown }>): Readonly<{ supported: boolean; provider?: string; model?: string; pricingProvider?: string }>;\n /** Consumer calls before request admission to pin demand; framework init also captures report subscriptions. */\n prepareRequest(requestId: string): boolean;\n}\n\nexport const TOKEN_PRICING_SERVICE_ID = 'token-stats.pricing.v1';\nexport const TOKEN_PRICING_CONTRACT_VERSION = 1;\n/** Costs are quantized to safe integer nanoUSD (1 USD = 1e9 nanoUSD); unknown remains null. */\nexport interface TokenPricingService {\n canPrice(input: Readonly<{ model?: string; pricingProvider?: string }>): Promise<boolean>;\n price(result: TokenMeteringResult): Promise<Readonly<{ costUsd: number | null; costNanoUsd: number | null }>>;\n}\n",
|
|
17
|
+
"/** Declarative repair request; the host owns the next upstream attempt. */\nconst retryActionBrand=Symbol.for('@jeffusion/bungee/request-retry-action');\nexport class RequestRetryAction extends Error {\n readonly body:unknown;\n constructor(body: unknown, readonly reason: string) {\n super('gateway request repair retry');\n this.name = 'RequestRetryAction';\n Object.defineProperty(this,retryActionBrand,{value:true});\n Object.defineProperty(this,'body',{value:body,enumerable:false});\n }\n /** Plugins and host may bundle the SDK independently in the same process. */\n static [Symbol.hasInstance](value:unknown):boolean {\n return value instanceof Error && (value as unknown as Record<symbol,unknown>)[retryActionBrand]===true;\n }\n}\n",
|
|
18
|
+
"import type { TokenStatsRange } from './plugin.types';\n\nconst HOUR = 3_600_000;\nexport const TOKEN_STATS_RETENTION_MS = 31 * 24 * HOUR;\nexport const TOKEN_STATS_RANGES = ['1h', '12h', '24h', '1d', '7d', '30d', 'day', 'week', 'month'] as const;\n\n/** Recent page ranges are consecutive elapsed hours; calendar ranges use local dates. */\nexport function tokenStatsWindow(range: TokenStatsRange, asOfMs: number, timeZone = 'UTC') {\n if (range === '1h' || range === '12h' || range === '24h') {\n const duration = { '1h': HOUR, '12h': 12 * HOUR, '24h': 24 * HOUR };\n const bucketMs = { '1h': 300_000, '12h': HOUR, '24h': 2 * HOUR }[range];\n return { startMs: asOfMs - duration[range], endMs: asOfMs, bucketMs };\n }\n if (range === '1d' || range === '7d' || range === '30d') {\n const days = { '1d': 1, '7d': 7, '30d': 30 }[range];\n const bucketMs = range === '1d' ? HOUR : 24 * HOUR;\n const startMs = asOfMs - days * 24 * HOUR;\n const bucketStarts = Array.from({ length: range === '1d' ? 24 : days }, (_, i) => startMs + i * bucketMs);\n return { startMs, endMs: asOfMs, bucketMs, bucketStarts };\n }\n const format = new Intl.DateTimeFormat('en-US', {\n timeZone, year: 'numeric', month: 'numeric', day: 'numeric',\n hour: 'numeric', minute: 'numeric', second: 'numeric', hourCycle: 'h23',\n });\n const parts = (ms: number) => Object.fromEntries(format.formatToParts(ms)\n .filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));\n const today = parts(asOfMs);\n const day = Date.UTC(today.year!, today.month! - 1, today.day!);\n // Resolve each local midnight separately so DST days can contain 23 or 25 hours.\n const midnight = (date: number) => {\n let candidate = date;\n for (let i = 0; i < 4; i++) {\n const p = parts(candidate);\n const local = Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!, p.second!);\n const next = candidate + date - local;\n if (next === candidate) return candidate;\n candidate = next;\n }\n return candidate;\n };\n if (range === 'day') {\n const startMs = midnight(day);\n const bucketEndMs = midnight(day + 24 * HOUR);\n const bucketStarts = Array.from({ length: Math.ceil((bucketEndMs - startMs) / HOUR) }, (_, i) => startMs + i * HOUR);\n return { startMs, endMs: asOfMs, bucketMs: HOUR, bucketStarts, bucketEndMs };\n }\n const firstDay = range === 'month' ? Date.UTC(today.year!, today.month! - 1, 1)\n : day - ((new Date(day).getUTCDay() + 6) % 7) * 24 * HOUR;\n const nextPeriod = range === 'month' ? Date.UTC(today.year!, today.month!, 1) : firstDay + 7 * 24 * HOUR;\n const days = (nextPeriod - firstDay) / (24 * HOUR);\n const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));\n return { startMs: bucketStarts[0]!, endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };\n}\n",
|
|
19
|
+
"/**\n * Public contract of the models-dev catalog provider.\n *\n * This is the ONLY file other plugins may import from models-dev. It contains the\n * declared service identity, the wire-contract snapshot literal and the data types\n * of the read surface; it never exposes the downloader, the private storage keys or\n * the internal catalog representation.\n *\n * Consumers must declare a real dependency on `models-dev` and consume the local\n * service for their own process. The service methods are synchronous and read an\n * already-loaded in-memory view: no per-request network or SQL is performed.\n */\n\n/** Provider plugin name. Must match the manifest. */\nexport const MODELS_DEV_PLUGIN_NAME = 'models-dev';\n\n/** The single upstream source; models-dev is the only component allowed to fetch it. */\nexport const MODELS_DEV_SOURCE_URL = 'https://models.dev/api.json';\n\n/** Same-process local read service, published in both the control and worker processes. */\nexport const MODELS_DEV_CATALOG_SERVICE_ID = 'models-dev.catalog.v1';\nexport const MODELS_DEV_CATALOG_CONTRACT_VERSION = 1;\n\n/** Versioned immutable snapshot of the full catalog, published by the control writer. */\nexport const MODELS_DEV_CATALOG_SNAPSHOT_ID = 'models-dev.catalog.snapshot.v1';\nexport const MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT_VERSION = 1;\n/**\n * One atomic record keeps fetchedAt and the immutable catalog with its version.\n * The catalog remains unrestricted JSON so every upstream field is preserved.\n */\nexport const MODELS_DEV_CATALOG_SNAPSHOT_SCHEMA = Object.freeze({\n type: 'object', properties: {\n version: { type: 'number', integer: true, minimum: 1 },\n fetchedAt: { type: 'number', minimum: 0 },\n catalog: { type: 'json', maxBytes: 32 * 1024 * 1024 },\n },\n} as const);\nexport const MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT = Object.freeze({\n id: MODELS_DEV_CATALOG_SNAPSHOT_ID,\n version: MODELS_DEV_CATALOG_SNAPSHOT_CONTRACT_VERSION,\n content: MODELS_DEV_CATALOG_SNAPSHOT_SCHEMA,\n});\n\n/** Catalog availability is separate from whether the service is published. */\nexport type ModelsDevCatalogState = 'empty' | 'ready' | 'stale' | 'failed';\n\nexport interface ModelsDevCatalogStatus {\n readonly state: ModelsDevCatalogState;\n /** Monotonic published data version; `null` before the first successful load. */\n readonly version: number | null;\n readonly fetchedAt: number | null;\n readonly providerCount: number;\n readonly modelCount: number;\n /** Last failure reason; `null` after a fully successful load. */\n readonly error: string | null;\n}\n\nexport interface ModelsDevProviderSummary {\n readonly provider: string;\n readonly name: string;\n /** Normalized upstream API base (`provider.api`), or `null` when models.dev declares none. */\n readonly api: string | null;\n readonly modelCount: number;\n}\n\n/** One selectable catalog model. `provider` is the pricing provider, never the protocol. */\nexport interface ModelsDevModelOption {\n readonly provider: string;\n readonly providerName: string;\n readonly model: string;\n readonly name: string;\n}\n\nexport interface ModelsDevModelPage {\n readonly models: readonly ModelsDevModelOption[];\n readonly total: number;\n /** 1-based page actually returned. */\n readonly page: number;\n readonly pageSize: number;\n}\n\n/** USD per million tokens, applied to the whole request at this input threshold. */\nexport interface ModelsDevContextTier {\n readonly minimumInputTokens: number;\n readonly input: number;\n readonly output: number;\n readonly cacheRead: number | null;\n readonly cacheWrite: number | null;\n}\n\n/** A resolved catalog entry with optional ascending context price bands. */\nexport interface ModelsDevModelMatch {\n readonly provider: string;\n readonly model: string;\n readonly input: number;\n readonly output: number;\n readonly cacheRead: number | null;\n readonly cacheWrite: number | null;\n readonly tiered: boolean;\n readonly contextTiers?: readonly ModelsDevContextTier[];\n}\n\nexport interface ModelsDevProviderMatch {\n readonly provider: string;\n}\n\n/**\n * The declared local read surface. Implementations must be side-effect free and\n * must never throw for a miss/corruption of the current view: an unavailable\n * catalog returns an `empty`/`failed` status instead of a fabricated price.\n */\nexport interface ModelsDevCatalogService {\n status(): ModelsDevCatalogStatus;\n providers(): readonly ModelsDevProviderSummary[];\n modelOptions(input?: { readonly provider?: string; readonly search?: string; readonly page?: number; readonly pageSize?: number }): ModelsDevModelPage;\n /**\n * Resolve exactly one catalog entry for a client model name.\n *\n * `url` (when supplied) is canonicalized to host + path and matched against the\n * full catalog's `provider.api`; more than one candidate is ambiguous and returns\n * null. `pricingProvider` is a catalog provider id and takes priority over URL and\n * prefix inference. A model id present under several providers without an explicit\n * provider is ambiguous. Matching defaults to exact and case-sensitive.\n * `estimate` additionally permits normalized names, original-lab prices and\n * dated members of the same family. Explicit provider IDs remain binding;\n * an unresolved URL is only a hint in estimate mode.\n */\n resolveModel(input: { readonly model: string; readonly pricingProvider?: string; readonly url?: string; readonly mode?: 'exact' | 'estimate' }): ModelsDevModelMatch | null;\n /** Resolve one provider from a real upstream URL via `provider.api`; ambiguous/none => null. */\n resolveProvider(input: { readonly url: string }): ModelsDevProviderMatch | null;\n}\n\n/** Capability reads are additive; existing catalog.v1 consumers stay unchanged. */\nexport const MODELS_DEV_CAPABILITIES_SERVICE_ID = 'models-dev.capabilities.v1';\nexport const MODELS_DEV_CAPABILITIES_CONTRACT_VERSION = 1;\nexport interface ModelsDevCapabilities {\n readonly provider: string;\n readonly model: string;\n readonly name: string;\n readonly contextWindow: number | null;\n readonly outputLimit: number | null;\n readonly toolCall: boolean;\n readonly reasoning: boolean;\n readonly inputModalities: readonly string[];\n}\nexport interface ModelsDevCapabilitiesService {\n status(): ModelsDevCatalogStatus;\n model(input: { readonly provider: string; readonly model: string }): ModelsDevCapabilities | null;\n}\n",
|
|
20
|
+
"export interface ModelBinding {\n provider: string;\n model: string;\n alias?: string;\n target: { type: 'route' | 'service'; id: string };\n capabilityOverrides?: { contextWindow?: number; tools?: boolean; reasoning?: boolean; images?: boolean };\n}\nexport function parseBindings(value: unknown): readonly ModelBinding[] {\n if (value === undefined) return [];\n if (!Array.isArray(value) || value.length > 100) throw new Error('codex_router_invalid_bindings');\n const ids = new Set<string>();\n return Object.freeze(value.map(entry => {\n if (!entry || typeof entry !== 'object' || Array.isArray(entry)\n || Object.keys(entry).some(key => !['provider','model','alias','target','capabilityOverrides'].includes(key))) throw new Error('codex_router_invalid_bindings');\n for (const text of [entry.provider, entry.model, ...(entry.alias === undefined ? [] : [entry.alias])]) {\n if (typeof text !== 'string' || !text || text !== text.trim() || text.length > 512 || /[\\x00-\\x1f\\x7f]/.test(text)) throw new Error('codex_router_invalid_bindings');\n }\n const target = entry.target;\n if (!target || !['route','service'].includes(target.type) || typeof target.id !== 'string' || !target.id\n || Object.keys(target).some(key => !['type','id'].includes(key))) throw new Error('codex_router_invalid_target');\n const publicId = entry.alias ?? entry.model;\n if (ids.has(publicId)) throw new Error('codex_router_model_conflict');\n ids.add(publicId);\n const overrides = entry.capabilityOverrides;\n if (overrides !== undefined) {\n if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) throw new Error('codex_router_invalid_capabilities');\n for (const [key, val] of Object.entries(overrides)) {\n if (key === 'contextWindow' ? typeof val !== 'number' || !Number.isSafeInteger(val) || val < 1\n : !['tools','reasoning','images'].includes(key) || typeof val !== 'boolean') throw new Error('codex_router_invalid_capabilities');\n }\n }\n return Object.freeze(structuredClone(entry)) as ModelBinding;\n }));\n}\n",
|
|
21
|
+
"import { createHash } from 'node:crypto';\nimport type { ModelsDevCapabilitiesService } from '../../models-dev/contract';\nimport type { ModelBinding } from './config';\nimport template from './model-template-0.160.1.json';\n\nexport function mergeCatalog(native: unknown, bindings: readonly ModelBinding[], catalog: ModelsDevCapabilitiesService): unknown {\n if (!native || typeof native !== 'object' || Array.isArray(native)) throw new Error('codex_router_invalid_catalog');\n const body = native as Record<string, any>;\n // Generic OpenAI consumers retain their original shape. Codex requires richer models.\n const rich = Array.isArray(body.models);\n if (!rich && !Array.isArray(body.data)) throw new Error('codex_router_invalid_catalog');\n const existing = rich ? body.models : body.data;\n const ids = new Set(existing.map((entry: any) => rich ? entry.slug : entry.id));\n const added: any[] = [];\n for (const binding of bindings) {\n const id = binding.alias ?? binding.model;\n if (ids.has(id)) throw new Error('codex_router_model_conflict');\n ids.add(id);\n const info = catalog.model(binding);\n if (!info || info.contextWindow === null || !info.inputModalities.includes('text')) continue;\n if (!rich) { added.push({id, object: 'model', owned_by: binding.provider}); continue; }\n const overrides = binding.capabilityOverrides;\n const context = Math.min(info.contextWindow, overrides?.contextWindow ?? info.contextWindow);\n const reasoning = info.reasoning && overrides?.reasoning !== false;\n // Only the implemented protocol subset is advertised; catalog fields are not promises of hosted tools.\n added.push({...template, slug:id, display_name:info.name, description:`${info.name} (${binding.provider})`,\n context_window:context, max_context_window:context, auto_compact_token_limit:Math.floor(context * 0.85),\n input_modalities: ['text', ...(info.inputModalities.includes('image') && overrides?.images !== false ? ['image'] : [])],\n supported_reasoning_levels: reasoning ? ['low','medium','high'].map(effort => ({effort,description:effort})) : [],\n default_reasoning_level:reasoning ? 'medium' : 'none', support_verbosity:false,\n });\n }\n return {...body, [rich ? 'models' : 'data']: [...existing, ...added]};\n}\n/** No shared identity cache: the upstream's per-request catalog is merged on demand. */\nexport function catalogEtag(body: unknown, version: number | null, clientVersion: string): string {\n return `\"${createHash('sha256').update(JSON.stringify([body,version,clientVersion])).digest('hex')}\"`;\n}\n",
|
|
22
|
+
"import { definePlugin, type Plugin, type PluginInitContext, type PluginHooks } from '@jeffusion/bungee-core/plugin';\nimport { MODELS_DEV_CAPABILITIES_SERVICE_ID, MODELS_DEV_CAPABILITIES_CONTRACT_VERSION, type ModelsDevCapabilitiesService } from '../../models-dev/contract';\nimport { parseBindings } from './config';\nimport { mergeCatalog, catalogEtag } from './catalog';\n\nexport const CodexRouterPlugin = definePlugin(class implements Plugin {\n static readonly name = 'codex-router';\n static readonly version = '1.0.0';\n private readonly bindings;\n private catalog!: ModelsDevCapabilitiesService;\n constructor(options?: { models?: unknown }) { this.bindings = parseBindings(options?.models); }\n async init(context: PluginInitContext) {\n if (context.scope?.type !== 'route') throw new Error('codex_router_requires_route_scope');\n this.catalog = context.services!.consume('models-dev', MODELS_DEV_CAPABILITIES_SERVICE_ID, MODELS_DEV_CAPABILITIES_CONTRACT_VERSION);\n }\n bodyRequirements(context: { method: string; url: URL }) {\n return {request:'none' as const, response: context.method === 'GET' && /\\/models$/.test(context.url.pathname) ? ['json' as const] : []};\n }\n register(hooks: PluginHooks) {\n hooks.onBeforeRequest.tap('codex-router.catalog-validator', context => {\n if (context.method === 'GET' && /\\/models$/.test(context.originalUrl.pathname)) {\n for (const key of Object.keys(context.headers)) if (['if-none-match','if-modified-since'].includes(key.toLowerCase())) delete context.headers[key];\n }\n return context;\n });\n hooks.onResponse.tapPromise('codex-router.catalog', async (response, context) => {\n if (context.method !== 'GET' || !/\\/models$/.test(context.originalUrl.pathname) || !response.ok) return response;\n const native = await context.bodyHandle!.json({id:'codex-router.catalog',mandatory:true});\n const body = mergeCatalog(native, this.bindings, this.catalog);\n const headers = new Headers(response.headers);\n for (const key of ['content-length','content-encoding','etag','last-modified']) headers.delete(key);\n headers.set('content-type','application/json');\n headers.set('cache-control','private, no-store');\n headers.set('etag', catalogEtag(body,this.catalog.status().version,context.originalUrl.searchParams.get('client_version') ?? ''));\n return new Response(JSON.stringify(body), {status:response.status,headers});\n });\n }\n});\nexport default CodexRouterPlugin;\n"
|
|
23
|
+
],
|
|
24
|
+
"mappings": ";;AAOA,IAAM,UAAU,OAAO,IAAI,mCAAmC;AAI9D,SAAS,YAAY,CAAC,WAAoB,CAAC,GAAkB;AAAA,EAC3D,MAAM,SAAS,CAAC,UACd,CAAC,OAAyB,YAAqB;AAAA,IAC7C,MAAM,OAAQ,WAAuC;AAAA,IACrD,IAAI,MAAM;AAAA,MACR,IAAI,OAAO,UAAU;AAAA,QAAU,KAAK,OAAO,UAAU,KAAK;AAAA,MACrD;AAAA,aAAK,OAAO,KAAI,aAAa,MAAK,GAAG,OAAO;AAAA,IACnD,EAAO,SAAI,UAAU,WAAW,QAAQ,IAAI,cAAc,SAAS;AAAA,MACjE,MAAM,QAAQ,UAAU,UAAU,QAAQ,QAAQ,QAAQ;AAAA,MAC1D,MAAM,YAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,OAAO,UAAU,WAAW,WAAW,KAAI,aAAa,MAAK,CAAC;AAAA,IAC3H;AAAA;AAAA,EAEJ,OAAO;AAAA,IAAC,MAAM,OAAO,MAAM;AAAA,IAAG,MAAM,OAAO,MAAM;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAC/F,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,WAAS,aAAa,KAAI,aAAa,MAAK,CAAC;AAAA,EAAC;AAAA;AAE1E,IAAM,SAAS,aAAa;;;ACd5B,IAAM,2BAA2B,OAAO,0BAA0B;;AC2jClE,SAAS,YAA8B,CAC5C,QACe;AAAA,EACf,OAAO;AAAA;;ACtkCF,IAAM,sBAAqC,OAAO,OAAO,EAAC,QAAQ,aAAa,OAAO,IAAI,mBAAmB,EAAC,CAAC;;ACmCtH,IAAM,YAAY,OAAO;;ACjBzB;;;ACiGO,IAAM,qBAAqB,KAAK;AAEhC,IAAM,yBAAyB,MAAM;AAQ5C,IAAM,oBAAoB,IAAI,IAAoB,CAAC,aAAa,cAAc,cAAc,WAAW,SAAS,CAAC;AACjH,IAAM,4BAA4B,IAAI,IAA6B,CAAC,qBAAqB,qBAAqB,MAAM,CAAC;AACrH,IAAM,0BAA0B,IAAI,IAAI,CAAC,iBAAiB,qBAAqB,cAAc,gBAAgB,CAAC;;;ACxF9G,IAAM,YAAY,IAAI,IAAY,CAAC,WAAW,UAAU,SAAS,CAAC;AAClE,IAAM,SAAS,IAAI,IAAY,CAAC,UAAU,SAAS,CAAC;AACpD,IAAM,WAAW,IAAI,IAAY,CAAC,aAAa,cAAc,cAAc,WAAW,SAAS,CAAC;AAqQhG,IAAM,YAAY,IAAI;AAEtB,IAAM,UAAU,IAAI;;;AFtOpB,IAAM,yBAA8D;AAAA,EAClE,cAAc;AAAA,EACd,WAAW;AAAA,EACX,SAAS;AAAA,EACT,SAAS;AAAA,EACT,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,SAAS;AAAA,EACT,SAAS;AAAA,EACT,wBAAwB;AAAA,EACxB,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS;AAAA,EACT,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,qBAAqB;AAAA,EACrB,sBAAsB;AACxB;AAEA,IAAM,sBAAsB,IAAI,IAAyB,OAAO,KAAK,sBAAsB,CAA0B;AA2RrH,IAAM,gBAAgC,OAAO,OAAO,CAAC,CAAC;AAWtD,IAAM,cAAc,IAAI;AA8CxB,IAAM,cAAc,IAAI;;AGnajB,IAAM,4BAA4B,IAAI;AAEtC,IAAM,2BAA2B,KAAK;AAEtC,IAAM,0BAA0B,KAAK;AAiDrC,IAAM,uBAAqD,OAAO,OAAO,CAAC,SAAS,YAAY,QAAQ,CAAC;AA4F/G,IAAM,cAAc,IAAI,IAA4B;AAAA,EAClD;AAAA,EAAe;AAAA,EAAa;AAAA,EAAgB;AAAA,EAAW;AAAA,EAAc;AAAA,EACrE;AAAA,EAAY;AAAA,EAAO;AAAA,EAAa;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EAAW;AAChF,CAAC;AAuCD,IAAM,qBAAoB,IAAI,IAAoB,CAAC,aAAa,cAAc,cAAc,WAAW,SAAS,CAAC;;;ACvI1G,IAAM,oCAAoC,IAAI;AAE9C,IAAM,iCAAiC,KAAK;AAE5C,IAAM,iCAAiC,KAAK,OAAO;AAEnD,IAAM,kCAAkC,IAAI;AAG5C,IAAM,sCAAsC,IAAI;AAchD,IAAM,6BAA6B,KAAK,OAAO;AAQ/C,IAAM,kCAAkC,KAAK;AAGpD,IAAM,QAAQ,IAAI,WAAW,CAAC;AA6gB9B,IAAM,uBAAuB,IAAI;;;ACjmBjC,IAAM,sBAAsB,KAAK;AAQjC,IAAM,uBAAuB,IAAI;;;AClBjC,IAAM,gBAAgB,IAAI,IAAI,CAAC,UAAU,YAAY,QAAQ,CAAC;;ACrB9D,IAAM,mBAAiB,OAAO,IAAI,wCAAwC;;ACC1E,IAAM,OAAO;AACN,IAAM,2BAA2B,KAAK,KAAK;;ACqB3C,IAAM,iCAAiC;AACvC,IAAM,+CAA+C;AAKrD,IAAM,qCAAqC,OAAO,OAAO;AAAA,EAC9D,MAAM;AAAA,EAAU,YAAY;AAAA,IAC1B,SAAS,EAAE,MAAM,UAAU,SAAS,MAAM,SAAS,EAAE;AAAA,IACrD,WAAW,EAAE,MAAM,UAAU,SAAS,EAAE;AAAA,IACxC,SAAS,EAAE,MAAM,QAAQ,UAAU,KAAK,OAAO,KAAK;AAAA,EACtD;AACF,CAAU;AACH,IAAM,uCAAuC,OAAO,OAAO;AAAA,EAChE,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,SAAS;AACX,CAAC;AA4FM,IAAM,qCAAqC;AAC3C,IAAM,2CAA2C;;;AC/HjD,SAAS,aAAa,CAAC,OAAyC;AAAA,EACrE,IAAI,UAAU;AAAA,IAAW,OAAO,CAAC;AAAA,EACjC,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS;AAAA,IAAK,MAAM,IAAI,MAAM,+BAA+B;AAAA,EAChG,MAAM,MAAM,IAAI;AAAA,EAChB,OAAO,OAAO,OAAO,MAAM,IAAI,WAAS;AAAA,IACtC,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,KACzD,OAAO,KAAK,KAAK,EAAE,KAAK,SAAO,CAAC,CAAC,YAAW,SAAQ,SAAQ,UAAS,qBAAqB,EAAE,SAAS,GAAG,CAAC;AAAA,MAAG,MAAM,IAAI,MAAM,+BAA+B;AAAA,IAChK,WAAW,QAAQ,CAAC,MAAM,UAAU,MAAM,OAAO,GAAI,MAAM,UAAU,YAAY,CAAC,IAAI,CAAC,MAAM,KAAK,CAAE,GAAG;AAAA,MACrG,IAAI,OAAO,SAAS,YAAY,CAAC,QAAQ,SAAS,KAAK,KAAK,KAAK,KAAK,SAAS,OAAO,kBAAkB,KAAK,IAAI;AAAA,QAAG,MAAM,IAAI,MAAM,+BAA+B;AAAA,IACrK;AAAA,IACA,MAAM,SAAS,MAAM;AAAA,IACrB,IAAI,CAAC,UAAU,CAAC,CAAC,SAAQ,SAAS,EAAE,SAAS,OAAO,IAAI,KAAK,OAAO,OAAO,OAAO,YAAY,CAAC,OAAO,MACjG,OAAO,KAAK,MAAM,EAAE,KAAK,SAAO,CAAC,CAAC,QAAO,IAAI,EAAE,SAAS,GAAG,CAAC;AAAA,MAAG,MAAM,IAAI,MAAM,6BAA6B;AAAA,IACjH,MAAM,WAAW,MAAM,SAAS,MAAM;AAAA,IACtC,IAAI,IAAI,IAAI,QAAQ;AAAA,MAAG,MAAM,IAAI,MAAM,6BAA6B;AAAA,IACpE,IAAI,IAAI,QAAQ;AAAA,IAChB,MAAM,YAAY,MAAM;AAAA,IACxB,IAAI,cAAc,WAAW;AAAA,MAC3B,IAAI,CAAC,aAAa,OAAO,cAAc,YAAY,MAAM,QAAQ,SAAS;AAAA,QAAG,MAAM,IAAI,MAAM,mCAAmC;AAAA,MAChI,YAAY,KAAK,QAAQ,OAAO,QAAQ,SAAS,GAAG;AAAA,QAClD,IAAI,QAAQ,kBAAkB,OAAO,QAAQ,YAAY,CAAC,OAAO,cAAc,GAAG,KAAK,MAAM,IACzF,CAAC,CAAC,SAAQ,aAAY,QAAQ,EAAE,SAAS,GAAG,KAAK,OAAO,QAAQ;AAAA,UAAW,MAAM,IAAI,MAAM,mCAAmC;AAAA,MACpI;AAAA,IACF;AAAA,IACA,OAAO,OAAO,OAAO,gBAAgB,KAAK,CAAC;AAAA,GAC5C,CAAC;AAAA;;;AChCJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKO,SAAS,YAAY,CAAC,QAAiB,UAAmC,SAAgD;AAAA,EAC/H,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM;AAAA,IAAG,MAAM,IAAI,MAAM,8BAA8B;AAAA,EAClH,MAAM,OAAO;AAAA,EAEb,MAAM,OAAO,MAAM,QAAQ,KAAK,MAAM;AAAA,EACtC,IAAI,CAAC,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI;AAAA,IAAG,MAAM,IAAI,MAAM,8BAA8B;AAAA,EACtF,MAAM,WAAW,OAAO,KAAK,SAAS,KAAK;AAAA,EAC3C,MAAM,MAAM,IAAI,IAAI,SAAS,IAAI,CAAC,UAAe,OAAO,MAAM,OAAO,MAAM,EAAE,CAAC;AAAA,EAC9E,MAAM,QAAe,CAAC;AAAA,EACtB,WAAW,WAAW,UAAU;AAAA,IAC9B,MAAM,KAAK,QAAQ,SAAS,QAAQ;AAAA,IACpC,IAAI,IAAI,IAAI,EAAE;AAAA,MAAG,MAAM,IAAI,MAAM,6BAA6B;AAAA,IAC9D,IAAI,IAAI,EAAE;AAAA,IACV,MAAM,OAAO,QAAQ,MAAM,OAAO;AAAA,IAClC,IAAI,CAAC,QAAQ,KAAK,kBAAkB,QAAQ,CAAC,KAAK,gBAAgB,SAAS,MAAM;AAAA,MAAG;AAAA,IACpF,IAAI,CAAC,MAAM;AAAA,MAAE,MAAM,KAAK,EAAC,IAAI,QAAQ,SAAS,UAAU,QAAQ,SAAQ,CAAC;AAAA,MAAG;AAAA,IAAU;AAAA,IACtF,MAAM,YAAY,QAAQ;AAAA,IAC1B,MAAM,UAAU,KAAK,IAAI,KAAK,eAAe,WAAW,iBAAiB,KAAK,aAAa;AAAA,IAC3F,MAAM,YAAY,KAAK,aAAa,WAAW,cAAc;AAAA,IAE7D,MAAM,KAAK;AAAA,SAAI;AAAA,MAAU,MAAK;AAAA,MAAI,cAAa,KAAK;AAAA,MAAM,aAAY,GAAG,KAAK,SAAS,QAAQ;AAAA,MAC7F,gBAAe;AAAA,MAAS,oBAAmB;AAAA,MAAS,0BAAyB,KAAK,MAAM,UAAU,IAAI;AAAA,MACtG,kBAAkB,CAAC,QAAQ,GAAI,KAAK,gBAAgB,SAAS,OAAO,KAAK,WAAW,WAAW,QAAQ,CAAC,OAAO,IAAI,CAAC,CAAE;AAAA,MACtH,4BAA4B,YAAY,CAAC,OAAM,UAAS,MAAM,EAAE,IAAI,aAAW,EAAC,QAAO,aAAY,OAAM,EAAE,IAAI,CAAC;AAAA,MAChH,yBAAwB,YAAY,WAAW;AAAA,MAAQ,mBAAkB;AAAA,IAC3E,CAAC;AAAA,EACH;AAAA,EACA,OAAO,KAAI,OAAO,OAAO,WAAW,SAAS,CAAC,GAAG,UAAU,GAAG,KAAK,EAAC;AAAA;AAG/D,SAAS,WAAW,CAAC,MAAe,SAAwB,eAA+B;AAAA,EAChG,OAAO,IAAI,WAAW,QAAQ,EAAE,OAAO,KAAK,UAAU,CAAC,MAAK,SAAQ,aAAa,CAAC,CAAC,EAAE,OAAO,KAAK;AAAA;;;AC/B5F,IAAM,oBAAoB,aAAa,MAAwB;AAAA,SACpD,OAAO;AAAA,SACP,UAAU;AAAA,EACT;AAAA,EACT;AAAA,EACR,WAAW,CAAC,SAAgC;AAAA,IAAE,KAAK,WAAW,cAAc,SAAS,MAAM;AAAA;AAAA,OACrF,KAAI,CAAC,SAA4B;AAAA,IACrC,IAAI,QAAQ,OAAO,SAAS;AAAA,MAAS,MAAM,IAAI,MAAM,mCAAmC;AAAA,IACxF,KAAK,UAAU,QAAQ,SAAU,QAAQ,cAAc,oCAAoC,wCAAwC;AAAA;AAAA,EAErI,gBAAgB,CAAC,SAAuC;AAAA,IACtD,OAAO,EAAC,SAAQ,QAAiB,UAAU,QAAQ,WAAW,SAAS,YAAY,KAAK,QAAQ,IAAI,QAAQ,IAAI,CAAC,MAAe,IAAI,CAAC,EAAC;AAAA;AAAA,EAExI,QAAQ,CAAC,OAAoB;AAAA,IAC3B,MAAM,gBAAgB,IAAI,kCAAkC,aAAW;AAAA,MACrE,IAAI,QAAQ,WAAW,SAAS,YAAY,KAAK,QAAQ,YAAY,QAAQ,GAAG;AAAA,QAC9E,WAAW,OAAO,OAAO,KAAK,QAAQ,OAAO;AAAA,UAAG,IAAI,CAAC,iBAAgB,mBAAmB,EAAE,SAAS,IAAI,YAAY,CAAC;AAAA,YAAG,OAAO,QAAQ,QAAQ;AAAA,MAChJ;AAAA,MACA,OAAO;AAAA,KACR;AAAA,IACD,MAAM,WAAW,WAAW,wBAAwB,OAAO,UAAU,YAAY;AAAA,MAC/E,IAAI,QAAQ,WAAW,SAAS,CAAC,YAAY,KAAK,QAAQ,YAAY,QAAQ,KAAK,CAAC,SAAS;AAAA,QAAI,OAAO;AAAA,MACxG,MAAM,SAAS,MAAM,QAAQ,WAAY,KAAK,EAAC,IAAG,wBAAuB,WAAU,KAAI,CAAC;AAAA,MACxF,MAAM,OAAO,aAAa,QAAQ,KAAK,UAAU,KAAK,OAAO;AAAA,MAC7D,MAAM,UAAU,IAAI,QAAQ,SAAS,OAAO;AAAA,MAC5C,WAAW,OAAO,CAAC,kBAAiB,oBAAmB,QAAO,eAAe;AAAA,QAAG,QAAQ,OAAO,GAAG;AAAA,MAClG,QAAQ,IAAI,gBAAe,kBAAkB;AAAA,MAC7C,QAAQ,IAAI,iBAAgB,mBAAmB;AAAA,MAC/C,QAAQ,IAAI,QAAQ,YAAY,MAAK,KAAK,QAAQ,OAAO,EAAE,SAAQ,QAAQ,YAAY,aAAa,IAAI,gBAAgB,KAAK,EAAE,CAAC;AAAA,MAChI,OAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG,EAAC,QAAO,SAAS,QAAO,QAAO,CAAC;AAAA,KAC3E;AAAA;AAEL,CAAC;AACD,IAAe;",
|
|
25
|
+
"debugId": "7896B09FAE2E997364756E2164756E21",
|
|
26
|
+
"names": []
|
|
27
|
+
}
|