@jeffusion/bungee-core 5.18.0 → 5.20.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/gateway/contracts.d.ts +31 -2
- package/dist/gateway/dispatch-plugin.d.ts +7 -0
- package/dist/gateway/dispatch-targets.d.ts +4 -0
- package/dist/gateway/plugin.js +2 -0
- package/dist/gateway/routing-plugin.d.ts +3 -1
- package/dist/hooks/plugin-hooks.d.ts +6 -1
- package/dist/main.js +182 -50
- package/dist/plugin-extensions.d.ts +2 -0
- package/dist/plugins/ai-transformer/index.js +11 -1
- package/dist/plugins/ai-transformer/index.js.map +6 -4
- package/dist/plugins/anthropic-request-sanitizer/index.js.map +1 -1
- package/dist/plugins/anthropic-tool-name-transformer/index.js.map +1 -1
- package/dist/plugins/chatgpt-oauth/control.js.map +1 -1
- package/dist/plugins/chatgpt-oauth/index.js.map +1 -1
- package/dist/plugins/codex-router/control.js +673 -2
- package/dist/plugins/codex-router/control.js.map +19 -4
- package/dist/plugins/codex-router/index.js +3938 -4
- package/dist/plugins/codex-router/index.js.map +24 -7
- package/dist/plugins/codex-router/manifest.json +15 -1
- package/dist/plugins/deepseek-reasoning-fix/index.js.map +1 -1
- package/dist/plugins/key-access/control.js.map +2 -2
- package/dist/plugins/key-access/index.js +14 -10
- package/dist/plugins/key-access/index.js.map +4 -4
- package/dist/plugins/key-access/ingress.js +14 -10
- package/dist/plugins/key-access/ingress.js.map +4 -4
- package/dist/plugins/key-rate-limit/index.js.map +1 -1
- package/dist/plugins/local-accounts/control.js.map +1 -1
- package/dist/plugins/local-accounts/index.js.map +1 -1
- package/dist/plugins/model-mapping/index.js.map +1 -1
- package/dist/plugins/models-dev/index.js.map +1 -1
- package/dist/plugins/openai-messages-to-chat/index.js +691 -543
- package/dist/plugins/openai-messages-to-chat/index.js.map +9 -5
- package/dist/plugins/signature-repair/index.js.map +1 -1
- package/dist/plugins/token-budget/control.js.map +1 -1
- package/dist/plugins/token-budget/index.js.map +1 -1
- package/dist/plugins/token-metering/index.js +652 -71
- package/dist/plugins/token-metering/index.js.map +6 -4
- package/dist/plugins/token-stats/control.js.map +1 -1
- package/dist/plugins/token-stats/index.js.map +1 -1
- package/dist/scoped-plugin-registry.d.ts +5 -2
- package/package.json +2 -2
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/** Shared process sink; the public SDK must not bundle file transports into plugins. */\ntype Context = Readonly<Record<string, unknown>>;\ntype LogMethod = { (context: Context, message?: string): void; (message: string): void };\nexport interface PluginLogSink {\n info: LogMethod; warn: LogMethod; error: LogMethod; debug: LogMethod; fatal: LogMethod;\n child(bindings: Context): PluginLogSink;\n}\nconst sinkKey = Symbol.for('@jeffusion/bungee/plugin-log-sink');\nexport function installPluginLogSink(sink: PluginLogSink): void {\n (globalThis as Record<symbol, unknown>)[sinkKey] = sink;\n}\nfunction createLogger(bindings: Context = {}): PluginLogSink {\n const method = (level: 'info' | 'warn' | 'error' | 'debug' | 'fatal'): LogMethod =>\n (value: Context | string, message?: string) => {\n const sink = (globalThis as Record<symbol, unknown>)[sinkKey] as PluginLogSink | undefined;\n if (sink) {\n if (typeof value === 'string') sink[level](bindings, value);\n else sink[level]({...bindings, ...value}, message);\n } else if (level !== 'debug' || process.env.LOG_LEVEL === 'debug') {\n const write = level === 'fatal' ? console.error : console[level];\n write(message ?? (typeof value === 'string' ? value : ''), typeof value === 'string' ? bindings : {...bindings, ...value});\n }\n };\n return {info: method('info'), warn: method('warn'), error: method('error'), debug: method('debug'),\n fatal: method('fatal'), child: extra => createLogger({...bindings, ...extra})};\n}\nexport const logger = createLogger();\n",
|
|
6
6
|
"/**\n * Hook 实现类\n *\n * 提供 4 种 Hook 类型的实现:\n * - AsyncParallelHook: 异步并行执行\n * - AsyncSeriesHook: 异步串行执行\n * - AsyncSeriesBailHook: 异步串行可中断\n * - AsyncSeriesWaterfallHook: 异步串行瀑布\n */\n\nimport { logger } from '../plugin-logger';\n/** Host-supplied view refresh, run between every waterfall tap. */\nexport const WATERFALL_VIEW_TRANSFORM = Symbol('waterfall-view-transform');\nimport type {\n TapInfo,\n Tap,\n IAsyncParallelHook,\n IAsyncSeriesHook,\n IAsyncSeriesBailHook,\n IAsyncSeriesWaterfallHook,\n IAsyncSeriesMapHook,\n HookStats,\n} from './types';\n\n/**\n * 标准化 TapInfo\n */\nfunction normalizeTapInfo(info: TapInfo | string): TapInfo {\n if (typeof info === 'string') {\n return { name: info, stage: 0 };\n }\n return { ...info, stage: info.stage ?? 0 };\n}\n\n/**\n * 基础 Hook 类\n */\nabstract class BaseHook<T extends any[]> {\n protected taps: Tap<T, any>[] = [];\n protected name: string;\n protected callCount = 0;\n protected totalTimeMs = 0;\n\n constructor(name?: string) {\n this.name = name ?? 'anonymous';\n }\n\n /**\n * 同步注册\n */\n tap(info: TapInfo | string, fn: (...args: T) => any): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'sync', fn });\n this.sortTaps();\n }\n\n /**\n * 异步回调风格注册\n */\n tapAsync(info: TapInfo | string, fn: (...args: any[]) => void): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'async', fn });\n this.sortTaps();\n }\n\n /**\n * Promise 风格注册\n */\n tapPromise(info: TapInfo | string, fn: (...args: T) => Promise<any>): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'promise', fn });\n this.sortTaps();\n }\n\n /**\n * 检查是否有注册的回调\n */\n hasCallbacks(): boolean {\n return this.taps.length > 0;\n }\n\n /**\n * 获取统计信息\n */\n getStats(): HookStats {\n return {\n name: this.name,\n tapCount: this.taps.length,\n callCount: this.callCount,\n totalTimeMs: this.totalTimeMs,\n avgTimeMs: this.callCount > 0 ? this.totalTimeMs / this.callCount : 0,\n };\n }\n\n /**\n * 重置统计信息\n */\n resetStats(): void {\n this.callCount = 0;\n this.totalTimeMs = 0;\n }\n\n /**\n * 清空所有注册的回调\n */\n clear(): void {\n this.taps = [];\n }\n\n /**\n * 按 stage 排序(稳定排序)\n */\n private sortTaps(): void {\n this.taps.sort((a, b) => (a.info.stage ?? 0) - (b.info.stage ?? 0));\n }\n\n /**\n * 执行单个 tap\n */\n protected async executeTap<R>(\n tap: Tap<T, R>,\n args: T\n ): Promise<R | undefined> {\n try {\n if (tap.type === 'sync') {\n return tap.fn(...args);\n } else if (tap.type === 'promise') {\n return await tap.fn(...args);\n } else {\n // async (callback style)\n return await new Promise<R | undefined>((resolve, reject) => {\n const done = (err?: Error, result?: R) => {\n if (err) reject(err);\n else resolve(result);\n };\n tap.fn(...args, done);\n });\n }\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n}\n\n/** Synchronous providers use the same registration, ordering and statistics as async hooks. */\nexport class SyncBailHook<T extends any[] = [], R = unknown> extends BaseHook<T> {\n override tapAsync(): never { throw new Error('synchronous provider requires tap'); }\n override tapPromise(): never { throw new Error('synchronous provider requires tap'); }\n call(...args: T): R | undefined {\n const started = performance.now();\n this.callCount++;\n try {\n for (const tap of this.taps) {\n const result = tap.fn(...args);\n if (result && typeof result.then === 'function') throw new Error('synchronous provider returned a Promise');\n if (result !== undefined) return result as R;\n }\n return undefined;\n } finally { this.totalTimeMs += performance.now() - started; }\n }\n}\n\n/**\n * 异步并行 Hook\n * 所有回调并行执行,全部完成后返回\n */\nexport class AsyncParallelHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncParallelHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 并行执行所有回调,错误独立处理不影响其他\n await Promise.all(\n this.taps.map(async (tap) => {\n try {\n await this.executeTap(tap, args);\n } catch (error) {\n // 并行 Hook 中单个回调的错误不应影响其他回调\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in parallel hook callback (ignored)'\n );\n }\n })\n );\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行 Hook\n * 所有回调按顺序串行执行\n */\nexport class AsyncSeriesHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncSeriesHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n await this.executeTap(tap, args);\n }\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行可中断 Hook\n * 任意回调返回非 undefined 值则停止执行并返回该值\n */\nexport class AsyncSeriesBailHook<T extends any[] = [], R = any>\n extends BaseHook<T>\n implements IAsyncSeriesBailHook<T, R>\n{\n async promise(...args: T): Promise<R | undefined> {\n if (this.taps.length === 0) return undefined;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n const result = await this.executeTap<R>(tap, args);\n if (result !== undefined) {\n logger.debug(\n { hookName: this.name, pluginName: tap.info.name },\n 'Hook bailed with result'\n );\n return result;\n }\n }\n return undefined;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行瀑布 Hook\n * 每个回调的返回值作为下一个回调的第一个参数\n */\nexport class AsyncSeriesWaterfallHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesWaterfallHook<T, A>\n{\n async promise(value: T, ...args: A): Promise<T> {\n if (this.taps.length === 0) return value;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n let current = value;\n for (const tap of this.taps) {\n const result = await this.executeTap<T>(tap, [current, ...args] as [T, ...A]);\n // 只有返回非 undefined 时才更新值\n if (result !== undefined) {\n const transform = args[0]?.[WATERFALL_VIEW_TRANSFORM];\n current = typeof transform === 'function' ? await transform(result,current) : result;\n }\n }\n return current;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行映射 Hook\n * 支持 N:M 转换:每个回调处理输入,可以返回 0 到多个输出\n *\n * 执行流程:\n * 1. 初始输入:单个 chunk\n * 2. 每个插件处理当前的所有 chunks,返回新的 chunks 数组\n * 3. 下一个插件处理上一步的所有输出\n *\n * 返回值约定:\n * - null/undefined: 不处理,原样输出当前 chunk\n * - []: 缓冲当前 chunk,不输出(N:0)\n * - [chunk]: 1:1 转换\n * - [chunk1, chunk2, ...]: 1:M 拆分\n *\n * 性能优化:\n * - 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n * - 适用于流式响应处理等高频调用场景\n */\nexport class AsyncSeriesMapHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesMapHook<T, A>\n{\n /**\n * 同步执行单个 tap(跳过 Promise 开销)\n */\n private executeTapSync<R>(tap: Tap<[T, ...A], R>, args: [T, ...A]): R | undefined {\n try {\n return tap.fn(...args);\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n\n async promise(value: T, ...args: A): Promise<T[]> {\n // 如果没有注册任何回调,直接返回原始值\n if (this.taps.length === 0) return [value];\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 初始输入为单个 chunk\n let chunks: T[] = [value];\n\n // 依次应用每个插件的转换\n for (const tap of this.taps) {\n const newChunks: T[] = [];\n\n // 对当前的每个 chunk 应用转换\n for (const chunk of chunks) {\n try {\n // 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n const result = tap.type === 'sync'\n ? this.executeTapSync<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A])\n : await this.executeTap<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A]);\n\n if (result === null || result === undefined) {\n // 不处理,原样输出\n newChunks.push(chunk);\n } else if (Array.isArray(result)) {\n // N:M 转换\n // [] = 缓冲(不输出)\n // [item] = 1:1 转换\n // [item1, item2, ...] = 1:M 拆分\n newChunks.push(...result);\n } else {\n // 非法返回值,警告并原样输出\n logger.warn(\n { hookName: this.name, pluginName: tap.info.name, result },\n 'AsyncSeriesMapHook callback must return an array or null'\n );\n newChunks.push(chunk);\n }\n } catch (error) {\n // 单个 chunk 处理失败,记录错误并原样输出\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in AsyncSeriesMapHook callback'\n );\n if ((args[0] as { strict?: boolean } | undefined)?.strict) {\n throw error;\n }\n newChunks.push(chunk);\n }\n }\n\n chunks = newChunks;\n }\n\n return chunks;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n",
|
|
7
|
-
"import type { 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",
|
|
7
|
+
"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 /** Host-pinned entry scope for one internal handoff. */\n readonly entryRouteId?: string;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n readonly routeId: string;\n readonly serviceId: string | null;\n readonly upstreamId: string;\n readonly url: string;\n readonly model: string | null;\n readonly now: number;\n}\nexport interface AdmissionDenial {\n readonly error: string;\n readonly status: 401 | 403 | 429 | 503 | 422;\n readonly retryAfter?: number;\n}\nexport interface AdmissionPlan {\n /** A complete JSON state replacement, staged by Host before the common decision. */\n readonly state?: DurableJson;\n /** Immutable policy snapshot retained by the grant for subsequent attempts. */\n readonly snapshot?: DurableJson;\n readonly denial?: AdmissionDenial;\n}\nexport interface IngressPlugin {\n /** Effective policy demand; no policy means no content decoding. */\n bodyRequirements(target: AdmissionTarget, policy: DurableJson): { readonly request: 'none' | 'json-read' };\n /** Optional per-principal state. Policies are frozen; plans receive only this key's clones.\n * Expiry must mean absence is behaviorally equivalent to retaining the state. */\n keyedState?: {\n readonly capacity: number;\n policyForKey(policy: DurableJson, keyId: string): DurableJson;\n expiresAt(state: DurableJson): number;\n reconcile(state: DurableJson, policy: DurableJson, now: number): DurableJson;\n };\n authenticate?(request: Request, policy: DurableJson, now: number): DataPrincipal | null;\n resolveIdentity?(target: AdmissionTarget, policy: DurableJson): DataPrincipal;\n 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",
|
|
8
8
|
"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",
|
|
9
9
|
"/**\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",
|
|
10
10
|
"/**\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",
|