@jeffusion/bungee-core 5.18.0 → 5.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/gateway/contracts.d.ts +29 -2
  2. package/dist/gateway/dispatch-plugin.d.ts +7 -0
  3. package/dist/gateway/dispatch-targets.d.ts +4 -0
  4. package/dist/gateway/plugin.js +2 -0
  5. package/dist/gateway/routing-plugin.d.ts +3 -1
  6. package/dist/hooks/plugin-hooks.d.ts +3 -1
  7. package/dist/main.js +146 -34
  8. package/dist/plugin-extensions.d.ts +2 -0
  9. package/dist/plugins/ai-transformer/index.js.map +1 -1
  10. package/dist/plugins/anthropic-request-sanitizer/index.js.map +1 -1
  11. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +1 -1
  12. package/dist/plugins/chatgpt-oauth/control.js.map +1 -1
  13. package/dist/plugins/chatgpt-oauth/index.js.map +1 -1
  14. package/dist/plugins/codex-router/index.js +179 -2
  15. package/dist/plugins/codex-router/index.js.map +6 -5
  16. package/dist/plugins/deepseek-reasoning-fix/index.js.map +1 -1
  17. package/dist/plugins/key-access/control.js.map +2 -2
  18. package/dist/plugins/key-access/index.js +14 -10
  19. package/dist/plugins/key-access/index.js.map +4 -4
  20. package/dist/plugins/key-access/ingress.js +14 -10
  21. package/dist/plugins/key-access/ingress.js.map +4 -4
  22. package/dist/plugins/key-rate-limit/index.js.map +1 -1
  23. package/dist/plugins/local-accounts/control.js.map +1 -1
  24. package/dist/plugins/local-accounts/index.js.map +1 -1
  25. package/dist/plugins/model-mapping/index.js.map +1 -1
  26. package/dist/plugins/models-dev/index.js.map +1 -1
  27. package/dist/plugins/openai-messages-to-chat/index.js.map +1 -1
  28. package/dist/plugins/signature-repair/index.js.map +1 -1
  29. package/dist/plugins/token-budget/control.js.map +1 -1
  30. package/dist/plugins/token-budget/index.js.map +1 -1
  31. package/dist/plugins/token-metering/index.js.map +1 -1
  32. package/dist/plugins/token-stats/control.js.map +1 -1
  33. package/dist/plugins/token-stats/index.js.map +1 -1
  34. package/dist/scoped-plugin-registry.d.ts +1 -0
  35. package/package.json +2 -2
@@ -190,10 +190,13 @@ function matchesModel(pattern, model) {
190
190
  }
191
191
  return cursor <= end;
192
192
  }
