@alvin0/ai-agent-sdk-core 0.1.3 → 0.1.5
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/README.md +13 -1
- package/dist/agent/accounting/ledger.js +1 -1
- package/dist/agent/accounting/ledger.js.map +1 -1
- package/dist/agent/accounting/report.d.ts +1 -1
- package/dist/agent/define/definition.d.ts +27 -6
- package/dist/agent/define/definition.d.ts.map +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/accounting.js +1 -1
- package/dist/agent/define/session/accounting.js.map +1 -1
- 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 +6 -3
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -2
- 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/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/config.js +1 -1
- package/dist/agent/loop/turn/config.js.map +1 -1
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- 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/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/compaction.d.ts.map +1 -1
- package/dist/agent/memory/compaction.js +1 -1
- package/dist/agent/memory/compaction.js.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/definition.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 +17 -10
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/runtime/owner.js +1 -1
- package/dist/composition/runtime/owner.js.map +1 -1
- package/dist/composition/runtime/types.d.ts +7 -1
- package/dist/composition/runtime/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/contract/adapter.d.ts +1 -1
- package/dist/contract/call-config.d.ts +8 -1
- package/dist/contract/call-config.d.ts.map +1 -1
- package/dist/contract/call-config.js +1 -1
- package/dist/contract/call-config.js.map +1 -1
- package/dist/contract/generate-options.d.ts +5 -0
- package/dist/contract/generate-options.d.ts.map +1 -1
- package/dist/contract/model-info.d.ts +26 -7
- package/dist/contract/model-info.d.ts.map +1 -1
- package/dist/errors/model-error.d.ts +0 -1
- package/dist/errors/model-error.d.ts.map +1 -1
- package/dist/errors/model-error.js +1 -1
- package/dist/errors/model-error.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/observation/report.d.ts +11 -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 +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.d.ts +7 -1
- package/dist/runtime/registry.d.ts.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/registry.js.map +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","names":[],"sources":["../../src/runtime/registry.ts"],"sourcesContent":["/**\n * The adapter registry and the streaming call API.\n *\n * This is the deepseek-harness `LlmRuntime` with its dependency-injection\n * framework removed: a plain `Map` for routes, an ordered array for the\n * interception point that was a cordis waterfall, and a listener set for the\n * topology event. What is kept is everything that made it trustworthy E * all-or-nothing validating registration, an atomic route swap, prepare/dispatch\n * generation binding, and a single failure funnel at the adapter boundary.\n *\n * @module ai-agent-sdk/core/runtime/registry\n */\n\nimport type { ModelAdapter } from '../contract/adapter.ts'\nimport {\n callConfigEquals,\n type CallConfig,\n type CallConfigAdapterDefaults,\n} from '../contract/call-config.ts'\nimport type { GenerateOptions } from '../contract/generate-options.ts'\nimport type {\n ModelContext,\n ModelCatalogOptions,\n ModelCatalogSnapshot,\n ModelInfo,\n ModelModality,\n ProviderInfo,\n ResolvedModelInfo,\n} from '../contract/model-info.ts'\nimport { resolveRetryPolicy, type ResolvedRetryPolicy } from '../contract/retry-policy.ts'\nimport { ModelError, REGISTRY_ERROR_CODES } from '../errors/model-error.ts'\nimport { deepFreeze } from '../primitives/freeze.ts'\nimport { SDK_VERSION } from '../primitives/version.ts'\nimport type { ObservationResource } from '../observation/event.ts'\nimport type { ObservationPort } from '../observation/port.ts'\nimport type { ModelCallHandle, ModelInvocationContext } from '../observation/report.ts'\nimport type { StreamChunk } from '../stream/chunk.ts'\nimport { createModelCallHandle } from './model-call-handle.ts'\nimport { normalizeResolvedModelInfo, resolveCallWithModelInfo,\n validateCatalogModels, validateModelCatalogSnapshot } from './model-metadata.ts'\nimport { streamAdapter, type PreparedDispatch,\n type RuntimeAdapterRegistration } from './model-stream.ts'\nimport {\n PLUGIN_ERROR_CODES,\n PluginError,\n type AdapterRegistrationHandle,\n type ModelProviderPlugin,\n type ModelProviderRegistrar,\n type PluginRegistrationHandle,\n type StreamMiddleware,\n} from '../plugin/provider-plugin.ts'\n\nexport type { AdapterRegistrationHandle, StreamMiddleware } from '../plugin/provider-plugin.ts'\n\n/**\n * Wraps every streaming model call. Call `next()` to reach the adapter, or yield\n * your own chunks to short-circuit it entirely.\n *\n * This is the extension point for retry, caching, request logging, replay, and\n * test doubles. Middleware registered EARLIER sits further out.\n */\n/** One call whose configuration and adapter registration were resolved together. */\nexport interface PreparedCall {\n /** Detached, deep-frozen config with any adapter-owned default materialized. */\n readonly config: CallConfig\n /** Immutable retry policy captured with the adapter registration. */\n readonly retryPolicy: ResolvedRetryPolicy\n /** Context capacity resolved with the registration-bound call. */\n readonly context?: ModelContext\n /** Exact model modalities captured with the dispatch generation. */\n readonly inputModalities?: readonly ModelModality[]\n /** Complete validated capability snapshot bound to this adapter generation. */\n readonly model: ResolvedModelInfo\n /** Which config fields the adapter supplied rather than the caller. */\n readonly adapterDefaults: CallConfigAdapterDefaults\n /**\n * Dispatch this call ONCE, through the registration captured at preparation.\n * @param options - the assembled request, carrying the prepared config.\n * @returns the chunk stream, including middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle\n}\n\nexport interface ModelRegistryOptions {\n /** Maximum model rows accepted from one adapter catalog. Defaults to 2,048. */\n readonly maxCatalogModels?: number\n /** Maximum serialized bytes accepted from a catalog or model-info record. Defaults to 4 MiB. */\n readonly maxCatalogBytes?: number\n /** Default observation port; a per-call invocation context may override it. */\n readonly observation?: ObservationPort\n /** Safe SDK/service/runtime identity copied onto observation events. */\n readonly observationResource?: ObservationResource\n}\n\ntype AdapterRegistration = RuntimeAdapterRegistration\n\ninterface InstalledPlugin {\n readonly routes: ReadonlySet<string>\n readonly registrations: readonly AdapterRegistration[]\n readonly middleware: readonly StreamMiddleware[]\n readonly cleanup?: () => void\n}\n\n\nfunction containThenable(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false\n let then: unknown\n try {\n then = Reflect.get(value, 'then')\n } catch {\n return true\n }\n if (typeof then !== 'function') return false\n try { void Promise.resolve(value).catch(() => {}) } catch { /* hostile thenable contained */ }\n return true\n}\n\nfunction synchronousCleanupFailure(cleanup: () => void): unknown | undefined {\n try {\n const result: unknown = cleanup()\n return containThenable(result) ? new TypeError('plugin cleanup must be synchronous') : undefined\n } catch (error) {\n return error\n }\n}\n\n\n/**\n * Routes model calls to registered adapters.\n *\n * Construct one per application or isolated runtime scope, register the adapters\n * you use, then call {@link stream} or {@link prepareCall}.\n */\nexport class ModelRegistry {\n private adapters = new Map<string, AdapterRegistration>()\n private middleware: StreamMiddleware[] = []\n private listeners = new Set<() => void>()\n private plugins = new Map<string, InstalledPlugin>()\n private readonly maxCatalogModels: number\n private readonly maxCatalogBytes: number\n private readonly observation: ObservationPort | undefined\n private readonly observationResource: ObservationResource\n\n constructor(options: ModelRegistryOptions = {}) {\n this.maxCatalogModels = positiveSafeInteger(options.maxCatalogModels ?? 2_048, 'maxCatalogModels')\n this.maxCatalogBytes = positiveSafeInteger(options.maxCatalogBytes ?? 4 * 1024 * 1024, 'maxCatalogBytes')\n this.observation = options.observation\n this.observationResource = deepFreeze(options.observationResource ?? {\n sdkName: 'ai-agent-sdk',\n sdkVersion: SDK_VERSION,\n runtime: 'unknown',\n })\n }\n\n /** Install one provider plugin as a single synchronous topology transaction. */\n install(plugin: ModelProviderPlugin): PluginRegistrationHandle {\n const pluginId = typeof plugin?.id === 'string' ? plugin.id : ''\n const fail = (message: string, cause?: unknown, cleanupFailures: readonly unknown[] = []): never => {\n const causes = [...cause === undefined ? [] : [cause], ...cleanupFailures]\n const wrappedCause = causes.length <= 1 ? causes[0] : new AggregateError(causes, `plugin ${pluginId} install cleanup failed`)\n throw new PluginError(message, PLUGIN_ERROR_CODES.INSTALL_FAILED, pluginId, wrappedCause === undefined ? undefined : { cause: wrappedCause })\n }\n if (pluginId.trim().length === 0 || pluginId !== pluginId.trim()) fail('plugin id must be a non-empty trimmed string')\n if (this.plugins.has(pluginId)) fail(`plugin \"${pluginId}\" is already installed`)\n if (typeof plugin.displayName !== 'string' || plugin.displayName.trim().length === 0) fail(`plugin \"${pluginId}\" displayName must be non-empty`)\n if (typeof plugin.setup !== 'function') fail(`plugin \"${pluginId}\" setup must be a function`)\n const family = plugin.family ?? pluginId\n if (typeof family !== 'string' || family.trim().length === 0 || family !== family.trim()) {\n fail(`plugin \"${pluginId}\" family must be a non-empty trimmed string`)\n }\n const owner = Object.freeze({ pluginId, family })\n\n interface StagedAdapter {\n active: boolean\n routes: string[]\n readonly adapter: ModelAdapter\n }\n interface StagedMiddleware { active: boolean; readonly middleware: StreamMiddleware }\n const stagedAdapters: StagedAdapter[] = []\n const stagedMiddleware: StagedMiddleware[] = []\n let staging = true\n\n const registrar: ModelProviderRegistrar = {\n registerAdapter: (routes, adapter) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (routes.length === 0) throw new ModelError('an adapter must register at least one provider route', REGISTRY_ERROR_CODES.INVALID_ADAPTER)\n const item: StagedAdapter = { active: true, routes: [...routes], adapter }\n // Validate metadata and conflicts without mutating live routes.\n const occupied = new Set(stagedAdapters.filter(value => value.active).flatMap(value => value.routes))\n for (const route of routes) if (occupied.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(routes, adapter, new Set(), owner)\n stagedAdapters.push(item)\n const handle = (() => {\n if (staging) item.active = false\n }) as AdapterRegistrationHandle\n handle.replace = (next) => {\n if (!staging || !item.active) throw new ModelError('a disposed staged registration cannot replace routes', REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED)\n const occupiedByOthers = new Set(stagedAdapters.filter(value => value.active && value !== item).flatMap(value => value.routes))\n for (const route of next) if (occupiedByOthers.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(next, adapter, new Set(), owner)\n item.routes = [...next]\n }\n return handle\n },\n use: (middleware) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (typeof middleware !== 'function') throw new TypeError('plugin middleware must be a function')\n const item: StagedMiddleware = { active: true, middleware }\n stagedMiddleware.push(item)\n return () => { if (staging) item.active = false }\n },\n }\n\n let cleanup: (() => void) | undefined\n try {\n const result = plugin.setup(registrar)\n if (containThenable(result)) fail(`plugin \"${pluginId}\" setup must be synchronous`)\n if (result !== undefined && typeof result !== 'function') fail(`plugin \"${pluginId}\" setup must be synchronous and return void or cleanup`)\n cleanup = typeof result === 'function' ? result : undefined\n } catch (error) {\n if (error instanceof PluginError && error.code === PLUGIN_ERROR_CODES.INSTALL_FAILED) throw error\n fail(`plugin \"${pluginId}\" setup failed`, error)\n } finally {\n staging = false\n }\n\n const registrations: AdapterRegistration[] = []\n const routeNames = new Set<string>()\n try {\n for (const item of stagedAdapters) {\n if (!item.active) continue\n for (const route of item.routes) {\n if (routeNames.has(route)) throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n routeNames.add(route)\n }\n registrations.push(...this.prepareRoutes(item.routes, item.adapter, new Set(), owner))\n }\n } catch (error) {\n const cleanupFailures: unknown[] = []\n if (cleanup) {\n const cleanupFailure = synchronousCleanupFailure(cleanup)\n if (cleanupFailure !== undefined) cleanupFailures.push(cleanupFailure)\n }\n fail(`plugin \"${pluginId}\" commit validation failed`, error, cleanupFailures)\n }\n\n const committedMiddleware = stagedMiddleware.filter(item => item.active).map(item => item.middleware)\n for (const registration of registrations) this.adapters.set(registration.provider.id, registration)\n this.middleware.push(...committedMiddleware)\n const installed: InstalledPlugin = {\n routes: routeNames,\n registrations,\n middleware: committedMiddleware,\n ...(cleanup === undefined ? {} : { cleanup }),\n }\n this.plugins.set(pluginId, installed)\n this.emitAdaptersUpdated()\n\n let disposed = false\n const dispose = (() => {\n if (disposed) return\n disposed = true\n this.plugins.delete(pluginId)\n for (const registration of installed.registrations) {\n if (this.adapters.get(registration.provider.id) === registration) this.adapters.delete(registration.provider.id)\n }\n for (let index = installed.middleware.length - 1; index >= 0; index--) {\n const middleware = installed.middleware[index]\n const liveIndex = middleware === undefined ? -1 : this.middleware.lastIndexOf(middleware)\n if (liveIndex >= 0) this.middleware.splice(liveIndex, 1)\n }\n this.emitAdaptersUpdated()\n const failures: unknown[] = []\n if (installed.cleanup) {\n const cleanupFailure = synchronousCleanupFailure(installed.cleanup)\n if (cleanupFailure !== undefined) failures.push(cleanupFailure)\n }\n if (failures.length > 0) {\n throw new PluginError(\n `plugin \"${pluginId}\" cleanup failed`,\n PLUGIN_ERROR_CODES.CLEANUP_FAILED,\n pluginId,\n { cause: new AggregateError(failures, `plugin \"${pluginId}\" cleanup failed`) },\n )\n }\n }) as PluginRegistrationHandle\n Object.defineProperty(dispose, 'pluginId', { value: pluginId, enumerable: true })\n return dispose\n }\n\n /**\n * Register an adapter for the given routes.\n *\n * All-or-nothing: if ANY route conflicts, nothing is registered. A partial\n * registration would leave the caller believing a route exists when it does not.\n * @param providers - every route this adapter should serve; must be non-empty.\n * @param adapter - the adapter that streams calls for those routes.\n * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.\n */\n registerAdapter(\n providers: readonly string[],\n adapter: ModelAdapter,\n ): AdapterRegistrationHandle {\n if (providers.length === 0) {\n throw new ModelError(\n 'an adapter must register at least one provider route',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n /** Routes this registration currently holds; `replace` rewrites it. */\n const owned = new Set<string>()\n // `owned` being empty cannot signal disposal on its own, because\n // `replace([])` legally leaves a live registration holding no routes.\n let released = false\n\n this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned))\n\n const handle = (() => {\n if (released) return\n released = true\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n this.emitAdaptersUpdated()\n }) as AdapterRegistrationHandle\n\n handle.replace = (next: readonly string[]): void => {\n // Registering after disposal would leak: nothing remains to release what\n // this call would put back into the map.\n if (released) {\n throw new ModelError(\n 'a disposed adapter registration cannot replace its routes',\n REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED,\n )\n }\n this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned))\n }\n return handle\n }\n\n /**\n * Validate one candidate route set, treating routes this registration already\n * holds as available. Mutates nothing Ea rejected candidate leaves the registry\n * exactly as it was.\n */\n private prepareRoutes(\n providers: readonly string[],\n adapter: ModelAdapter,\n owned: ReadonlySet<string>,\n owner?: Readonly<{ pluginId: string; family: string }>,\n ): AdapterRegistration[] {\n const unique = new Set<string>()\n const registrations: AdapterRegistration[] = []\n for (const provider of providers) {\n if (typeof provider !== 'string' || provider.length === 0) {\n throw new ModelError(\n 'adapter provider route names must be non-empty strings',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n if (unique.has(provider) || (this.adapters.has(provider) && !owned.has(provider))) {\n throw new ModelError(\n `an adapter for provider route \"${provider}\" is already registered`,\n REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER,\n )\n }\n const info = adapter.providerInfo(provider)\n if (typeof info.id !== 'string' || info.id !== provider\n || typeof info.name !== 'string' || info.name.length === 0) {\n throw new ModelError(\n `adapter metadata for route \"${provider}\" must preserve its id and carry a non-empty name`,\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n unique.add(provider)\n registrations.push({\n adapter,\n provider: { id: info.id, name: info.name },\n ...(owner === undefined ? {} : owner),\n // Captured at REGISTRATION time, not per call. An adapter whose policy\n // follows mutable configuration re-registers via `handle.replace`.\n retryPolicy: adapter.providerRetryPolicy(provider)\n ?? resolveRetryPolicy(undefined, `provider \"${provider}\" retryPolicy`),\n })\n }\n return registrations\n }\n\n /**\n * Swap this registration's routes in ONE synchronous section, so no caller can\n * observe the registry between the release and the re-registration.\n */\n private commitRoutes(\n owned: Set<string>,\n registrations: readonly AdapterRegistration[],\n ): void {\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n for (const registration of registrations) {\n this.adapters.set(registration.provider.id, registration)\n owned.add(registration.provider.id)\n }\n this.emitAdaptersUpdated()\n }\n\n /**\n * Install streaming middleware.\n * @param middleware - wrapper invoked around every call; earlier registrations sit further out.\n * @returns a disposer that removes exactly this middleware.\n */\n use(middleware: StreamMiddleware): () => void {\n this.middleware.push(middleware)\n return () => {\n const index = this.middleware.indexOf(middleware)\n if (index >= 0) this.middleware.splice(index, 1)\n }\n }\n\n /**\n * Observe route-topology changes (registration, replacement, disposal).\n * @param listener - payload-free notification; re-read `listProviders()` for new state.\n * @returns a disposer that removes the listener.\n */\n onAdaptersUpdated(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => void this.listeners.delete(listener)\n }\n\n /**\n * Notify topology observers.\n *\n * Each listener is contained independently: a topology notification is not a\n * veto, so one broken observer must not starve the others or roll back a\n * registration that already happened.\n */\n private emitAdaptersUpdated(): void {\n for (const listener of [...this.listeners]) {\n try {\n listener()\n } catch {\n // Contained deliberately; see above.\n }\n }\n }\n\n /**\n * Describe every route with a registered adapter.\n * @returns detached provider metadata, in registration order.\n */\n listProviders(): ProviderInfo[] {\n return [...this.adapters.values()].map(({ provider }) => ({ ...provider }))\n }\n\n /**\n * List the models one route advertises.\n *\n * Re-validated here rather than trusted, because a malformed catalog entry\n * surfaces in a caller's model picker where its origin is far from obvious.\n * @param provider - a registered route.\n * @returns detached, validated model metadata.\n */\n async listModels(provider: string, signal?: AbortSignal): Promise<ModelInfo[]> {\n const registration = this.registration(provider)\n const models = await registration.adapter.listModels(provider, signal)\n return validateCatalogModels(provider, models, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /** Resolve and validate one uncached adapter-level catalog generation. */\n async modelCatalog(provider: string, options: ModelCatalogOptions = {}): Promise<ModelCatalogSnapshot> {\n const registration = this.registration(provider)\n const snapshot = await registration.adapter.modelCatalog(provider, options)\n return validateModelCatalogSnapshot(provider, snapshot, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /**\n * Resolve metadata for one exact model.\n * @param provider - a registered route.\n * @param model - exact model id.\n * @param signal - cancellation for adapter-side resolution.\n * @returns validated, detached metadata.\n */\n async resolveModelInfo(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n const registration = this.registration(provider)\n const resolved = await registration.adapter.resolveModel(provider, model, signal)\n return normalizeResolvedModelInfo(registration.provider.id, model, resolved, this.maxCatalogBytes)\n }\n\n /** The retry policy captured for one route. */\n retryPolicy(provider: string): ResolvedRetryPolicy {\n return this.registration(provider).retryPolicy\n }\n\n /**\n * Resolve one call under its CURRENT adapter registration, returning a one-shot\n * handle that keeps that registration through to dispatch.\n * @param config - route, model, and optional request controls.\n * @param signal - cancellation for adapter-side capability lookup.\n * @returns the prepared config and its registration-bound stream entry point.\n */\n async prepareCall(\n config: CallConfig,\n signal?: AbortSignal,\n invocationContext?: ModelInvocationContext,\n ): Promise<PreparedCall> {\n const registration = this.registration(config.provider)\n const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal, invocationContext)\n const modelInfo = normalizeResolvedModelInfo(\n registration.provider.id, config.model, adapterCall.model, this.maxCatalogBytes,\n )\n const resolved = resolveCallWithModelInfo(config, modelInfo)\n const resolvedConfig = deepFreeze(structuredClone(resolved.config))\n const context = resolved.context === undefined\n ? undefined\n : deepFreeze(structuredClone(resolved.context))\n const adapterDefaults = deepFreeze<CallConfigAdapterDefaults>({\n ...config.reasoningEffort === undefined && resolvedConfig.reasoningEffort !== undefined\n ? { reasoningEffort: true as const }\n : {},\n ...config.maxTokens === undefined && resolvedConfig.maxTokens !== undefined\n ? { maxTokens: true as const }\n : {},\n })\n\n let dispatched = false\n const model = deepFreeze(structuredClone(modelInfo))\n return Object.freeze({\n config: resolvedConfig,\n model,\n retryPolicy: registration.retryPolicy,\n adapterDefaults,\n ...context === undefined ? {} : { context },\n ...modelInfo.inputModalities === undefined\n ? {}\n : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },\n stream: (options: GenerateOptions, context = invocationContext): ModelCallHandle => {\n // Both guards below exist so a stale handle fails loudly instead of\n // quietly dispatching against a configuration nobody vetted.\n if (dispatched) {\n throw new ModelError(\n 'a prepared call can only be dispatched once',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n if (!callConfigEquals(options, resolvedConfig)) {\n throw new ModelError(\n 'prepared call config changed before adapter dispatch',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n dispatched = true\n return this.dispatch(options, context, {\n registration,\n config: resolvedConfig,\n modelInfo,\n dispatch: (request, activeContext) => adapterCall.stream(request, activeContext),\n })\n },\n })\n }\n\n /**\n * Stream one model call as raw chunks.\n *\n * Adapter selection, dispatch, and iteration failures become terminal `error` or\n * `aborted` finish chunks. Middleware and consumer failures stay THROWN Ethose\n * are bugs in code the caller controls, and converting them to a finish reason\n * would hide them.\n * @param options - the full request; `options.provider` selects the adapter.\n * @returns the chunk stream, wrapped by any installed middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle {\n return this.dispatch(options, context)\n }\n\n private dispatch(\n options: GenerateOptions,\n context?: ModelInvocationContext,\n prepared?: PreparedDispatch,\n ): ModelCallHandle {\n let dispatchState: 'not-sent' | 'unknown' = 'not-sent'\n const registration = prepared?.registration ?? this.adapters.get(options.provider)\n return createModelCallHandle({\n options,\n ...(registration?.family === undefined ? {} : { providerFamily: registration.family }),\n ...(registration?.pluginId === undefined ? {} : { providerPluginId: registration.pluginId }),\n ...(registration === undefined ? {} : { isRetryable: (code: string) => (\n registration.retryPolicy.mode === 'always'\n || registration.retryPolicy.retryableCodes.includes(code)\n ) }),\n ...(context === undefined ? {} : { context }),\n ...(this.observation === undefined ? {} : { defaultObservation: this.observation }),\n resource: this.observationResource,\n routePresent: prepared !== undefined || this.adapters.has(options.provider),\n dispatchState: () => dispatchState,\n stream: activeContext => this.dispatchRaw(\n options,\n activeContext,\n () => { dispatchState = 'unknown' },\n prepared,\n ),\n })\n }\n\n /**\n * Compose installed middleware around the adapter boundary.\n *\n * Composition is deferred to the first iteration rather than done eagerly, so\n * that `stream()` ALWAYS returns an iterable and every failure — including a\n * middleware that throws synchronously — surfaces on the same path. Composing\n * eagerly would give callers two different error channels for the same class of\n * fault, and they would inevitably handle only one.\n *\n * The middleware list is snapshotted here so that installing or removing\n * middleware mid-stream cannot change the chain of a call already in flight.\n */\n private dispatchRaw(\n options: GenerateOptions,\n context: ModelInvocationContext,\n onDispatch: () => void,\n prepared?: PreparedDispatch,\n ): AsyncIterable<StreamChunk> {\n const chain = [...this.middleware]\n const run = (): AsyncIterable<StreamChunk> => {\n let next = (): AsyncIterable<StreamChunk> => streamAdapter({\n options, context, onDispatch, maxCatalogBytes: this.maxCatalogBytes,\n registration: provider => this.registration(provider),\n registeredAdapter: provider => this.adapters.get(provider)?.adapter,\n ...(prepared === undefined ? {} : { prepared }),\n })\n for (let index = chain.length - 1; index >= 0; index--) {\n const middleware = chain[index]\n if (middleware === undefined) continue\n const inner = next\n next = () => middleware(options, inner, context)\n }\n return next()\n }\n return {\n async * [Symbol.asyncIterator]() {\n yield* run()\n },\n }\n }\n\n private registration(provider: string): AdapterRegistration {\n const registration = this.adapters.get(provider)\n if (registration === undefined) {\n throw new ModelError(\n `no adapter registered for provider route \"${provider}\"`,\n REGISTRY_ERROR_CODES.NO_ADAPTER,\n )\n }\n return registration\n }\n\n}\n\nfunction positiveSafeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`ModelRegistry ${label} must be a positive safe integer`)\n }\n return value\n}\n"],"mappings":"qoBAuGA,SAAS,EAAgB,EAAyB,CAChD,IAAK,OAAO,GAAU,WAAY,IAAmB,OAAO,GAAU,WAAY,MAAO,GACzF,IAAI,EACJ,GAAI,CACF,EAAO,QAAQ,IAAI,EAAO,MAAM,CAClC,MAAQ,CACN,MAAO,EACT,CACA,GAAI,OAAO,GAAS,WAAY,MAAO,GACvC,GAAI,CAAE,QAAa,QAAQ,CAAK,CAAC,CAAC,UAAY,CAAC,CAAC,CAAE,MAAQ,CAAmC,CAC7F,MAAO,EACT,CAEA,SAAS,EAA0B,EAA0C,CAC3E,GAAI,CAEF,OAAO,EADiB,EACI,CAAC,EAAQ,UAAU,oCAAoC,EAAI,IAAA,EACzF,OAAS,EAAO,CACd,OAAO,CACT,CACF,CASA,IAAa,EAAb,KAA2B,CACzB,SAAmB,IAAI,IACvB,WAAyC,CAAC,EAC1C,UAAoB,IAAI,IACxB,QAAkB,IAAI,IACtB,iBACA,gBACA,YACA,oBAEA,YAAY,EAAgC,CAAC,EAAG,CAC9C,KAAK,iBAAmB,EAAoB,EAAQ,kBAAoB,KAAO,kBAAkB,EACjG,KAAK,gBAAkB,EAAoB,EAAQ,iBAAmB,QAAiB,iBAAiB,EACxG,KAAK,YAAc,EAAQ,YAC3B,KAAK,oBAAsB,EAAW,EA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AU,WAAW,iBAAiB,EAAM,iCAAiC,EAE/E,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"registry.js","names":[],"sources":["../../src/runtime/registry.ts"],"sourcesContent":["/**\n * The adapter registry and the streaming call API.\n *\n * This is the deepseek-harness `LlmRuntime` with its dependency-injection\n * framework removed: a plain `Map` for routes, an ordered array for the\n * interception point that was a cordis waterfall, and a listener set for the\n * topology event. What is kept is everything that made it trustworthy E * all-or-nothing validating registration, an atomic route swap, prepare/dispatch\n * generation binding, and a single failure funnel at the adapter boundary.\n *\n * @module ai-agent-sdk/core/runtime/registry\n */\n\nimport type { ModelAdapter } from '../contract/adapter.ts'\nimport {\n callConfigEquals,\n type CallConfig,\n type CallConfigAdapterDefaults,\n} from '../contract/call-config.ts'\nimport type { GenerateOptions } from '../contract/generate-options.ts'\nimport type {\n ModelContext,\n ModelCatalogOptions,\n ModelCatalogSnapshot,\n ModelInfo,\n ModelModality,\n ProviderInfo,\n ResolvedModelInfo,\n RuntimeDefaults,\n} from '../contract/model-info.ts'\nimport { resolveRetryPolicy, type ResolvedRetryPolicy } from '../contract/retry-policy.ts'\nimport { ModelError, REGISTRY_ERROR_CODES } from '../errors/model-error.ts'\nimport { deepFreeze } from '../primitives/freeze.ts'\nimport { SDK_VERSION } from '../primitives/version.ts'\nimport type { ObservationResource } from '../observation/event.ts'\nimport type { ObservationPort } from '../observation/port.ts'\nimport type { ModelCallHandle, ModelInvocationContext } from '../observation/report.ts'\nimport type { StreamChunk } from '../stream/chunk.ts'\nimport { createModelCallHandle } from './model-call-handle.ts'\nimport { normalizeResolvedModelInfo, resolveCallWithModelInfo,\n validateCatalogModels, validateModelCatalogSnapshot } from './model-metadata.ts'\nimport { streamAdapter, type PreparedDispatch,\n type RuntimeAdapterRegistration } from './model-stream.ts'\nimport {\n PLUGIN_ERROR_CODES,\n PluginError,\n type AdapterRegistrationHandle,\n type ModelProviderPlugin,\n type ModelProviderRegistrar,\n type PluginRegistrationHandle,\n type StreamMiddleware,\n} from '../plugin/provider-plugin.ts'\n\nexport type { AdapterRegistrationHandle, StreamMiddleware } from '../plugin/provider-plugin.ts'\n\n/**\n * Wraps every streaming model call. Call `next()` to reach the adapter, or yield\n * your own chunks to short-circuit it entirely.\n *\n * This is the extension point for retry, caching, request logging, replay, and\n * test doubles. Middleware registered EARLIER sits further out.\n */\n/** One call whose configuration and adapter registration were resolved together. */\nexport interface PreparedCall {\n /** Detached, deep-frozen config with any adapter-owned default materialized. */\n readonly config: CallConfig\n /** Immutable retry policy captured with the adapter registration. */\n readonly retryPolicy: ResolvedRetryPolicy\n /** Context capacity resolved with the registration-bound call. */\n readonly context?: ModelContext\n /** Exact model modalities captured with the dispatch generation. */\n readonly inputModalities?: readonly ModelModality[]\n /** Complete validated capability snapshot bound to this adapter generation. */\n readonly model: ResolvedModelInfo\n /** Which config fields the adapter supplied rather than the caller. */\n readonly adapterDefaults: CallConfigAdapterDefaults\n /**\n * Dispatch this call ONCE, through the registration captured at preparation.\n * @param options - the assembled request, carrying the prepared config.\n * @returns the chunk stream, including middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle\n}\n\nexport interface ModelRegistryOptions {\n /** Maximum model rows accepted from one adapter catalog. Defaults to 2,048. */\n readonly maxCatalogModels?: number\n /** Maximum serialized bytes accepted from a catalog or model-info record. Defaults to 4 MiB. */\n readonly maxCatalogBytes?: number\n /** Default observation port; a per-call invocation context may override it. */\n readonly observation?: ObservationPort\n /** Safe SDK/service/runtime identity copied onto observation events. */\n readonly observationResource?: ObservationResource\n /**\n * SDK-wide fallbacks (context window, output cap, accepted modalities) used\n * only when neither a model nor its route names one. See {@link RuntimeDefaults}.\n */\n readonly defaults?: RuntimeDefaults\n}\n\ntype AdapterRegistration = RuntimeAdapterRegistration\n\ninterface InstalledPlugin {\n readonly routes: ReadonlySet<string>\n readonly registrations: readonly AdapterRegistration[]\n readonly middleware: readonly StreamMiddleware[]\n readonly cleanup?: () => void\n}\n\n\nfunction containThenable(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false\n let then: unknown\n try {\n then = Reflect.get(value, 'then')\n } catch {\n return true\n }\n if (typeof then !== 'function') return false\n try { void Promise.resolve(value).catch(() => {}) } catch { /* hostile thenable contained */ }\n return true\n}\n\nfunction synchronousCleanupFailure(cleanup: () => void): unknown | undefined {\n try {\n const result: unknown = cleanup()\n return containThenable(result) ? new TypeError('plugin cleanup must be synchronous') : undefined\n } catch (error) {\n return error\n }\n}\n\n\n/**\n * Routes model calls to registered adapters.\n *\n * Construct one per application or isolated runtime scope, register the adapters\n * you use, then call {@link stream} or {@link prepareCall}.\n */\nexport class ModelRegistry {\n private adapters = new Map<string, AdapterRegistration>()\n private middleware: StreamMiddleware[] = []\n private listeners = new Set<() => void>()\n private plugins = new Map<string, InstalledPlugin>()\n private readonly maxCatalogModels: number\n private readonly maxCatalogBytes: number\n private readonly observation: ObservationPort | undefined\n private readonly observationResource: ObservationResource\n private readonly defaults: RuntimeDefaults\n\n constructor(options: ModelRegistryOptions = {}) {\n this.maxCatalogModels = positiveSafeInteger(options.maxCatalogModels ?? 2_048, 'maxCatalogModels')\n this.maxCatalogBytes = positiveSafeInteger(options.maxCatalogBytes ?? 4 * 1024 * 1024, 'maxCatalogBytes')\n this.observation = options.observation\n this.defaults = validateRuntimeDefaults(options.defaults ?? {})\n this.observationResource = deepFreeze(options.observationResource ?? {\n sdkName: 'ai-agent-sdk',\n sdkVersion: SDK_VERSION,\n runtime: 'unknown',\n })\n }\n\n /** Install one provider plugin as a single synchronous topology transaction. */\n install(plugin: ModelProviderPlugin): PluginRegistrationHandle {\n const pluginId = typeof plugin?.id === 'string' ? plugin.id : ''\n const fail = (message: string, cause?: unknown, cleanupFailures: readonly unknown[] = []): never => {\n const causes = [...cause === undefined ? [] : [cause], ...cleanupFailures]\n const wrappedCause = causes.length <= 1 ? causes[0] : new AggregateError(causes, `plugin ${pluginId} install cleanup failed`)\n throw new PluginError(message, PLUGIN_ERROR_CODES.INSTALL_FAILED, pluginId, wrappedCause === undefined ? undefined : { cause: wrappedCause })\n }\n if (pluginId.trim().length === 0 || pluginId !== pluginId.trim()) fail('plugin id must be a non-empty trimmed string')\n if (this.plugins.has(pluginId)) fail(`plugin \"${pluginId}\" is already installed`)\n if (typeof plugin.displayName !== 'string' || plugin.displayName.trim().length === 0) fail(`plugin \"${pluginId}\" displayName must be non-empty`)\n if (typeof plugin.setup !== 'function') fail(`plugin \"${pluginId}\" setup must be a function`)\n const family = plugin.family ?? pluginId\n if (typeof family !== 'string' || family.trim().length === 0 || family !== family.trim()) {\n fail(`plugin \"${pluginId}\" family must be a non-empty trimmed string`)\n }\n const owner = Object.freeze({ pluginId, family })\n\n interface StagedAdapter {\n active: boolean\n routes: string[]\n readonly adapter: ModelAdapter\n }\n interface StagedMiddleware { active: boolean; readonly middleware: StreamMiddleware }\n const stagedAdapters: StagedAdapter[] = []\n const stagedMiddleware: StagedMiddleware[] = []\n let staging = true\n\n const registrar: ModelProviderRegistrar = {\n registerAdapter: (routes, adapter) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (routes.length === 0) throw new ModelError('an adapter must register at least one provider route', REGISTRY_ERROR_CODES.INVALID_ADAPTER)\n const item: StagedAdapter = { active: true, routes: [...routes], adapter }\n // Validate metadata and conflicts without mutating live routes.\n const occupied = new Set(stagedAdapters.filter(value => value.active).flatMap(value => value.routes))\n for (const route of routes) if (occupied.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(routes, adapter, new Set(), owner)\n stagedAdapters.push(item)\n const handle = (() => {\n if (staging) item.active = false\n }) as AdapterRegistrationHandle\n handle.replace = (next) => {\n if (!staging || !item.active) throw new ModelError('a disposed staged registration cannot replace routes', REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED)\n const occupiedByOthers = new Set(stagedAdapters.filter(value => value.active && value !== item).flatMap(value => value.routes))\n for (const route of next) if (occupiedByOthers.has(route)) {\n throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n }\n this.prepareRoutes(next, adapter, new Set(), owner)\n item.routes = [...next]\n }\n return handle\n },\n use: (middleware) => {\n if (!staging) fail(`plugin \"${pluginId}\" staging registrar is closed`)\n if (typeof middleware !== 'function') throw new TypeError('plugin middleware must be a function')\n const item: StagedMiddleware = { active: true, middleware }\n stagedMiddleware.push(item)\n return () => { if (staging) item.active = false }\n },\n }\n\n let cleanup: (() => void) | undefined\n try {\n const result = plugin.setup(registrar)\n if (containThenable(result)) fail(`plugin \"${pluginId}\" setup must be synchronous`)\n if (result !== undefined && typeof result !== 'function') fail(`plugin \"${pluginId}\" setup must be synchronous and return void or cleanup`)\n cleanup = typeof result === 'function' ? result : undefined\n } catch (error) {\n if (error instanceof PluginError && error.code === PLUGIN_ERROR_CODES.INSTALL_FAILED) throw error\n fail(`plugin \"${pluginId}\" setup failed`, error)\n } finally {\n staging = false\n }\n\n const registrations: AdapterRegistration[] = []\n const routeNames = new Set<string>()\n try {\n for (const item of stagedAdapters) {\n if (!item.active) continue\n for (const route of item.routes) {\n if (routeNames.has(route)) throw new ModelError(`an adapter for provider route \"${route}\" is already staged`, REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER)\n routeNames.add(route)\n }\n registrations.push(...this.prepareRoutes(item.routes, item.adapter, new Set(), owner))\n }\n } catch (error) {\n const cleanupFailures: unknown[] = []\n if (cleanup) {\n const cleanupFailure = synchronousCleanupFailure(cleanup)\n if (cleanupFailure !== undefined) cleanupFailures.push(cleanupFailure)\n }\n fail(`plugin \"${pluginId}\" commit validation failed`, error, cleanupFailures)\n }\n\n const committedMiddleware = stagedMiddleware.filter(item => item.active).map(item => item.middleware)\n for (const registration of registrations) this.adapters.set(registration.provider.id, registration)\n this.middleware.push(...committedMiddleware)\n const installed: InstalledPlugin = {\n routes: routeNames,\n registrations,\n middleware: committedMiddleware,\n ...(cleanup === undefined ? {} : { cleanup }),\n }\n this.plugins.set(pluginId, installed)\n this.emitAdaptersUpdated()\n\n let disposed = false\n const dispose = (() => {\n if (disposed) return\n disposed = true\n this.plugins.delete(pluginId)\n for (const registration of installed.registrations) {\n if (this.adapters.get(registration.provider.id) === registration) this.adapters.delete(registration.provider.id)\n }\n for (let index = installed.middleware.length - 1; index >= 0; index--) {\n const middleware = installed.middleware[index]\n const liveIndex = middleware === undefined ? -1 : this.middleware.lastIndexOf(middleware)\n if (liveIndex >= 0) this.middleware.splice(liveIndex, 1)\n }\n this.emitAdaptersUpdated()\n const failures: unknown[] = []\n if (installed.cleanup) {\n const cleanupFailure = synchronousCleanupFailure(installed.cleanup)\n if (cleanupFailure !== undefined) failures.push(cleanupFailure)\n }\n if (failures.length > 0) {\n throw new PluginError(\n `plugin \"${pluginId}\" cleanup failed`,\n PLUGIN_ERROR_CODES.CLEANUP_FAILED,\n pluginId,\n { cause: new AggregateError(failures, `plugin \"${pluginId}\" cleanup failed`) },\n )\n }\n }) as PluginRegistrationHandle\n Object.defineProperty(dispose, 'pluginId', { value: pluginId, enumerable: true })\n return dispose\n }\n\n /**\n * Register an adapter for the given routes.\n *\n * All-or-nothing: if ANY route conflicts, nothing is registered. A partial\n * registration would leave the caller believing a route exists when it does not.\n * @param providers - every route this adapter should serve; must be non-empty.\n * @param adapter - the adapter that streams calls for those routes.\n * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.\n */\n registerAdapter(\n providers: readonly string[],\n adapter: ModelAdapter,\n ): AdapterRegistrationHandle {\n if (providers.length === 0) {\n throw new ModelError(\n 'an adapter must register at least one provider route',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n /** Routes this registration currently holds; `replace` rewrites it. */\n const owned = new Set<string>()\n // `owned` being empty cannot signal disposal on its own, because\n // `replace([])` legally leaves a live registration holding no routes.\n let released = false\n\n this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned))\n\n const handle = (() => {\n if (released) return\n released = true\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n this.emitAdaptersUpdated()\n }) as AdapterRegistrationHandle\n\n handle.replace = (next: readonly string[]): void => {\n // Registering after disposal would leak: nothing remains to release what\n // this call would put back into the map.\n if (released) {\n throw new ModelError(\n 'a disposed adapter registration cannot replace its routes',\n REGISTRY_ERROR_CODES.REGISTRATION_DISPOSED,\n )\n }\n this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned))\n }\n return handle\n }\n\n /**\n * Validate one candidate route set, treating routes this registration already\n * holds as available. Mutates nothing Ea rejected candidate leaves the registry\n * exactly as it was.\n */\n private prepareRoutes(\n providers: readonly string[],\n adapter: ModelAdapter,\n owned: ReadonlySet<string>,\n owner?: Readonly<{ pluginId: string; family: string }>,\n ): AdapterRegistration[] {\n const unique = new Set<string>()\n const registrations: AdapterRegistration[] = []\n for (const provider of providers) {\n if (typeof provider !== 'string' || provider.length === 0) {\n throw new ModelError(\n 'adapter provider route names must be non-empty strings',\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n if (unique.has(provider) || (this.adapters.has(provider) && !owned.has(provider))) {\n throw new ModelError(\n `an adapter for provider route \"${provider}\" is already registered`,\n REGISTRY_ERROR_CODES.DUPLICATE_ADAPTER,\n )\n }\n const info = adapter.providerInfo(provider)\n if (typeof info.id !== 'string' || info.id !== provider\n || typeof info.name !== 'string' || info.name.length === 0) {\n throw new ModelError(\n `adapter metadata for route \"${provider}\" must preserve its id and carry a non-empty name`,\n REGISTRY_ERROR_CODES.INVALID_ADAPTER,\n )\n }\n unique.add(provider)\n registrations.push({\n adapter,\n provider: { id: info.id, name: info.name },\n ...(owner === undefined ? {} : owner),\n // Captured at REGISTRATION time, not per call. An adapter whose policy\n // follows mutable configuration re-registers via `handle.replace`.\n retryPolicy: adapter.providerRetryPolicy(provider)\n ?? resolveRetryPolicy(undefined, `provider \"${provider}\" retryPolicy`),\n })\n }\n return registrations\n }\n\n /**\n * Swap this registration's routes in ONE synchronous section, so no caller can\n * observe the registry between the release and the re-registration.\n */\n private commitRoutes(\n owned: Set<string>,\n registrations: readonly AdapterRegistration[],\n ): void {\n for (const provider of owned) this.adapters.delete(provider)\n owned.clear()\n for (const registration of registrations) {\n this.adapters.set(registration.provider.id, registration)\n owned.add(registration.provider.id)\n }\n this.emitAdaptersUpdated()\n }\n\n /**\n * Install streaming middleware.\n * @param middleware - wrapper invoked around every call; earlier registrations sit further out.\n * @returns a disposer that removes exactly this middleware.\n */\n use(middleware: StreamMiddleware): () => void {\n this.middleware.push(middleware)\n return () => {\n const index = this.middleware.indexOf(middleware)\n if (index >= 0) this.middleware.splice(index, 1)\n }\n }\n\n /**\n * Observe route-topology changes (registration, replacement, disposal).\n * @param listener - payload-free notification; re-read `listProviders()` for new state.\n * @returns a disposer that removes the listener.\n */\n onAdaptersUpdated(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => void this.listeners.delete(listener)\n }\n\n /**\n * Notify topology observers.\n *\n * Each listener is contained independently: a topology notification is not a\n * veto, so one broken observer must not starve the others or roll back a\n * registration that already happened.\n */\n private emitAdaptersUpdated(): void {\n for (const listener of [...this.listeners]) {\n try {\n listener()\n } catch {\n // Contained deliberately; see above.\n }\n }\n }\n\n /**\n * Describe every route with a registered adapter.\n * @returns detached provider metadata, in registration order.\n */\n listProviders(): ProviderInfo[] {\n return [...this.adapters.values()].map(({ provider }) => ({ ...provider }))\n }\n\n /**\n * List the models one route advertises.\n *\n * Re-validated here rather than trusted, because a malformed catalog entry\n * surfaces in a caller's model picker where its origin is far from obvious.\n * @param provider - a registered route.\n * @returns detached, validated model metadata.\n */\n async listModels(provider: string, signal?: AbortSignal): Promise<ModelInfo[]> {\n const registration = this.registration(provider)\n const models = await registration.adapter.listModels(provider, signal)\n return validateCatalogModels(provider, models, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /** Resolve and validate one uncached adapter-level catalog generation. */\n async modelCatalog(provider: string, options: ModelCatalogOptions = {}): Promise<ModelCatalogSnapshot> {\n const registration = this.registration(provider)\n const snapshot = await registration.adapter.modelCatalog(provider, options)\n return validateModelCatalogSnapshot(provider, snapshot, this.maxCatalogModels, this.maxCatalogBytes)\n }\n\n /**\n * Resolve metadata for one exact model.\n * @param provider - a registered route.\n * @param model - exact model id.\n * @param signal - cancellation for adapter-side resolution.\n * @returns validated, detached metadata.\n */\n async resolveModelInfo(\n provider: string,\n model: string,\n signal?: AbortSignal,\n ): Promise<ResolvedModelInfo> {\n const registration = this.registration(provider)\n const resolved = await registration.adapter.resolveModel(provider, model, signal)\n return normalizeResolvedModelInfo(registration.provider.id, model, resolved, this.maxCatalogBytes, this.defaults)\n }\n\n /** The retry policy captured for one route. */\n retryPolicy(provider: string): ResolvedRetryPolicy {\n return this.registration(provider).retryPolicy\n }\n\n /**\n * Resolve one call under its CURRENT adapter registration, returning a one-shot\n * handle that keeps that registration through to dispatch.\n * @param config - route, model, and optional request controls.\n * @param signal - cancellation for adapter-side capability lookup.\n * @returns the prepared config and its registration-bound stream entry point.\n */\n async prepareCall(\n config: CallConfig,\n signal?: AbortSignal,\n invocationContext?: ModelInvocationContext,\n ): Promise<PreparedCall> {\n const registration = this.registration(config.provider)\n const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal, invocationContext)\n const modelInfo = normalizeResolvedModelInfo(\n registration.provider.id, config.model, adapterCall.model, this.maxCatalogBytes, this.defaults,\n )\n const resolved = resolveCallWithModelInfo(config, modelInfo, this.defaults)\n const resolvedConfig = deepFreeze(structuredClone(resolved.config))\n const context = resolved.context === undefined\n ? undefined\n : deepFreeze(structuredClone(resolved.context))\n const adapterDefaults = deepFreeze<CallConfigAdapterDefaults>({\n ...config.maxTokens === undefined && resolvedConfig.maxTokens !== undefined\n ? { maxTokens: true as const }\n : {},\n })\n\n let dispatched = false\n const model = deepFreeze(structuredClone(modelInfo))\n return Object.freeze({\n config: resolvedConfig,\n model,\n retryPolicy: registration.retryPolicy,\n adapterDefaults,\n ...context === undefined ? {} : { context },\n ...resolved.inputModalities === undefined\n ? {}\n : { inputModalities: Object.freeze([...resolved.inputModalities]) },\n stream: (options: GenerateOptions, context = invocationContext): ModelCallHandle => {\n // Both guards below exist so a stale handle fails loudly instead of\n // quietly dispatching against a configuration nobody vetted.\n if (dispatched) {\n throw new ModelError(\n 'a prepared call can only be dispatched once',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n if (!callConfigEquals(options, resolvedConfig)) {\n throw new ModelError(\n 'prepared call config changed before adapter dispatch',\n REGISTRY_ERROR_CODES.INVALID_PREPARED_CALL,\n )\n }\n dispatched = true\n return this.dispatch(options, context, {\n registration,\n config: resolvedConfig,\n modelInfo,\n dispatch: (request, activeContext) => adapterCall.stream(request, activeContext),\n })\n },\n })\n }\n\n /**\n * Stream one model call as raw chunks.\n *\n * Adapter selection, dispatch, and iteration failures become terminal `error` or\n * `aborted` finish chunks. Middleware and consumer failures stay THROWN Ethose\n * are bugs in code the caller controls, and converting them to a finish reason\n * would hide them.\n * @param options - the full request; `options.provider` selects the adapter.\n * @returns the chunk stream, wrapped by any installed middleware.\n */\n stream(options: GenerateOptions, context?: ModelInvocationContext): ModelCallHandle {\n return this.dispatch(options, context)\n }\n\n private dispatch(\n options: GenerateOptions,\n context?: ModelInvocationContext,\n prepared?: PreparedDispatch,\n ): ModelCallHandle {\n let dispatchState: 'not-sent' | 'unknown' = 'not-sent'\n const registration = prepared?.registration ?? this.adapters.get(options.provider)\n return createModelCallHandle({\n options,\n ...(registration?.family === undefined ? {} : { providerFamily: registration.family }),\n ...(registration?.pluginId === undefined ? {} : { providerPluginId: registration.pluginId }),\n ...(registration === undefined ? {} : { isRetryable: (code: string) => (\n registration.retryPolicy.mode === 'always'\n || registration.retryPolicy.retryableCodes.includes(code)\n ) }),\n ...(context === undefined ? {} : { context }),\n ...(this.observation === undefined ? {} : { defaultObservation: this.observation }),\n resource: this.observationResource,\n routePresent: prepared !== undefined || this.adapters.has(options.provider),\n dispatchState: () => dispatchState,\n stream: activeContext => this.dispatchRaw(\n options,\n activeContext,\n () => { dispatchState = 'unknown' },\n prepared,\n ),\n })\n }\n\n /**\n * Compose installed middleware around the adapter boundary.\n *\n * Composition is deferred to the first iteration rather than done eagerly, so\n * that `stream()` ALWAYS returns an iterable and every failure — including a\n * middleware that throws synchronously — surfaces on the same path. Composing\n * eagerly would give callers two different error channels for the same class of\n * fault, and they would inevitably handle only one.\n *\n * The middleware list is snapshotted here so that installing or removing\n * middleware mid-stream cannot change the chain of a call already in flight.\n */\n private dispatchRaw(\n options: GenerateOptions,\n context: ModelInvocationContext,\n onDispatch: () => void,\n prepared?: PreparedDispatch,\n ): AsyncIterable<StreamChunk> {\n const chain = [...this.middleware]\n const run = (): AsyncIterable<StreamChunk> => {\n let next = (): AsyncIterable<StreamChunk> => streamAdapter({\n options, context, onDispatch, maxCatalogBytes: this.maxCatalogBytes, defaults: this.defaults,\n registration: provider => this.registration(provider),\n registeredAdapter: provider => this.adapters.get(provider)?.adapter,\n ...(prepared === undefined ? {} : { prepared }),\n })\n for (let index = chain.length - 1; index >= 0; index--) {\n const middleware = chain[index]\n if (middleware === undefined) continue\n const inner = next\n next = () => middleware(options, inner, context)\n }\n return next()\n }\n return {\n async * [Symbol.asyncIterator]() {\n yield* run()\n },\n }\n }\n\n private registration(provider: string): AdapterRegistration {\n const registration = this.adapters.get(provider)\n if (registration === undefined) {\n throw new ModelError(\n `no adapter registered for provider route \"${provider}\"`,\n REGISTRY_ERROR_CODES.NO_ADAPTER,\n )\n }\n return registration\n }\n\n}\n\nfunction positiveSafeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`ModelRegistry ${label} must be a positive safe integer`)\n }\n return value\n}\n\nfunction validateRuntimeDefaults(defaults: RuntimeDefaults): RuntimeDefaults {\n if (defaults.contextWindow !== undefined) positiveSafeInteger(defaults.contextWindow, 'defaults.contextWindow')\n if (defaults.maxTokens !== undefined) positiveSafeInteger(defaults.maxTokens, 'defaults.maxTokens')\n if (defaults.inputModalities !== undefined\n && (defaults.inputModalities.length === 0\n || new Set(defaults.inputModalities).size !== defaults.inputModalities.length)) {\n throw new RangeError('ModelRegistry defaults.inputModalities must be non-empty and unique')\n }\n return deepFreeze({\n ...(defaults.contextWindow === undefined ? {} : { contextWindow: defaults.contextWindow }),\n ...(defaults.maxTokens === undefined ? {} : { maxTokens: defaults.maxTokens }),\n ...(defaults.inputModalities === undefined ? {} : { inputModalities: [...defaults.inputModalities] }),\n })\n}\n"],"mappings":"qoBA6GA,SAAS,EAAgB,EAAyB,CAChD,IAAK,OAAO,GAAU,WAAY,IAAmB,OAAO,GAAU,WAAY,MAAO,GACzF,IAAI,EACJ,GAAI,CACF,EAAO,QAAQ,IAAI,EAAO,MAAM,CAClC,MAAQ,CACN,MAAO,EACT,CACA,GAAI,OAAO,GAAS,WAAY,MAAO,GACvC,GAAI,CAAE,QAAa,QAAQ,CAAK,CAAC,CAAC,UAAY,CAAC,CAAC,CAAE,MAAQ,CAAmC,CAC7F,MAAO,EACT,CAEA,SAAS,EAA0B,EAA0C,CAC3E,GAAI,CAEF,OAAO,EADiB,EACI,CAAC,EAAQ,UAAU,oCAAoC,EAAI,IAAA,EACzF,OAAS,EAAO,CACd,OAAO,CACT,CACF,CASA,IAAa,EAAb,KAA2B,CACzB,SAAmB,IAAI,IACvB,WAAyC,CAAC,EAC1C,UAAoB,IAAI,IACxB,QAAkB,IAAI,IACtB,iBACA,gBACA,YACA,oBACA,SAEA,YAAY,EAAgC,CAAC,EAAG,CAC9C,KAAK,iBAAmB,EAAoB,EAAQ,kBAAoB,KAAO,kBAAkB,EACjG,KAAK,gBAAkB,EAAoB,EAAQ,iBAAmB,QAAiB,iBAAiB,EACxG,KAAK,YAAc,EAAQ,YAC3B,KAAK,SAAW,EAAwB,EAAQ,UAAY,CAAC,CAAC,EAC9D,KAAK,oBAAsB,EAAW,EAAQ,qBAAuB,CACnE,QAAS,eACT,WAAA,QACA,QAAS,SAC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GAFI,EAAS,gBAAkB,IAAA,IAAW,EAAoB,EAAS,cAAe,wBAAwB,EAC1G,EAAS,YAAc,IAAA,IAAW,EAAoB,EAAS,UAAW,oBAAoB,EAC9F,EAAS,kBAAoB,IAAA,KAC3B,EAAS,gBAAgB,SAAW,GACnC,IAAI,IAAI,EAAS,eAAe,CAAC,CAAC,OAAS,EAAS,gBAAgB,QACzE,MAAU,WAAW,qEAAqE,EAE5F,OAAO,EAAW,CAChB,GAAI,EAAS,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAe,EAAS,aAAc,EACxF,GAAI,EAAS,YAAc,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAS,SAAU,EAC5E,GAAI,EAAS,kBAAoB,IAAA,GAAY,CAAC,EAAI,CAAE,gBAAiB,CAAC,GAAG,EAAS,eAAe,CAAE,CACrG,CAAC,CACH"}
|
package/dist/tools.d.ts
CHANGED
|
@@ -6,10 +6,13 @@ import { MemorySpillStoreLimits, SPILL_TOOL_NAME, SpillRecord, SpillSlice, Spill
|
|
|
6
6
|
import { ApprovalBroker, ApprovalDecision, ApprovalRequest, ApprovalStateStore, InteractiveApprovalBroker, InteractiveApprovalBrokerOptions, createApprovalBroker, createApprovalRequest, fixedApprovalBroker, withApprovalPersistence } from "./agent/tool/approval.js";
|
|
7
7
|
import { REGISTRY_ERROR_CODES, ToolCatalog, ToolFilter, ToolRegistry } from "./agent/tool/registry.js";
|
|
8
8
|
import { AuthorizationOutcome, AuthorizedToolCall, DispatchToolCallOptions, PostToolDecision, PreToolDecision, PreparedToolCall, ToolCallContext, ToolCallRequest, ToolInterceptor, authorizeToolCall, dispatchAuthorizedToolCall, dispatchToolCall, finalizeToolCall, prepareToolCall, toolFailure } from "./agent/tool/pipeline.js";
|
|
9
|
+
import { ExperimentalProgramGrant, NESTED_TOOL_ERROR_CODES, NestedCallOptions, NestedLoadResult, NestedToolDescriptor, NestedToolPort, NestedToolResult, nestedToolPort } from "./agent/tool/nested.js";
|
|
9
10
|
import { ToolCatalogSnapshot, ToolSource, ToolSourceDefinition, ToolSourceRunReference, ToolSourceSnapshotOptions } from "./agent/tool/source-types.js";
|
|
11
|
+
import { EvidenceLine, EvidenceReducer, EvidenceReductionInput, EvidenceReductionResult, createModelEvidenceReducer, diagnosticLineNumbers, reduceEvidence } from "./agent/tool/evidence-reducer.js";
|
|
10
12
|
import { TOOL_ERROR_CODES, ToolError, ToolErrorDisposition, toolErrorDisposition } from "./agent/tool/errors.js";
|
|
11
13
|
import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
|
|
12
14
|
import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
|
|
15
|
+
import { ActionFusionStep, defineActionFusion } from "./agent/tool/action-fusion.js";
|
|
13
16
|
import { TOOL_SOURCE_API_VERSION } from "./composition/tool-source/config.js";
|
|
14
17
|
import { defineToolSource } from "./composition/tool-source/definition.js";
|
|
15
|
-
export { type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AuthorizationOutcome, type AuthorizedToolCall, type DispatchToolCallOptions, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type JsonObject, type JsonValue, type MemorySpillStoreLimits, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RuntimeSchema, SPILL_TOOL_NAME, type SdkLogger, type SpillRecord, type SpillSlice, type SpillStore, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, TOOL_SOURCE_API_VERSION, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCatalog, type ToolCatalogSnapshot, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSchema, type ToolSource, type ToolSourceDefinition, type ToolSourceRunReference, type ToolSourceSnapshotOptions, type ToolSuccess, type TruncatedText, authorizeToolCall, createApprovalBroker, createApprovalRequest, createMemorySpillStore, createToolExecutionInterceptor, defineTool, defineToolFromSchema, defineToolSource, dispatchAuthorizedToolCall, dispatchToolCall, estimateTextBlockTokens, estimateTextTokens, executionModeOf, finalizeToolCall, fixedApprovalBroker, localToolExecutionBackend, prepareToolCall, previewForSpill, readSpillTool, renderJsonValue, toolErrorDisposition, toolFailure, truncateMiddleToTokens, withApprovalPersistence };
|
|
18
|
+
export { type ActionFusionStep, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AuthorizationOutcome, type AuthorizedToolCall, type DispatchToolCallOptions, NESTED_TOOL_ERROR_CODES as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES, type EvidenceLine, type EvidenceReducer, type EvidenceReductionInput, type EvidenceReductionResult, type NestedCallOptions as ExperimentalNestedCallOptions, type NestedLoadResult as ExperimentalNestedLoadResult, type NestedToolDescriptor as ExperimentalNestedToolDescriptor, type NestedToolPort as ExperimentalNestedToolPort, type NestedToolResult as ExperimentalNestedToolResult, type ExperimentalProgramGrant, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type JsonObject, type JsonValue, type MemorySpillStoreLimits, type PostToolDecision, type PreToolDecision, type PreparedToolCall, type RuntimeSchema, SPILL_TOOL_NAME, type SdkLogger, type SpillRecord, type SpillSlice, type SpillStore, TOOL_ERROR_CODES, REGISTRY_ERROR_CODES as TOOL_REGISTRY_ERROR_CODES, TOOL_SOURCE_API_VERSION, type ToolCallContext, type ToolCallPosition, type ToolCallRequest, type ToolCatalog, type ToolCatalogSnapshot, type ToolDefinition, ToolError, type ToolErrorDisposition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionMode, type ToolExecutionRequest, type ToolExecutionResult, type ToolExecutionStore, type ToolFailure, type ToolFilter, type ToolInterceptor, type ToolOperation, type ToolOperationClaim, type ToolOutputOverflowPolicy, ToolRegistry, type ToolRunContext, type ToolSchema, type ToolSource, type ToolSourceDefinition, type ToolSourceRunReference, type ToolSourceSnapshotOptions, type ToolSuccess, type TruncatedText, authorizeToolCall, createApprovalBroker, createApprovalRequest, createMemorySpillStore, createModelEvidenceReducer, createToolExecutionInterceptor, defineActionFusion, defineTool, defineToolFromSchema, defineToolSource, diagnosticLineNumbers, dispatchAuthorizedToolCall, dispatchToolCall, estimateTextBlockTokens, estimateTextTokens, executionModeOf, nestedToolPort as experimentalNestedToolPort, finalizeToolCall, fixedApprovalBroker, localToolExecutionBackend, prepareToolCall, previewForSpill, readSpillTool, reduceEvidence, renderJsonValue, toolErrorDisposition, toolFailure, truncateMiddleToTokens, withApprovalPersistence };
|
package/dist/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineTool as e,executionModeOf as t,renderJsonValue as n}from"./agent/tool/definition.js";import{
|
|
1
|
+
import{defineTool as e,executionModeOf as t,renderJsonValue as n}from"./agent/tool/definition.js";import{SPILL_TOOL_NAME as r,createMemorySpillStore as i,estimateTextBlockTokens as a,estimateTextTokens as o,previewForSpill as s,readSpillTool as c,truncateMiddleToTokens as l}from"./agent/tool/output-budget.js";import{createModelEvidenceReducer as u,diagnosticLineNumbers as d,reduceEvidence as f}from"./agent/tool/evidence-reducer.js";import{REGISTRY_ERROR_CODES as p,ToolRegistry as m}from"./agent/tool/registry.js";import{TOOL_ERROR_CODES as h,ToolError as g,toolErrorDisposition as _}from"./agent/tool/errors.js";import{createApprovalBroker as v,createApprovalRequest as y,fixedApprovalBroker as b,withApprovalPersistence as x}from"./agent/tool/approval.js";import{NESTED_TOOL_ERROR_CODES as S,nestedToolPort as C}from"./agent/tool/nested.js";import{authorizeToolCall as w,dispatchAuthorizedToolCall as T,dispatchToolCall as E,finalizeToolCall as D,prepareToolCall as O,toolFailure as k}from"./agent/tool/pipeline.js";import{TOOL_SOURCE_API_VERSION as A}from"./composition/tool-source/config.js";import{defineToolSource as j}from"./composition/tool-source/definition.js";import{defineToolFromSchema as M}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as N,localToolExecutionBackend as P}from"./agent/tool/execution.js";import{defineActionFusion as F}from"./agent/tool/action-fusion.js";export{S as EXPERIMENTAL_NESTED_TOOL_ERROR_CODES,r as SPILL_TOOL_NAME,h as TOOL_ERROR_CODES,p as TOOL_REGISTRY_ERROR_CODES,A as TOOL_SOURCE_API_VERSION,g as ToolError,m as ToolRegistry,w as authorizeToolCall,v as createApprovalBroker,y as createApprovalRequest,i as createMemorySpillStore,u as createModelEvidenceReducer,N as createToolExecutionInterceptor,F as defineActionFusion,e as defineTool,M as defineToolFromSchema,j as defineToolSource,d as diagnosticLineNumbers,T as dispatchAuthorizedToolCall,E as dispatchToolCall,a as estimateTextBlockTokens,o as estimateTextTokens,t as executionModeOf,C as experimentalNestedToolPort,D as finalizeToolCall,b as fixedApprovalBroker,P as localToolExecutionBackend,O as prepareToolCall,s as previewForSpill,c as readSpillTool,f as reduceEvidence,n as renderJsonValue,_ as toolErrorDisposition,k as toolFailure,l as truncateMiddleToTokens,x as withApprovalPersistence};
|
package/package.json
CHANGED