@alvin0/ai-agent-sdk-core 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/define/session/model-config.js +1 -1
- package/dist/agent/define/session/model-config.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +21 -0
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +2 -0
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/history/validation.js +1 -1
- package/dist/agent/history/validation.js.map +1 -1
- package/dist/agent/loop/events.d.ts +5 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +1 -1
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/types.d.ts +2 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/loop/turn/validation.js +1 -1
- package/dist/agent/loop/turn/validation.js.map +1 -1
- package/dist/agent/memory/compaction.d.ts +10 -1
- package/dist/agent/memory/compaction.d.ts.map +1 -1
- package/dist/agent/memory/compaction.js +2 -2
- package/dist/agent/memory/compaction.js.map +1 -1
- package/dist/agent/memory/token-estimator.js +1 -1
- package/dist/agent/memory/token-estimator.js.map +1 -1
- package/dist/agent/mode/run-agent.js +1 -1
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +43 -1
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/common/errors.d.ts.map +1 -1
- package/dist/composition/common/errors.js +1 -1
- package/dist/composition/common/errors.js.map +1 -1
- package/dist/composition/embedding/activation.js +2 -0
- package/dist/composition/embedding/activation.js.map +1 -0
- package/dist/composition/embedding/cache.js +2 -0
- package/dist/composition/embedding/cache.js.map +1 -0
- package/dist/composition/embedding/definition.d.ts +7 -0
- package/dist/composition/embedding/definition.d.ts.map +1 -0
- package/dist/composition/embedding/definition.js +2 -0
- package/dist/composition/embedding/definition.js.map +1 -0
- package/dist/composition/embedding/handle.js +2 -0
- package/dist/composition/embedding/handle.js.map +1 -0
- package/dist/composition/embedding/limiter.js +2 -0
- package/dist/composition/embedding/limiter.js.map +1 -0
- package/dist/composition/embedding/manager.js +2 -0
- package/dist/composition/embedding/manager.js.map +1 -0
- package/dist/composition/embedding/observation.js +2 -0
- package/dist/composition/embedding/observation.js.map +1 -0
- package/dist/composition/embedding/planner.js +2 -0
- package/dist/composition/embedding/planner.js.map +1 -0
- package/dist/composition/embedding/plugin-types.d.ts +48 -0
- package/dist/composition/embedding/plugin-types.d.ts.map +1 -0
- package/dist/composition/embedding/plugin-types.js +2 -0
- package/dist/composition/embedding/plugin-types.js.map +1 -0
- package/dist/composition/embedding/preflight.js +2 -0
- package/dist/composition/embedding/preflight.js.map +1 -0
- package/dist/composition/embedding/registry.js +2 -0
- package/dist/composition/embedding/registry.js.map +1 -0
- package/dist/composition/embedding/retry.js +2 -0
- package/dist/composition/embedding/retry.js.map +1 -0
- package/dist/composition/embedding/usage.js +2 -0
- package/dist/composition/embedding/usage.js.map +1 -0
- package/dist/composition/lifecycle/types.d.ts +5 -1
- package/dist/composition/lifecycle/types.d.ts.map +1 -1
- package/dist/composition/lifecycle/types.js +1 -1
- package/dist/composition/lifecycle/types.js.map +1 -1
- package/dist/composition/preflight.js +1 -1
- package/dist/composition/preflight.js.map +1 -1
- package/dist/composition/provider/activation.js +1 -1
- package/dist/composition/provider/activation.js.map +1 -1
- package/dist/composition/provider/model-selection.js +1 -1
- package/dist/composition/provider/model-selection.js.map +1 -1
- package/dist/composition/provider/preflight.js +1 -1
- package/dist/composition/provider/preflight.js.map +1 -1
- package/dist/composition/runtime/owner.js +1 -1
- package/dist/composition/runtime/owner.js.map +1 -1
- package/dist/composition/runtime/public.js +1 -1
- package/dist/composition/runtime/public.js.map +1 -1
- package/dist/composition/runtime/types.d.ts +25 -2
- package/dist/composition/runtime/types.d.ts.map +1 -1
- package/dist/composition/startup.js +1 -1
- package/dist/composition/startup.js.map +1 -1
- package/dist/composition/team/options.js +1 -1
- package/dist/composition/team/options.js.map +1 -1
- package/dist/composition/team/runtime.js +1 -1
- package/dist/composition/team/runtime.js.map +1 -1
- package/dist/composition/team/types.d.ts +3 -0
- package/dist/composition/team/types.d.ts.map +1 -1
- package/dist/contract/generate-options.d.ts +2 -0
- package/dist/contract/generate-options.d.ts.map +1 -1
- package/dist/contract/model-info.d.ts +12 -2
- package/dist/contract/model-info.d.ts.map +1 -1
- package/dist/embedding/adapter.d.ts +104 -0
- package/dist/embedding/adapter.d.ts.map +1 -0
- package/dist/embedding/adapter.js +2 -0
- package/dist/embedding/adapter.js.map +1 -0
- package/dist/embedding/catalog.d.ts +82 -0
- package/dist/embedding/catalog.d.ts.map +1 -0
- package/dist/embedding/catalog.js +2 -0
- package/dist/embedding/catalog.js.map +1 -0
- package/dist/embedding/errors.d.ts +98 -0
- package/dist/embedding/errors.d.ts.map +1 -0
- package/dist/embedding/errors.js +2 -0
- package/dist/embedding/errors.js.map +1 -0
- package/dist/embedding/handle.d.ts +76 -0
- package/dist/embedding/handle.d.ts.map +1 -0
- package/dist/embedding/limits.d.ts +47 -0
- package/dist/embedding/limits.d.ts.map +1 -0
- package/dist/embedding/limits.js +2 -0
- package/dist/embedding/limits.js.map +1 -0
- package/dist/embedding/profile.d.ts +89 -0
- package/dist/embedding/profile.d.ts.map +1 -0
- package/dist/embedding/profile.js +2 -0
- package/dist/embedding/profile.js.map +1 -0
- package/dist/embedding/purpose.d.ts +37 -0
- package/dist/embedding/purpose.d.ts.map +1 -0
- package/dist/embedding/request.d.ts +54 -0
- package/dist/embedding/request.d.ts.map +1 -0
- package/dist/embedding/request.js +2 -0
- package/dist/embedding/request.js.map +1 -0
- package/dist/embedding/result.d.ts +50 -0
- package/dist/embedding/result.d.ts.map +1 -0
- package/dist/embedding/usage.d.ts +64 -0
- package/dist/embedding/usage.d.ts.map +1 -0
- package/dist/embedding/usage.js +2 -0
- package/dist/embedding/usage.js.map +1 -0
- package/dist/embedding/validation.d.ts +68 -0
- package/dist/embedding/validation.d.ts.map +1 -0
- package/dist/embedding/validation.js +2 -0
- package/dist/embedding/validation.js.map +1 -0
- package/dist/embedding.d.ts +12 -0
- package/dist/embedding.js +1 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +1 -1
- package/dist/message/content.d.ts +71 -1
- package/dist/message/content.d.ts.map +1 -1
- package/dist/message/projection.d.ts +28 -2
- package/dist/message/projection.d.ts.map +1 -1
- package/dist/message/projection.js +1 -1
- package/dist/message/projection.js.map +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/observation/event.d.ts +1 -1
- package/dist/observation/event.d.ts.map +1 -1
- package/dist/observation/event.js.map +1 -1
- package/dist/observation/port.d.ts +1 -1
- package/dist/observation/port.d.ts.map +1 -1
- package/dist/observation/port.js.map +1 -1
- package/dist/observation/privacy.js +1 -1
- package/dist/observation/privacy.js.map +1 -1
- package/dist/observation/report.d.ts +2 -0
- package/dist/observation/report.d.ts.map +1 -1
- package/dist/observation/report.js.map +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/provider.d.ts +3 -1
- package/dist/provider.js +1 -1
- package/dist/runtime/model-call-handle.js +1 -1
- package/dist/runtime/model-call-handle.js.map +1 -1
- package/dist/runtime/model-metadata.js +1 -1
- package/dist/runtime/model-metadata.js.map +1 -1
- package/dist/runtime/model-stream.js +1 -1
- package/dist/runtime/model-stream.js.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/with-retry.d.ts.map +1 -1
- package/dist/runtime/with-retry.js +1 -1
- package/dist/runtime/with-retry.js.map +1 -1
- package/dist/stream/assembler.d.ts.map +1 -1
- package/dist/stream/assembler.js +1 -1
- package/dist/stream/assembler.js.map +1 -1
- package/dist/stream/chunk.d.ts +6 -0
- package/dist/stream/chunk.d.ts.map +1 -1
- package/package.json +6 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activation.js","names":[],"sources":["../../../src/composition/provider/activation.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelAdapter } from '../../contract/adapter.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { AdapterRegistrationHandle, ModelProviderRegistrar, StreamMiddleware } from '../../plugin/provider-plugin.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText } from '../common/data.ts'\nimport { AgentRuntimeConstructionError, checkPreflightAbort } from '../common/errors.ts'\nimport type { RuntimeComponentCloseReport, RuntimeConstructionFailureCode } from '../common/errors.ts'\nimport type { CapturedProvider } from './types.ts'\nimport { beginCoreCapabilityOperation } from '../logging/capability.ts'\n\ninterface RouteRegistration {\n active: boolean\n routes: readonly string[]\n}\n\nexport interface RuntimeProviderRegistrar extends ModelProviderRegistrar {\n readonly logger: SdkLogger\n}\n\nexport interface ProviderRegistration {\n readonly id: string\n close(deadline?: ProviderCleanupDeadline): RuntimeComponentCloseReport\n}\n\nexport interface ProviderCleanupDeadline {\n readonly at: number\n readonly now: () => number\n}\n\nexport interface ProviderActivationDeadlines {\n readonly startup: ProviderCleanupDeadline\n readonly rollback: () => ProviderCleanupDeadline\n}\n\nconst lifecycleError = () => new AgentSdkError('Provider registration is outside setup or cleanup', 'PROVIDER_REGISTRAR_SEALED')\nconst claimError = () => new AgentSdkError('Provider registration must cover its declared routes exactly once', 'PROVIDER_CLAIMS_INVALID')\n\n/** Reject and observe asynchronous returns without reading a then property a second time. */\nfunction asynchronous(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false\n let then: unknown\n try { then = Reflect.get(value, 'then') } catch { return true }\n if (typeof then !== 'function') return false\n void new Promise((resolve, reject) => { Reflect.apply(then, value, [resolve, reject]) }).catch(() => undefined)\n return true\n}\n\ntype CleanupCode = 'CAPABILITY_CLEANUP_FAILED' | 'PROVIDER_CLEANUP_ASYNC_UNSUPPORTED' | 'CAPABILITY_CLEANUP_TIMEOUT'\n\nfunction closeRow(id: string, code?: CleanupCode): RuntimeComponentCloseReport {\n return Object.freeze({\n kind: 'provider-registration', id,\n status: code === undefined ? 'closed' : code === 'CAPABILITY_CLEANUP_TIMEOUT' ? 'timed-out' : 'failed',\n ...(code !== undefined ? { error: Object.freeze({\n code, stage: 'provider-cleanup', message: 'Provider cleanup did not complete synchronously',\n }) } : {}),\n })\n}\n\n/** Activate already-captured providers. The caller owns bus/exporter startup and the overall deadline. */\nexport function activateProviders(\n registry: ModelRegistry,\n providers: readonly CapturedProvider[],\n logger: SdkLogger,\n signal?: AbortSignal,\n deadlines?: ProviderActivationDeadlines,\n): readonly ProviderRegistration[] {\n checkPreflightAbort(signal)\n const installed: ProviderRegistration[] = []\n for (const [index, provider] of providers.entries()) {\n const setupOperation = beginCoreCapabilityOperation(\n logger.child({ providerIndex: index }), 'core-provider', 'setup',\n )\n let phase: 'setup' | 'sealed' | 'cleanup' | 'closed' = 'setup'\n let failureCode: RuntimeConstructionFailureCode = 'CAPABILITY_STARTUP_FAILED'\n let failureCleanup: RuntimeComponentCloseReport | undefined\n let cleanup: (() => void) | undefined\n let cleaned = false\n let committed = false\n let cleanupDeadline: ProviderCleanupDeadline | undefined\n let failureWasAbort: boolean | undefined\n // Support reports do not echo an arbitrary user-supplied identity.\n const reportId = `provider-${index}`\n const finishCleanup = (): RuntimeComponentCloseReport => {\n if (cleaned) return failureCleanup ?? closeRow(reportId)\n if (!committed) failureWasAbort ??= signal?.aborted === true\n cleaned = true\n phase = 'cleanup'\n let code: CleanupCode | undefined\n try {\n if (!committed) cleanupDeadline ??= deadlines?.rollback()\n if (cleanup !== undefined) {\n if (cleanupDeadline !== undefined && cleanupDeadline.now() >= cleanupDeadline.at) code = 'CAPABILITY_CLEANUP_TIMEOUT'\n else if (asynchronous(cleanup())) code = 'PROVIDER_CLEANUP_ASYNC_UNSUPPORTED'\n }\n } catch { code = 'CAPABILITY_CLEANUP_FAILED' }\n finally { phase = 'closed' }\n const row = closeRow(reportId, code)\n failureCleanup = row\n return row\n }\n try {\n checkPreflightAbort(signal)\n if (deadlines !== undefined && deadlines.startup.now() >= deadlines.startup.at) {\n failureCode = 'CAPABILITY_STARTUP_TIMEOUT'\n throw new Error('Provider startup deadline exhausted')\n }\n const dispose = registry.install({\n id: provider.id, displayName: provider.displayName, family: provider.family,\n setup(upstream) {\n const registrations: RouteRegistration[] = []\n const setupOnly = (): void => {\n if (phase !== 'setup') throw lifecycleError()\n checkPreflightAbort(signal)\n }\n const disposeOnly = (): void => {\n if (phase !== 'setup' && phase !== 'cleanup' && phase !== 'closed') throw lifecycleError()\n }\n const routesFor = (input: unknown, current?: RouteRegistration): readonly string[] => {\n setupOnly()\n const routes = arrayData(input, COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n const occupied = new Set(registrations.filter(row => row.active && row !== current).flatMap(row => row.routes))\n for (const route of routes) {\n if (!provider.routes.includes(route) || occupied.has(route)) throw claimError()\n occupied.add(route)\n }\n return Object.freeze(routes)\n }\n const registrar: RuntimeProviderRegistrar = Object.freeze({\n logger,\n registerAdapter(input: readonly string[], adapter: ModelAdapter) {\n const routes = routesFor(input)\n if (routes.length === 0) throw claimError()\n const handle = upstream.registerAdapter(routes, adapter)\n const row: RouteRegistration = { active: true, routes }\n registrations.push(row)\n const release = (() => {\n disposeOnly()\n if (!row.active) return\n handle()\n row.active = false\n }) as AdapterRegistrationHandle\n release.replace = next => {\n if (!row.active) throw lifecycleError()\n const replacement = routesFor(next, row)\n handle.replace(replacement)\n row.routes = replacement\n }\n return Object.freeze(release)\n },\n use(middleware: StreamMiddleware) {\n setupOnly()\n const release = upstream.use(middleware)\n let released = false\n return () => {\n disposeOnly()\n if (released) return\n released = true\n release()\n }\n },\n })\n try {\n const result = provider.setup(registrar)\n phase = 'sealed'\n cleanup = typeof result === 'function' ? result : undefined\n if (asynchronous(result)) {\n failureCode = 'PROVIDER_SETUP_ASYNC_UNSUPPORTED'\n throw new Error('Asynchronous provider setup is unsupported')\n }\n if (result !== undefined && typeof result !== 'function') throw new Error('Invalid provider setup result')\n checkPreflightAbort(signal)\n const routes = registrations.filter(row => row.active).flatMap(row => row.routes)\n if (routes.length !== provider.routes.length || provider.routes.some(route => !routes.includes(route))) {\n throw claimError()\n }\n setupOperation.success()\n return () => {\n const row = finishCleanup()\n if (row.status !== 'closed') throw new Error('Provider cleanup did not complete')\n }\n } catch (error) {\n if (signal?.aborted === true) setupOperation.abort(); else setupOperation.fail(error)\n failureWasAbort = signal?.aborted === true\n phase = 'sealed'\n if (cleanup !== undefined) failureCleanup = finishCleanup()\n throw error\n } finally {\n if (phase === 'setup') phase = 'sealed'\n }\n },\n })\n committed = true\n let report: RuntimeComponentCloseReport | undefined\n installed.push(Object.freeze({\n id: provider.id,\n close(deadline?: ProviderCleanupDeadline) {\n if (report !== undefined) return report\n cleanupDeadline = deadline\n // Prevent recursive disposal while user cleanup is executing.\n report = closeRow(reportId)\n try { dispose() } catch { report = failureCleanup ?? closeRow(reportId, 'CAPABILITY_CLEANUP_FAILED') }\n return report\n },\n }))\n checkPreflightAbort(signal)\n } catch (error: unknown) {\n const aborted = failureWasAbort ?? signal?.aborted === true\n if (aborted) setupOperation.abort(); else setupOperation.fail(error)\n const cleanupRows: RuntimeComponentCloseReport[] = []\n if (failureCleanup !== undefined) cleanupRows.push(failureCleanup)\n const deadline = deadlines?.rollback()\n for (const registration of [...installed].reverse()) cleanupRows.push(registration.close(deadline))\n throw new AgentRuntimeConstructionError({\n failureCode: aborted ? 'CAPABILITY_STARTUP_ABORTED' : failureCode,\n stage: 'provider-setup', reason: aborted ? 'aborted' : failureCode === 'CAPABILITY_STARTUP_TIMEOUT' ? 'timed-out' : 'failed',\n component: { kind: 'provider-plugin', id: reportId }, cleanup: cleanupRows,\n })\n }\n }\n return Object.freeze(installed)\n}\n"],"mappings":"uYAoCA,MAAM,MAAuB,IAAI,EAAc,oDAAqD,2BAA2B,EACzH,MAAmB,IAAI,EAAc,oEAAqE,yBAAyB,EAGzI,SAAS,EAAa,EAAyB,CAC7C,IAAK,OAAO,GAAU,WAAY,IAAmB,OAAO,GAAU,WAAY,MAAO,GACzF,IAAI,EACJ,GAAI,CAAE,EAAO,QAAQ,IAAI,EAAO,MAAM,CAAE,MAAQ,CAAE,MAAO,EAAK,CAG9D,OAFI,OAAO,GAAS,aACpB,IAAS,SAAS,EAAS,IAAW,CAAE,QAAQ,MAAM,EAAM,EAAO,CAAC,EAAS,CAAM,CAAC,CAAE,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,EACvG,GACT,CAIA,SAAS,EAAS,EAAY,EAAiD,CAC7E,OAAO,OAAO,OAAO,CACnB,KAAM,wBAAyB,KAC/B,OAAQ,IAAS,IAAA,GAAY,SAAW,IAAS,6BAA+B,YAAc,SAC9F,GAAI,IAAS,IAAA,GAEN,CAAC,EAFiB,CAAE,MAAO,OAAO,OAAO,CAC9C,OAAM,MAAO,mBAAoB,QAAS,iDAC5C,CAAC,CAAE,CACL,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACiC,CACjC,EAAoB,CAAM,EAC1B,IAAM,EAAoC,CAAC,EAC3C,IAAK,GAAM,CAAC,EAAO,KAAa,EAAU,QAAQ,EAAG,CACnD,IAAM,EAAiB,EACrB,EAAO,MAAM,CAAE,cAAe,CAAM,CAAC,EAAG,gBAAiB,OAC3D,EACI,EAAmD,QACnD,EAA8C,4BAC9C,EACA,EACA,EAAU,GACV,EAAY,GACZ,EACA,EAEE,EAAW,YAAY,IACvB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mC,CAClF,CACF,OAAS,EAAO,CAKd,MAJI,GAAQ,UAAY,GAAM,EAAe,MAAM,EAAQ,EAAe,KAAK,CAAK,EACpF,EAAkB,GAAQ,UAAY,GACtC,EAAQ,SACJ,IAAY,IAAA,KAAW,EAAiB,EAAc,GACpD,CACR,QAAU,CACJ,IAAU,UAAS,EAAQ,SACjC,CACF,CACF,CAAC,EACD,EAAY,GACZ,IAAI,EACJ,EAAU,KAAK,OAAO,OAAO,CAC3B,GAAI,EAAS,GACb,MAAM,EAAoC,CACxC,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,EAAkB,EAElB,EAAS,EAAS,CAAQ,EAC1B,GAAI,CAAE,EAAQ,CAAE,MAAQ,CAAE,EAAS,GAAkB,EAAS,EAAU,2BAA2B,CAAE,CACrG,OAAO,CACT,CACF,CAAC,CAAC,EACF,EAAoB,CAAM,CAC5B,OAAS,EAAgB,CACvB,IAAM,EAAU,GAAmB,GAAQ,UAAY,GACnD,EAAS,EAAe,MAAM,EAAQ,EAAe,KAAK,CAAK,EACnE,IAAM,EAA6C,CAAC,EAChD,IAAmB,IAAA,IAAW,EAAY,KAAK,CAAc,EACjE,IAAM,EAAW,GAAW,SAAS,EACrC,IAAK,IAAM,IAAgB,CAAC,GAAG,CAAS,CAAC,CAAC,QAAQ,EAAG,EAAY,KAAK,EAAa,MAAM,CAAQ,CAAC,EAClG,MAAM,IAAI,EAA8B,CACtC,YAAa,EAAU,6BAA+B,EACtD,MAAO,iBAAkB,OAAQ,EAAU,UAAY,IAAgB,6BAA+B,YAAc,SACpH,UAAW,CAAE,KAAM,kBAAmB,GAAI,CAAS,EAAG,QAAS,CACjE,CAAC,CACH,CACF,CACA,OAAO,OAAO,OAAO,CAAS,CAChC"}
|
|
1
|
+
{"version":3,"file":"activation.js","names":[],"sources":["../../../src/composition/provider/activation.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport type { ModelAdapter } from '../../contract/adapter.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { AdapterRegistrationHandle, ModelProviderRegistrar, StreamMiddleware } from '../../plugin/provider-plugin.ts'\nimport type { ModelRegistry } from '../../runtime/registry.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText } from '../common/data.ts'\nimport { AgentRuntimeConstructionError, checkPreflightAbort } from '../common/errors.ts'\nimport type { RuntimeComponentCloseReport, RuntimeConstructionFailureCode } from '../common/errors.ts'\nimport type { CapturedProvider } from './types.ts'\nimport { beginCoreCapabilityOperation } from '../logging/capability.ts'\n\ninterface RouteRegistration {\n active: boolean\n routes: readonly string[]\n}\n\nexport interface RuntimeProviderRegistrar extends ModelProviderRegistrar {\n readonly logger: SdkLogger\n}\n\nexport interface ProviderRegistration {\n readonly id: string\n close(deadline?: ProviderCleanupDeadline): RuntimeComponentCloseReport\n}\n\nexport interface ProviderCleanupDeadline {\n readonly at: number\n readonly now: () => number\n}\n\nexport interface ProviderActivationDeadlines {\n readonly startup: ProviderCleanupDeadline\n readonly rollback: () => ProviderCleanupDeadline\n}\n\n/**\n * The ONE rollback list, shared across both provider plugin kinds.\n *\n * Generation and embedding plugins are separate objects with separate `install()`\n * calls, so no registry transaction spans them. What makes startup look atomic\n * from outside is that both activations append to the same `installed` array and\n * every failure path rolls back that whole array in reverse order — a generation\n * registration is released when a LATER embedding plugin fails, and the other way\n * round (Requirement 11.7).\n *\n * Omit it and an activation owns a private list, which is what a single-kind\n * caller wants.\n */\nexport interface SharedProviderActivation {\n readonly installed: ProviderRegistration[]\n}\n\nexport const providerLifecycleError = () => new AgentSdkError('Provider registration is outside setup or cleanup', 'PROVIDER_REGISTRAR_SEALED')\nexport const providerClaimError = () => new AgentSdkError('Provider registration must cover its declared routes exactly once', 'PROVIDER_CLAIMS_INVALID')\nconst lifecycleError = providerLifecycleError\nconst claimError = providerClaimError\n\n/** Reject and observe asynchronous returns without reading a then property a second time. */\nexport function asynchronous(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false\n let then: unknown\n try { then = Reflect.get(value, 'then') } catch { return true }\n if (typeof then !== 'function') return false\n void new Promise((resolve, reject) => { Reflect.apply(then, value, [resolve, reject]) }).catch(() => undefined)\n return true\n}\n\nexport type CleanupCode = 'CAPABILITY_CLEANUP_FAILED' | 'PROVIDER_CLEANUP_ASYNC_UNSUPPORTED' | 'CAPABILITY_CLEANUP_TIMEOUT'\n\nexport function closeRow(id: string, code?: CleanupCode): RuntimeComponentCloseReport {\n return Object.freeze({\n kind: 'provider-registration', id,\n status: code === undefined ? 'closed' : code === 'CAPABILITY_CLEANUP_TIMEOUT' ? 'timed-out' : 'failed',\n ...(code !== undefined ? { error: Object.freeze({\n code, stage: 'provider-cleanup', message: 'Provider cleanup did not complete synchronously',\n }) } : {}),\n })\n}\n\n/**\n * Activate already-captured providers. The caller owns bus/exporter startup and the overall deadline.\n *\n * @param shared - the cross-kind rollback list; omit for a private one.\n * @returns every registration in `shared.installed`, this activation's included,\n * so the caller can hand one list to the runtime regardless of how many kinds\n * contributed to it.\n */\nexport function activateProviders(\n registry: ModelRegistry,\n providers: readonly CapturedProvider[],\n logger: SdkLogger,\n signal?: AbortSignal,\n deadlines?: ProviderActivationDeadlines,\n shared?: SharedProviderActivation,\n): readonly ProviderRegistration[] {\n checkPreflightAbort(signal)\n const installed: ProviderRegistration[] = shared?.installed ?? []\n // Report ids stay positional in the COMBINED list, so `provider-N` means the\n // same registration to activation rollback and to the runtime close report.\n const idOffset = installed.length\n for (const [index, provider] of providers.entries()) {\n const setupOperation = beginCoreCapabilityOperation(\n logger.child({ providerIndex: idOffset + index }), 'core-provider', 'setup',\n )\n let phase: 'setup' | 'sealed' | 'cleanup' | 'closed' = 'setup'\n let failureCode: RuntimeConstructionFailureCode = 'CAPABILITY_STARTUP_FAILED'\n let failureCleanup: RuntimeComponentCloseReport | undefined\n let cleanup: (() => void) | undefined\n let cleaned = false\n let committed = false\n let cleanupDeadline: ProviderCleanupDeadline | undefined\n let failureWasAbort: boolean | undefined\n // Support reports do not echo an arbitrary user-supplied identity.\n const reportId = `provider-${idOffset + index}`\n const finishCleanup = (): RuntimeComponentCloseReport => {\n if (cleaned) return failureCleanup ?? closeRow(reportId)\n if (!committed) failureWasAbort ??= signal?.aborted === true\n cleaned = true\n phase = 'cleanup'\n let code: CleanupCode | undefined\n try {\n if (!committed) cleanupDeadline ??= deadlines?.rollback()\n if (cleanup !== undefined) {\n if (cleanupDeadline !== undefined && cleanupDeadline.now() >= cleanupDeadline.at) code = 'CAPABILITY_CLEANUP_TIMEOUT'\n else if (asynchronous(cleanup())) code = 'PROVIDER_CLEANUP_ASYNC_UNSUPPORTED'\n }\n } catch { code = 'CAPABILITY_CLEANUP_FAILED' }\n finally { phase = 'closed' }\n const row = closeRow(reportId, code)\n failureCleanup = row\n return row\n }\n try {\n checkPreflightAbort(signal)\n if (deadlines !== undefined && deadlines.startup.now() >= deadlines.startup.at) {\n failureCode = 'CAPABILITY_STARTUP_TIMEOUT'\n throw new Error('Provider startup deadline exhausted')\n }\n const dispose = registry.install({\n id: provider.id, displayName: provider.displayName, family: provider.family,\n setup(upstream) {\n const registrations: RouteRegistration[] = []\n const setupOnly = (): void => {\n if (phase !== 'setup') throw lifecycleError()\n checkPreflightAbort(signal)\n }\n const disposeOnly = (): void => {\n if (phase !== 'setup' && phase !== 'cleanup' && phase !== 'closed') throw lifecycleError()\n }\n const routesFor = (input: unknown, current?: RouteRegistration): readonly string[] => {\n setupOnly()\n const routes = arrayData(input, COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n const occupied = new Set(registrations.filter(row => row.active && row !== current).flatMap(row => row.routes))\n for (const route of routes) {\n if (!provider.routes.includes(route) || occupied.has(route)) throw claimError()\n occupied.add(route)\n }\n return Object.freeze(routes)\n }\n const registrar: RuntimeProviderRegistrar = Object.freeze({\n logger,\n registerAdapter(input: readonly string[], adapter: ModelAdapter) {\n const routes = routesFor(input)\n if (routes.length === 0) throw claimError()\n const handle = upstream.registerAdapter(routes, adapter)\n const row: RouteRegistration = { active: true, routes }\n registrations.push(row)\n const release = (() => {\n disposeOnly()\n if (!row.active) return\n handle()\n row.active = false\n }) as AdapterRegistrationHandle\n release.replace = next => {\n if (!row.active) throw lifecycleError()\n const replacement = routesFor(next, row)\n handle.replace(replacement)\n row.routes = replacement\n }\n return Object.freeze(release)\n },\n use(middleware: StreamMiddleware) {\n setupOnly()\n const release = upstream.use(middleware)\n let released = false\n return () => {\n disposeOnly()\n if (released) return\n released = true\n release()\n }\n },\n })\n try {\n const result = provider.setup(registrar)\n phase = 'sealed'\n cleanup = typeof result === 'function' ? result : undefined\n if (asynchronous(result)) {\n failureCode = 'PROVIDER_SETUP_ASYNC_UNSUPPORTED'\n throw new Error('Asynchronous provider setup is unsupported')\n }\n if (result !== undefined && typeof result !== 'function') throw new Error('Invalid provider setup result')\n checkPreflightAbort(signal)\n const routes = registrations.filter(row => row.active).flatMap(row => row.routes)\n if (routes.length !== provider.routes.length || provider.routes.some(route => !routes.includes(route))) {\n throw claimError()\n }\n setupOperation.success()\n return () => {\n const row = finishCleanup()\n if (row.status !== 'closed') throw new Error('Provider cleanup did not complete')\n }\n } catch (error) {\n if (signal?.aborted === true) setupOperation.abort(); else setupOperation.fail(error)\n failureWasAbort = signal?.aborted === true\n phase = 'sealed'\n if (cleanup !== undefined) failureCleanup = finishCleanup()\n throw error\n } finally {\n if (phase === 'setup') phase = 'sealed'\n }\n },\n })\n committed = true\n let report: RuntimeComponentCloseReport | undefined\n installed.push(Object.freeze({\n id: provider.id,\n close(deadline?: ProviderCleanupDeadline) {\n if (report !== undefined) return report\n cleanupDeadline = deadline\n // Prevent recursive disposal while user cleanup is executing.\n report = closeRow(reportId)\n try { dispose() } catch { report = failureCleanup ?? closeRow(reportId, 'CAPABILITY_CLEANUP_FAILED') }\n return report\n },\n }))\n checkPreflightAbort(signal)\n } catch (error: unknown) {\n const aborted = failureWasAbort ?? signal?.aborted === true\n if (aborted) setupOperation.abort(); else setupOperation.fail(error)\n const cleanupRows: RuntimeComponentCloseReport[] = []\n if (failureCleanup !== undefined) cleanupRows.push(failureCleanup)\n const deadline = deadlines?.rollback()\n for (const registration of [...installed].reverse()) cleanupRows.push(registration.close(deadline))\n throw new AgentRuntimeConstructionError({\n failureCode: aborted ? 'CAPABILITY_STARTUP_ABORTED' : failureCode,\n stage: 'provider-setup', reason: aborted ? 'aborted' : failureCode === 'CAPABILITY_STARTUP_TIMEOUT' ? 'timed-out' : 'failed',\n component: { kind: 'provider-plugin', id: reportId }, cleanup: cleanupRows,\n })\n }\n }\n // A copy: the shared list must stay appendable for the next kind.\n return Object.freeze([...installed])\n}\n"],"mappings":"uYAqDA,MAAa,MAA+B,IAAI,EAAc,oDAAqD,2BAA2B,EACjI,MAA2B,IAAI,EAAc,oEAAqE,yBAAyB,EAClJ,EAAiB,EACjB,EAAa,EAGnB,SAAgB,EAAa,EAAyB,CACpD,IAAK,OAAO,GAAU,WAAY,IAAmB,OAAO,GAAU,WAAY,MAAO,GACzF,IAAI,EACJ,GAAI,CAAE,EAAO,QAAQ,IAAI,EAAO,MAAM,CAAE,MAAQ,CAAE,MAAO,EAAK,CAG9D,OAFI,OAAO,GAAS,aACpB,IAAS,SAAS,EAAS,IAAW,CAAE,QAAQ,MAAM,EAAM,EAAO,CAAC,EAAS,CAAM,CAAC,CAAE,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,EACvG,GACT,CAIA,SAAgB,EAAS,EAAY,EAAiD,CACpF,OAAO,OAAO,OAAO,CACnB,KAAM,wBAAyB,KAC/B,OAAQ,IAAS,IAAA,GAAY,SAAW,IAAS,6BAA+B,YAAc,SAC9F,GAAI,IAAS,IAAA,GAEN,CAAC,EAFiB,CAAE,MAAO,OAAO,OAAO,CAC9C,OAAM,MAAO,mBAAoB,QAAS,iDAC5C,CAAC,CAAE,CACL,CAAC,CACH,CAUA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACi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,MAAO,iBAAkB,OAAQ,EAAU,UAAY,IAAgB,6BAA+B,YAAc,SACpH,UAAW,CAAE,KAAM,kBAAmB,GAAI,CAAS,EAAG,QAAS,CACjE,CAAC,CACH,CACF,CAEA,OAAO,OAAO,OAAO,CAAC,GAAG,CAAS,CAAC,CACrC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{boundedText as t,objectValue as n,ownData as r}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as i,MODEL_BINDING_ERROR_CODES as a}from"../../capability/common/config.js";function o(e,a){let o=n(e);if(Reflect.ownKeys(o).some(e=>e!==`provider`&&e!==`id`))throw TypeError(`Model target contains unsupported fields`);let s=t(r(o,`provider`),i.identityBytes),c=Object.getOwnPropertyDescriptor(o,`id`);if(c!==void 0&&!(`value`in c))throw TypeError(`Model ID must be data`);let l=c===void 0&&a?void 0:t(c?.value,i.modelIdBytes);return Object.freeze({provider:s,...l===void 0?{}:{id:l}})}function s(t,n){let r;try{r=n===void 0?void 0:o(n,!0)}catch{throw new e(`Agent model target is invalid`,a.INVALID)}let i=r?.provider??t.defaultProvider;if(i!==void 0){let n=t.providers.find(e=>e.routes.includes(i));if(n===void 0)throw new e(`Agent model route is unavailable`,a.UNKNOWN_ROUTE);if(r?.id!==void 0)return Object.freeze({provider:i,id:r.id});if(n.defaultModel?.provider===i)return Object.freeze({...n.defaultModel});throw new e(`
|
|
1
|
+
import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{boundedText as t,objectValue as n,ownData as r}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as i,MODEL_BINDING_ERROR_CODES as a}from"../../capability/common/config.js";function o(e,a){let o=n(e);if(Reflect.ownKeys(o).some(e=>e!==`provider`&&e!==`id`))throw TypeError(`Model target contains unsupported fields`);let s=t(r(o,`provider`),i.identityBytes),c=Object.getOwnPropertyDescriptor(o,`id`);if(c!==void 0&&!(`value`in c))throw TypeError(`Model ID must be data`);let l=c===void 0&&a?void 0:t(c?.value,i.modelIdBytes);return Object.freeze({provider:s,...l===void 0?{}:{id:l}})}function s(e){let t=e.providers.flatMap(e=>e.routes);return t.length===0?`<none>`:t.map(e=>JSON.stringify(e)).join(`, `)}function c(t,n){let r;try{r=n===void 0?void 0:o(n,!0)}catch{throw new e(`Agent model target is invalid`,a.INVALID)}let i=r?.provider??t.defaultProvider;if(i!==void 0){let n=t.providers.find(e=>e.routes.includes(i));if(n===void 0)throw new e(`Agent model route ${JSON.stringify(i)} is unavailable; configured routes: ${s(t)}`,a.UNKNOWN_ROUTE);if(r?.id!==void 0)return Object.freeze({provider:i,id:r.id});if(n.defaultModel?.provider===i)return Object.freeze({...n.defaultModel});throw new e(`Route ${JSON.stringify(i)} has no configured model default; give the agent a full target { provider: ${JSON.stringify(i)}, id: '<model-id>' } or set defaultModel on that route`,a.MISSING_DEFAULT)}let c=t.providers.flatMap(e=>e.defaultModel===void 0?[]:[e.defaultModel]);if(c.length===0)throw new e(`Agent model requires an explicit target or default; give the agent { provider, id } or set defaultModel on one of the configured routes: ${s(t)}`,a.MISSING_DEFAULT);if(c.length!==1)throw new e(`Agent model defaults are ambiguous: ${c.map(e=>JSON.stringify(e.provider)).join(`, `)} each configure a defaultModel. Resolve it explicitly: set \`defaultProvider\` on the runtime options to pick one route, or give the agent a { provider, id } model target`,a.AMBIGUOUS_DEFAULT);return Object.freeze({...c[0]})}function l(e){return Object.freeze(e.providers.flatMap(e=>e.routes.map(t=>Object.freeze({id:t,route:t,name:e.displayName,pluginId:e.id,family:e.family,...e.defaultModel?.provider===t?{defaultModel:Object.freeze({...e.defaultModel})}:{}}))))}export{o as captureModelTarget,l as providerTopology,c as resolveAgentModel};
|
|
2
2
|
//# sourceMappingURL=model-selection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-selection.js","names":[],"sources":["../../../src/composition/provider/model-selection.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport { COMPOSITION_LIMITS, MODEL_BINDING_ERROR_CODES } from '../common/config.ts'\nimport { boundedText, objectValue, ownData } from '../common/data.ts'\nimport type { ModelTarget, ProviderSelection, RuntimeProviderInfo } from './types.ts'\n\nexport function captureModelTarget(value: unknown, allowRouteOnly: false): ModelTarget\nexport function captureModelTarget(value: unknown, allowRouteOnly: true): { readonly provider: string; readonly id?: string }\nexport function captureModelTarget(value: unknown, allowRouteOnly: boolean) {\n const input = objectValue(value)\n if (Reflect.ownKeys(input).some(key => key !== 'provider' && key !== 'id')) {\n throw new TypeError('Model target contains unsupported fields')\n }\n const provider = boundedText(ownData(input, 'provider'), COMPOSITION_LIMITS.identityBytes)\n const descriptor = Object.getOwnPropertyDescriptor(input, 'id')\n if (descriptor !== undefined && !('value' in descriptor)) throw new TypeError('Model ID must be data')\n const id = descriptor === undefined && allowRouteOnly\n ? undefined : boundedText(descriptor?.value, COMPOSITION_LIMITS.modelIdBytes)\n return Object.freeze({ provider, ...(id === undefined ? {} : { id }) })\n}\n\n/** No discovery or error-time failover: only explicit targets and captured omission defaults. */\nexport function resolveAgentModel(selection: ProviderSelection, input?: unknown): ModelTarget {\n let target: { readonly provider: string; readonly id?: string } | undefined\n try { target = input === undefined ? undefined : captureModelTarget(input, true) }\n catch { throw new AgentSdkError('Agent model target is invalid', MODEL_BINDING_ERROR_CODES.INVALID) }\n const route = target?.provider ?? selection.defaultProvider\n if (route !== undefined) {\n const owner = selection.providers.find(provider => provider.routes.includes(route))\n if (owner === undefined) throw new AgentSdkError(
|
|
1
|
+
{"version":3,"file":"model-selection.js","names":[],"sources":["../../../src/composition/provider/model-selection.ts"],"sourcesContent":["import { AgentSdkError } from '../../errors/agent-sdk-error.ts'\nimport { COMPOSITION_LIMITS, MODEL_BINDING_ERROR_CODES } from '../common/config.ts'\nimport { boundedText, objectValue, ownData } from '../common/data.ts'\nimport type { ModelTarget, ProviderSelection, RuntimeProviderInfo } from './types.ts'\n\nexport function captureModelTarget(value: unknown, allowRouteOnly: false): ModelTarget\nexport function captureModelTarget(value: unknown, allowRouteOnly: true): { readonly provider: string; readonly id?: string }\nexport function captureModelTarget(value: unknown, allowRouteOnly: boolean) {\n const input = objectValue(value)\n if (Reflect.ownKeys(input).some(key => key !== 'provider' && key !== 'id')) {\n throw new TypeError('Model target contains unsupported fields')\n }\n const provider = boundedText(ownData(input, 'provider'), COMPOSITION_LIMITS.identityBytes)\n const descriptor = Object.getOwnPropertyDescriptor(input, 'id')\n if (descriptor !== undefined && !('value' in descriptor)) throw new TypeError('Model ID must be data')\n const id = descriptor === undefined && allowRouteOnly\n ? undefined : boundedText(descriptor?.value, COMPOSITION_LIMITS.modelIdBytes)\n return Object.freeze({ provider, ...(id === undefined ? {} : { id }) })\n}\n\n/** Configured routes, in registration order, for a diagnostic that names the real choices. */\nfunction routeList(selection: ProviderSelection): string {\n const routes = selection.providers.flatMap(provider => provider.routes)\n return routes.length === 0 ? '<none>' : routes.map(route => JSON.stringify(route)).join(', ')\n}\n\n/** No discovery or error-time failover: only explicit targets and captured omission defaults. */\nexport function resolveAgentModel(selection: ProviderSelection, input?: unknown): ModelTarget {\n let target: { readonly provider: string; readonly id?: string } | undefined\n try { target = input === undefined ? undefined : captureModelTarget(input, true) }\n catch { throw new AgentSdkError('Agent model target is invalid', MODEL_BINDING_ERROR_CODES.INVALID) }\n const route = target?.provider ?? selection.defaultProvider\n if (route !== undefined) {\n const owner = selection.providers.find(provider => provider.routes.includes(route))\n if (owner === undefined) {\n throw new AgentSdkError(\n `Agent model route ${JSON.stringify(route)} is unavailable; configured routes: ${routeList(selection)}`,\n MODEL_BINDING_ERROR_CODES.UNKNOWN_ROUTE,\n )\n }\n if (target?.id !== undefined) return Object.freeze({ provider: route, id: target.id })\n if (owner.defaultModel?.provider === route) return Object.freeze({ ...owner.defaultModel })\n throw new AgentSdkError(\n `Route ${JSON.stringify(route)} has no configured model default; give the agent a full target `\n + `{ provider: ${JSON.stringify(route)}, id: '<model-id>' } or set defaultModel on that route`,\n MODEL_BINDING_ERROR_CODES.MISSING_DEFAULT,\n )\n }\n const defaults = selection.providers.flatMap(provider => provider.defaultModel === undefined ? [] : [provider.defaultModel])\n if (defaults.length === 0) {\n throw new AgentSdkError(\n 'Agent model requires an explicit target or default; give the agent { provider, id } '\n + `or set defaultModel on one of the configured routes: ${routeList(selection)}`,\n MODEL_BINDING_ERROR_CODES.MISSING_DEFAULT,\n )\n }\n if (defaults.length !== 1) {\n throw new AgentSdkError(\n `Agent model defaults are ambiguous: ${defaults.map(entry => JSON.stringify(entry.provider)).join(', ')} `\n + 'each configure a defaultModel. Resolve it explicitly: set `defaultProvider` on the runtime '\n + 'options to pick one route, or give the agent a { provider, id } model target',\n MODEL_BINDING_ERROR_CODES.AMBIGUOUS_DEFAULT,\n )\n }\n return Object.freeze({ ...defaults[0]! })\n}\n\nexport function providerTopology(selection: ProviderSelection): readonly RuntimeProviderInfo[] {\n return Object.freeze(selection.providers.flatMap(provider => provider.routes.map(route => Object.freeze({\n id: route, route, name: provider.displayName, pluginId: provider.id, family: provider.family,\n ...(provider.defaultModel?.provider === route ? { defaultModel: Object.freeze({ ...provider.defaultModel }) } : {}),\n }))))\n}\n"],"mappings":"kQAOA,SAAgB,EAAmB,EAAgB,EAAyB,CAC1E,IAAM,EAAQ,EAAY,CAAK,EAC/B,GAAI,QAAQ,QAAQ,CAAK,CAAC,CAAC,KAAK,GAAO,IAAQ,YAAc,IAAQ,IAAI,EACvE,MAAU,UAAU,0CAA0C,EAEhE,IAAM,EAAW,EAAY,EAAQ,EAAO,UAAU,EAAG,EAAmB,aAAa,EACnF,EAAa,OAAO,yBAAyB,EAAO,IAAI,EAC9D,GAAI,IAAe,IAAA,IAAa,EAAE,UAAW,GAAa,MAAU,UAAU,uBAAuB,EACrG,IAAM,EAAK,IAAe,IAAA,IAAa,EACnC,IAAA,GAAY,EAAY,GAAY,MAAO,EAAmB,YAAY,EAC9E,OAAO,OAAO,OAAO,CAAE,WAAU,GAAI,IAAO,IA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C,EAAS,IAAI,GAAS,KAAK,UAAU,EAAM,QAAQ,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,4KAGxG,EAA0B,iBAC5B,EAEF,OAAO,OAAO,OAAO,CAAE,GAAG,EAAS,EAAI,CAAC,CAC1C,CAEA,SAAgB,EAAiB,EAA8D,CAC7F,OAAO,OAAO,OAAO,EAAU,UAAU,QAAQ,GAAY,EAAS,OAAO,IAAI,GAAS,OAAO,OAAO,CACtG,GAAI,EAAO,QAAO,KAAM,EAAS,YAAa,SAAU,EAAS,GAAI,OAAQ,EAAS,OACtF,GAAI,EAAS,cAAc,WAAa,EAAQ,CAAE,aAAc,OAAO,OAAO,CAAE,GAAG,EAAS,YAAa,CAAC,CAAE,EAAI,CAAC,CACnH,CAAC,CAAC,CAAC,CAAC,CACN"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{arrayData as e,boundedText as t,capturedMethod as n,
|
|
1
|
+
import{arrayData as e,boundedText as t,capturedMethod as n,ownData as r}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as i}from"../../capability/common/config.js";import{checkPreflightAbort as a,invalidPreflight as o}from"../common/errors.js";import{captureModelTarget as s}from"./model-selection.js";const c=new WeakMap,l=new WeakMap;function u(e){return f(e)}function d(e,t,n){let r=Object.freeze({providers:Object.freeze([...e]),...n===void 0?{}:{defaultProvider:n}});return c.set(r,Object.freeze([...t])),r}function f(n){let a=t(r(n,`id`),i.identityBytes),c=t(r(n,`displayName`),i.displayNameBytes),l=r(n,`family`,!1),u=l===void 0?a:t(l,i.identityBytes),d=e(r(n,`routes`),i.routesPerProvider).map(e=>t(e,i.identityBytes));if(d.length===0)throw o();let f=r(n,`defaultModel`,!1),p=f===void 0?void 0:s(f,!1);if(p!==void 0&&!d.includes(p.provider))throw o();return Object.freeze({id:a,displayName:c,family:u,routes:Object.freeze(d),...p===void 0?{}:{defaultModel:p}})}function p(e,t){a(t);let r=l.get(e);if(r!==void 0)return r;let i=c.get(e);if(i===void 0)throw o();c.delete(e);try{let r=e.providers.map((e,r)=>{a(t);let o=n(i[r],`setup`);return Object.freeze({...e,setup:o})});a(t);let o=Object.freeze(r);return l.set(e,o),o}catch{throw a(t),o()}}export{p as captureProviderMethods,d as createProviderIdentityPlan,u as readProviderMetadata};
|
|
2
2
|
//# sourceMappingURL=preflight.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preflight.js","names":[],"sources":["../../../src/composition/provider/preflight.ts"],"sourcesContent":["import type { ModelProviderRegistrar } from '../../plugin/provider-plugin.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText, capturedMethod, objectValue, ownData } from '../common/data.ts'\nimport { checkPreflightAbort, invalidPreflight } from '../common/errors.ts'\nimport type { CapabilityIdentityConflict } from '../common/errors.ts'\nimport { capabilityIdentityConflict } from '../identity/error.ts'\nimport { captureModelTarget } from './model-selection.ts'\nimport { PROVIDER_PLUGIN_API_VERSION, type CapturedProvider, type ProviderMetadata, type ProviderSelection } from './types.ts'\n\n/** Internal phase token: identity validation is separate from executable method capture. */\nexport interface ProviderIdentityPlan extends ProviderSelection {}\nconst sourcesByPlan = new WeakMap<ProviderIdentityPlan, readonly object[]>()\nconst methodsByPlan = new WeakMap<ProviderIdentityPlan, readonly CapturedProvider[]>()\n\nfunction conflict(namespace: CapabilityIdentityConflict['namespace'], firstIndex: number, secondIndex: number) {\n return invalidPreflight(namespace === 'provider-route' ? 'PROVIDER_ROUTE_CONFLICT' : 'CAPABILITY_ID_CONFLICT',\n capabilityIdentityConflict(namespace, firstIndex, secondIndex))\n}\n\nfunction metadata(source: object): ProviderMetadata {\n const id = boundedText(ownData(source, 'id'), COMPOSITION_LIMITS.identityBytes)\n const displayName = boundedText(ownData(source, 'displayName'), COMPOSITION_LIMITS.displayNameBytes)\n const rawFamily = ownData(source, 'family', false)\n const family = rawFamily === undefined ? id : boundedText(rawFamily, COMPOSITION_LIMITS.identityBytes)\n const routes = arrayData(ownData(source, 'routes'), COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n if (routes.length === 0) throw invalidPreflight()\n const rawDefault = ownData(source, 'defaultModel', false)\n const defaultModel = rawDefault === undefined ? undefined : captureModelTarget(rawDefault, false)\n if (defaultModel !== undefined && !routes.includes(defaultModel.provider)) throw invalidPreflight()\n return Object.freeze({\n id, displayName, family, routes: Object.freeze(routes),\n ...(defaultModel === undefined ? {} : { defaultModel }),\n })\n}\n\n/** No setup lookup, allocation, registration, discovery, or ownership transfer in this phase. */\nexport function preflightProviderIdentities(\n input: unknown,\n defaultProvider?: unknown,\n signal?: AbortSignal,\n): ProviderIdentityPlan {\n checkPreflightAbort(signal)\n const failures = new Set<unknown>()\n // Retain only errors we created; never trust a foreign exception's shape/code/message.\n const fail = (error: Error): never => { failures.add(error); throw error }\n try {\n const sources = arrayData(input, COMPOSITION_LIMITS.providers).map(objectValue)\n const providers: ProviderMetadata[] = []\n const ids = new Map<string, number>()\n const routes = new Map<string, number>()\n for (const [index, source] of sources.entries()) {\n checkPreflightAbort(signal)\n // Marker comparisons are done here so foreign property-access exceptions are never passed through.\n if (ownData(source, 'kind', false) !== 'model-provider-plugin') fail(invalidPreflight('CAPABILITY_KIND_MISMATCH'))\n if (ownData(source, 'apiVersion', false) !== PROVIDER_PLUGIN_API_VERSION) fail(invalidPreflight('CAPABILITY_API_UNSUPPORTED'))\n const provider = metadata(source)\n const previous = ids.get(provider.id)\n if (previous !== undefined) fail(conflict('provider-plugin-id', previous, index))\n ids.set(provider.id, index)\n for (const route of provider.routes) {\n const first = routes.get(route)\n if (first !== undefined) fail(conflict('provider-route', first, index))\n routes.set(route, index)\n }\n providers.push(provider)\n }\n const selected = defaultProvider === undefined ? undefined\n : boundedText(defaultProvider, COMPOSITION_LIMITS.identityBytes)\n if (selected !== undefined && !providers.some(provider => provider.defaultModel?.provider === selected)) {\n fail(invalidPreflight())\n }\n checkPreflightAbort(signal)\n const plan: ProviderIdentityPlan = Object.freeze({\n providers: Object.freeze(providers), ...(selected === undefined ? {} : { defaultProvider: selected }),\n })\n sourcesByPlan.set(plan, Object.freeze(sources))\n return plan\n } catch (error) {\n if (signal?.aborted) checkPreflightAbort(signal)\n if (failures.has(error)) throw error\n throw invalidPreflight()\n }\n}\n\n/** Call only after ALL runtime identity namespaces (including exporters) have passed preflight. */\nexport function captureProviderMethods(plan: ProviderIdentityPlan, signal?: AbortSignal): readonly CapturedProvider[] {\n checkPreflightAbort(signal)\n const captured = methodsByPlan.get(plan)\n if (captured !== undefined) return captured\n const sources = sourcesByPlan.get(plan)\n if (sources === undefined) throw invalidPreflight()\n // A failed capture is terminal too: never reread a partially observed method table.\n sourcesByPlan.delete(plan)\n try {\n const result = plan.providers.map((provider, index) => {\n checkPreflightAbort(signal)\n const setup = capturedMethod<[ModelProviderRegistrar], void | (() => void)>(sources[index]!, 'setup')\n return Object.freeze({ ...provider, setup })\n })\n checkPreflightAbort(signal)\n const captured = Object.freeze(result)\n methodsByPlan.set(plan, captured)\n return captured\n } catch {\n checkPreflightAbort(signal)\n throw invalidPreflight()\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"preflight.js","names":[],"sources":["../../../src/composition/provider/preflight.ts"],"sourcesContent":["import type { ModelProviderRegistrar } from '../../plugin/provider-plugin.ts'\nimport { COMPOSITION_LIMITS } from '../common/config.ts'\nimport { arrayData, boundedText, capturedMethod, objectValue, ownData } from '../common/data.ts'\nimport { checkPreflightAbort, invalidPreflight } from '../common/errors.ts'\nimport type { CapabilityIdentityConflict } from '../common/errors.ts'\nimport { capabilityIdentityConflict } from '../identity/error.ts'\nimport { captureModelTarget } from './model-selection.ts'\nimport { PROVIDER_PLUGIN_API_VERSION, type CapturedProvider, type ProviderMetadata, type ProviderSelection } from './types.ts'\n\n/** Internal phase token: identity validation is separate from executable method capture. */\nexport interface ProviderIdentityPlan extends ProviderSelection {}\nconst sourcesByPlan = new WeakMap<ProviderIdentityPlan, readonly object[]>()\nconst methodsByPlan = new WeakMap<ProviderIdentityPlan, readonly CapturedProvider[]>()\n\nfunction conflict(namespace: CapabilityIdentityConflict['namespace'], firstIndex: number, secondIndex: number) {\n return invalidPreflight(namespace === 'provider-route' ? 'PROVIDER_ROUTE_CONFLICT' : 'CAPABILITY_ID_CONFLICT',\n capabilityIdentityConflict(namespace, firstIndex, secondIndex))\n}\n\n/**\n * Read the inert identity of one plugin object.\n *\n * Shared with the embedding kind: both kinds declare the same identity shape, so\n * duplicating this reader is how one of the two copies would eventually forget a\n * bound. Throws a generic `invalidPreflight()` on any shape violation.\n */\nexport function readProviderMetadata(source: object): ProviderMetadata {\n return metadata(source)\n}\n\n/**\n * Freeze a generation plan from ALREADY validated metadata and register its\n * sources for {@link captureProviderMethods}.\n *\n * Exists so a whole-input sweep can validate every kind first and still hand the\n * generation subset to the existing capture phase (Requirement 11.6).\n */\nexport function createProviderIdentityPlan(\n providers: readonly ProviderMetadata[],\n sources: readonly object[],\n defaultProvider?: string,\n): ProviderIdentityPlan {\n const plan: ProviderIdentityPlan = Object.freeze({\n providers: Object.freeze([...providers]),\n ...(defaultProvider === undefined ? {} : { defaultProvider }),\n })\n sourcesByPlan.set(plan, Object.freeze([...sources]))\n return plan\n}\n\nfunction metadata(source: object): ProviderMetadata {\n const id = boundedText(ownData(source, 'id'), COMPOSITION_LIMITS.identityBytes)\n const displayName = boundedText(ownData(source, 'displayName'), COMPOSITION_LIMITS.displayNameBytes)\n const rawFamily = ownData(source, 'family', false)\n const family = rawFamily === undefined ? id : boundedText(rawFamily, COMPOSITION_LIMITS.identityBytes)\n const routes = arrayData(ownData(source, 'routes'), COMPOSITION_LIMITS.routesPerProvider)\n .map(route => boundedText(route, COMPOSITION_LIMITS.identityBytes))\n if (routes.length === 0) throw invalidPreflight()\n const rawDefault = ownData(source, 'defaultModel', false)\n const defaultModel = rawDefault === undefined ? undefined : captureModelTarget(rawDefault, false)\n if (defaultModel !== undefined && !routes.includes(defaultModel.provider)) throw invalidPreflight()\n return Object.freeze({\n id, displayName, family, routes: Object.freeze(routes),\n ...(defaultModel === undefined ? {} : { defaultModel }),\n })\n}\n\n/** No setup lookup, allocation, registration, discovery, or ownership transfer in this phase. */\nexport function preflightProviderIdentities(\n input: unknown,\n defaultProvider?: unknown,\n signal?: AbortSignal,\n): ProviderIdentityPlan {\n checkPreflightAbort(signal)\n const failures = new Set<unknown>()\n // Retain only errors we created; never trust a foreign exception's shape/code/message.\n const fail = (error: Error): never => { failures.add(error); throw error }\n try {\n const sources = arrayData(input, COMPOSITION_LIMITS.providers).map(objectValue)\n const providers: ProviderMetadata[] = []\n const ids = new Map<string, number>()\n const routes = new Map<string, number>()\n for (const [index, source] of sources.entries()) {\n checkPreflightAbort(signal)\n // Marker comparisons are done here so foreign property-access exceptions are never passed through.\n if (ownData(source, 'kind', false) !== 'model-provider-plugin') fail(invalidPreflight('CAPABILITY_KIND_MISMATCH'))\n if (ownData(source, 'apiVersion', false) !== PROVIDER_PLUGIN_API_VERSION) fail(invalidPreflight('CAPABILITY_API_UNSUPPORTED'))\n const provider = metadata(source)\n const previous = ids.get(provider.id)\n if (previous !== undefined) fail(conflict('provider-plugin-id', previous, index))\n ids.set(provider.id, index)\n for (const route of provider.routes) {\n const first = routes.get(route)\n if (first !== undefined) fail(conflict('provider-route', first, index))\n routes.set(route, index)\n }\n providers.push(provider)\n }\n const selected = defaultProvider === undefined ? undefined\n : boundedText(defaultProvider, COMPOSITION_LIMITS.identityBytes)\n if (selected !== undefined && !providers.some(provider => provider.defaultModel?.provider === selected)) {\n fail(invalidPreflight())\n }\n checkPreflightAbort(signal)\n const plan: ProviderIdentityPlan = Object.freeze({\n providers: Object.freeze(providers), ...(selected === undefined ? {} : { defaultProvider: selected }),\n })\n sourcesByPlan.set(plan, Object.freeze(sources))\n return plan\n } catch (error) {\n if (signal?.aborted) checkPreflightAbort(signal)\n if (failures.has(error)) throw error\n throw invalidPreflight()\n }\n}\n\n/** Call only after ALL runtime identity namespaces (including exporters) have passed preflight. */\nexport function captureProviderMethods(plan: ProviderIdentityPlan, signal?: AbortSignal): readonly CapturedProvider[] {\n checkPreflightAbort(signal)\n const captured = methodsByPlan.get(plan)\n if (captured !== undefined) return captured\n const sources = sourcesByPlan.get(plan)\n if (sources === undefined) throw invalidPreflight()\n // A failed capture is terminal too: never reread a partially observed method table.\n sourcesByPlan.delete(plan)\n try {\n const result = plan.providers.map((provider, index) => {\n checkPreflightAbort(signal)\n const setup = capturedMethod<[ModelProviderRegistrar], void | (() => void)>(sources[index]!, 'setup')\n return Object.freeze({ ...provider, setup })\n })\n checkPreflightAbort(signal)\n const captured = Object.freeze(result)\n methodsByPlan.set(plan, captured)\n return captured\n } catch {\n checkPreflightAbort(signal)\n throw invalidPreflight()\n }\n}\n"],"mappings":"+TAWA,MAAM,EAAgB,IAAI,QACpB,EAAgB,IAAI,QAc1B,SAAgB,EAAqB,EAAkC,CACrE,OAAO,EAAS,CAAM,CACxB,CASA,SAAgB,EACd,EACA,EACA,EACsB,CACtB,IAAM,EAA6B,OAAO,OAAO,CAC/C,UAAW,OAAO,OAAO,CAAC,GAAG,CAAS,CAAC,EACvC,GAAI,IAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,iBAAgB,CAC7D,CAAC,EAED,OADA,EAAc,IAAI,EAAM,OAAO,OAAO,CAAC,GAAG,CAAO,CAAC,CAAC,EAC5C,CACT,CAEA,SAAS,EAAS,EAAkC,CAClD,IAAM,EAAK,EAAY,EAAQ,EAAQ,IAAI,EAAG,EAAmB,aAAa,EACxE,EAAc,EAAY,EAAQ,EAAQ,aAAa,EAAG,EAAmB,gBAAgB,EAC7F,EAAY,EAAQ,EAAQ,SAAU,EAAK,EAC3C,EAAS,IAAc,IAAA,GAAY,EAAK,EAAY,EAAW,EAAmB,aAAa,EAC/F,EAAS,EAAU,EAAQ,EAAQ,QAAQ,EAAG,EAAmB,iBAAiB,CAAC,CACtF,IAAI,GAAS,EAAY,EAAO,EAAmB,aAAa,CAAC,EACpE,GAAI,EAAO,SAAW,EAAG,MAAM,EAAiB,EAChD,IAAM,EAAa,EAAQ,EAAQ,eAAgB,EAAK,EAClD,EAAe,IAAe,IAAA,GAAY,IAAA,GAAY,EAAmB,EAAY,EAAK,EAChG,GAAI,IAAiB,IAAA,IAAa,CAAC,EAAO,SAAS,EAAa,QAAQ,EAAG,MAAM,EAAiB,EAClG,OAAO,OAAO,OAAO,CACnB,KAAI,cAAa,SAAQ,OAAQ,OAAO,OAAO,CAAM,EACrD,GAAI,IAAiB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAa,CACvD,CAAC,CACH,CAoDA,SAAgB,EAAuB,EAA4B,EAAmD,CACpH,EAAoB,CAAM,EAC1B,IAAM,EAAW,EAAc,IAAI,CAAI,EACvC,GAAI,IAAa,IAAA,GAAW,OAAO,EACnC,IAAM,EAAU,EAAc,IAAI,CAAI,EACtC,GAAI,IAAY,IAAA,GAAW,MAAM,EAAiB,EAElD,EAAc,OAAO,CAAI,EACzB,GAAI,CACF,IAAM,EAAS,EAAK,UAAU,KAAK,EAAU,IAAU,CACrD,EAAoB,CAAM,EAC1B,IAAM,EAAQ,EAA8D,EAAQ,GAAS,OAAO,EACpG,OAAO,OAAO,OAAO,CAAE,GAAG,EAAU,OAAM,CAAC,CAC7C,CAAC,EACD,EAAoB,CAAM,EAC1B,IAAM,EAAW,OAAO,OAAO,CAAM,EAErC,OADA,EAAc,IAAI,EAAM,CAAQ,EACzB,CACT,MAAQ,CAEN,MADA,EAAoB,CAAM,EACpB,EAAiB,CACzB,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRuntimePlatform as e}from"../../platform/adapter.js";import{ModelRegistry as t}from"../../runtime/registry.js";import{
|
|
1
|
+
import{createRuntimePlatform as e}from"../../platform/adapter.js";import{ModelRegistry as t}from"../../runtime/registry.js";import{EmbeddingRegistry as n}from"../embedding/registry.js";import{RuntimeEmbedding as r}from"../embedding/manager.js";import{RuntimeResources as i}from"../../platform/resources.js";import{createRuntimeResource as a}from"../delivery/resource.js";import{RuntimeObservationPort as o}from"../observation/port.js";import{providerTopology as s}from"../provider/model-selection.js";import{preflightRuntimeCapabilities as c}from"../preflight.js";import{activateRuntimeCapabilities as l}from"../startup.js";import{RuntimeOperations as u}from"../lifecycle/operations.js";import{captureCloseSignal as d,captureRuntimeOwnerOptions as f}from"./config.js";import{bindRuntimeAgentDefinition as p}from"../agent/definition.js";import{createRuntimeAgent as m}from"../agent/session.js";import{RuntimeModelCatalog as h}from"../model-catalog/manager.js";import{createRuntimeAgentTeam as g}from"../team/runtime.js";var _=class{platform;resources;observation;resource;topology;selection;providersOwned;exporters;closeTimeoutMs;embeddingRegistry;registry;operations;closing;catalogs;embeddings;teams=[];closedTeams=[];constructor(e,t,i,a,o,s,c,l,u,d,f,p=new n){this.platform=i,this.resources=a,this.observation=o,this.resource=s,this.topology=c,this.selection=l,this.providersOwned=u,this.exporters=d,this.closeTimeoutMs=f,this.embeddingRegistry=p,this.registry=e,this.operations=t,this.catalogs=new h(e,t,a,c),this.embeddings=new r({registry:this.embeddingRegistry,operations:t,observation:o,resource:s})}providers(){return this.topology}modelCatalog(e,t){return this.catalogs.get(e,t)}embeddingModel(e){return this.embeddings.model(e)}agent(e){return this.operations.assertActive(),m(this,p(e,this.selection))}team(e){let t=g(this,e,e=>this.retireTeam(e));return this.teams.push(t),t.view}logger(e){return this.observation.logger(e)}diagnostics(){return this.observation.diagnostics()}close(e){if(this.closing!==void 0)return this.closing;let t=d(e),n,r;this.closing=new Promise((e,t)=>{n=e,r=t});let i=this.closing;try{let e=this.operations.beginClose({timeoutMs:this.closeTimeoutMs,...t===void 0?{}:{signal:t}});return this.observation.stopAdmission(),this.finishClose(e).then(n,r),i}catch(e){throw this.closing=void 0,e}}async finishClose(e){let t=await e;this.embeddings.dispose();let n=this.operations.closeDeadlineAt(),r=[...this.closedTeams];for(let e of[...this.teams].reverse())r.push(await e.closeForRuntime(n));for(let[e,t]of[...this.providersOwned].reverse().entries()){let i=this.providersOwned.length-e-1;this.platform.monotonicNow()>=n?r.push(y(i)):r.push(t.close({at:n,now:()=>this.platform.monotonicNow()}))}let i=this.observation.observationDeadline(n);return await this.observation.flushUntil(i),this.observation.seal(),r.push(...await this.exporters.close(i)),this.operations.finishClose(),Object.freeze({state:`closed`,...t,components:Object.freeze(r),observationHealth:this.observation.health()})}retireTeam(e){let t=this.teams.indexOf(e);t<0||(this.teams.splice(t,1),this.closedTeams.push(Object.freeze({kind:`agent-team`,id:e.id,status:`closed`})),this.closedTeams.length>1024&&this.closedTeams.shift())}};async function v(n,r=globalThis){let d=e(r),p=f(n),m=c(p.providers,p.observability.exporters,p.defaultProvider,p.signal),h=new i(d),g;try{let e=a(p.resource,d);g=new o(e,m.exporters,d,h,{mode:p.observability.mode,...p.observability.content===void 0?{}:{content:p.observability.content},...p.observability.minimumLogLevel===void 0?{}:{minimumLogLevel:p.observability.minimumLogLevel},...p.observability.processors===void 0?{}:{processors:p.observability.processors},...p.observability.redactors===void 0?{}:{redactors:p.observability.redactors},...p.observability.includeErrorStacks===void 0?{}:{includeErrorStacks:p.observability.includeErrorStacks},...p.observability.openSpan===void 0?{}:{openSpan:p.observability.openSpan},...p.observability.maxQueueEvents===void 0?{}:{maxEvents:p.observability.maxQueueEvents},...p.observability.maxQueueBytes===void 0?{}:{maxBytes:p.observability.maxQueueBytes},...p.observability.maxBatchEvents===void 0?{}:{maxBatchEvents:p.observability.maxBatchEvents},...p.observability.maxBatchBytes===void 0?{}:{maxBatchBytes:p.observability.maxBatchBytes},...p.observability.flushTimeoutMs===void 0?{}:{flushTimeoutMs:p.observability.flushTimeoutMs},...p.observability.shutdownTimeoutMs===void 0?{}:{shutdownTimeoutMs:p.observability.shutdownTimeoutMs},...p.diagnosticMaxEvents===void 0?{}:{diagnosticMaxEvents:p.diagnosticMaxEvents},...p.diagnosticMaxBytes===void 0?{}:{diagnosticMaxBytes:p.diagnosticMaxBytes}});let n=new t({observation:g,observationResource:e}),r=await l(m,n,g.logger({scope:`sdk.provider.setup`}),h,{startupTimeoutMs:p.startupTimeoutMs,rollbackTimeoutMs:p.closeTimeoutMs,...p.signal===void 0?{}:{signal:p.signal}});return new _(n,new u(h),d,h,g,e,s(m.selection),m.selection,r.providers,r.exporters,p.closeTimeoutMs,r.embeddingRegistry)}catch(e){throw g?.seal(),h.close(),e}}function y(e){return Object.freeze({kind:`provider-registration`,id:`provider-${e}`,status:`timed-out`,error:Object.freeze({code:`CAPABILITY_CLEANUP_TIMEOUT`,stage:`provider-cleanup`,message:`Provider cleanup did not start before the runtime close deadline`})})}export{_ as RuntimeCompositionOwner,v as createRuntimeCompositionOwner};
|
|
2
2
|
//# sourceMappingURL=owner.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"owner.js","names":[],"sources":["../../../src/composition/runtime/owner.ts"],"sourcesContent":["import { ModelRegistry } from '../../runtime/registry.ts'\nimport { createRuntimePlatform, type RuntimePlatform } from '../../platform/adapter.ts'\nimport { RuntimeResources } from '../../platform/resources.ts'\nimport { createRuntimeResource } from '../delivery/resource.ts'\nimport { RuntimeObservationPort, type RuntimeDiagnosticSnapshot } from '../observation/port.ts'\nimport { preflightRuntimeCapabilities } from '../preflight.ts'\nimport { providerTopology } from '../provider/model-selection.ts'\nimport type { ProviderRegistration } from '../provider/activation.ts'\nimport type { RuntimeProviderInfo } from '../provider/types.ts'\nimport { activateRuntimeCapabilities } from '../startup.ts'\nimport { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { QuiescenceReport } from '../lifecycle/types.ts'\nimport type { RuntimeComponentCloseReport } from '../common/errors.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { RuntimeLoggerContext } from '../logging/logger.ts'\nimport { captureCloseSignal, captureRuntimeOwnerOptions } from './config.ts'\nimport type { RuntimeCloseReport, RuntimeCompositionView, RuntimeOwnerOptions } from './types.ts'\nimport { bindRuntimeAgentDefinition } from '../agent/definition.ts'\nimport { createRuntimeAgent } from '../agent/session.ts'\nimport type { RuntimeAgent, RuntimeAgentBindingInput } from '../agent/types.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { RuntimeModelCatalog } from '../model-catalog/manager.ts'\nimport type { ModelCatalogOptions } from '../../contract/model-info.ts'\nimport type { RuntimeModelCatalogSnapshot } from '../model-catalog/types.ts'\nimport { createRuntimeAgentTeam } from '../team/runtime.ts'\nimport type { RuntimeAgentTeam, RuntimeAgentTeamOptions, RuntimeTeamRegistration } from '../team/types.ts'\n\n/** Internal composition owner used to finish lifecycle semantics before the public agent surface is exported. */\nexport class RuntimeCompositionOwner implements RuntimeCompositionView {\n readonly registry: ModelRegistry\n readonly operations: RuntimeOperations\n private closing: Promise<RuntimeCloseReport> | undefined\n private readonly catalogs: RuntimeModelCatalog\n private readonly teams: RuntimeTeamRegistration[] = []\n private readonly closedTeams: RuntimeComponentCloseReport[] = []\n\n constructor(\n registry: ModelRegistry,\n operations: RuntimeOperations,\n private readonly platform: RuntimePlatform,\n readonly resources: RuntimeResources,\n readonly observation: RuntimeObservationPort,\n readonly resource: import('../delivery/resource.ts').RuntimeObservationResource,\n private readonly topology: readonly RuntimeProviderInfo[],\n private readonly selection: ProviderSelection,\n private readonly providersOwned: readonly ProviderRegistration[],\n private readonly exporters: Awaited<ReturnType<typeof activateRuntimeCapabilities>>['exporters'],\n private readonly closeTimeoutMs: number,\n ) {\n this.registry = registry\n this.operations = operations\n this.catalogs = new RuntimeModelCatalog(registry, operations, resources, topology)\n }\n\n providers(): readonly RuntimeProviderInfo[] { return this.topology }\n modelCatalog(route: string, options?: ModelCatalogOptions): Promise<RuntimeModelCatalogSnapshot> {\n return this.catalogs.get(route, options)\n }\n agent(input: RuntimeAgentBindingInput): RuntimeAgent {\n this.operations.assertActive()\n return createRuntimeAgent(this, bindRuntimeAgentDefinition(input, this.selection))\n }\n team(input: RuntimeAgentTeamOptions): RuntimeAgentTeam {\n const registration = createRuntimeAgentTeam(this, input, closed => this.retireTeam(closed))\n this.teams.push(registration)\n return registration.view\n }\n logger(context?: RuntimeLoggerContext): SdkLogger { return this.observation.logger(context) }\n diagnostics(): RuntimeDiagnosticSnapshot { return this.observation.diagnostics() }\n\n close(input?: { readonly signal?: AbortSignal }): Promise<RuntimeCloseReport> {\n if (this.closing !== undefined) return this.closing\n const signal = captureCloseSignal(input)\n let resolve!: (report: RuntimeCloseReport) => void\n let reject!: (error: unknown) => void\n this.closing = new Promise((done, fail) => { resolve = done; reject = fail })\n const shared = this.closing\n try {\n const quiescence = this.operations.beginClose({ timeoutMs: this.closeTimeoutMs, ...(signal === undefined ? {} : { signal }) })\n this.observation.stopAdmission()\n void this.finishClose(quiescence).then(resolve, reject)\n return shared\n } catch (error) {\n this.closing = undefined\n throw error\n }\n }\n\n private async finishClose(quiescenceTask: Promise<QuiescenceReport>): Promise<RuntimeCloseReport> {\n const quiescence = await quiescenceTask\n const deadlineAt = this.operations.closeDeadlineAt()\n const components: RuntimeComponentCloseReport[] = [...this.closedTeams]\n for (const team of [...this.teams].reverse()) components.push(await team.closeForRuntime(deadlineAt))\n for (const [reverseIndex, registration] of [...this.providersOwned].reverse().entries()) {\n const originalIndex = this.providersOwned.length - reverseIndex - 1\n if (this.platform.monotonicNow() >= deadlineAt) components.push(timedOutProvider(originalIndex))\n else components.push(registration.close({ at: deadlineAt, now: () => this.platform.monotonicNow() }))\n }\n const observationDeadline = this.observation.observationDeadline(deadlineAt)\n await this.observation.flushUntil(observationDeadline)\n this.observation.seal()\n components.push(...await this.exporters.close(observationDeadline))\n this.operations.finishClose()\n return Object.freeze({ state: 'closed', ...quiescence, components: Object.freeze(components),\n observationHealth: this.observation.health() })\n }\n\n private retireTeam(registration: RuntimeTeamRegistration): void {\n const index = this.teams.indexOf(registration)\n if (index < 0) return\n this.teams.splice(index, 1)\n this.closedTeams.push(Object.freeze({ kind: 'agent-team', id: registration.id, status: 'closed' }))\n // Reporting metadata is intentionally bounded independently of heavyweight\n // team state. Older tombstones can be omitted from a later runtime report.\n if (this.closedTeams.length > 1_024) this.closedTeams.shift()\n }\n}\n\n/** Web preflight and whole-input identity validation both precede runtime-owned allocations. */\nexport async function createRuntimeCompositionOwner(\n input: RuntimeOwnerOptions,\n host: typeof globalThis = globalThis,\n): Promise<RuntimeCompositionOwner> {\n const platform = createRuntimePlatform(host)\n const options = captureRuntimeOwnerOptions(input)\n const plan = preflightRuntimeCapabilities(options.providers, options.observability.exporters,\n options.defaultProvider, options.signal)\n const resources = new RuntimeResources(platform)\n let observation: RuntimeObservationPort | undefined\n try {\n const resource = createRuntimeResource(options.resource, platform)\n observation = new RuntimeObservationPort(resource, plan.exporters, platform, resources, {\n mode: options.observability.mode,\n ...(options.observability.content === undefined ? {} : { content: options.observability.content }),\n ...(options.observability.minimumLogLevel === undefined ? {} : { minimumLogLevel: options.observability.minimumLogLevel }),\n ...(options.observability.processors === undefined ? {} : { processors: options.observability.processors }),\n ...(options.observability.redactors === undefined ? {} : { redactors: options.observability.redactors }),\n ...(options.observability.includeErrorStacks === undefined ? {} : { includeErrorStacks: options.observability.includeErrorStacks }),\n ...(options.observability.openSpan === undefined ? {} : { openSpan: options.observability.openSpan }),\n ...(options.observability.maxQueueEvents === undefined ? {} : { maxEvents: options.observability.maxQueueEvents }),\n ...(options.observability.maxQueueBytes === undefined ? {} : { maxBytes: options.observability.maxQueueBytes }),\n ...(options.observability.maxBatchEvents === undefined ? {} : { maxBatchEvents: options.observability.maxBatchEvents }),\n ...(options.observability.maxBatchBytes === undefined ? {} : { maxBatchBytes: options.observability.maxBatchBytes }),\n ...(options.observability.flushTimeoutMs === undefined ? {} : { flushTimeoutMs: options.observability.flushTimeoutMs }),\n ...(options.observability.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.observability.shutdownTimeoutMs }),\n ...(options.diagnosticMaxEvents === undefined ? {} : { diagnosticMaxEvents: options.diagnosticMaxEvents }),\n ...(options.diagnosticMaxBytes === undefined ? {} : { diagnosticMaxBytes: options.diagnosticMaxBytes }),\n })\n const registry = new ModelRegistry({ observation, observationResource: resource })\n const capabilities = await activateRuntimeCapabilities(plan, registry,\n observation.logger({ scope: 'sdk.provider.setup' }), resources, {\n startupTimeoutMs: options.startupTimeoutMs, rollbackTimeoutMs: options.closeTimeoutMs,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n return new RuntimeCompositionOwner(registry, new RuntimeOperations(resources), platform, resources,\n observation, resource, providerTopology(plan.selection), plan.selection,\n capabilities.providers, capabilities.exporters, options.closeTimeoutMs)\n } catch (error) {\n observation?.seal()\n resources.close()\n throw error\n }\n}\n\nfunction timedOutProvider(index: number): RuntimeComponentCloseReport {\n return Object.freeze({ kind: 'provider-registration', id: `provider-${index}`, status: 'timed-out',\n error: Object.freeze({ code: 'CAPABILITY_CLEANUP_TIMEOUT', stage: 'provider-cleanup',\n message: 'Provider cleanup did not start before the runtime close deadline' }) })\n}\n"],"mappings":"m4BA4BA,IAAa,EAAb,KAAuE,CAWlD,SACR,UACA,YACA,SACQ,SACA,UACA,eACA,UACA,eAlBnB,SACA,WACA,QACA,SACA,MAAoD,CAAC,EACrD,YAA8D,CAAC,EAE/D,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CATiB,KAAA,SAAA,EACR,KAAA,UAAA,EACA,KAAA,YAAA,EACA,KAAA,SAAA,EACQ,KAAA,SAAA,EACA,KAAA,UAAA,EACA,KAAA,eAAA,EACA,KAAA,UAAA,EACA,KAAA,eAAA,EAEjB,KAAK,SAAW,EAChB,KAAK,WAAa,EAClB,KAAK,SAAW,IAAI,EAAoB,EAAU,EAAY,EAAW,CAAQ,CACnF,CAEA,WAA4C,CAAE,OAAO,KAAK,QAAS,CACnE,aAAa,EAAe,EAAqE,CAC/F,OAAO,KAAK,SAAS,IAAI,EAAO,CAAO,CACzC,CACA,MAAM,EAA+C,CAEnD,OADA,KAAK,WAAW,aAAa,EACtB,EAAmB,KAAM,EAA2B,EAAO,KAAK,SAAS,CAAC,CACnF,CACA,KAAK,EAAkD,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E,GAAI,EAAQ,SAAW,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,EAAQ,MAAO,CACnE,CAAC,EACH,OAAO,IAAI,EAAwB,EAAU,IAAI,EAAkB,CAAS,EAAG,EAAU,EACvF,EAAa,EAAU,EAAiB,EAAK,SAAS,EAAG,EAAK,UAC9D,EAAa,UAAW,EAAa,UAAW,EAAQ,cAAc,CAC1E,OAAS,EAAO,CAGd,MAFA,GAAa,KAAK,EAClB,EAAU,MAAM,EACV,CACR,CACF,CAEA,SAAS,EAAiB,EAA4C,CACpE,OAAO,OAAO,OAAO,CAAE,KAAM,wBAAyB,GAAI,YAAY,IAAS,OAAQ,YACrF,MAAO,OAAO,OAAO,CAAE,KAAM,6BAA8B,MAAO,mBAChE,QAAS,kEAAmE,CAAC,CAAE,CAAC,CACtF"}
|
|
1
|
+
{"version":3,"file":"owner.js","names":[],"sources":["../../../src/composition/runtime/owner.ts"],"sourcesContent":["import { ModelRegistry } from '../../runtime/registry.ts'\nimport { EmbeddingRegistry } from '../embedding/registry.ts'\nimport { RuntimeEmbedding } from '../embedding/manager.ts'\nimport type { EmbeddingModelHandle, EmbeddingModelOptions } from '../../embedding/handle.ts'\nimport { createRuntimePlatform, type RuntimePlatform } from '../../platform/adapter.ts'\nimport { RuntimeResources } from '../../platform/resources.ts'\nimport { createRuntimeResource } from '../delivery/resource.ts'\nimport { RuntimeObservationPort, type RuntimeDiagnosticSnapshot } from '../observation/port.ts'\nimport { preflightRuntimeCapabilities } from '../preflight.ts'\nimport { providerTopology } from '../provider/model-selection.ts'\nimport type { ProviderRegistration } from '../provider/activation.ts'\nimport type { RuntimeProviderInfo } from '../provider/types.ts'\nimport { activateRuntimeCapabilities } from '../startup.ts'\nimport { RuntimeOperations } from '../lifecycle/operations.ts'\nimport type { QuiescenceReport } from '../lifecycle/types.ts'\nimport type { RuntimeComponentCloseReport } from '../common/errors.ts'\nimport type { SdkLogger } from '../../logging/types.ts'\nimport type { RuntimeLoggerContext } from '../logging/logger.ts'\nimport { captureCloseSignal, captureRuntimeOwnerOptions } from './config.ts'\nimport type { RuntimeCloseReport, RuntimeCompositionView, RuntimeOwnerOptions } from './types.ts'\nimport { bindRuntimeAgentDefinition } from '../agent/definition.ts'\nimport { createRuntimeAgent } from '../agent/session.ts'\nimport type { RuntimeAgent, RuntimeAgentBindingInput } from '../agent/types.ts'\nimport type { ProviderSelection } from '../provider/types.ts'\nimport { RuntimeModelCatalog } from '../model-catalog/manager.ts'\nimport type { ModelCatalogOptions } from '../../contract/model-info.ts'\nimport type { RuntimeModelCatalogSnapshot } from '../model-catalog/types.ts'\nimport { createRuntimeAgentTeam } from '../team/runtime.ts'\nimport type { RuntimeAgentTeam, RuntimeAgentTeamOptions, RuntimeTeamRegistration } from '../team/types.ts'\n\n/** Internal composition owner used to finish lifecycle semantics before the public agent surface is exported. */\nexport class RuntimeCompositionOwner implements RuntimeCompositionView {\n readonly registry: ModelRegistry\n readonly operations: RuntimeOperations\n private closing: Promise<RuntimeCloseReport> | undefined\n private readonly catalogs: RuntimeModelCatalog\n private readonly embeddings: RuntimeEmbedding\n private readonly teams: RuntimeTeamRegistration[] = []\n private readonly closedTeams: RuntimeComponentCloseReport[] = []\n\n constructor(\n registry: ModelRegistry,\n operations: RuntimeOperations,\n private readonly platform: RuntimePlatform,\n readonly resources: RuntimeResources,\n readonly observation: RuntimeObservationPort,\n readonly resource: import('../delivery/resource.ts').RuntimeObservationResource,\n private readonly topology: readonly RuntimeProviderInfo[],\n /** Read by the agent surface so a per-invocation model override resolves against these routes. */\n readonly selection: ProviderSelection,\n private readonly providersOwned: readonly ProviderRegistration[],\n private readonly exporters: Awaited<ReturnType<typeof activateRuntimeCapabilities>>['exporters'],\n private readonly closeTimeoutMs: number,\n /**\n * Runtime-owned embedding topology. Present even with zero embedding plugins,\n * so a generation-only runtime resolves nothing rather than failing on a\n * missing registry (Requirement 11.8).\n */\n readonly embeddingRegistry: EmbeddingRegistry = new EmbeddingRegistry(),\n ) {\n this.registry = registry\n this.operations = operations\n this.catalogs = new RuntimeModelCatalog(registry, operations, resources, topology)\n // Constructed unconditionally, exactly like the catalog manager: a runtime\n // with zero embedding plugins resolves nothing and reports\n // `EMBEDDING_ADAPTER_MISSING`, which is a better answer than a missing\n // manager (Requirement 11.8). The runtime observation port and resource are\n // forwarded so every handle emits its call and batch spans into this\n // runtime's trace when the caller supplies no context of its own.\n this.embeddings = new RuntimeEmbedding({\n registry: this.embeddingRegistry, operations, observation, resource,\n })\n }\n\n providers(): readonly RuntimeProviderInfo[] { return this.topology }\n modelCatalog(route: string, options?: ModelCatalogOptions): Promise<RuntimeModelCatalogSnapshot> {\n return this.catalogs.get(route, options)\n }\n /**\n * Synchronous adapter resolution; admission is checked by the manager FIRST,\n * before any option is read, and nothing agent-shaped is constructed.\n */\n embeddingModel(options: EmbeddingModelOptions): EmbeddingModelHandle {\n return this.embeddings.model(options)\n }\n agent(input: RuntimeAgentBindingInput): RuntimeAgent {\n this.operations.assertActive()\n return createRuntimeAgent(this, bindRuntimeAgentDefinition(input, this.selection))\n }\n team(input: RuntimeAgentTeamOptions): RuntimeAgentTeam {\n const registration = createRuntimeAgentTeam(this, input, closed => this.retireTeam(closed))\n this.teams.push(registration)\n return registration.view\n }\n logger(context?: RuntimeLoggerContext): SdkLogger { return this.observation.logger(context) }\n diagnostics(): RuntimeDiagnosticSnapshot { return this.observation.diagnostics() }\n\n close(input?: { readonly signal?: AbortSignal }): Promise<RuntimeCloseReport> {\n if (this.closing !== undefined) return this.closing\n const signal = captureCloseSignal(input)\n let resolve!: (report: RuntimeCloseReport) => void\n let reject!: (error: unknown) => void\n this.closing = new Promise((done, fail) => { resolve = done; reject = fail })\n const shared = this.closing\n try {\n const quiescence = this.operations.beginClose({ timeoutMs: this.closeTimeoutMs, ...(signal === undefined ? {} : { signal }) })\n this.observation.stopAdmission()\n void this.finishClose(quiescence).then(resolve, reject)\n return shared\n } catch (error) {\n this.closing = undefined\n throw error\n }\n }\n\n private async finishClose(quiescenceTask: Promise<QuiescenceReport>): Promise<RuntimeCloseReport> {\n const quiescence = await quiescenceTask\n // Every embedding operation has settled or been abandoned by now, so the\n // remembered handles and the registry subscription behind them are dead\n // weight. Dropping them here — before provider registrations unwind — keeps\n // no handle pointing at an adapter that is about to be torn down.\n this.embeddings.dispose()\n const deadlineAt = this.operations.closeDeadlineAt()\n const components: RuntimeComponentCloseReport[] = [...this.closedTeams]\n for (const team of [...this.teams].reverse()) components.push(await team.closeForRuntime(deadlineAt))\n for (const [reverseIndex, registration] of [...this.providersOwned].reverse().entries()) {\n const originalIndex = this.providersOwned.length - reverseIndex - 1\n if (this.platform.monotonicNow() >= deadlineAt) components.push(timedOutProvider(originalIndex))\n else components.push(registration.close({ at: deadlineAt, now: () => this.platform.monotonicNow() }))\n }\n const observationDeadline = this.observation.observationDeadline(deadlineAt)\n await this.observation.flushUntil(observationDeadline)\n this.observation.seal()\n components.push(...await this.exporters.close(observationDeadline))\n this.operations.finishClose()\n return Object.freeze({ state: 'closed', ...quiescence, components: Object.freeze(components),\n observationHealth: this.observation.health() })\n }\n\n private retireTeam(registration: RuntimeTeamRegistration): void {\n const index = this.teams.indexOf(registration)\n if (index < 0) return\n this.teams.splice(index, 1)\n this.closedTeams.push(Object.freeze({ kind: 'agent-team', id: registration.id, status: 'closed' }))\n // Reporting metadata is intentionally bounded independently of heavyweight\n // team state. Older tombstones can be omitted from a later runtime report.\n if (this.closedTeams.length > 1_024) this.closedTeams.shift()\n }\n}\n\n/** Web preflight and whole-input identity validation both precede runtime-owned allocations. */\nexport async function createRuntimeCompositionOwner(\n input: RuntimeOwnerOptions,\n host: typeof globalThis = globalThis,\n): Promise<RuntimeCompositionOwner> {\n const platform = createRuntimePlatform(host)\n const options = captureRuntimeOwnerOptions(input)\n const plan = preflightRuntimeCapabilities(options.providers, options.observability.exporters,\n options.defaultProvider, options.signal)\n const resources = new RuntimeResources(platform)\n let observation: RuntimeObservationPort | undefined\n try {\n const resource = createRuntimeResource(options.resource, platform)\n observation = new RuntimeObservationPort(resource, plan.exporters, platform, resources, {\n mode: options.observability.mode,\n ...(options.observability.content === undefined ? {} : { content: options.observability.content }),\n ...(options.observability.minimumLogLevel === undefined ? {} : { minimumLogLevel: options.observability.minimumLogLevel }),\n ...(options.observability.processors === undefined ? {} : { processors: options.observability.processors }),\n ...(options.observability.redactors === undefined ? {} : { redactors: options.observability.redactors }),\n ...(options.observability.includeErrorStacks === undefined ? {} : { includeErrorStacks: options.observability.includeErrorStacks }),\n ...(options.observability.openSpan === undefined ? {} : { openSpan: options.observability.openSpan }),\n ...(options.observability.maxQueueEvents === undefined ? {} : { maxEvents: options.observability.maxQueueEvents }),\n ...(options.observability.maxQueueBytes === undefined ? {} : { maxBytes: options.observability.maxQueueBytes }),\n ...(options.observability.maxBatchEvents === undefined ? {} : { maxBatchEvents: options.observability.maxBatchEvents }),\n ...(options.observability.maxBatchBytes === undefined ? {} : { maxBatchBytes: options.observability.maxBatchBytes }),\n ...(options.observability.flushTimeoutMs === undefined ? {} : { flushTimeoutMs: options.observability.flushTimeoutMs }),\n ...(options.observability.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.observability.shutdownTimeoutMs }),\n ...(options.diagnosticMaxEvents === undefined ? {} : { diagnosticMaxEvents: options.diagnosticMaxEvents }),\n ...(options.diagnosticMaxBytes === undefined ? {} : { diagnosticMaxBytes: options.diagnosticMaxBytes }),\n })\n const registry = new ModelRegistry({ observation, observationResource: resource })\n const capabilities = await activateRuntimeCapabilities(plan, registry,\n observation.logger({ scope: 'sdk.provider.setup' }), resources, {\n startupTimeoutMs: options.startupTimeoutMs, rollbackTimeoutMs: options.closeTimeoutMs,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n return new RuntimeCompositionOwner(registry, new RuntimeOperations(resources), platform, resources,\n observation, resource, providerTopology(plan.selection), plan.selection,\n capabilities.providers, capabilities.exporters, options.closeTimeoutMs,\n capabilities.embeddingRegistry)\n } catch (error) {\n observation?.seal()\n resources.close()\n throw error\n }\n}\n\nfunction timedOutProvider(index: number): RuntimeComponentCloseReport {\n return Object.freeze({ kind: 'provider-registration', id: `provider-${index}`, status: 'timed-out',\n error: Object.freeze({ code: 'CAPABILITY_CLEANUP_TIMEOUT', stage: 'provider-cleanup',\n message: 'Provider cleanup did not start before the runtime close deadline' }) })\n}\n"],"mappings":"2/BA+BA,IAAa,EAAb,KAAuE,CAYlD,SACR,UACA,YACA,SACQ,SAER,UACQ,eACA,UACA,eAMR,kBA1BX,SACA,WACA,QACA,SACA,WACA,MAAoD,CAAC,EACrD,YAA8D,CAAC,EAE/D,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,EACA,EACA,EACA,EAMA,EAAgD,IAAI,EACpD,CAhBiB,KAAA,SAAA,EACR,KAAA,UAAA,EACA,KAAA,YAAA,EACA,KAAA,SAAA,EACQ,KAAA,SAAA,EAER,KAAA,UAAA,EACQ,KAAA,eAAA,EACA,KAAA,UAAA,EACA,KAAA,eAAA,EAMR,KAAA,kBAAA,EAET,KAAK,SAAW,EAChB,KAAK,WAAa,EAClB,KAAK,SAAW,IAAI,EAAoB,EAAU,EAAY,EAAW,CAAQ,EAOjF,KAAK,WAAa,IAAI,EAAiB,CACrC,SAAU,KAAK,kBAAmB,aAAY,cAAa,UAC7D,CAAC,CACH,CAEA,WAA4C,CAAE,OAAO,KAAK,QAAS,CACnE,aAAa,EAAe,EAAqE,CAC/F,OAAO,KAAK,SAAS,IAAI,EAAO,CAAO,CACzC,CAKA,eAAe,EAAsD,CACnE,OAAO,KAAK,WAAW,MAAM,CAAO,CACtC,CACA,MAAM,EAA+C,CAEnD,OADA,KAAK,WAAW,aAAa,EACtB,EAAmB,KAAM,EAA2B,EAAO,KAAK,SAAS,CAAC,CACnF,CACA,KAAK,EAAkD,CACrD,IAAM,EAAe,EAAuB,KAAM,EAAO,GAAU,KAAK,WAAW,CAAM,CAAC,EAE1F,OADA,KAAK,MAAM,KAAK,CAAY,EACrB,EAAa,IACtB,CACA,OA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AAI,EAAwB,EAAU,IAAI,EAAkB,CAAS,EAAG,EAAU,EACvF,EAAa,EAAU,EAAiB,EAAK,SAAS,EAAG,EAAK,UAC9D,EAAa,UAAW,EAAa,UAAW,EAAQ,eACxD,EAAa,iBAAiB,CAClC,OAAS,EAAO,CAGd,MAFA,GAAa,KAAK,EAClB,EAAU,MAAM,EACV,CACR,CACF,CAEA,SAAS,EAAiB,EAA4C,CACpE,OAAO,OAAO,OAAO,CAAE,KAAM,wBAAyB,GAAI,YAAY,IAAS,OAAQ,YACrF,MAAO,OAAO,OAAO,CAAE,KAAM,6BAA8B,MAAO,mBAChE,QAAS,kEAAmE,CAAC,CAAE,CAAC,CACtF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRuntimeCompositionOwner as e}from"./owner.js";async function t(t){let n=await e(t);return Object.freeze({providers:()=>n.providers(),modelCatalog:(e,t)=>n.modelCatalog(e,t),agent:e=>n.agent(e),team:e=>n.team(e),logger:e=>n.logger(e),diagnostics:()=>n.diagnostics(),close:e=>n.close(e)})}export{t as createAgentRuntime};
|
|
1
|
+
import{createRuntimeCompositionOwner as e}from"./owner.js";async function t(t){let n=await e(t);return Object.freeze({providers:()=>n.providers(),modelCatalog:(e,t)=>n.modelCatalog(e,t),embeddingModel:e=>n.embeddingModel(e),agent:e=>n.agent(e),team:e=>n.team(e),logger:e=>n.logger(e),diagnostics:()=>n.diagnostics(),close:e=>n.close(e)})}export{t as createAgentRuntime};
|
|
2
2
|
//# sourceMappingURL=public.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.js","names":[],"sources":["../../../src/composition/runtime/public.ts"],"sourcesContent":["import { createRuntimeCompositionOwner } from './owner.ts'\nimport type { AgentRuntime, AgentRuntimeOptions } from './types.ts'\n\n/** Construct the immutable public composition facade; mutable internals stay closure-owned. */\nexport async function createAgentRuntime(options: AgentRuntimeOptions): Promise<AgentRuntime> {\n const owner = await createRuntimeCompositionOwner(options)\n const facade: AgentRuntime = {\n providers: () => owner.providers(),\n modelCatalog: (route, catalogOptions) => owner.modelCatalog(route, catalogOptions),\n agent: definition => owner.agent(definition),\n team: teamOptions => owner.team(teamOptions),\n logger: context => owner.logger(context),\n diagnostics: () => owner.diagnostics(),\n close: closeOptions => owner.close(closeOptions),\n }\n return Object.freeze(facade)\n}\n"],"mappings":"2DAIA,eAAsB,EAAmB,EAAqD,CAC5F,IAAM,EAAQ,MAAM,EAA8B,CAAO,
|
|
1
|
+
{"version":3,"file":"public.js","names":[],"sources":["../../../src/composition/runtime/public.ts"],"sourcesContent":["import { createRuntimeCompositionOwner } from './owner.ts'\nimport type { AgentRuntime, AgentRuntimeOptions } from './types.ts'\n\n/** Construct the immutable public composition facade; mutable internals stay closure-owned. */\nexport async function createAgentRuntime(options: AgentRuntimeOptions): Promise<AgentRuntime> {\n const owner = await createRuntimeCompositionOwner(options)\n const facade: AgentRuntime = {\n providers: () => owner.providers(),\n modelCatalog: (route, catalogOptions) => owner.modelCatalog(route, catalogOptions),\n embeddingModel: embeddingOptions => owner.embeddingModel(embeddingOptions),\n agent: definition => owner.agent(definition),\n team: teamOptions => owner.team(teamOptions),\n logger: context => owner.logger(context),\n diagnostics: () => owner.diagnostics(),\n close: closeOptions => owner.close(closeOptions),\n }\n return Object.freeze(facade)\n}\n"],"mappings":"2DAIA,eAAsB,EAAmB,EAAqD,CAC5F,IAAM,EAAQ,MAAM,EAA8B,CAAO,EAWzD,OAAO,OAAO,OAAO,CATnB,cAAiB,EAAM,UAAU,EACjC,cAAe,EAAO,IAAmB,EAAM,aAAa,EAAO,CAAc,EACjF,eAAgB,GAAoB,EAAM,eAAe,CAAgB,EACzE,MAAO,GAAc,EAAM,MAAM,CAAU,EAC3C,KAAM,GAAe,EAAM,KAAK,CAAW,EAC3C,OAAQ,GAAW,EAAM,OAAO,CAAO,EACvC,gBAAmB,EAAM,YAAY,EACrC,MAAO,GAAgB,EAAM,MAAM,CAAY,CAEvB,CAAC,CAC7B"}
|
|
@@ -3,7 +3,7 @@ import { ObservationResourceInput } from "../../observation/event.js";
|
|
|
3
3
|
import { DeliveryMode, ObservationSpan, OpenObservationSpanInput } from "../../observation/port.js";
|
|
4
4
|
import { LogLevel, SdkLogger } from "../../logging/types.js";
|
|
5
5
|
import { ModelCatalogOptions } from "../../contract/model-info.js";
|
|
6
|
-
import {
|
|
6
|
+
import { RuntimeProviderInfo } from "../provider/types.js";
|
|
7
7
|
import { RuntimeObservationExporterRegistration } from "../exporter/types.js";
|
|
8
8
|
import { ContentRedactor, ObservationProcessor } from "../../observation/telemetry-types.js";
|
|
9
9
|
import { RuntimeObservationHealthSnapshot } from "../observation/health.js";
|
|
@@ -11,6 +11,8 @@ import { RuntimeDiagnosticSnapshot } from "../observation/port.js";
|
|
|
11
11
|
import { RuntimeAgent, RuntimeAgentBindingInput } from "../agent/types.js";
|
|
12
12
|
import { RuntimeComponentCloseReport } from "../common/errors.js";
|
|
13
13
|
import { RuntimeOperationCloseSummary } from "../lifecycle/types.js";
|
|
14
|
+
import { ComposableRuntimeProviderPlugin } from "../embedding/plugin-types.js";
|
|
15
|
+
import { EmbeddingModelHandle, EmbeddingModelOptions } from "../../embedding/handle.js";
|
|
14
16
|
import { RuntimeModelCatalogSnapshot } from "../model-catalog/types.js";
|
|
15
17
|
import { RuntimeAgentTeam, RuntimeAgentTeamOptions } from "../team/types.js";
|
|
16
18
|
//#region src/composition/runtime/types.d.ts
|
|
@@ -33,7 +35,15 @@ interface RuntimeOwnerObservabilityOptions {
|
|
|
33
35
|
interface RuntimeObservationResourceInput extends ObservationResourceInput {}
|
|
34
36
|
/** Internal I3 owner input. Remaining public agent/processor fields join at their composition layer. */
|
|
35
37
|
interface RuntimeOwnerOptions {
|
|
36
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Both provider plugin kinds in ONE list, discriminated by `kind` at preflight.
|
|
40
|
+
*
|
|
41
|
+
* A single list rather than a second `embeddingProviders` field is what keeps
|
|
42
|
+
* ordering, preflight failure indexes and the shared rollback list meaningful
|
|
43
|
+
* across kinds: `provider-2` names the third entry the caller wrote, whichever
|
|
44
|
+
* kind it is (Requirement 11.4).
|
|
45
|
+
*/
|
|
46
|
+
readonly providers: readonly ComposableRuntimeProviderPlugin[];
|
|
37
47
|
readonly defaultProvider?: string;
|
|
38
48
|
readonly signal?: AbortSignal;
|
|
39
49
|
readonly resource?: RuntimeObservationResourceInput;
|
|
@@ -57,6 +67,19 @@ interface RuntimeCloseReport {
|
|
|
57
67
|
interface RuntimeCompositionView {
|
|
58
68
|
providers(): readonly RuntimeProviderInfo[];
|
|
59
69
|
modelCatalog(route: string, options?: ModelCatalogOptions): Promise<RuntimeModelCatalogSnapshot>;
|
|
70
|
+
/**
|
|
71
|
+
* Resolve one route + model into an {@link EmbeddingModelHandle}, synchronously.
|
|
72
|
+
*
|
|
73
|
+
* Deliberately NOT a promise and deliberately not routed through an agent: it
|
|
74
|
+
* admits, captures the options and resolves an adapter, so a document indexing
|
|
75
|
+
* service pays for none of the agent, team or session machinery
|
|
76
|
+
* (Requirements 3.1, 3.4, 19.4). A route with no embedding adapter — including
|
|
77
|
+
* one that carries only a generation adapter — fails here with
|
|
78
|
+
* `EMBEDDING_ADAPTER_MISSING` rather than at the first `embed()`
|
|
79
|
+
* (Requirement 3.5), and a runtime that has begun closing refuses to hand out
|
|
80
|
+
* a handle at all (Requirement 12.6).
|
|
81
|
+
*/
|
|
82
|
+
embeddingModel(options: EmbeddingModelOptions): EmbeddingModelHandle;
|
|
60
83
|
agent(definition: RuntimeAgentBindingInput): RuntimeAgent;
|
|
61
84
|
team(options: RuntimeAgentTeamOptions): RuntimeAgentTeam;
|
|
62
85
|
logger(context?: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/runtime/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/composition/runtime/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;UAkBiB;WACN,OAAO;WACP;WACA,kBAAkB;WAClB,qBAAqB;WACrB,sBAAsB;WACtB,qBAAqB;WACrB;WACA,YAAY,OAAO,6BAA6B;WAChD;WACA;WACA;WACA;WACA;WACA;;UAGM,wCAAwC;;UAGxC;;;;;;;;;WASN,oBAAoB;WACpB;WACA,SAAS;WACT,WAAW;WACX,gBAAgB;WAChB;WACA;WACA;WACA;;UAGM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,qBAAqB;WACrB,qBAAqB;WACrB,mBAAmB;;UAGb;EACf,sBAAsB;EACtB,aAAa,eAAe,UAAU,sBAAsB,QAAQ;;;;;;;;;;;;;EAapE,eAAe,SAAS,wBAAwB;EAChD,MAAM,YAAY,2BAA2B;EAC7C,KAAK,SAAS,0BAA0B;EACxC,OAAO;aAAqB;aAAyB,SAAS,SAAS;MAAgB;EACvF,eAAe;EACf,MAAM;aAAqB,SAAS;MAAgB,QAAQ;;UAG7C,qBAAqB;UACrB,4BAA4B;KACjC,qBAAqB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{timeoutValue as e}from"../platform/config.js";import{AgentRuntimeConstructionError as
|
|
1
|
+
import{timeoutValue as e}from"../platform/config.js";import{EmbeddingRegistry as t}from"./embedding/registry.js";import{AgentRuntimeConstructionError as n,checkPreflightAbort as r}from"./common/errors.js";import{RuntimeExporters as i}from"./exporter/lifecycle.js";import{activateRuntimeProviders as a}from"./embedding/activation.js";async function o(o,s,c,l,u){let d=e(u.startupTimeoutMs),f=e(u.rollbackTimeoutMs),p=u.signal;r(p);let m=l.platform.monotonicNow()+d,h,g=()=>(h??=l.platform.monotonicNow()+f,{at:h,now:()=>l.platform.monotonicNow()}),_=new i(o.exporters,l),v=new t,y=[];try{if(y=a({registry:s,embeddingRegistry:v,providers:o.providers,embeddingProviders:o.embeddingProviders,logger:c,...p===void 0?{}:{signal:p},deadlines:{startup:{at:m,now:()=>l.platform.monotonicNow()},rollback:g}}),await _.ready(m,p),p?.aborted)throw new n({failureCode:`CAPABILITY_STARTUP_ABORTED`,stage:`activation`,reason:`aborted`});if(l.platform.monotonicNow()>=m)throw new n({failureCode:`CAPABILITY_STARTUP_TIMEOUT`,stage:`activation`,reason:`timed-out`});return Object.freeze({providers:y,embeddingRegistry:v,exporters:_})}catch(e){let t=e instanceof n?e:new n({failureCode:`CAPABILITY_STARTUP_FAILED`,stage:`activation`,reason:`failed`}),r=g(),i=[...t.cleanup,...[...y].reverse().map(e=>e.close(r)),...await _.close(r.at)];throw new n({failureCode:t.failureCode,stage:t.stage,reason:t.reason,...t.component===void 0?{}:{component:t.component},...t.conflict===void 0?{}:{conflict:t.conflict},...t.aggregate.length===0?{}:{aggregate:t.aggregate},cleanup:i})}}export{o as activateRuntimeCapabilities};
|
|
2
2
|
//# sourceMappingURL=startup.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startup.js","names":[],"sources":["../../src/composition/startup.ts"],"sourcesContent":["import type { SdkLogger } from '../logging/types.ts'\nimport { RuntimeResources } from '../platform/resources.ts'\nimport { timeoutValue } from '../platform/config.ts'\nimport type { ModelRegistry } from '../runtime/registry.ts'\nimport { AgentRuntimeConstructionError, checkPreflightAbort } from './common/errors.ts'\nimport { RuntimeExporters } from './exporter/lifecycle.ts'\nimport {
|
|
1
|
+
{"version":3,"file":"startup.js","names":[],"sources":["../../src/composition/startup.ts"],"sourcesContent":["import type { SdkLogger } from '../logging/types.ts'\nimport { RuntimeResources } from '../platform/resources.ts'\nimport { timeoutValue } from '../platform/config.ts'\nimport type { ModelRegistry } from '../runtime/registry.ts'\nimport { AgentRuntimeConstructionError, checkPreflightAbort } from './common/errors.ts'\nimport { RuntimeExporters } from './exporter/lifecycle.ts'\nimport { activateRuntimeProviders } from './embedding/activation.ts'\nimport { EmbeddingRegistry } from './embedding/registry.ts'\nimport type { ProviderRegistration } from './provider/activation.ts'\nimport type { RuntimeCapabilityPlan } from './preflight.ts'\n\nexport interface CapabilityStartupOptions {\n readonly startupTimeoutMs: number\n readonly rollbackTimeoutMs: number\n readonly signal?: AbortSignal\n}\n\nexport interface ActivatedRuntimeCapabilities {\n /** Generation AND embedding registrations, in installation order (Requirement 11.7). */\n readonly providers: readonly ProviderRegistration[]\n /** Owned here so it exists even when no embedding plugin was supplied. */\n readonly embeddingRegistry: EmbeddingRegistry\n readonly exporters: RuntimeExporters\n}\n\n/** Transactional inner startup; the composition root supplies its canonical registry, logger and resources. */\nexport async function activateRuntimeCapabilities(\n plan: RuntimeCapabilityPlan, registry: ModelRegistry, logger: SdkLogger,\n resources: RuntimeResources, options: CapabilityStartupOptions,\n): Promise<ActivatedRuntimeCapabilities> {\n const startupTimeoutMs = timeoutValue(options.startupTimeoutMs)\n const rollbackTimeoutMs = timeoutValue(options.rollbackTimeoutMs)\n const signal = options.signal\n checkPreflightAbort(signal)\n const deadlineAt = resources.platform.monotonicNow() + startupTimeoutMs\n let rollbackDeadlineAt: number | undefined\n const rollbackDeadline = () => {\n rollbackDeadlineAt ??= resources.platform.monotonicNow() + rollbackTimeoutMs\n return { at: rollbackDeadlineAt, now: () => resources.platform.monotonicNow() }\n }\n const exporters = new RuntimeExporters(plan.exporters, resources)\n const embeddingRegistry = new EmbeddingRegistry()\n let providers: readonly ProviderRegistration[] = []\n try {\n providers = activateRuntimeProviders({\n registry, embeddingRegistry, providers: plan.providers,\n embeddingProviders: plan.embeddingProviders, logger,\n ...(signal === undefined ? {} : { signal }),\n deadlines: {\n startup: { at: deadlineAt, now: () => resources.platform.monotonicNow() }, rollback: rollbackDeadline,\n },\n })\n await exporters.ready(deadlineAt, signal)\n if (signal?.aborted) throw new AgentRuntimeConstructionError({\n failureCode: 'CAPABILITY_STARTUP_ABORTED', stage: 'activation', reason: 'aborted',\n })\n if (resources.platform.monotonicNow() >= deadlineAt) throw new AgentRuntimeConstructionError({\n failureCode: 'CAPABILITY_STARTUP_TIMEOUT', stage: 'activation', reason: 'timed-out',\n })\n return Object.freeze({ providers, embeddingRegistry, exporters })\n } catch (error) {\n // Capture the primary classification before cleanup can abort the caller or throw.\n const failure = error instanceof AgentRuntimeConstructionError ? error : new AgentRuntimeConstructionError({\n failureCode: 'CAPABILITY_STARTUP_FAILED', stage: 'activation', reason: 'failed',\n })\n const deadline = rollbackDeadline()\n const cleanup = [...failure.cleanup, ...[...providers].reverse().map(provider => provider.close(deadline)),\n ...await exporters.close(deadline.at)]\n throw new AgentRuntimeConstructionError({\n failureCode: failure.failureCode, stage: failure.stage, reason: failure.reason,\n ...(failure.component === undefined ? {} : { component: failure.component }),\n ...(failure.conflict === undefined ? {} : { conflict: failure.conflict }),\n ...(failure.aggregate.length === 0 ? {} : { aggregate: failure.aggregate }), cleanup,\n })\n }\n}\n"],"mappings":"6UA0BA,eAAsB,EACpB,EAA6B,EAAyB,EACtD,EAA6B,EACU,CACvC,IAAM,EAAmB,EAAa,EAAQ,gBAAgB,EACxD,EAAoB,EAAa,EAAQ,iBAAiB,EAC1D,EAAS,EAAQ,OACvB,EAAoB,CAAM,EAC1B,IAAM,EAAa,EAAU,SAAS,aAAa,EAAI,EACnD,EACE,OACJ,IAAuB,EAAU,SAAS,aAAa,EAAI,EACpD,CAAE,GAAI,EAAoB,QAAW,EAAU,SAAS,aAAa,CAAE,GAE1E,EAAY,IAAI,EAAiB,EAAK,UAAW,CAAS,EAC1D,EAAoB,IAAI,EAC1B,EAA6C,CAAC,EAClD,GAAI,CAUF,GATA,EAAY,EAAyB,CACnC,WAAU,oBAAmB,UAAW,EAAK,UAC7C,mBAAoB,EAAK,mBAAoB,SAC7C,GAAI,IAAW,IAAA,GAAY,CAAC,EAAI,CAAE,QAAO,EACzC,UAAW,CACT,QAAS,CAAE,GAAI,EAAY,QAAW,EAAU,SAAS,aAAa,CAAE,EAAG,SAAU,CACvF,CACF,CAAC,EACD,MAAM,EAAU,MAAM,EAAY,CAAM,EACpC,GAAQ,QAAS,MAAM,IAAI,EAA8B,CAC3D,YAAa,6BAA8B,MAAO,aAAc,OAAQ,SAC1E,CAAC,EACD,GAAI,EAAU,SAAS,aAAa,GAAK,EAAY,MAAM,IAAI,EAA8B,CAC3F,YAAa,6BAA8B,MAAO,aAAc,OAAQ,WAC1E,CAAC,EACD,OAAO,OAAO,OAAO,CAAE,YAAW,oBAAmB,WAAU,CAAC,CAClE,OAAS,EAAO,CAEd,IAAM,EAAU,aAAiB,EAAgC,EAAQ,IAAI,EAA8B,CACzG,YAAa,4BAA6B,MAAO,aAAc,OAAQ,QACzE,CAAC,EACK,EAAW,EAAiB,EAC5B,EAAU,CAAC,GAAG,EAAQ,QAAS,GAAG,CAAC,GAAG,CAAS,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,GAAY,EAAS,MAAM,CAAQ,CAAC,EACvG,GAAG,MAAM,EAAU,MAAM,EAAS,EAAE,CAAC,EACvC,MAAM,IAAI,EAA8B,CACtC,YAAa,EAAQ,YAAa,MAAO,EAAQ,MAAO,OAAQ,EAAQ,OACxE,GAAI,EAAQ,YAAc,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,SAAU,EAC1E,GAAI,EAAQ,WAAa,IAAA,GAAY,CAAC,EAAI,CAAE,SAAU,EAAQ,QAAS,EACvE,GAAI,EAAQ,UAAU,SAAW,EAAI,CAAC,EAAI,CAAE,UAAW,EAAQ,SAAU,EAAI,SAC/E,CAAC,CACH,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{arrayData as e,boundedText as t,objectValue as n,ownData as r}from"../../capability/common/data.js";import{capabilityIdentityError as i}from"../../errors/capability-identity.js";import{captureRuntimeSessionOptions as a}from"../agent/options.js";import{memberName as o}from"../../agent/team/common.js";import{RUNTIME_TEAM_LIMITS as s}from"./config.js";const c=new Set([`id`,`members`,`maxMessages`,`maxMessageBytes`,`operationTimeoutMs`,`observerTimeoutMs`,`onEvent`]),l=new Set([`name`,`agent`,`description`,`instructions`,`role`,`tools`,`session`]);function u(u){let m=n(u);p(m,c);let h=t(r(m,`id`),s.idBytes),g=e(r(m,`members`),s.members);if(g.length===0)throw TypeError(`Runtime team requires at least one member`);let _=new Map,v=0,y=g.map((e,t)=>{let s=n(e);p(s,l);let c=o(r(s,`name`)),u=_.get(c);if(u!==void 0)throw i(`TEAM_MEMBER_CONFLICT`,`team-member-name`,u,t);_.set(c,t);let f=r(s,`role`,!1)??(t===0?`lead`:`peer`);if(f!==`lead`&&f!==`peer`)throw TypeError(`Runtime team member role is invalid`);if(f===`lead`&&++v>1)throw TypeError(`Runtime team has more than one lead`);let m=d(s,`description`),h=d(s,`instructions`),g=r(s,`tools`,!1);if(g!==void 0&&typeof g!=`boolean`&&g!==`full`&&g!==`reporting`)throw TypeError(`Runtime team tools flag is invalid`);return Object.freeze({name:c,agent:r(s,`agent`),role:f,session:a(r(s,`session`,!1)),...m===void 0?{}:{description:m},...h===void 0?{}:{instructions:h},...g===void 0?{}:{tools:g}})}),b=r(m,`onEvent`,!1);if(b!==void 0&&typeof b!=`function`)throw TypeError(`Runtime team observer is invalid`);let x=b===void 0?void 0:e=>{Reflect.apply(b,m,[e])};return Object.freeze({id:h,members:Object.freeze(y),...f(m,[`maxMessages`,`maxMessageBytes`,`operationTimeoutMs`,`observerTimeoutMs`]),...x===void 0?{}:{onEvent:x}})}function d(e,n){let i=r(e,n,!1);return i===void 0?void 0:t(i,s.metadataBytes)}function f(e,t){let n=Object.create(null);for(let i of t){let t=r(e,i,!1);if(t!==void 0){if(!Number.isSafeInteger(t)||Number(t)<1)throw TypeError(`Runtime team ${i} is invalid`);n[i]=Number(t)}}return n}function p(e,t){if(Reflect.ownKeys(e).some(e=>typeof e!=`string`||!t.has(e)))throw TypeError(`Runtime team options contain unsupported fields`)}export{u as captureRuntimeTeamOptions};
|
|
1
|
+
import{arrayData as e,boundedText as t,objectValue as n,ownData as r}from"../../capability/common/data.js";import{capabilityIdentityError as i}from"../../errors/capability-identity.js";import{captureRuntimeSessionOptions as a}from"../agent/options.js";import{memberName as o}from"../../agent/team/common.js";import{RUNTIME_TEAM_LIMITS as s}from"./config.js";const c=new Set([`id`,`members`,`maxMessages`,`maxMessageBytes`,`operationTimeoutMs`,`observerTimeoutMs`,`onEvent`,`onAgentEvent`]),l=new Set([`name`,`agent`,`description`,`instructions`,`role`,`tools`,`session`]);function u(u){let m=n(u);p(m,c);let h=t(r(m,`id`),s.idBytes),g=e(r(m,`members`),s.members);if(g.length===0)throw TypeError(`Runtime team requires at least one member`);let _=new Map,v=0,y=g.map((e,t)=>{let s=n(e);p(s,l);let c=o(r(s,`name`)),u=_.get(c);if(u!==void 0)throw i(`TEAM_MEMBER_CONFLICT`,`team-member-name`,u,t);_.set(c,t);let f=r(s,`role`,!1)??(t===0?`lead`:`peer`);if(f!==`lead`&&f!==`peer`)throw TypeError(`Runtime team member role is invalid`);if(f===`lead`&&++v>1)throw TypeError(`Runtime team has more than one lead`);let m=d(s,`description`),h=d(s,`instructions`),g=r(s,`tools`,!1);if(g!==void 0&&typeof g!=`boolean`&&g!==`full`&&g!==`reporting`)throw TypeError(`Runtime team tools flag is invalid`);return Object.freeze({name:c,agent:r(s,`agent`),role:f,session:a(r(s,`session`,!1)),...m===void 0?{}:{description:m},...h===void 0?{}:{instructions:h},...g===void 0?{}:{tools:g}})}),b=r(m,`onEvent`,!1);if(b!==void 0&&typeof b!=`function`)throw TypeError(`Runtime team observer is invalid`);let x=b===void 0?void 0:e=>{Reflect.apply(b,m,[e])},S=r(m,`onAgentEvent`,!1);if(S!==void 0&&typeof S!=`function`)throw TypeError(`Runtime team agent observer is invalid`);let C=S===void 0?void 0:(e,t)=>Reflect.apply(S,m,[e,t]);return Object.freeze({id:h,members:Object.freeze(y),...f(m,[`maxMessages`,`maxMessageBytes`,`operationTimeoutMs`,`observerTimeoutMs`]),...x===void 0?{}:{onEvent:x},...C===void 0?{}:{onAgentEvent:C}})}function d(e,n){let i=r(e,n,!1);return i===void 0?void 0:t(i,s.metadataBytes)}function f(e,t){let n=Object.create(null);for(let i of t){let t=r(e,i,!1);if(t!==void 0){if(!Number.isSafeInteger(t)||Number(t)<1)throw TypeError(`Runtime team ${i} is invalid`);n[i]=Number(t)}}return n}function p(e,t){if(Reflect.ownKeys(e).some(e=>typeof e!=`string`||!t.has(e)))throw TypeError(`Runtime team options contain unsupported fields`)}export{u as captureRuntimeTeamOptions};
|
|
2
2
|
//# sourceMappingURL=options.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/team/options.ts"],"sourcesContent":["import { memberName } from '../../agent/team/common.ts'\nimport { arrayData, boundedText, objectValue, ownData } from '../common/data.ts'\nimport { captureRuntimeSessionOptions } from '../agent/options.ts'\nimport { capabilityIdentityError } from '../identity/error.ts'\nimport type { AgentTeamMemberInput, RuntimeAgentTeamEvent, RuntimeAgentTeamOptions } from './types.ts'\nimport { RUNTIME_TEAM_LIMITS } from './config.ts'\n\nconst ROOT_KEYS = new Set(['id', 'members', 'maxMessages', 'maxMessageBytes', 'operationTimeoutMs',\n 'observerTimeoutMs', 'onEvent'])\nconst MEMBER_KEYS = new Set(['name', 'agent', 'description', 'instructions', 'role', 'tools', 'session'])\n\nexport interface CapturedTeamMember extends AgentTeamMemberInput {\n readonly role: 'lead' | 'peer'\n readonly session: NonNullable<AgentTeamMemberInput['session']>\n}\n\nexport interface CapturedRuntimeTeamOptions extends RuntimeAgentTeamOptions {\n readonly members: readonly CapturedTeamMember[]\n readonly onEvent?: (event: RuntimeAgentTeamEvent) => void\n}\n\nexport function captureRuntimeTeamOptions(value: unknown): CapturedRuntimeTeamOptions {\n const source = objectValue(value)\n rejectUnknown(source, ROOT_KEYS)\n const id = boundedText(ownData(source, 'id'), RUNTIME_TEAM_LIMITS.idBytes)\n const members = arrayData(ownData(source, 'members'), RUNTIME_TEAM_LIMITS.members)\n if (members.length === 0) throw new TypeError('Runtime team requires at least one member')\n const seen = new Map<string, number>()\n let leads = 0\n const captured = members.map((raw, index): CapturedTeamMember => {\n const member = objectValue(raw)\n rejectUnknown(member, MEMBER_KEYS)\n const name = memberName(ownData(member, 'name'))\n const first = seen.get(name)\n if (first !== undefined) throw capabilityIdentityError(\n 'TEAM_MEMBER_CONFLICT', 'team-member-name', first, index,\n )\n seen.set(name, index)\n const role = ownData(member, 'role', false) ?? (index === 0 ? 'lead' : 'peer')\n if (role !== 'lead' && role !== 'peer') throw new TypeError('Runtime team member role is invalid')\n if (role === 'lead' && ++leads > 1) throw new TypeError('Runtime team has more than one lead')\n const description = optionalBounded(member, 'description')\n const instructions = optionalBounded(member, 'instructions')\n const tools = ownData(member, 'tools', false)\n if (tools !== undefined && typeof tools !== 'boolean'\n && tools !== 'full' && tools !== 'reporting') {\n throw new TypeError('Runtime team tools flag is invalid')\n }\n return Object.freeze({ name, agent: ownData(member, 'agent') as AgentTeamMemberInput['agent'], role,\n session: captureRuntimeSessionOptions(ownData(member, 'session', false)),\n ...(description === undefined ? {} : { description }),\n ...(instructions === undefined ? {} : { instructions }),\n ...(tools === undefined ? {} : { tools }) })\n })\n const callback = ownData(source, 'onEvent', false)\n if (callback !== undefined && typeof callback !== 'function') throw new TypeError('Runtime team observer is invalid')\n const onEvent = callback === undefined ? undefined\n : (event: RuntimeAgentTeamEvent): void => { Reflect.apply(callback, source, [event]) }\n return Object.freeze({ id, members: Object.freeze(captured),\n ...copyPositive(source, ['maxMessages', 'maxMessageBytes', 'operationTimeoutMs', 'observerTimeoutMs']),\n ...(onEvent === undefined ? {} : { onEvent }) })\n}\n\nfunction optionalBounded(source: object, key: string): string | undefined {\n const value = ownData(source, key, false)\n return value === undefined ? undefined : boundedText(value, RUNTIME_TEAM_LIMITS.metadataBytes)\n}\n\nfunction copyPositive(source: object, keys: readonly string[]): Record<string, number> {\n const output: Record<string, number> = Object.create(null) as Record<string, number>\n for (const key of keys) {\n const value = ownData(source, key, false)\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || Number(value) < 1) throw new TypeError(`Runtime team ${key} is invalid`)\n output[key] = Number(value)\n }\n return output\n}\n\nfunction rejectUnknown(source: object, keys: ReadonlySet<string>): void {\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !keys.has(key))) {\n throw new TypeError('Runtime team options contain unsupported fields')\n }\n}\n"],"mappings":"sWAOA,MAAM,EAAY,IAAI,IAAI,CAAC,KAAM,UAAW,cAAe,kBAAmB,qBAC5E,oBAAqB,
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../../src/composition/team/options.ts"],"sourcesContent":["import { memberName } from '../../agent/team/common.ts'\nimport { arrayData, boundedText, objectValue, ownData } from '../common/data.ts'\nimport { captureRuntimeSessionOptions } from '../agent/options.ts'\nimport { capabilityIdentityError } from '../identity/error.ts'\nimport type { AgentTeamMemberInput, RuntimeAgentTeamEvent, RuntimeAgentTeamOptions } from './types.ts'\nimport { RUNTIME_TEAM_LIMITS } from './config.ts'\n\nconst ROOT_KEYS = new Set(['id', 'members', 'maxMessages', 'maxMessageBytes', 'operationTimeoutMs',\n 'observerTimeoutMs', 'onEvent', 'onAgentEvent'])\nconst MEMBER_KEYS = new Set(['name', 'agent', 'description', 'instructions', 'role', 'tools', 'session'])\n\nexport interface CapturedTeamMember extends AgentTeamMemberInput {\n readonly role: 'lead' | 'peer'\n readonly session: NonNullable<AgentTeamMemberInput['session']>\n}\n\nexport interface CapturedRuntimeTeamOptions extends RuntimeAgentTeamOptions {\n readonly members: readonly CapturedTeamMember[]\n readonly onEvent?: (event: RuntimeAgentTeamEvent) => void\n readonly onAgentEvent?: Exclude<RuntimeAgentTeamOptions['onAgentEvent'], undefined>\n}\n\nexport function captureRuntimeTeamOptions(value: unknown): CapturedRuntimeTeamOptions {\n const source = objectValue(value)\n rejectUnknown(source, ROOT_KEYS)\n const id = boundedText(ownData(source, 'id'), RUNTIME_TEAM_LIMITS.idBytes)\n const members = arrayData(ownData(source, 'members'), RUNTIME_TEAM_LIMITS.members)\n if (members.length === 0) throw new TypeError('Runtime team requires at least one member')\n const seen = new Map<string, number>()\n let leads = 0\n const captured = members.map((raw, index): CapturedTeamMember => {\n const member = objectValue(raw)\n rejectUnknown(member, MEMBER_KEYS)\n const name = memberName(ownData(member, 'name'))\n const first = seen.get(name)\n if (first !== undefined) throw capabilityIdentityError(\n 'TEAM_MEMBER_CONFLICT', 'team-member-name', first, index,\n )\n seen.set(name, index)\n const role = ownData(member, 'role', false) ?? (index === 0 ? 'lead' : 'peer')\n if (role !== 'lead' && role !== 'peer') throw new TypeError('Runtime team member role is invalid')\n if (role === 'lead' && ++leads > 1) throw new TypeError('Runtime team has more than one lead')\n const description = optionalBounded(member, 'description')\n const instructions = optionalBounded(member, 'instructions')\n const tools = ownData(member, 'tools', false)\n if (tools !== undefined && typeof tools !== 'boolean'\n && tools !== 'full' && tools !== 'reporting') {\n throw new TypeError('Runtime team tools flag is invalid')\n }\n return Object.freeze({ name, agent: ownData(member, 'agent') as AgentTeamMemberInput['agent'], role,\n session: captureRuntimeSessionOptions(ownData(member, 'session', false)),\n ...(description === undefined ? {} : { description }),\n ...(instructions === undefined ? {} : { instructions }),\n ...(tools === undefined ? {} : { tools }) })\n })\n const callback = ownData(source, 'onEvent', false)\n if (callback !== undefined && typeof callback !== 'function') throw new TypeError('Runtime team observer is invalid')\n const onEvent = callback === undefined ? undefined\n : (event: RuntimeAgentTeamEvent): void => { Reflect.apply(callback, source, [event]) }\n const agentCallback = ownData(source, 'onAgentEvent', false)\n if (agentCallback !== undefined && typeof agentCallback !== 'function') throw new TypeError('Runtime team agent observer is invalid')\n const onAgentEvent = agentCallback === undefined ? undefined\n : (member: string, event: Parameters<NonNullable<RuntimeAgentTeamOptions['onAgentEvent']>>[1]): void | Promise<void> => (\n Reflect.apply(agentCallback, source, [member, event])\n )\n return Object.freeze({ id, members: Object.freeze(captured),\n ...copyPositive(source, ['maxMessages', 'maxMessageBytes', 'operationTimeoutMs', 'observerTimeoutMs']),\n ...(onEvent === undefined ? {} : { onEvent }),\n ...(onAgentEvent === undefined ? {} : { onAgentEvent }) })\n}\n\nfunction optionalBounded(source: object, key: string): string | undefined {\n const value = ownData(source, key, false)\n return value === undefined ? undefined : boundedText(value, RUNTIME_TEAM_LIMITS.metadataBytes)\n}\n\nfunction copyPositive(source: object, keys: readonly string[]): Record<string, number> {\n const output: Record<string, number> = Object.create(null) as Record<string, number>\n for (const key of keys) {\n const value = ownData(source, key, false)\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || Number(value) < 1) throw new TypeError(`Runtime team ${key} is invalid`)\n output[key] = Number(value)\n }\n return output\n}\n\nfunction rejectUnknown(source: object, keys: ReadonlySet<string>): void {\n if (Reflect.ownKeys(source).some(key => typeof key !== 'string' || !keys.has(key))) {\n throw new TypeError('Runtime team options contain unsupported fields')\n }\n}\n"],"mappings":"sWAOA,MAAM,EAAY,IAAI,IAAI,CAAC,KAAM,UAAW,cAAe,kBAAmB,qBAC5E,oBAAqB,UAAW,cAAc,CAAC,EAC3C,EAAc,IAAI,IAAI,CAAC,OAAQ,QAAS,cAAe,eAAgB,OAAQ,QAAS,SAAS,CAAC,EAaxG,SAAgB,EAA0B,EAA4C,CACpF,IAAM,EAAS,EAAY,CAAK,EAChC,EAAc,EAAQ,CAAS,EAC/B,IAAM,EAAK,EAAY,EAAQ,EAAQ,IAAI,EAAG,EAAoB,OAAO,EACnE,EAAU,EAAU,EAAQ,EAAQ,SAAS,EAAG,EAAoB,OAAO,EACjF,GAAI,EAAQ,SAAW,EAAG,MAAU,UAAU,2CAA2C,EACzF,IAAM,EAAO,IAAI,IACb,EAAQ,EACN,EAAW,EAAQ,KAAK,EAAK,IAA8B,CAC/D,IAAM,EAAS,EAAY,CAAG,EAC9B,EAAc,EAAQ,CAAW,EACjC,IAAM,EAAO,EAAW,EAAQ,EAAQ,MAAM,CAAC,EACzC,EAAQ,EAAK,IAAI,CAAI,EAC3B,GAAI,IAAU,IAAA,GAAW,MAAM,EAC7B,uBAAwB,mBAAoB,EAAO,CACrD,EACA,EAAK,IAAI,EAAM,CAAK,EACpB,IAAM,EAAO,EAAQ,EAAQ,OAAQ,EAAK,IAAM,IAAU,EAAI,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AI,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,EAC3C,GAAI,IAAiB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAa,CAAG,CAAC,CAC7D,CAEA,SAAS,EAAgB,EAAgB,EAAiC,CACxE,IAAM,EAAQ,EAAQ,EAAQ,EAAK,EAAK,EACxC,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAY,EAAO,EAAoB,aAAa,CAC/F,CAEA,SAAS,EAAa,EAAgB,EAAiD,CACrF,IAAM,EAAiC,OAAO,OAAO,IAAI,EACzD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAQ,EAAQ,EAAQ,EAAK,EAAK,EACpC,OAAU,IAAA,GACd,IAAI,CAAC,OAAO,cAAc,CAAK,GAAK,OAAO,CAAK,EAAI,EAAG,MAAU,UAAU,gBAAgB,EAAI,YAAY,EAC3G,EAAO,GAAO,OAAO,CAAK,CADiF,CAE7G,CACA,OAAO,CACT,CAEA,SAAS,EAAc,EAAgB,EAAiC,CACtE,GAAI,QAAQ,QAAQ,CAAM,CAAC,CAAC,KAAK,GAAO,OAAO,GAAQ,UAAY,CAAC,EAAK,IAAI,CAAG,CAAC,EAC/E,MAAU,UAAU,iDAAiD,CAEzE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{boundedText as t,capturedMethod as n,objectValue as r,optionalAbortSignal as i,ownData as a}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as o}from"../../capability/common/config.js";import{BoundaryFailure as s,atDeadline as c}from"../lifecycle/bounded.js";import{captureCloseSignal as l}from"../runtime/config.js";import{captureInvocationOptions as u}from"../agent/options.js";import{createRuntimeTeamMemberSession as d,preflightRuntimeTeamMember as f}from"../agent/session.js";import{NOT_APPLICABLE_USAGE_COVERAGE as p}from"../../support-safe/error.js";import{TEAM_TOOL_NAMES as m,memberName as h}from"../../agent/team/common.js";import{AgentTeam as g}from"../../agent/team/team.js";import{RUNTIME_TEAM_ERROR_CODES as _,RUNTIME_TEAM_LIMITS as v}from"./config.js";import{captureRuntimeTeamOptions as y}from"./options.js";var b=class{host;team;sessions;onClosed;lifecycle;id;view;closing;draining;closed=!1;activeRuns=new Set;constructor(e,t,n,r,i,a){this.host=e,this.team=t,this.sessions=n,this.onClosed=i,this.lifecycle=a,this.id=t.id,this.view=Object.freeze({id:t.id,memberNames:r,linkAgent:e=>this.linkAgent(e),sendMessage:e=>this.sendMessage(e),session:e=>this.session(e),run:(e,t,n)=>this.run(e,t,n),close:e=>this.close(e)})}assertActive(){if(this.host.operations.assertActive(),this.closed)throw new e(`Runtime team is closed`,_.closed)}session(t){this.assertActive();let n=this.sessions.get(h(t));if(n===void 0)throw new e(`Runtime team member is unavailable`,_.invalid);return n}run(e,t,n){if(this.assertActive(),typeof t!=`string`)throw TypeError(`Runtime team input must be a string`);let r=u(n),i=this.session(e),a=r.signal===void 0?this.lifecycle.signal:AbortSignal.any([r.signal,this.lifecycle.signal]),o=this.host.operations.execute(`team-operation`,{signal:a},e=>i.run(t,{...r,signal:e.signal})),s=o.then(()=>void 0,()=>void 0);return this.activeRuns.add(s),s.finally(()=>this.activeRuns.delete(s)),o}sendMessage(e){this.assertActive();let t=S(e);return this.host.operations.execute(`team-operation`,{...t.signal===void 0?{}:{signal:t.signal}},e=>this.team.sendMessage({...t,signal:e.signal}))}linkAgent(e){this.assertActive();let t=C(e,this.host,this.team.id),n=this.team.linkAgent(t),r=!0;return()=>{r&&=(n(),!1)}}close(t){if(this.closing!==void 0)return this.closing;let n=l(t),r,i;this.closing=new Promise((e,t)=>{r=e,i=t});let a=this.closing;a.catch(()=>void 0),this.closed=!0;try{this.lifecycle.abort(Error(`Runtime agent team is closing`));let t=[...this.activeRuns],a=[...this.sessions.values()],o=Promise.all([this.team.dispose(Error(`Runtime agent team is closing`)),Promise.all(t),Promise.all(a.map(e=>e.whenIdle()))]).then(()=>void 0).finally(()=>{this.sessions.clear()});this.draining=o,o.then(()=>this.onClosed(this),()=>void 0),c(this.host.resources,this.host.resources.platform.monotonicNow()+v.closeTimeoutMs,()=>o,n).then(r,t=>{let n=t instanceof s&&t.reason===`aborted`;i(new e(n?`Runtime team close wait was aborted`:`Runtime team did not close within 30000ms`,n?`TEAM_CLOSE_ABORTED`:`TEAM_DISPOSE_TIMEOUT`))})}catch(e){i(e)}return a}async closeForRuntime(e){try{return this.close(),await c(this.host.resources,e,()=>this.draining),Object.freeze({kind:`agent-team`,id:this.team.id,status:`closed`})}catch{return Object.freeze({kind:`agent-team`,id:this.team.id,status:`timed-out`,error:Object.freeze({code:`CAPABILITY_CLEANUP_TIMEOUT`,stage:`team-cleanup`,message:`Runtime agent team did not close before the shared deadline`})})}}};function x(e,t,n=()=>void 0){e.operations.assertActive();let r=y(t);for(let t of r.members)f(e,t.agent,t.session,t.tools===!1?[]:Object.values(m));let i=[],a=new AbortController,o=e=>{i.push(e)},s=new g({id:r.id,maxMembers:v.members,...r.maxMessages===void 0?{}:{maxMessages:r.maxMessages},...r.maxMessageBytes===void 0?{}:{maxMessageBytes:r.maxMessageBytes},...r.operationTimeoutMs===void 0?{}:{operationTimeoutMs:r.operationTimeoutMs},...r.observerTimeoutMs===void 0?{}:{observerTimeoutMs:r.observerTimeoutMs},onEvent:e=>{e.type!==`team-disposed`&&o(w(e))}},t=>{let n=e.operations.acquire(`team-operation`,{signal:t});return()=>n.settle()}),c=new Map,l=new Map,u=[],p=Object.freeze({attach(e,t={}){u.push(t)},toolsFor:e=>s.toolsFor(e),instructionsFor:e=>s.instructionsFor(e)});try{for(let t of r.members){let n=d(e,t.agent,t.session,{team:p,name:t.name,role:t.role,...t.description===void 0?{}:{description:t.description},...t.instructions===void 0?{}:{instructions:t.instructions},...t.tools===void 0?{}:{tools:t.tools}},a.signal);c.set(t.name,n.view),l.set(t.name,n.port)}for(let e of u){let t=h(e.name),n=l.get(t);if(n===void 0)throw Error(`Runtime team session '${t}' was not staged`);s.attach(n,e)}}catch(e){throw a.abort(Error(`Runtime agent team construction failed`)),s.dispose().catch(()=>void 0),e}o=t=>{e.operations.status!==`closed`&&r.onEvent?.(t)};for(let e of i)o(e);return new b(e,s,c,Object.freeze([...c.keys()]),e=>{n(e);try{o(Object.freeze({type:`team-closed`,teamId:s.id}))}catch{}},a)}function S(e){let t=r(e),n=new Set([`from`,`target`,`message`,`delivery`,`signal`]);if(Reflect.ownKeys(t).some(e=>typeof e!=`string`||!n.has(e)))throw TypeError(`Runtime team message contains unsupported fields`);let o=i(a(t,`signal`,!1)),s=a(t,`delivery`,!1);return Object.freeze({from:h(a(t,`from`)),target:h(a(t,`target`)),message:a(t,`message`),...s===void 0?{}:{delivery:s},...o===void 0?{}:{signal:o}})}function C(e,i,s){let c=r(e),l=h(a(c,`name`)),u=a(c,`description`,!1),d=r(a(c,`transport`)),f=t(a(d,`protocol`),o.identityBytes),p=t(a(d,`agentId`),o.identityBytes),m=n(d,`send`),g=i.observation.logger({scope:`sdk.team.transport`,fields:{teamId:s,member:l}});return Object.freeze({name:l,...u===void 0?{}:{description:t(u,8192)},transport:Object.freeze({protocol:f,agentId:p,send:e=>m({...e,logger:g})})})}function w(e){return e.type===`member-attached`?Object.freeze({type:e.type,member:e.member.name}):e.type===`member-linked`?Object.freeze({type:e.type,member:e.member.name,protocol:e.member.protocol??`unknown`}):e.type===`message-accepted`?Object.freeze({type:e.type,messageId:e.message.id,target:e.message.target}):e.type===`member-run-start`||e.type===`member-run-end`?Object.freeze(e):e.type===`member-run-error`?Object.freeze({type:e.type,member:e.member,error:Object.freeze({code:`TEAM_MEMBER_RUN_FAILED`,stage:`team-operation`,message:`Runtime team member operation failed`,usageCoverage:p,possiblyBilledAttemptsWithoutUsage:0})}):e.type===`team-disposed`?Object.freeze({type:`team-closed`,teamId:e.teamId}):Object.freeze({type:`member-run-end`,member:e.member})}export{x as createRuntimeAgentTeam};
|
|
1
|
+
import{AgentSdkError as e}from"../../errors/agent-sdk-error.js";import{boundedText as t,capturedMethod as n,objectValue as r,optionalAbortSignal as i,ownData as a}from"../../capability/common/data.js";import{COMPOSITION_LIMITS as o}from"../../capability/common/config.js";import{BoundaryFailure as s,atDeadline as c}from"../lifecycle/bounded.js";import{captureCloseSignal as l}from"../runtime/config.js";import{captureInvocationOptions as u}from"../agent/options.js";import{createRuntimeTeamMemberSession as d,preflightRuntimeTeamMember as f}from"../agent/session.js";import{NOT_APPLICABLE_USAGE_COVERAGE as p}from"../../support-safe/error.js";import{TEAM_TOOL_NAMES as m,memberName as h}from"../../agent/team/common.js";import{AgentTeam as g}from"../../agent/team/team.js";import{RUNTIME_TEAM_ERROR_CODES as _,RUNTIME_TEAM_LIMITS as v}from"./config.js";import{captureRuntimeTeamOptions as y}from"./options.js";var b=class{host;team;sessions;onClosed;lifecycle;id;view;closing;draining;closed=!1;activeRuns=new Set;constructor(e,t,n,r,i,a){this.host=e,this.team=t,this.sessions=n,this.onClosed=i,this.lifecycle=a,this.id=t.id,this.view=Object.freeze({id:t.id,memberNames:r,linkAgent:e=>this.linkAgent(e),sendMessage:e=>this.sendMessage(e),session:e=>this.session(e),run:(e,t,n)=>this.run(e,t,n),close:e=>this.close(e)})}assertActive(){if(this.host.operations.assertActive(),this.closed)throw new e(`Runtime team is closed`,_.closed)}session(t){this.assertActive();let n=this.sessions.get(h(t));if(n===void 0)throw new e(`Runtime team member is unavailable`,_.invalid);return n}run(e,t,n){if(this.assertActive(),typeof t!=`string`)throw TypeError(`Runtime team input must be a string`);let r=u(n),i=this.session(e),a=r.signal===void 0?this.lifecycle.signal:AbortSignal.any([r.signal,this.lifecycle.signal]),o=this.host.operations.execute(`team-operation`,{signal:a},e=>i.run(t,{...r,signal:e.signal})),s=o.then(()=>void 0,()=>void 0);return this.activeRuns.add(s),s.finally(()=>this.activeRuns.delete(s)),o}sendMessage(e){this.assertActive();let t=S(e);return this.host.operations.execute(`team-operation`,{...t.signal===void 0?{}:{signal:t.signal}},e=>this.team.sendMessage({...t,signal:e.signal}))}linkAgent(e){this.assertActive();let t=C(e,this.host,this.team.id),n=this.team.linkAgent(t),r=!0;return()=>{r&&=(n(),!1)}}close(t){if(this.closing!==void 0)return this.closing;let n=l(t),r,i;this.closing=new Promise((e,t)=>{r=e,i=t});let a=this.closing;a.catch(()=>void 0),this.closed=!0;try{this.lifecycle.abort(Error(`Runtime agent team is closing`));let t=[...this.activeRuns],a=[...this.sessions.values()],o=Promise.all([this.team.dispose(Error(`Runtime agent team is closing`)),Promise.all(t),Promise.all(a.map(e=>e.whenIdle()))]).then(()=>void 0).finally(()=>{this.sessions.clear()});this.draining=o,o.then(()=>this.onClosed(this),()=>void 0),c(this.host.resources,this.host.resources.platform.monotonicNow()+v.closeTimeoutMs,()=>o,n).then(r,t=>{let n=t instanceof s&&t.reason===`aborted`;i(new e(n?`Runtime team close wait was aborted`:`Runtime team did not close within 30000ms`,n?`TEAM_CLOSE_ABORTED`:`TEAM_DISPOSE_TIMEOUT`))})}catch(e){i(e)}return a}async closeForRuntime(e){try{return this.close(),await c(this.host.resources,e,()=>this.draining),Object.freeze({kind:`agent-team`,id:this.team.id,status:`closed`})}catch{return Object.freeze({kind:`agent-team`,id:this.team.id,status:`timed-out`,error:Object.freeze({code:`CAPABILITY_CLEANUP_TIMEOUT`,stage:`team-cleanup`,message:`Runtime agent team did not close before the shared deadline`})})}}};function x(e,t,n=()=>void 0){e.operations.assertActive();let r=y(t);for(let t of r.members)f(e,t.agent,t.session,t.tools===!1?[]:Object.values(m));let i=[],a=new AbortController,o=e=>{i.push(e)},s=new g({id:r.id,maxMembers:v.members,...r.maxMessages===void 0?{}:{maxMessages:r.maxMessages},...r.maxMessageBytes===void 0?{}:{maxMessageBytes:r.maxMessageBytes},...r.operationTimeoutMs===void 0?{}:{operationTimeoutMs:r.operationTimeoutMs},...r.observerTimeoutMs===void 0?{}:{observerTimeoutMs:r.observerTimeoutMs},onEvent:e=>{e.type!==`team-disposed`&&o(w(e))},...r.onAgentEvent===void 0?{}:{onAgentEvent:r.onAgentEvent}},t=>{let n=e.operations.acquire(`team-operation`,{signal:t});return()=>n.settle()}),c=new Map,l=new Map,u=[],p=Object.freeze({attach(e,t={}){u.push(t)},toolsFor:e=>s.toolsFor(e),instructionsFor:e=>s.instructionsFor(e)});try{for(let t of r.members){let n=d(e,t.agent,t.session,{team:p,name:t.name,role:t.role,...t.description===void 0?{}:{description:t.description},...t.instructions===void 0?{}:{instructions:t.instructions},...t.tools===void 0?{}:{tools:t.tools}},a.signal);c.set(t.name,n.view),l.set(t.name,n.port)}for(let e of u){let t=h(e.name),n=l.get(t);if(n===void 0)throw Error(`Runtime team session '${t}' was not staged`);s.attach(n,e)}}catch(e){throw a.abort(Error(`Runtime agent team construction failed`)),s.dispose().catch(()=>void 0),e}o=t=>{e.operations.status!==`closed`&&r.onEvent?.(t)};for(let e of i)o(e);return new b(e,s,c,Object.freeze([...c.keys()]),e=>{n(e);try{o(Object.freeze({type:`team-closed`,teamId:s.id}))}catch{}},a)}function S(e){let t=r(e),n=new Set([`from`,`target`,`message`,`delivery`,`signal`]);if(Reflect.ownKeys(t).some(e=>typeof e!=`string`||!n.has(e)))throw TypeError(`Runtime team message contains unsupported fields`);let o=i(a(t,`signal`,!1)),s=a(t,`delivery`,!1);return Object.freeze({from:h(a(t,`from`)),target:h(a(t,`target`)),message:a(t,`message`),...s===void 0?{}:{delivery:s},...o===void 0?{}:{signal:o}})}function C(e,i,s){let c=r(e),l=h(a(c,`name`)),u=a(c,`description`,!1),d=r(a(c,`transport`)),f=t(a(d,`protocol`),o.identityBytes),p=t(a(d,`agentId`),o.identityBytes),m=n(d,`send`),g=i.observation.logger({scope:`sdk.team.transport`,fields:{teamId:s,member:l}});return Object.freeze({name:l,...u===void 0?{}:{description:t(u,8192)},transport:Object.freeze({protocol:f,agentId:p,send:e=>m({...e,logger:g})})})}function w(e){return e.type===`member-attached`?Object.freeze({type:e.type,member:e.member.name}):e.type===`member-linked`?Object.freeze({type:e.type,member:e.member.name,protocol:e.member.protocol??`unknown`}):e.type===`message-accepted`?Object.freeze({type:e.type,messageId:e.message.id,target:e.message.target}):e.type===`member-run-start`||e.type===`member-run-end`?Object.freeze(e):e.type===`member-run-error`?Object.freeze({type:e.type,member:e.member,error:Object.freeze({code:`TEAM_MEMBER_RUN_FAILED`,stage:`team-operation`,message:`Runtime team member operation failed`,usageCoverage:p,possiblyBilledAttemptsWithoutUsage:0})}):e.type===`team-disposed`?Object.freeze({type:`team-closed`,teamId:e.teamId}):Object.freeze({type:`member-run-end`,member:e.member})}export{x as createRuntimeAgentTeam};
|
|
2
2
|
//# sourceMappingURL=runtime.js.map
|