193
- function check(target, policy) {
193
+ function protectedScopes(target, publication) {
194
+ return [...new Set([target.entryRouteId, target.routeId].filter((id) => !!id && publication.protectedRouteIds.includes(id)))];
195
+ }
196
+ function check(target, policy, scopes = [target.routeId]) {
194
197
  if (target.principal.domain === "anonymous")
195
198
  return null;
196
- if (policy && (policy.routes !== null && !policy.routes.includes(target.routeId) || policy.models !== null && (!target.model || !policy.models.some((pattern) => matchesModel(pattern, target.model)))))
199
+ if (policy && (policy.routes !== null && !scopes.every((id) => policy.routes.includes(id)) || policy.models !== null && (!target.model || !policy.models.some((pattern) => matchesModel(pattern, target.model)))))
197
200
  return { error: "key-access.scope_denied", status: 403 };
198
201
  return null;
199
202
  }
@@ -201,7 +204,7 @@ function createIngress() {
201
204
  return {
202
205
  bodyRequirements(target, value) {
203
206
  const publication = validatePublication(value);
204
- if (!publication.protectedRouteIds.includes(target.routeId) || target.principal.domain !== "data")
207
+ if (protectedScopes(target, publication).length === 0 || target.principal.domain !== "data")
205
208
  return { request: "none" };
206
209
  const policy = validatePolicy(publication.byKey[target.principal.keyId] ?? null);
207
210
  const urlModel = /\/models\/([^/:]+):(?:streamGenerateContent|generateContent)$/.test(new URL(target.url).pathname);
@@ -221,7 +224,7 @@ function createIngress() {
221
224
  },
222
225
  resolveIdentity(target, value) {
223
226
  const p = validatePublication(value);
224
- if (!p.protectedRouteIds.includes(target.routeId))
227
+ if (protectedScopes(target, p).length === 0)
225
228
  return ANONYMOUS_PRINCIPAL;
226
229
  if (!validPrincipal(target.principal, p, target.now))
227
230
  throw new DataAdmissionError(401, "unauthorized");
@@ -230,13 +233,14 @@ function createIngress() {
230
233
  plan(target, value) {
231
234
  try {
232
235
  const p = validatePublication(value);
233
- if (!p.protectedRouteIds.includes(target.routeId))
236
+ if (protectedScopes(target, p).length === 0)
234
237
  return { snapshot: null };
235
238
  if (target.principal.domain === "anonymous")
236
239
  return { denial: { error: "unauthorized", status: 401 } };
237
240
  const policy = validatePolicy(p.byKey[target.principal.keyId] ?? null);
238
- const denial = check(target, policy);
239
- return denial ? { denial } : { snapshot: { routeId: target.routeId, policy } };
241
+ const scopes = protectedScopes(target, p);
242
+ const denial = check(target, policy, scopes);
243
+ return denial ? { denial } : { snapshot: { routeId: target.routeId, entryRouteId: target.entryRouteId ?? null, scopes, policy } };
240
244
  } catch {
241
245
  return { denial: { error: "key-access.policy_unavailable", status: 503 } };
242
246
  }
@@ -246,9 +250,9 @@ function createIngress() {
246
250
  return target.principal.domain === "anonymous" ? null : { error: "key-access.invalid_grant", status: 503 };
247
251
  try {
248
252
  const s = snapshot;
249
- if (!s || s.routeId !== target.routeId)
253
+ if (!s || s.routeId !== target.routeId || (s.entryRouteId ?? null) !== (target.entryRouteId ?? null))
250
254
  return { error: "key-access.scope_denied", status: 403 };
251
- return check(target, validatePolicy(s.policy));
255
+ return check(target, validatePolicy(s.policy), s.scopes ?? [target.routeId]);
252
256
  } catch {
253
257
  return { error: "key-access.policy_unavailable", status: 503 };
254
258
  }
@@ -263,4 +267,4 @@ export {
263
267
  validatePublication
264
268
  };
265
269
 
266
- //# debugId=B8625603C2EACD9764756E2164756E21
270
+ //# debugId=F3ECF1925A73000F64756E2164756E21
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../../../plugins/key-access/server/policy.ts", "../../../src/plugin-logger.ts", "../../../src/hooks/impl.ts", "../../../src/plugin-extensions.ts", "../../../src/data-admission/errors.ts", "../../../src/plugin-durable-state.ts", "../../../src/plugin-services/host-rpc.ts", "../../../src/plugin-services/wire-contract.ts", "../../../src/plugin-services/rpc-runtime.ts", "../../../src/plugin-services/peer-channel-protocol.ts", "../../../src/plugin-services/peer-channel-hub.ts", "../../../src/plugin-services/snapshot-store.ts", "../../../src/plugin-services.ts", "../../../src/gateway/retry-action.ts", "../../../src/token-stats-window.ts"],
4
4
  "sourcesContent": [
5
- "import { createHash, timingSafeEqual } from 'node:crypto';\nimport { ANONYMOUS_PRINCIPAL, type DataPrincipal, type AdmissionTarget, type AdmissionDenial, type IngressPlugin } from '@jeffusion/bungee-core/plugin';\nimport { DataAdmissionError } from '@jeffusion/bungee-core/plugin';\n\nexport interface AccessPolicy { routes: string[] | null; models: string[] | null }\nexport interface AccessCredential {\n id: string; domain: 'data'; name: string; prefix: string; digest: string;\n createdAt: number; expiresAt: number | null; revokedAt: number | null; credentialVersion: number;\n}\nexport interface AccessPublication {\n protectedRouteIds: string[];\n byKey: Record<string, AccessPolicy | null>;\n credentials: AccessCredential[];\n}\nexport function stringIds(value: unknown): string[] {\n if (!Array.isArray(value) || value.length > 1000 || value.some(x => typeof x !== 'string' || !x.length || x.length > 256)\n || new Set(value).size !== value.length) throw new Error('invalid_policy');\n return [...value];\n}\nexport function validatePolicy(value: unknown): AccessPolicy | null {\n if (value === null) return null;\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !['routes', 'models'].includes(k))) throw new Error('invalid_policy');\n const p = value as AccessPolicy;\n return {routes: p.routes === null ? null : stringIds(p.routes), models: p.models === null ? null : stringIds(p.models)};\n}\nexport function validatePublication(value: unknown): AccessPublication {\n const p = value as AccessPublication;\n if (!p || typeof p !== 'object' || !p.byKey || typeof p.byKey !== 'object' || Array.isArray(p.byKey)\n || !Array.isArray(p.credentials)) throw new Error('invalid_policy');\n const protectedRouteIds = stringIds(p.protectedRouteIds);\n for (const key of p.credentials) {\n if (!key || key.domain !== 'data' || typeof key.id !== 'string' || !key.id || !/^[a-f0-9]{64}$/.test(key.digest)\n || !Number.isSafeInteger(key.credentialVersion) || key.credentialVersion < 1\n || (key.expiresAt !== null && !Number.isSafeInteger(key.expiresAt))\n || (key.revokedAt !== null && !Number.isSafeInteger(key.revokedAt))) throw new Error('invalid_credentials');\n }\n return {...p, protectedRouteIds};\n}\nexport function validPrincipal(principal: DataPrincipal, value: AccessPublication, now: number): boolean {\n const key = value.credentials.find(key => key.id === principal.keyId);\n return principal.domain === 'data' && !!key && key.credentialVersion === principal.credentialVersion\n && key.revokedAt === null && (key.expiresAt === null || key.expiresAt > now);\n}\n/** Only * is special; every other character is literal. Match the entire model. */\nfunction matchesModel(pattern: string, model: string): boolean {\n const parts = pattern.split('*');\n if (parts.length === 1) return pattern === model;\n const first = parts[0]!, last = parts[parts.length - 1]!;\n if (!model.startsWith(first) || !model.endsWith(last)) return false;\n let cursor = first.length;\n const end = model.length - last.length;\n for (const part of parts.slice(1, -1)) {\n const index = model.indexOf(part, cursor);\n if (index < 0) return false;\n cursor = index + part.length;\n }\n return cursor <= end;\n}\nfunction check(target: AdmissionTarget, policy: AccessPolicy | null): AdmissionDenial | null {\n if (target.principal.domain === 'anonymous') return null;\n if (policy && ((policy.routes !== null && !policy.routes.includes(target.routeId))\n || (policy.models !== null && (!target.model || !policy.models.some(pattern => matchesModel(pattern, target.model!)))))) return {error: 'key-access.scope_denied', status: 403};\n return null;\n}\nexport function createIngress(): IngressPlugin { return {\n bodyRequirements(target, value) {\n const publication = validatePublication(value);\n if (!publication.protectedRouteIds.includes(target.routeId) || target.principal.domain !== 'data') return { request: 'none' };\n const policy = validatePolicy(publication.byKey[target.principal.keyId] ?? null);\n const urlModel = /\\/models\\/([^/:]+):(?:streamGenerateContent|generateContent)$/.test(new URL(target.url).pathname);\n return { request: policy?.models !== null && policy?.models !== undefined && policy.models.length > 0 && !urlModel ? 'json-read' : 'none' };\n },\n authenticate(request, value, now) {\n const p = validatePublication(value);\n const match = /^Bearer (bng_data_[A-Za-z0-9_-]{43})$/i.exec(request.headers.get('authorization') ?? '');\n if (!match) return null;\n const digest = createHash('sha256').update(match[1]!).digest('hex');\n const key = p.credentials.find(key => timingSafeEqual(Buffer.from(key.digest, 'hex'), Buffer.from(digest, 'hex')));\n if (!key) return null;\n const principal = {domain: 'data', keyId: key.id, credentialVersion: key.credentialVersion};\n return validPrincipal(principal, p, now) ? principal : null;\n },\n resolveIdentity(target, value) {\n const p = validatePublication(value);\n if (!p.protectedRouteIds.includes(target.routeId)) return ANONYMOUS_PRINCIPAL;\n if (!validPrincipal(target.principal, p, target.now)) throw new DataAdmissionError(401, 'unauthorized');\n return target.principal;\n },\n plan(target, value) {\n try {\n const p = validatePublication(value);\n if (!p.protectedRouteIds.includes(target.routeId)) return {snapshot: null};\n if (target.principal.domain === 'anonymous') return {denial: {error: 'unauthorized', status: 401}};\n const policy = validatePolicy(p.byKey[target.principal.keyId] ?? null);\n const denial = check(target, policy);\n return denial ? {denial} : {snapshot: {routeId: target.routeId, policy: policy as any}};\n } catch { return {denial: {error: 'key-access.policy_unavailable', status: 503}}; }\n },\n beforeAttempt(target, snapshot) {\n if (snapshot === null) return target.principal.domain === 'anonymous' ? null : {error: 'key-access.invalid_grant', status: 503};\n try {\n const s = snapshot as {routeId: string; policy: AccessPolicy | null};\n if (!s || s.routeId !== target.routeId) return {error: 'key-access.scope_denied', status: 403};\n return check(target, validatePolicy(s.policy));\n } catch { return {error: 'key-access.policy_unavailable', status: 503}; }\n },\n}; }\n",
5
+ "import { createHash, timingSafeEqual } from 'node:crypto';\nimport { ANONYMOUS_PRINCIPAL, type DataPrincipal, type AdmissionTarget, type AdmissionDenial, type IngressPlugin } from '@jeffusion/bungee-core/plugin';\nimport { DataAdmissionError } from '@jeffusion/bungee-core/plugin';\n\nexport interface AccessPolicy { routes: string[] | null; models: string[] | null }\nexport interface AccessCredential {\n id: string; domain: 'data'; name: string; prefix: string; digest: string;\n createdAt: number; expiresAt: number | null; revokedAt: number | null; credentialVersion: number;\n}\nexport interface AccessPublication {\n protectedRouteIds: string[];\n byKey: Record<string, AccessPolicy | null>;\n credentials: AccessCredential[];\n}\nexport function stringIds(value: unknown): string[] {\n if (!Array.isArray(value) || value.length > 1000 || value.some(x => typeof x !== 'string' || !x.length || x.length > 256)\n || new Set(value).size !== value.length) throw new Error('invalid_policy');\n return [...value];\n}\nexport function validatePolicy(value: unknown): AccessPolicy | null {\n if (value === null) return null;\n if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !['routes', 'models'].includes(k))) throw new Error('invalid_policy');\n const p = value as AccessPolicy;\n return {routes: p.routes === null ? null : stringIds(p.routes), models: p.models === null ? null : stringIds(p.models)};\n}\nexport function validatePublication(value: unknown): AccessPublication {\n const p = value as AccessPublication;\n if (!p || typeof p !== 'object' || !p.byKey || typeof p.byKey !== 'object' || Array.isArray(p.byKey)\n || !Array.isArray(p.credentials)) throw new Error('invalid_policy');\n const protectedRouteIds = stringIds(p.protectedRouteIds);\n for (const key of p.credentials) {\n if (!key || key.domain !== 'data' || typeof key.id !== 'string' || !key.id || !/^[a-f0-9]{64}$/.test(key.digest)\n || !Number.isSafeInteger(key.credentialVersion) || key.credentialVersion < 1\n || (key.expiresAt !== null && !Number.isSafeInteger(key.expiresAt))\n || (key.revokedAt !== null && !Number.isSafeInteger(key.revokedAt))) throw new Error('invalid_credentials');\n }\n return {...p, protectedRouteIds};\n}\nexport function validPrincipal(principal: DataPrincipal, value: AccessPublication, now: number): boolean {\n const key = value.credentials.find(key => key.id === principal.keyId);\n return principal.domain === 'data' && !!key && key.credentialVersion === principal.credentialVersion\n && key.revokedAt === null && (key.expiresAt === null || key.expiresAt > now);\n}\n/** Only * is special; every other character is literal. Match the entire model. */\nfunction matchesModel(pattern: string, model: string): boolean {\n const parts = pattern.split('*');\n if (parts.length === 1) return pattern === model;\n const first = parts[0]!, last = parts[parts.length - 1]!;\n if (!model.startsWith(first) || !model.endsWith(last)) return false;\n let cursor = first.length;\n const end = model.length - last.length;\n for (const part of parts.slice(1, -1)) {\n const index = model.indexOf(part, cursor);\n if (index < 0) return false;\n cursor = index + part.length;\n }\n return cursor <= end;\n}\nfunction protectedScopes(target: AdmissionTarget, publication: AccessPublication): string[] {\n return [...new Set([target.entryRouteId,target.routeId].filter((id): id is string => !!id && publication.protectedRouteIds.includes(id)))];\n}\nfunction check(target: AdmissionTarget, policy: AccessPolicy | null, scopes: string[] = [target.routeId]): AdmissionDenial | null {\n if (target.principal.domain === 'anonymous') return null;\n if (policy && ((policy.routes !== null && !scopes.every(id => policy.routes!.includes(id)))\n || (policy.models !== null && (!target.model || !policy.models.some(pattern => matchesModel(pattern, target.model!)))))) return {error: 'key-access.scope_denied', status: 403};\n return null;\n}\nexport function createIngress(): IngressPlugin { return {\n bodyRequirements(target, value) {\n const publication = validatePublication(value);\n if (protectedScopes(target,publication).length === 0 || target.principal.domain !== 'data') return { request: 'none' };\n const policy = validatePolicy(publication.byKey[target.principal.keyId] ?? null);\n const urlModel = /\\/models\\/([^/:]+):(?:streamGenerateContent|generateContent)$/.test(new URL(target.url).pathname);\n return { request: policy?.models !== null && policy?.models !== undefined && policy.models.length > 0 && !urlModel ? 'json-read' : 'none' };\n },\n authenticate(request, value, now) {\n const p = validatePublication(value);\n const match = /^Bearer (bng_data_[A-Za-z0-9_-]{43})$/i.exec(request.headers.get('authorization') ?? '');\n if (!match) return null;\n const digest = createHash('sha256').update(match[1]!).digest('hex');\n const key = p.credentials.find(key => timingSafeEqual(Buffer.from(key.digest, 'hex'), Buffer.from(digest, 'hex')));\n if (!key) return null;\n const principal = {domain: 'data', keyId: key.id, credentialVersion: key.credentialVersion};\n return validPrincipal(principal, p, now) ? principal : null;\n },\n resolveIdentity(target, value) {\n const p = validatePublication(value);\n if (protectedScopes(target,p).length === 0) return ANONYMOUS_PRINCIPAL;\n if (!validPrincipal(target.principal, p, target.now)) throw new DataAdmissionError(401, 'unauthorized');\n return target.principal;\n },\n plan(target, value) {\n try {\n const p = validatePublication(value);\n if (protectedScopes(target,p).length === 0) return {snapshot: null};\n if (target.principal.domain === 'anonymous') return {denial: {error: 'unauthorized', status: 401}};\n const policy = validatePolicy(p.byKey[target.principal.keyId] ?? null);\n const scopes = protectedScopes(target,p);\n const denial = check(target, policy,scopes);\n return denial ? {denial} : {snapshot: {routeId: target.routeId, entryRouteId:target.entryRouteId ?? null, scopes, policy: policy as any}};\n } catch { return {denial: {error: 'key-access.policy_unavailable', status: 503}}; }\n },\n beforeAttempt(target, snapshot) {\n if (snapshot === null) return target.principal.domain === 'anonymous' ? null : {error: 'key-access.invalid_grant', status: 503};\n try {\n const s = snapshot as {routeId: string; entryRouteId?: string | null; scopes?: string[]; policy: AccessPolicy | null};\n if (!s || s.routeId !== target.routeId || (s.entryRouteId ?? null) !== (target.entryRouteId ?? null)) return {error: 'key-access.scope_denied', status: 403};\n return check(target, validatePolicy(s.policy),s.scopes ?? [target.routeId]);\n } catch { return {error: 'key-access.policy_unavailable', status: 503}; }\n },\n}; }\n",
6
6
  "/** 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",
7
7
  "/**\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",
8
- "import type { PluginDurableState, DurableJson } from './plugin-durable-state';\n\n/** Anonymous is an explicit, signed data identity; it carries no key authority. */\nexport type DataPrincipal = { readonly domain: string; readonly keyId: string; readonly credentialVersion: number };\nexport const ANONYMOUS_PRINCIPAL: DataPrincipal = Object.freeze({domain: 'anonymous', keyId: '', credentialVersion: 0});\nexport interface AdmissionRequirement { readonly plugin: string; readonly routeIds: readonly string[] }\n/** Public contracts. Business rules belong to the implementing plugin. */\nexport interface ManagementSubject {\n readonly id: string;\n readonly provider: string;\n readonly capabilities: readonly string[];\n readonly requiresPasswordChange?: boolean;\n}\nexport interface ManagementProvider {\n authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): boolean;\n login(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): boolean;\n revokeSessions(): void;\n validateWrite?(request: Request): void;\n csrfToken?(request: Request): string | undefined;\n /** Optional browser cookie renewal after successful session verification. Must not extend the server-side absolute deadline. */\n sessionCookie?(request: Request): string | undefined;\n}\nexport interface AdmissionTarget {\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n readonly routeId: string;\n readonly serviceId: string | null;\n readonly upstreamId: string;\n readonly url: string;\n readonly model: string | null;\n readonly now: number;\n}\nexport interface AdmissionDenial {\n readonly error: string;\n readonly status: 401 | 403 | 429 | 503 | 422;\n readonly retryAfter?: number;\n}\nexport interface AdmissionPlan {\n /** A complete JSON state replacement, staged by Host before the common decision. */\n readonly state?: DurableJson;\n /** Immutable policy snapshot retained by the grant for subsequent attempts. */\n readonly snapshot?: DurableJson;\n readonly denial?: AdmissionDenial;\n}\nexport interface IngressPlugin {\n /** Effective policy demand; no policy means no content decoding. */\n bodyRequirements(target: AdmissionTarget, policy: DurableJson): { readonly request: 'none' | 'json-read' };\n /** Optional per-principal state. Policies are frozen; plans receive only this key's clones.\n * Expiry must mean absence is behaviorally equivalent to retaining the state. */\n keyedState?: {\n readonly capacity: number;\n policyForKey(policy: DurableJson, keyId: string): DurableJson;\n expiresAt(state: DurableJson): number;\n reconcile(state: DurableJson, policy: DurableJson, now: number): DurableJson;\n };\n authenticate?(request: Request, policy: DurableJson, now: number): DataPrincipal | null;\n resolveIdentity?(target: AdmissionTarget, policy: DurableJson): DataPrincipal;\n plan(target: AdmissionTarget, policy: DurableJson, state: DurableJson): AdmissionPlan;\n beforeAttempt?(target: AdmissionTarget, snapshot: DurableJson): AdmissionDenial | null;\n}\nexport interface IngressPluginModule { createIngress(): IngressPlugin }\nexport interface PluginStateRpcContext {\n readonly state: PluginDurableState;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n}\nexport interface PluginPolicyPublication {\n readonly version: number;\n readonly value: DurableJson;\n}\n",
8
+ "import type { PluginDurableState, DurableJson } from './plugin-durable-state';\n\n/** Anonymous is an explicit, signed data identity; it carries no key authority. */\nexport type DataPrincipal = { readonly domain: string; readonly keyId: string; readonly credentialVersion: number };\nexport const ANONYMOUS_PRINCIPAL: DataPrincipal = Object.freeze({domain: 'anonymous', keyId: '', credentialVersion: 0});\nexport interface AdmissionRequirement { readonly plugin: string; readonly routeIds: readonly string[] }\n/** Public contracts. Business rules belong to the implementing plugin. */\nexport interface ManagementSubject {\n readonly id: string;\n readonly provider: string;\n readonly capabilities: readonly string[];\n readonly requiresPasswordChange?: boolean;\n}\nexport interface ManagementProvider {\n authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): boolean;\n login(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): boolean;\n revokeSessions(): void;\n validateWrite?(request: Request): void;\n csrfToken?(request: Request): string | undefined;\n /** Optional browser cookie renewal after successful session verification. Must not extend the server-side absolute deadline. */\n sessionCookie?(request: Request): string | undefined;\n}\nexport interface AdmissionTarget {\n /** 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",
9
9
  "/** Shared inert error contract; importing it never loads admission runtime modules. */\nexport class DataAdmissionError extends Error {\n readonly name = 'DataAdmissionError';\n constructor(readonly status: number, readonly code: string, readonly retryAfter?: number) { super(code); }\n}\n\n/** Plugin bundles have their own class identity; normalize their explicit error contract. */\nexport function normalizeAdmissionError(error: unknown): DataAdmissionError | null {\n if (error instanceof DataAdmissionError) return error;\n if (!(error instanceof Error) || error.name !== 'DataAdmissionError') return null;\n const value = error as Error & {status?: unknown; code?: unknown; retryAfter?: unknown};\n if (typeof value.status !== 'number' || ![401,403,409,422,429,503].includes(value.status)\n || typeof value.code !== 'string' || !/^[a-zA-Z0-9_.-]{1,128}$/.test(value.code)\n || (value.retryAfter !== undefined && (typeof value.retryAfter !== 'number' || !Number.isFinite(value.retryAfter) || value.retryAfter < 0))) return null;\n return new DataAdmissionError(value.status,value.code,value.retryAfter as number | undefined);\n}\n",
10
10
  "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",
11
11
  "/**\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",
@@ -18,7 +18,7 @@
18
18
  "/** Declarative repair request; the host owns the next upstream attempt. */\nconst retryActionBrand=Symbol.for('@jeffusion/bungee/request-retry-action');\nexport class RequestRetryAction extends Error {\n readonly body:unknown;\n constructor(body: unknown, readonly reason: string) {\n super('gateway request repair retry');\n this.name = 'RequestRetryAction';\n Object.defineProperty(this,retryActionBrand,{value:true});\n Object.defineProperty(this,'body',{value:body,enumerable:false});\n }\n /** Plugins and host may bundle the SDK independently in the same process. */\n static [Symbol.hasInstance](value:unknown):boolean {\n return value instanceof Error && (value as unknown as Record<symbol,unknown>)[retryActionBrand]===true;\n }\n}\n",
19
19
  "import type { TokenStatsRange } from './plugin.types';\n\nconst HOUR = 3_600_000;\nexport const TOKEN_STATS_RETENTION_MS = 31 * 24 * HOUR;\nexport const TOKEN_STATS_RANGES = ['1h', '12h', '24h', '1d', '7d', '30d', 'day', 'week', 'month'] as const;\n\n/** Recent page ranges are consecutive elapsed hours; calendar ranges use local dates. */\nexport function tokenStatsWindow(range: TokenStatsRange, asOfMs: number, timeZone = 'UTC') {\n if (range === '1h' || range === '12h' || range === '24h') {\n const duration = { '1h': HOUR, '12h': 12 * HOUR, '24h': 24 * HOUR };\n const bucketMs = { '1h': 300_000, '12h': HOUR, '24h': 2 * HOUR }[range];\n return { startMs: asOfMs - duration[range], endMs: asOfMs, bucketMs };\n }\n if (range === '1d' || range === '7d' || range === '30d') {\n const days = { '1d': 1, '7d': 7, '30d': 30 }[range];\n const bucketMs = range === '1d' ? HOUR : 24 * HOUR;\n const startMs = asOfMs - days * 24 * HOUR;\n const bucketStarts = Array.from({ length: range === '1d' ? 24 : days }, (_, i) => startMs + i * bucketMs);\n return { startMs, endMs: asOfMs, bucketMs, bucketStarts };\n }\n const format = new Intl.DateTimeFormat('en-US', {\n timeZone, year: 'numeric', month: 'numeric', day: 'numeric',\n hour: 'numeric', minute: 'numeric', second: 'numeric', hourCycle: 'h23',\n });\n const parts = (ms: number) => Object.fromEntries(format.formatToParts(ms)\n .filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));\n const today = parts(asOfMs);\n const day = Date.UTC(today.year!, today.month! - 1, today.day!);\n // Resolve each local midnight separately so DST days can contain 23 or 25 hours.\n const midnight = (date: number) => {\n let candidate = date;\n for (let i = 0; i < 4; i++) {\n const p = parts(candidate);\n const local = Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!, p.second!);\n const next = candidate + date - local;\n if (next === candidate) return candidate;\n candidate = next;\n }\n return candidate;\n };\n if (range === 'day') {\n const startMs = midnight(day);\n const bucketEndMs = midnight(day + 24 * HOUR);\n const bucketStarts = Array.from({ length: Math.ceil((bucketEndMs - startMs) / HOUR) }, (_, i) => startMs + i * HOUR);\n return { startMs, endMs: asOfMs, bucketMs: HOUR, bucketStarts, bucketEndMs };\n }\n const firstDay = range === 'month' ? Date.UTC(today.year!, today.month! - 1, 1)\n : day - ((new Date(day).getUTCDay() + 6) % 7) * 24 * HOUR;\n const nextPeriod = range === 'month' ? Date.UTC(today.year!, today.month!, 1) : firstDay + 7 * 24 * HOUR;\n const days = (nextPeriod - firstDay) / (24 * HOUR);\n const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));\n return { startMs: bucketStarts[0]!, endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };\n}\n"
20
20
  ],
21
- "mappings": ";;AAAA;;;ACOA,IAAM,UAAU,OAAO,IAAI,mCAAmC;AAI9D,SAAS,YAAY,CAAC,WAAoB,CAAC,GAAkB;AAAA,EAC3D,MAAM,SAAS,CAAC,UACd,CAAC,OAAyB,YAAqB;AAAA,IAC7C,MAAM,OAAQ,WAAuC;AAAA,IACrD,IAAI,MAAM;AAAA,MACR,IAAI,OAAO,UAAU;AAAA,QAAU,KAAK,OAAO,UAAU,KAAK;AAAA,MACrD;AAAA,aAAK,OAAO,KAAI,aAAa,MAAK,GAAG,OAAO;AAAA,IACnD,EAAO,SAAI,UAAU,WAAW,QAAQ,IAAI,cAAc,SAAS;AAAA,MACjE,MAAM,QAAQ,UAAU,UAAU,QAAQ,QAAQ,QAAQ;AAAA,MAC1D,MAAM,YAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,OAAO,UAAU,WAAW,WAAW,KAAI,aAAa,MAAK,CAAC;AAAA,IAC3H;AAAA;AAAA,EAEJ,OAAO;AAAA,IAAC,MAAM,OAAO,MAAM;AAAA,IAAG,MAAM,OAAO,MAAM;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAC/F,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,WAAS,aAAa,KAAI,aAAa,MAAK,CAAC;AAAA,EAAC;AAAA;AAE1E,IAAM,SAAS,aAAa;;;ACd5B,IAAM,2BAA2B,OAAO,0BAA0B;;ACRlE,IAAM,sBAAqC,OAAO,OAAO,EAAC,QAAQ,aAAa,OAAO,IAAI,mBAAmB,EAAC,CAAC;;ACH/G,MAAM,2BAA2B,MAAM;AAAA,EAEvB;AAAA,EAAyB;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