@dual-os/sdk 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"DualRuntime.js","names":["Func","AiProvider.registryId","AgentChannelRuntime.Service","Trigger.activate","Trigger.deactivate","Trigger.verify","Trigger.parse","Trigger.poll","AuthMethodExecution.decodeSetup","AuthMethodExecution.prepare","prepareOAuth2Tokens","AuthMethodExecution.prepareOAuth2Tokens","AuthMethodExecution.refreshUnknown","AuthMethodExecution.resolveDecoded","AuthMethodExecution.resolve","AuthMethodBinding.makeBinding","AiProvider.RuntimeConfig","AuthMethodExecution.executeJson","AgentChannelRuntime.layer"],"sources":["../src/DualRuntime.ts"],"sourcesContent":["/**\n * Dual action invocation, trigger lifecycle, and auth runtime.\n *\n * @since 0.0.0\n */\nimport {\n Array,\n Context,\n Effect,\n Function as Func,\n Layer,\n Predicate,\n Result,\n Schema,\n pipe,\n} from \"effect\";\n\nimport { type HttpClientRequest, Url } from \"effect/http\";\n\nimport {\n ActionHandlerError,\n RetryableActionHandlerError,\n type ActionHandlerFailure,\n} from \"./Action.ts\";\nimport * as AgentChannelRuntime from \"./AgentChannelRuntime.ts\";\nimport * as AiProvider from \"./AiProvider.ts\";\nimport type * as AuthMethod from \"./AuthMethod.ts\";\nimport * as AuthMethodBinding from \"./AuthMethodBinding.ts\";\nimport * as AuthMethodExecution from \"./AuthMethodExecution.ts\";\nimport {\n ConnectionIdNotAllowedError,\n ConnectionReauthorizationRequiredError,\n ConnectionRequiredError,\n ConnectionSelectionRequiredError,\n ConnectionResolverStoreError,\n InvalidConnectionIdError,\n InvalidResolvedConnectionError,\n type ConnectionResolutionContext,\n} from \"./ConnectionResolver.ts\";\nimport { BuilderCollisionError } from \"./DefinitionError.ts\";\nimport { TriggerNotFoundError } from \"./DualRegistry.ts\";\nimport { authRuntimeContext } from \"./internal/auth-execution.ts\";\nimport { resolveAction, type PluginActions } from \"./internal/dual/actions.ts\";\nimport {\n ActionNotFoundError,\n FieldIssue,\n InvalidActionInputError,\n InvalidActionOutputError,\n ActionHandlerNotFoundError,\n type InvokeError,\n type InvokeMeta,\n type InvokeRequest,\n type InvokeRequirementsFor,\n type InvokeSuccess,\n type PluginRequirements,\n invokeResolvedAction,\n invokeResolvedActionJson,\n} from \"./internal/dual/invoke.ts\";\nimport { resolveRuntimeTrigger } from \"./internal/dual/triggers.ts\";\nimport { indexGroups } from \"./internal/handler-context.ts\";\nimport type * as Plugin from \"./Plugin.ts\";\nimport * as Trigger from \"./Trigger.ts\";\n\n/**\n * One installed plugin release.\n *\n * @since 0.7.0\n * @category models\n */\nexport interface PluginInstallation<P extends Plugin.Any = Plugin.Any> {\n readonly plugin: P;\n /** The plugin's package version. */\n readonly version: string;\n}\n\n/**\n * The plugin releases and AI providers one runtime executes, with the services their handlers need.\n *\n * @since 0.7.0\n * @category models\n */\nexport interface App<\n out P extends Plugin.Any = Plugin.Any,\n LayerOutput = never,\n out LayerError = never,\n out LayerRequirements = never,\n out AiProviders extends readonly AiProvider.Any[] = readonly AiProvider.Any[],\n> {\n readonly identifier: string;\n readonly aiProviders: AiProviders;\n readonly plugins: readonly PluginInstallation<P>[];\n readonly layer: Layer.Layer<LayerOutput, LayerError, LayerRequirements>;\n}\n\n/**\n * Constraint type for working with any {@link App}.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface AnyApp extends App<Plugin.Any, never, any, any, readonly AiProvider.Any[]> {}\n\n/**\n * Install one plugin release.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const install = <P extends Plugin.Any>(\n plugin: P,\n version: string,\n): PluginInstallation<P> => ({ plugin, version });\n\n/**\n * The runtime of one plugin release, as the plugin's own process runs it. `version` defaults to\n * `0.0.0` for tests that do not need the package version.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const fromPlugin = <const P extends Plugin.Any>(\n plugin: P,\n version = \"0.0.0\",\n): App<\n P,\n Plugin.LayerOutput<readonly [P]>,\n Plugin.LayerError<readonly [P]>,\n Plugin.LayerRequirements<readonly [P]>,\n readonly []\n> =>\n ({\n aiProviders: [],\n identifier: plugin.identifier,\n layer: plugin.layer,\n plugins: [install(plugin, version)],\n }) as never;\n\n/**\n * An app runtime without plugins, for {@link withPlugin} and {@link withPlugins} to fill.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const make = (identifier: string): App<never, never, never, never, readonly []> => ({\n aiProviders: [],\n identifier,\n layer: Layer.empty,\n plugins: [],\n});\n\ntype AppPlugin<A extends AnyApp> = A extends App<infer P, any, any, any, any> ? P : never;\ntype AppLayerOutput<A extends AnyApp> =\n A extends App<any, infer Output, any, any, any> ? Output : never;\ntype AppLayerError<A extends AnyApp> =\n A extends App<any, any, infer Error, any, any> ? Error : never;\ntype AppLayerRequirements<A extends AnyApp> =\n A extends App<any, any, any, infer Requirements, any> ? Requirements : never;\n\n/**\n * Result of adding a plugin release to an app runtime. A named interface keeps declaration emit\n * from expanding every plugin and layer member at large call sites.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface WithPlugin<Self extends AnyApp, Added extends Plugin.Any> extends App<\n AppPlugin<Self> | Added,\n AppLayerOutput<Self> | Plugin.LayerOutput<readonly [Added]>,\n AppLayerError<Self> | Plugin.LayerError<readonly [Added]>,\n | Plugin.LayerRequirements<readonly [Added]>\n | Exclude<AppLayerRequirements<Self>, Plugin.LayerOutput<readonly [Added]>>,\n Self[\"aiProviders\"]\n // oxlint-disable-next-line typescript/no-empty-object-type -- TypeScript declaration emit expands a type alias at every app call site (TS7056).\n> {}\n\n// Match the runtime's left-to-right provideMerge fold: later plugins can\n// satisfy earlier requirements, but earlier outputs cannot satisfy later ones.\ntype BulkLayerRequirements<\n Added extends readonly Plugin.Any[],\n Requirements,\n> = number extends Added[\"length\"]\n ? Requirements | Layer.Services<Added[number][\"layer\"]>\n : Added extends readonly [\n infer Head extends Plugin.Any,\n ...infer Tail extends readonly Plugin.Any[],\n ]\n ? BulkLayerRequirements<\n Tail,\n Layer.Services<Head[\"layer\"]> | Exclude<Requirements, Layer.Success<Head[\"layer\"]>>\n >\n : Requirements;\n\n/**\n * Result of adding several plugin releases to an app runtime in one step.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface WithPlugins<Self extends AnyApp, Added extends readonly Plugin.Any[]> extends App<\n AppPlugin<Self> | Added[number],\n AppLayerOutput<Self> | Layer.Success<Added[number][\"layer\"]>,\n AppLayerError<Self> | Layer.Error<Added[number][\"layer\"]>,\n BulkLayerRequirements<Added, AppLayerRequirements<Self>>,\n Self[\"aiProviders\"]\n // oxlint-disable-next-line typescript/no-empty-object-type -- TypeScript declaration emit expands a type alias at every app call site (TS7056).\n> {}\n\n/** A plugin and the package version of its release. */\ntype PluginEntry = readonly [plugin: Plugin.Any, version: string];\n\ntype PluginsOf<Entries extends readonly PluginEntry[]> = {\n readonly [K in keyof Entries]: Entries[K][0];\n};\n\nfunction addPlugins(app: AnyApp, entries: readonly PluginEntry[]): AnyApp {\n const seen = new Set(Array.map(app.plugins, installation => installation.plugin.identifier));\n for (const [plugin] of entries) {\n if (seen.has(plugin.identifier)) {\n throw new BuilderCollisionError({\n childKind: \"plugin\",\n existingChildKind: \"plugin\",\n identifier: plugin.identifier,\n ownerIdentifier: app.identifier,\n ownerKind: \"dual\",\n });\n }\n seen.add(plugin.identifier);\n }\n return {\n ...app,\n layer: Array.reduce(entries, app.layer, (layer, [plugin]) =>\n Layer.provideMerge(layer, plugin.layer),\n ),\n plugins: [\n ...app.plugins,\n ...Array.map(entries, ([plugin, version]) => install(plugin, version)),\n ],\n };\n}\n\n/**\n * Add one plugin release: the plugin and its package version.\n *\n * @since 0.7.0\n * @category combinators\n */\nexport const withPlugin: {\n <const P extends Plugin.Any>(\n plugin: P,\n version: string,\n ): <Self extends AnyApp>(app: Self) => WithPlugin<Self, P>;\n <Self extends AnyApp, const P extends Plugin.Any>(\n app: Self,\n plugin: P,\n version: string,\n ): WithPlugin<Self, P>;\n} = Func.dual(3, (app: AnyApp, plugin: Plugin.Any, version: string) =>\n addPlugins(app, [[plugin, version]]),\n);\n\n/**\n * Add several plugin releases in one step, which keeps a large app's inferred type compact.\n *\n * @since 0.7.0\n * @category combinators\n */\nexport const withPlugins: {\n <const E extends readonly PluginEntry[]>(\n entries: E,\n ): <Self extends AnyApp>(app: Self) => WithPlugins<Self, PluginsOf<E>>;\n <Self extends AnyApp, const E extends readonly PluginEntry[]>(\n app: Self,\n entries: E,\n ): WithPlugins<Self, PluginsOf<E>>;\n} = Func.dual(2, addPlugins);\n\nconst pluginOf = (app: AnyApp, identifier: string): Plugin.Any | undefined =>\n app.plugins.find(installation => installation.plugin.identifier === identifier)?.plugin;\n\n/**\n * Request payload accepted by {@link invoke}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeRequest };\n\n/**\n * Metadata returned alongside successful invocation data.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeMeta };\n\n/**\n * Successful invocation envelope returned by {@link invoke}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeSuccess };\n\n/**\n * Structured field-level validation issue surfaced by {@link InvalidActionInputError}.\n *\n * @since 0.0.0\n * @category models\n */\nexport { FieldIssue };\n\n/**\n * Raised when an invocation references an unknown action id.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionNotFoundError };\n\n/**\n * @since 0.0.0\n * @category errors\n */\n\n/**\n * Raised when invocation input fails schema validation.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidActionInputError };\n\n/**\n * Raised when action handler output fails schema validation.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidActionOutputError };\n\n/**\n * Raised when the runtime action handler service is missing.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionHandlerNotFoundError };\n\n/**\n * Non-retryable failure reported by a trusted action handler.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionHandlerError };\n\n/**\n * Retryable failure reported by a trusted action handler.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { RetryableActionHandlerError };\n\n/**\n * Stable trusted action handler failure contract.\n *\n * @since 0.0.0\n * @category errors\n */\nexport type { ActionHandlerFailure };\n\n/**\n * Raised when an action does not accept a connection but a connectionId was still provided.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionIdNotAllowedError };\n\n/**\n * Raised when invocation requires a connection and no compatible binding is available.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionRequiredError };\n\n/**\n * Raised when several compatible connection bindings exist and the caller must choose one.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionSelectionRequiredError };\n\n/**\n * Raised when the provider refuses a connection's stored grant and the user must sign in again.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionReauthorizationRequiredError };\n\n/**\n * Raised when the host connection store is unavailable.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionResolverStoreError };\n\n/**\n * Raised when a connectionId does not resolve to a compatible binding.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidConnectionIdError };\n\n/**\n * Raised when a resolved connection binding does not satisfy its auth method schema.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidResolvedConnectionError };\n\n/**\n * Structured SDK-owned invocation failures.\n *\n * @since 0.0.0\n * @category errors\n */\nexport type { InvokeError };\nexport type { InvokeRequirementsFor };\n\n/**\n * Invoke an action directly in-process.\n *\n * The invocation boundary resolves an action by canonical machine id, validates\n * unknown input against the resolved runtime schema, runs the handler, and\n * returns a standard success envelope. This mirrors the server trusted invoke\n * boundary: runtime schema validation is authoritative.\n *\n * @since 0.0.0\n * @category execution\n */\nconst failInvokeActionNotFound = (\n actionId: string,\n): Effect.Effect<InvokeSuccess, ActionNotFoundError> =>\n Effect.fail(new ActionNotFoundError({ actionId }));\n\nconst invokeRaw = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n request: InvokeRequest,\n json = false,\n): Effect.Effect<InvokeSuccess, InvokeError, RuntimeRequirementsFor<P>> => {\n const resolved = resolveAction(app.plugins, request.actionId, request.actionVersion);\n\n if (\n resolved === undefined ||\n (request.pluginKey !== undefined && resolved.providerId !== request.pluginKey)\n ) {\n return failInvokeActionNotFound(request.actionId);\n }\n\n // The runtime entry is resolved from erased plugin trees, so the precise\n // per-action requirement union in the return annotation cannot be recovered\n // here; the annotation is the contract, the cast is the boundary.\n return (json ? invokeResolvedActionJson : invokeResolvedAction)(\n resolved.providerId,\n resolved.actionId,\n resolved.pluginVersion,\n resolved.action,\n resolved.authMethods,\n request,\n ) as never;\n};\n\nexport const invoke = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n request: InvokeRequest,\n): Effect.Effect<\n InvokeSuccess,\n InvokeError | LayerError,\n LayerRequirements | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n> => invokeRaw(app, request).pipe(Effect.provide(app.layer));\n\n/**\n * Runtime-first invocation request accepted by {@link Service}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type RuntimeInvokeRequest = InvokeRequest;\n\n/**\n * Runtime-first trigger lifecycle request accepted by {@link Service}.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface RuntimeTriggerLifecycleRequest {\n readonly triggerId: string;\n readonly pluginKey?: string;\n /** The exact plugin release the caller pinned; another installed release does not run. */\n readonly triggerVersion?: string | undefined;\n readonly config: unknown;\n readonly state?: unknown | undefined;\n readonly connectionId?: string | undefined;\n readonly context?: ConnectionResolutionContext | undefined;\n}\n\nexport interface RuntimeWebhookActivationRequest extends RuntimeTriggerLifecycleRequest {\n readonly webhookUrl: string;\n}\n\nexport interface RuntimeWebhookTriggerLifecycleRequest extends RuntimeWebhookActivationRequest {\n readonly request: Trigger.WebhookRequest;\n}\n\nexport interface AuthMethodRequest {\n readonly providerId: string;\n readonly authMethodId: string;\n}\n\nexport interface DecodeAuthMethodSetupRequest extends AuthMethodRequest {\n readonly encoding?: \"json\";\n readonly setup: unknown;\n}\n\nexport interface PrepareAuthMethodRequest extends AuthMethodRequest {\n readonly input: unknown;\n readonly setup: unknown;\n}\n\nexport interface PrepareOAuth2TokensRequest extends AuthMethodRequest {\n readonly tokens: AuthMethod.OAuth2TokenResponse;\n readonly setup: unknown;\n}\n\nexport interface RefreshAuthMethodRequest extends AuthMethodRequest {\n readonly material: unknown;\n readonly setup: unknown;\n readonly now: number;\n readonly minValidityMs: number;\n readonly reason: AuthMethod.RefreshReason;\n}\n\nexport interface ResolveAuthMethodRequest extends AuthMethodRequest {\n /** `json` when the material and setup arrive in their canonical JSON encoding, as in the sandbox. */\n readonly encoding?: \"json\";\n readonly material: unknown;\n readonly setup: unknown;\n}\n\nexport interface ResolveAiModelConfigRequest extends ResolveAuthMethodRequest {\n readonly model: AiProvider.RuntimeModel;\n}\n\nexport class AuthMethodNotFoundError extends Schema.TaggedError<AuthMethodNotFoundError>()(\n \"AuthMethodNotFoundError\",\n { authMethodId: Schema.String, providerId: Schema.String },\n) {}\n\nexport type AuthMethodExecutionError =\n | AuthMethodNotFoundError\n | Schema.SchemaError\n | AuthMethod.ExpectedOAuth2MethodError\n | AuthMethod.OAuth2RefreshTokenUnavailableError\n | AuthMethod.AuthMethodHookError;\n\nexport class AiProviderRuntimeNotConfiguredError extends Schema.TaggedError<AiProviderRuntimeNotConfiguredError>()(\n \"AiProviderRuntimeNotConfiguredError\",\n { providerId: Schema.String },\n) {}\n\nexport type AiModelConfigError = AuthMethodExecutionError | AiProviderRuntimeNotConfiguredError;\n\n/** Raised when a provider declares no sandbox access. */\nexport class SandboxAccessNotDeclaredError extends Schema.TaggedError<SandboxAccessNotDeclaredError>()(\n \"SandboxAccessNotDeclaredError\",\n { providerId: Schema.String },\n) {}\n\n/** Raised when the Connection may not be sent with a sandbox request: another origin, or a request the provider refuses. */\nexport class SandboxRequestNotAllowedError extends Schema.TaggedError<SandboxRequestNotAllowedError>()(\n \"SandboxRequestNotAllowedError\",\n { origin: Schema.String, path: Schema.String, providerId: Schema.String },\n) {}\n\nexport type SandboxAccessError = AuthMethodExecutionError | SandboxAccessNotDeclaredError;\n\n/** One Connection's sandbox access: where its credential may go, and how a request gets it. */\nexport interface ResolvedSandboxAccess {\n readonly origins: readonly string[];\n readonly authorize: (\n request: HttpClientRequest.HttpClientRequest,\n ) => Effect.Effect<HttpClientRequest.HttpClientRequest, SandboxRequestNotAllowedError>;\n}\n\n/**\n * Runtime service materialized from an {@link App}.\n *\n * @since 0.0.0\n * @category services\n */\nexport interface RuntimeService {\n readonly executeAuthJson: (\n request: AuthMethodExecution.JsonRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly invokeJson: (\n request: RuntimeInvokeRequest,\n ) => Effect.Effect<InvokeSuccess<string, Schema.Json>, InvokeError | Schema.SchemaError>;\n readonly decodeAgentChannelDefinitionSettings: AgentChannelRuntime.Interface[\"decodeDefinitionSettings\"];\n readonly decodeAgentChannelDeploymentSettings: AgentChannelRuntime.Interface[\"decodeDeploymentSettings\"];\n readonly getAgentChannel: AgentChannelRuntime.Interface[\"get\"];\n readonly checkAccessAgentChannel: AgentChannelRuntime.Interface[\"checkAccess\"];\n readonly executeAgentChannel: AgentChannelRuntime.Interface[\"execute\"];\n readonly invoke: (request: RuntimeInvokeRequest) => Effect.Effect<InvokeSuccess, InvokeError>;\n readonly activateTrigger: (\n request: RuntimeWebhookActivationRequest,\n ) => Effect.Effect<Trigger.ActivateSuccess, unknown>;\n readonly deactivateTrigger: (\n request: RuntimeWebhookActivationRequest,\n ) => Effect.Effect<Trigger.DeactivateSuccess, unknown>;\n readonly verifyTrigger: (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.VerifySuccess, unknown>;\n readonly parseTrigger: (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.EmittedEventsSuccess<string, \"parse\">, unknown>;\n readonly pollTrigger: (\n request: RuntimeTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.EmittedEventsSuccess<string, \"poll\">, unknown>;\n readonly getAuthMethod: (\n request: AuthMethodRequest,\n ) => Effect.Effect<AuthMethod.Any, AuthMethodNotFoundError>;\n // TODO(live-schema-validation): expose live action/trigger schema decoders by capability version.\n // Server authoring/runtime must validate against SDK declarations, not JSON Schema projections.\n readonly decodeAuthMethodSetup: (\n request: DecodeAuthMethodSetupRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly prepareAuthMethod: (\n request: PrepareAuthMethodRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly prepareOAuth2Tokens: (\n request: PrepareOAuth2TokensRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly refreshAuthMethod: (\n request: RefreshAuthMethodRequest,\n ) => Effect.Effect<unknown | undefined, AuthMethodExecutionError>;\n readonly resolveAuthMethod: (\n request: ResolveAuthMethodRequest,\n ) => Effect.Effect<AuthMethodBinding.Binding, AuthMethodExecutionError>;\n readonly resolveAiModelConfig: (\n request: ResolveAiModelConfigRequest,\n ) => Effect.Effect<AiProvider.RuntimeConfig, AiModelConfigError>;\n readonly resolveSandboxAccess: (\n request: ResolveAuthMethodRequest,\n ) => Effect.Effect<ResolvedSandboxAccess, SandboxAccessError>;\n}\n\n/**\n * Effect service provided by {@link toLayer}.\n *\n * @since 0.0.0\n * @category services\n */\nexport class Service extends Context.Service<Service, RuntimeService>()(\n \"@dual-os/sdk/Dual/Service\",\n) {}\n\nexport type RuntimeRequirementsFor<P extends Plugin.Any> =\n | AgentChannelRuntime.Requirements<P>\n | (P extends Plugin.Any ? PluginRequirements<P, PluginActions<P>> : never);\n\ntype AuthProvider = Plugin.Any | AiProvider.Any;\n\ntype AuthMethodFor<Providers extends AuthProvider> = Providers[\"authMethods\"][number];\n\ntype AuthMethodSetupDecodeRequirements<Method extends AuthMethod.Any> =\n AuthMethod.SetupSchema<Method> extends Schema.Top\n ? Schema.Codec.DecodingServices<AuthMethod.SetupSchema<Method>>\n : never;\n\ntype AuthMethodInputDecodeRequirements<Method extends AuthMethod.Any> =\n AuthMethod.InputSchema<Method> extends Schema.Top\n ? Schema.Codec.DecodingServices<AuthMethod.InputSchema<Method>>\n : never;\n\ntype AuthMethodExecutionRequirementsFor<Providers extends AuthProvider> =\n AuthMethodFor<Providers> extends infer Method\n ? Method extends AuthMethod.Any\n ?\n | AuthMethod.Requirements<Method>\n | AuthMethodSetupDecodeRequirements<Method>\n | AuthMethodInputDecodeRequirements<Method>\n | Schema.Codec.DecodingServices<AuthMethod.MaterialSchema<Method>>\n | Schema.Codec.DecodingServices<AuthMethod.ValueSchema<Method>>\n | Schema.Codec.EncodingServices<AuthMethod.MaterialSchema<Method>>\n | Schema.Codec.EncodingServices<AuthMethod.ValueSchema<Method>>\n | (AuthMethod.SetupSchema<Method> extends Schema.Top\n ? Schema.Codec.EncodingServices<AuthMethod.SetupSchema<Method>>\n : never)\n : never\n : never;\n\n/**\n * Requirements still needed by {@link toLayer} for an app.\n *\n * Hosts (the server, a worker, a test harness) never know an app's concrete\n * implementations: they talk to it exclusively through the generic\n * {@link Service} layer. App-specific dependencies — a plugin's API client, an\n * auth hook's token service — are discharged where they are known, at the\n * plugin or app definition (the `Exclude<..., LayerOutput>` below cancels\n * them). Only what the definition did not discharge surfaces here,\n * generically, and the host entrypoint forces it to `never` before anything\n * runs.\n *\n * @since 0.0.0\n * @category type-level\n */\nexport type ToLayerRequirements<A extends AnyApp> =\n A extends App<\n infer P extends Plugin.Any,\n infer LayerOutput,\n any,\n infer LayerRequirements,\n infer AiProviders extends readonly AiProvider.Any[]\n >\n ?\n | LayerRequirements\n | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n | Exclude<AuthMethodExecutionRequirementsFor<P | AiProviders[number]>, LayerOutput>\n : never;\n\n/**\n * Layer-construction errors surfaced by {@link toLayer} for an app.\n *\n * @since 0.0.0\n * @category type-level\n */\nexport type ToLayerError<A extends AnyApp> =\n A extends App<any, any, infer LayerError, any, any> ? LayerError : never;\n\n/**\n * Turn an {@link App} into a runtime Effect service layer.\n *\n * @since 0.0.0\n * @category layers\n */\nexport const toLayer = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n): Layer.Layer<\n Service,\n LayerError,\n | LayerRequirements\n | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n | Exclude<AuthMethodExecutionRequirementsFor<P | AiProviders[number]>, LayerOutput>\n> => {\n const fullAuthMethodId = (providerId: string, method: AuthMethod.Any): string =>\n `${providerId}/${method.identifier}`;\n\n const findAuthMethod = (\n providerId: string,\n authMethodId: string,\n ): Effect.Effect<AuthMethod.Any, AuthMethodNotFoundError> => {\n const provider =\n pluginOf(app, providerId) ??\n app.aiProviders.find(candidate => AiProvider.registryId(candidate.identifier) === providerId);\n const method = provider?.authMethods.find(\n candidate =>\n candidate.identifier === authMethodId ||\n fullAuthMethodId(providerId, candidate) === authMethodId,\n );\n\n return method === undefined\n ? Effect.fail(new AuthMethodNotFoundError({ authMethodId, providerId }))\n : Effect.succeed(method);\n };\n\n const serviceLayer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const channels = yield* AgentChannelRuntime.Service;\n const context = yield* Effect.context<\n RuntimeRequirementsFor<P> | AuthMethodExecutionRequirementsFor<P | AiProviders[number]>\n >();\n\n const appContext = indexGroups(context);\n\n const provideRuntimeContext = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(Effect.updateContext(input => Context.merge(appContext, input)));\n\n // Requirements are satisfied by the context captured at layer build time;\n // the cast erases them so service methods expose closed effects.\n const runWithCapturedAppContext = <A, E>(\n effect: Effect.Effect<A, E, unknown>,\n ): Effect.Effect<A, E> => provideRuntimeContext(effect) as never;\n\n const getAuthMethod = (request: AuthMethodRequest) =>\n findAuthMethod(request.providerId, request.authMethodId);\n\n const getTrigger = (request: RuntimeTriggerLifecycleRequest) => {\n const resolved = resolveRuntimeTrigger(\n app.plugins,\n request.triggerId,\n request.triggerVersion,\n );\n return resolved === undefined ||\n (request.pluginKey !== undefined && resolved.providerId !== request.pluginKey)\n ? Effect.fail(new TriggerNotFoundError({ triggerId: request.triggerId }))\n : Effect.succeed(resolved);\n };\n\n const triggerLifecycleRequest = (\n request: RuntimeTriggerLifecycleRequest,\n ): Trigger.LifecycleRequest => ({\n config: request.config,\n ...(request.state === undefined ? {} : { state: request.state }),\n ...(request.connectionId === undefined ? {} : { connectionId: request.connectionId }),\n ...(request.context === undefined ? {} : { context: request.context }),\n });\n\n const webhookActivationRequest = (\n request: RuntimeWebhookActivationRequest,\n ): Trigger.WebhookActivationRequest => ({\n ...triggerLifecycleRequest(request),\n webhookUrl: request.webhookUrl,\n });\n\n // A host can pass the raw body as text; handlers verify signatures over its bytes.\n const webhookTriggerLifecycleRequest = (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ): Trigger.WebhookExecutionRequest => ({\n ...webhookActivationRequest(request),\n request: Predicate.isString(request.request.rawBody)\n ? { ...request.request, rawBody: new TextEncoder().encode(request.request.rawBody) }\n : request.request,\n });\n\n const activateTrigger = (request: RuntimeWebhookActivationRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.activate(entry, webhookActivationRequest(request));\n }),\n );\n\n const deactivateTrigger = (request: RuntimeWebhookActivationRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.deactivate(entry, webhookActivationRequest(request));\n }),\n );\n\n const verifyTrigger = (request: RuntimeWebhookTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.verify(entry, webhookTriggerLifecycleRequest(request));\n }),\n );\n\n const parseTrigger = (request: RuntimeWebhookTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.parse(entry, webhookTriggerLifecycleRequest(request));\n }),\n );\n\n const pollTrigger = (request: RuntimeTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.poll(entry, triggerLifecycleRequest(request));\n }),\n );\n\n const decodeAuthMethodSetup = (request: DecodeAuthMethodSetupRequest) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method => {\n if (request.encoding === \"json\" && method.setup !== undefined) {\n return Schema.decodeUnknownEffect(Schema.toCodecJson(method.setup))(request.setup);\n }\n return AuthMethodExecution.decodeSetup(method, request.setup);\n }),\n ),\n );\n\n const withAuthMethodSetup = <A, E, R>(\n request: DecodeAuthMethodSetupRequest,\n execute: (\n method: AuthMethod.Any,\n setup: AuthMethod.Setup<AuthMethod.Any>,\n ) => Effect.Effect<A, E, R>,\n ) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method =>\n AuthMethodExecution.decodeSetup(method, request.setup).pipe(\n Effect.flatMap(setup => execute(method, setup)),\n ),\n ),\n ),\n );\n\n const prepareAuthMethod = (request: PrepareAuthMethodRequest) =>\n withAuthMethodSetup(request, (method, setup) =>\n AuthMethodExecution.prepare(method, request.input, { setup }),\n );\n\n const prepareOAuth2Tokens = (request: PrepareOAuth2TokensRequest) =>\n withAuthMethodSetup(request, (method, setup) =>\n AuthMethodExecution.prepareOAuth2Tokens(method, request.tokens, { setup }),\n );\n\n const refreshAuthMethod = (request: RefreshAuthMethodRequest) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method =>\n AuthMethodExecution.decodeSetup(method, request.setup).pipe(\n Effect.flatMap(setup =>\n AuthMethodExecution.refreshUnknown(method, request.material, {\n minValidityMs: request.minValidityMs,\n now: request.now,\n reason: request.reason,\n setup,\n }),\n ),\n ),\n ),\n ),\n );\n\n const resolveAuthMethod = (request: ResolveAuthMethodRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const method = yield* getAuthMethod(request);\n const setup = yield* decodeAuthMethodSetup(request);\n const value =\n request.encoding === \"json\"\n ? yield* AuthMethodExecution.resolveDecoded(\n method,\n yield* Schema.decodeUnknownEffect(Schema.toCodecJson(method.material))(\n request.material,\n ),\n { setup },\n )\n : yield* AuthMethodExecution.resolve(method, request.material, { setup });\n return AuthMethodBinding.makeBinding({\n connectionId: undefined,\n method,\n providerId: request.providerId,\n value,\n });\n }),\n );\n\n const resolveAiModelConfig = (request: ResolveAiModelConfigRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const provider = app.aiProviders.find(\n candidate => AiProvider.registryId(candidate.identifier) === request.providerId,\n );\n if (provider?.resolveRuntimeConfig === undefined) {\n return yield* new AiProviderRuntimeNotConfiguredError({\n providerId: request.providerId,\n });\n }\n const binding = yield* resolveAuthMethod(request);\n // SAFETY: the resolver belongs to this provider and the binding was\n // resolved from the same provider's declared auth-method list.\n const resolveRuntimeConfig =\n provider.resolveRuntimeConfig as AiProvider.RuntimeConfigResolver<\n readonly AuthMethod.Any[]\n >;\n return yield* Schema.decodeUnknownEffect(AiProvider.RuntimeConfig)(\n resolveRuntimeConfig({ binding, model: request.model }),\n );\n }),\n );\n\n const resolveSandboxAccess = (request: ResolveAuthMethodRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const access = pluginOf(app, request.providerId)?.sandboxAccess;\n if (access === undefined) {\n return yield* new SandboxAccessNotDeclaredError({ providerId: request.providerId });\n }\n const context = authRuntimeContext(yield* resolveAuthMethod(request));\n // Declared origins compare as URL origins, so `https://GHES.example:443` matches requests.\n const origins = Array.map(\n access.origins(context),\n origin => Result.getOrUndefined(Url.fromString(origin))?.origin ?? origin,\n );\n const authorize = (outgoing: HttpClientRequest.HttpClientRequest) => {\n const url = Result.getOrUndefined(Url.fromString(outgoing.url));\n const refused = new SandboxRequestNotAllowedError({\n origin: url?.origin ?? outgoing.url,\n path: url?.pathname ?? \"\",\n providerId: request.providerId,\n });\n if (url === undefined || !origins.includes(url.origin)) return Effect.fail(refused);\n return Effect.fromOption(access.authorize(outgoing, context), () => refused);\n };\n return { authorize, origins } satisfies ResolvedSandboxAccess;\n }),\n );\n\n return Service.of({\n activateTrigger,\n checkAccessAgentChannel: channels.checkAccess,\n deactivateTrigger,\n decodeAgentChannelDefinitionSettings: channels.decodeDefinitionSettings,\n decodeAgentChannelDeploymentSettings: channels.decodeDeploymentSettings,\n decodeAuthMethodSetup,\n executeAgentChannel: channels.execute,\n executeAuthJson: request =>\n runWithCapturedAppContext(\n pipe(\n getAuthMethod(request),\n Effect.flatMap(method => AuthMethodExecution.executeJson(method, request)),\n ),\n ),\n getAgentChannel: channels.get,\n getAuthMethod,\n invoke: request => runWithCapturedAppContext(invokeRaw(app, request)),\n invokeJson: request =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const result = yield* invokeRaw(app, request, true);\n return {\n ...result,\n data: yield* Schema.decodeUnknownEffect(Schema.Json)(result.data),\n };\n }),\n ),\n parseTrigger,\n pollTrigger,\n prepareAuthMethod,\n prepareOAuth2Tokens,\n refreshAuthMethod,\n resolveAiModelConfig,\n resolveAuthMethod,\n resolveSandboxAccess,\n verifyTrigger,\n });\n }),\n );\n\n return serviceLayer.pipe(\n Layer.provide(AgentChannelRuntime.layer(app.plugins.map(installation => installation.plugin))),\n Layer.provide(app.layer),\n );\n};\n\nexport * as DualRuntime from \"./DualRuntime.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,MAAa,WACX,QACA,aAC2B;CAAE;CAAQ;AAAQ;;;;;;;;AAS/C,MAAa,cACX,QACA,UAAU,aAQT;CACC,aAAa,CAAC;CACd,YAAY,OAAO;CACnB,OAAO,OA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0BACE,OAAO,IAAI,aAAa;IACtB,MAAM,SAAS,OAAO,UAAU,KAAK,SAAS,IAAI;IAClD,OAAO;KACL,GAAG;KACH,MAAM,OAAO,OAAO,oBAAoB,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI;IAClE;GACF,CAAC,CACH;GACF;GACA;GACA;GACA,qBAAA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;CACH,CAAC,CAGe,CAAC,CAAC,KAClB,MAAM,QAAQC,MAA0B,IAAI,QAAQ,KAAI,iBAAgB,aAAa,MAAM,CAAC,CAAC,GAC7F,MAAM,QAAQ,IAAI,KAAK,CACzB;AACF"}
1
+ {"version":3,"file":"DualRuntime.js","names":["Func","AiProvider.registryId","AgentChannelRuntime.Service","Trigger.activate","Trigger.deactivate","Trigger.verify","Trigger.parse","Trigger.poll","AuthMethodExecution.decodeSetup","AuthMethodExecution.prepare","prepareOAuth2Tokens","AuthMethodExecution.prepareOAuth2Tokens","AuthMethodExecution.refreshUnknown","AuthMethodExecution.resolveDecoded","AuthMethodExecution.resolve","AuthMethodBinding.makeBinding","AiProvider.RuntimeConfig","AuthMethodExecution.executeJson","AgentChannelRuntime.layer"],"sources":["../src/DualRuntime.ts"],"sourcesContent":["/**\n * Dual action invocation, trigger lifecycle, and auth runtime.\n *\n * @since 0.0.0\n */\nimport {\n Array,\n Context,\n Effect,\n Function as Func,\n Layer,\n Predicate,\n Result,\n Schema,\n pipe,\n} from \"effect\";\n\nimport { type HttpClientRequest, Url } from \"effect/http\";\n\nimport {\n ActionHandlerError,\n RetryableActionHandlerError,\n type ActionHandlerFailure,\n} from \"./Action.ts\";\nimport * as AgentChannelRuntime from \"./AgentChannelRuntime.ts\";\nimport * as AiProvider from \"./AiProvider.ts\";\nimport type * as AuthMethod from \"./AuthMethod.ts\";\nimport * as AuthMethodBinding from \"./AuthMethodBinding.ts\";\nimport * as AuthMethodExecution from \"./AuthMethodExecution.ts\";\nimport {\n ConnectionIdNotAllowedError,\n ConnectionReauthorizationRequiredError,\n ConnectionRequiredError,\n ConnectionSelectionRequiredError,\n ConnectionResolverStoreError,\n InvalidConnectionIdError,\n InvalidResolvedConnectionError,\n type ConnectionResolutionContext,\n} from \"./ConnectionResolver.ts\";\nimport { BuilderCollisionError } from \"./DefinitionError.ts\";\nimport { TriggerNotFoundError } from \"./DualRegistry.ts\";\nimport { authRuntimeContext } from \"./internal/auth-execution.ts\";\nimport { resolveAction, type PluginActions } from \"./internal/dual/actions.ts\";\nimport {\n ActionNotFoundError,\n FieldIssue,\n InvalidActionInputError,\n InvalidActionOutputError,\n ActionHandlerNotFoundError,\n type InvokeError,\n type InvokeMeta,\n type InvokeRequest,\n type InvokeRequirementsFor,\n type InvokeSuccess,\n type PluginRequirements,\n invokeResolvedAction,\n invokeResolvedActionJson,\n} from \"./internal/dual/invoke.ts\";\nimport { resolveRuntimeTrigger } from \"./internal/dual/triggers.ts\";\nimport { indexGroups } from \"./internal/handler-context.ts\";\nimport type * as Plugin from \"./Plugin.ts\";\nimport * as Trigger from \"./Trigger.ts\";\n\n/**\n * One installed plugin release.\n *\n * @since 0.7.0\n * @category models\n */\nexport interface PluginInstallation<P extends Plugin.Any = Plugin.Any> {\n readonly plugin: P;\n /** The plugin's package version. */\n readonly version: string;\n}\n\n/**\n * The plugin releases and AI providers one runtime executes, with the services their handlers need.\n *\n * @since 0.7.0\n * @category models\n */\nexport interface App<\n out P extends Plugin.Any = Plugin.Any,\n LayerOutput = never,\n out LayerError = never,\n out LayerRequirements = never,\n out AiProviders extends readonly AiProvider.Any[] = readonly AiProvider.Any[],\n> {\n readonly identifier: string;\n readonly aiProviders: AiProviders;\n readonly plugins: readonly PluginInstallation<P>[];\n readonly layer: Layer.Layer<LayerOutput, LayerError, LayerRequirements>;\n}\n\n/**\n * Constraint type for working with any {@link App}.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface AnyApp extends App<Plugin.Any, never, any, any, readonly AiProvider.Any[]> {}\n\n/**\n * Install one plugin release.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const install = <P extends Plugin.Any>(\n plugin: P,\n version: string,\n): PluginInstallation<P> => ({ plugin, version });\n\n/**\n * The runtime of one plugin release, as the plugin's own process runs it. `version` defaults to\n * `0.0.0` for tests that do not need the package version.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const fromPlugin = <const P extends Plugin.Any>(\n plugin: P,\n version = \"0.0.0\",\n): App<\n P,\n Plugin.LayerOutput<readonly [P]>,\n Plugin.LayerError<readonly [P]>,\n Plugin.LayerRequirements<readonly [P]>,\n readonly []\n> =>\n ({\n aiProviders: [],\n identifier: plugin.identifier,\n layer: plugin.layer,\n plugins: [install(plugin, version)],\n }) as never;\n\n/**\n * An app runtime without plugins, for {@link withPlugin} and {@link withPlugins} to fill.\n *\n * @since 0.7.0\n * @category constructors\n */\nexport const make = (identifier: string): App<never, never, never, never, readonly []> => ({\n aiProviders: [],\n identifier,\n layer: Layer.empty,\n plugins: [],\n});\n\ntype AppPlugin<A extends AnyApp> = A extends App<infer P, any, any, any, any> ? P : never;\ntype AppLayerOutput<A extends AnyApp> =\n A extends App<any, infer Output, any, any, any> ? Output : never;\ntype AppLayerError<A extends AnyApp> =\n A extends App<any, any, infer Error, any, any> ? Error : never;\ntype AppLayerRequirements<A extends AnyApp> =\n A extends App<any, any, any, infer Requirements, any> ? Requirements : never;\n\n/**\n * Result of adding a plugin release to an app runtime. A named interface keeps declaration emit\n * from expanding every plugin and layer member at large call sites.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface WithPlugin<Self extends AnyApp, Added extends Plugin.Any> extends App<\n AppPlugin<Self> | Added,\n AppLayerOutput<Self> | Plugin.LayerOutput<readonly [Added]>,\n AppLayerError<Self> | Plugin.LayerError<readonly [Added]>,\n | Plugin.LayerRequirements<readonly [Added]>\n | Exclude<AppLayerRequirements<Self>, Plugin.LayerOutput<readonly [Added]>>,\n Self[\"aiProviders\"]\n // oxlint-disable-next-line typescript/no-empty-object-type -- TypeScript declaration emit expands a type alias at every app call site (TS7056).\n> {}\n\n// Match the runtime's left-to-right provideMerge fold: later plugins can\n// satisfy earlier requirements, but earlier outputs cannot satisfy later ones.\ntype BulkLayerRequirements<\n Added extends readonly Plugin.Any[],\n Requirements,\n> = number extends Added[\"length\"]\n ? Requirements | Layer.Services<Added[number][\"layer\"]>\n : Added extends readonly [\n infer Head extends Plugin.Any,\n ...infer Tail extends readonly Plugin.Any[],\n ]\n ? BulkLayerRequirements<\n Tail,\n Layer.Services<Head[\"layer\"]> | Exclude<Requirements, Layer.Success<Head[\"layer\"]>>\n >\n : Requirements;\n\n/**\n * Result of adding several plugin releases to an app runtime in one step.\n *\n * @since 0.7.0\n * @category type-level\n */\nexport interface WithPlugins<Self extends AnyApp, Added extends readonly Plugin.Any[]> extends App<\n AppPlugin<Self> | Added[number],\n AppLayerOutput<Self> | Layer.Success<Added[number][\"layer\"]>,\n AppLayerError<Self> | Layer.Error<Added[number][\"layer\"]>,\n BulkLayerRequirements<Added, AppLayerRequirements<Self>>,\n Self[\"aiProviders\"]\n // oxlint-disable-next-line typescript/no-empty-object-type -- TypeScript declaration emit expands a type alias at every app call site (TS7056).\n> {}\n\n/** A plugin and the package version of its release. */\ntype PluginEntry = readonly [plugin: Plugin.Any, version: string];\n\ntype PluginsOf<Entries extends readonly PluginEntry[]> = {\n readonly [K in keyof Entries]: Entries[K][0];\n};\n\nfunction addPlugins(app: AnyApp, entries: readonly PluginEntry[]): AnyApp {\n const seen = new Set(Array.map(app.plugins, installation => installation.plugin.identifier));\n for (const [plugin] of entries) {\n if (seen.has(plugin.identifier)) {\n throw new BuilderCollisionError({\n childKind: \"plugin\",\n existingChildKind: \"plugin\",\n identifier: plugin.identifier,\n ownerIdentifier: app.identifier,\n ownerKind: \"dual\",\n });\n }\n seen.add(plugin.identifier);\n }\n return {\n ...app,\n layer: Array.reduce(entries, app.layer, (layer, [plugin]) =>\n Layer.provideMerge(layer, plugin.layer),\n ),\n plugins: [\n ...app.plugins,\n ...Array.map(entries, ([plugin, version]) => install(plugin, version)),\n ],\n };\n}\n\n/**\n * Add one plugin release: the plugin and its package version.\n *\n * @since 0.7.0\n * @category combinators\n */\nexport const withPlugin: {\n <const P extends Plugin.Any>(\n plugin: P,\n version: string,\n ): <Self extends AnyApp>(app: Self) => WithPlugin<Self, P>;\n <Self extends AnyApp, const P extends Plugin.Any>(\n app: Self,\n plugin: P,\n version: string,\n ): WithPlugin<Self, P>;\n} = Func.dual(3, (app: AnyApp, plugin: Plugin.Any, version: string) =>\n addPlugins(app, [[plugin, version]]),\n);\n\n/**\n * Add several plugin releases in one step, which keeps a large app's inferred type compact.\n *\n * @since 0.7.0\n * @category combinators\n */\nexport const withPlugins: {\n <const E extends readonly PluginEntry[]>(\n entries: E,\n ): <Self extends AnyApp>(app: Self) => WithPlugins<Self, PluginsOf<E>>;\n <Self extends AnyApp, const E extends readonly PluginEntry[]>(\n app: Self,\n entries: E,\n ): WithPlugins<Self, PluginsOf<E>>;\n} = Func.dual(2, addPlugins);\n\nconst pluginOf = (app: AnyApp, identifier: string): Plugin.Any | undefined =>\n app.plugins.find(installation => installation.plugin.identifier === identifier)?.plugin;\n\n/**\n * Request payload accepted by {@link invoke}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeRequest };\n\n/**\n * Metadata returned alongside successful invocation data.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeMeta };\n\n/**\n * Successful invocation envelope returned by {@link invoke}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type { InvokeSuccess };\n\n/**\n * Structured field-level validation issue surfaced by {@link InvalidActionInputError}.\n *\n * @since 0.0.0\n * @category models\n */\nexport { FieldIssue };\n\n/**\n * Raised when an invocation references an unknown action id.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionNotFoundError };\n\n/**\n * @since 0.0.0\n * @category errors\n */\n\n/**\n * Raised when invocation input fails schema validation.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidActionInputError };\n\n/**\n * Raised when action handler output fails schema validation.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidActionOutputError };\n\n/**\n * Raised when the runtime action handler service is missing.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionHandlerNotFoundError };\n\n/**\n * Non-retryable failure reported by a trusted action handler.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ActionHandlerError };\n\n/**\n * Retryable failure reported by a trusted action handler.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { RetryableActionHandlerError };\n\n/**\n * Stable trusted action handler failure contract.\n *\n * @since 0.0.0\n * @category errors\n */\nexport type { ActionHandlerFailure };\n\n/**\n * Raised when an action does not accept a connection but a connectionId was still provided.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionIdNotAllowedError };\n\n/**\n * Raised when invocation requires a connection and no compatible binding is available.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionRequiredError };\n\n/**\n * Raised when several compatible connection bindings exist and the caller must choose one.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionSelectionRequiredError };\n\n/**\n * Raised when the provider refuses a connection's stored grant and the user must sign in again.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionReauthorizationRequiredError };\n\n/**\n * Raised when the host connection store is unavailable.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { ConnectionResolverStoreError };\n\n/**\n * Raised when a connectionId does not resolve to a compatible binding.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidConnectionIdError };\n\n/**\n * Raised when a resolved connection binding does not satisfy its auth method schema.\n *\n * @since 0.0.0\n * @category errors\n */\nexport { InvalidResolvedConnectionError };\n\n/**\n * Structured SDK-owned invocation failures.\n *\n * @since 0.0.0\n * @category errors\n */\nexport type { InvokeError };\nexport type { InvokeRequirementsFor };\n\n/**\n * Invoke an action directly in-process.\n *\n * The invocation boundary resolves an action by canonical machine id, validates\n * unknown input against the resolved runtime schema, runs the handler, and\n * returns a standard success envelope. This mirrors the server trusted invoke\n * boundary: runtime schema validation is authoritative.\n *\n * @since 0.0.0\n * @category execution\n */\nconst failInvokeActionNotFound = (\n actionId: string,\n): Effect.Effect<InvokeSuccess, ActionNotFoundError> =>\n Effect.fail(new ActionNotFoundError({ actionId }));\n\nconst invokeRaw = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n request: InvokeRequest,\n json = false,\n): Effect.Effect<InvokeSuccess, InvokeError, RuntimeRequirementsFor<P>> => {\n const resolved = resolveAction(app.plugins, request.actionId, request.actionVersion);\n\n if (\n resolved === undefined ||\n (request.pluginKey !== undefined && resolved.providerId !== request.pluginKey)\n ) {\n return failInvokeActionNotFound(request.actionId);\n }\n\n // The runtime entry is resolved from erased plugin trees, so the precise\n // per-action requirement union in the return annotation cannot be recovered\n // here; the annotation is the contract, the cast is the boundary.\n return (json ? invokeResolvedActionJson : invokeResolvedAction)(\n resolved.providerId,\n resolved.actionId,\n resolved.pluginVersion,\n resolved.action,\n resolved.authMethods,\n request,\n ) as never;\n};\n\nexport const invoke = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n request: InvokeRequest,\n): Effect.Effect<\n InvokeSuccess,\n InvokeError | LayerError,\n LayerRequirements | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n> => invokeRaw(app, request).pipe(Effect.provide(app.layer));\n\n/**\n * Runtime-first invocation request accepted by {@link Service}.\n *\n * @since 0.0.0\n * @category models\n */\nexport type RuntimeInvokeRequest = InvokeRequest;\n\n/**\n * Runtime-first trigger lifecycle request accepted by {@link Service}.\n *\n * @since 0.0.0\n * @category models\n */\nexport interface RuntimeTriggerLifecycleRequest {\n readonly triggerId: string;\n readonly pluginKey?: string;\n /** The exact plugin release the caller pinned; another installed release does not run. */\n readonly triggerVersion?: string | undefined;\n readonly config: unknown;\n readonly state?: unknown | undefined;\n readonly connectionId?: string | undefined;\n readonly context?: ConnectionResolutionContext | undefined;\n}\n\nexport interface RuntimeWebhookActivationRequest extends RuntimeTriggerLifecycleRequest {\n readonly webhookUrl: string;\n}\n\nexport interface RuntimeWebhookTriggerLifecycleRequest extends RuntimeWebhookActivationRequest {\n readonly request: Trigger.WebhookRequest;\n}\n\nexport interface AuthMethodRequest {\n readonly providerId: string;\n readonly authMethodId: string;\n}\n\nexport interface DecodeAuthMethodSetupRequest extends AuthMethodRequest {\n readonly encoding?: \"json\";\n readonly setup: unknown;\n}\n\nexport interface PrepareAuthMethodRequest extends AuthMethodRequest {\n readonly input: unknown;\n readonly setup: unknown;\n}\n\nexport interface PrepareOAuth2TokensRequest extends AuthMethodRequest {\n readonly tokens: AuthMethod.OAuth2TokenResponse;\n readonly setup: unknown;\n}\n\nexport interface RefreshAuthMethodRequest extends AuthMethodRequest {\n readonly material: unknown;\n readonly setup: unknown;\n readonly now: number;\n readonly minValidityMs: number;\n readonly reason: AuthMethod.RefreshReason;\n}\n\nexport interface ResolveAuthMethodRequest extends AuthMethodRequest {\n /** `json` when the material and setup arrive in their canonical JSON encoding, as in the sandbox. */\n readonly encoding?: \"json\";\n readonly material: unknown;\n readonly setup: unknown;\n}\n\nexport interface ResolveAiModelConfigRequest extends ResolveAuthMethodRequest {\n readonly model: AiProvider.RuntimeModel;\n}\n\nexport class AuthMethodNotFoundError extends Schema.TaggedError<AuthMethodNotFoundError>()(\n \"AuthMethodNotFoundError\",\n { authMethodId: Schema.String, providerId: Schema.String },\n) {}\n\nexport type AuthMethodExecutionError =\n | AuthMethodNotFoundError\n | Schema.SchemaError\n | AuthMethod.ExpectedOAuth2MethodError\n | AuthMethod.OAuth2RefreshTokenUnavailableError\n | AuthMethod.AuthMethodHookError;\n\nexport class AiProviderRuntimeNotConfiguredError extends Schema.TaggedError<AiProviderRuntimeNotConfiguredError>()(\n \"AiProviderRuntimeNotConfiguredError\",\n { providerId: Schema.String },\n) {}\n\nexport class AiModelNotAllowedError extends Schema.TaggedError<AiModelNotAllowedError>()(\n \"AiModelNotAllowedError\",\n { modelId: Schema.String, providerId: Schema.String },\n) {}\n\nexport type AiModelConfigError =\n | AuthMethodExecutionError\n | AiProviderRuntimeNotConfiguredError\n | AiModelNotAllowedError;\n\n/** Raised when a provider declares no sandbox access. */\nexport class SandboxAccessNotDeclaredError extends Schema.TaggedError<SandboxAccessNotDeclaredError>()(\n \"SandboxAccessNotDeclaredError\",\n { providerId: Schema.String },\n) {}\n\n/** Raised when the Connection may not be sent with a sandbox request: another origin, or a request the provider refuses. */\nexport class SandboxRequestNotAllowedError extends Schema.TaggedError<SandboxRequestNotAllowedError>()(\n \"SandboxRequestNotAllowedError\",\n { origin: Schema.String, path: Schema.String, providerId: Schema.String },\n) {}\n\nexport type SandboxAccessError = AuthMethodExecutionError | SandboxAccessNotDeclaredError;\n\n/** One Connection's sandbox access: where its credential may go, and how a request gets it. */\nexport interface ResolvedSandboxAccess {\n readonly origins: readonly string[];\n readonly authorize: (\n request: HttpClientRequest.HttpClientRequest,\n ) => Effect.Effect<HttpClientRequest.HttpClientRequest, SandboxRequestNotAllowedError>;\n}\n\n/**\n * Runtime service materialized from an {@link App}.\n *\n * @since 0.0.0\n * @category services\n */\nexport interface RuntimeService {\n readonly executeAuthJson: (\n request: AuthMethodExecution.JsonRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly invokeJson: (\n request: RuntimeInvokeRequest,\n ) => Effect.Effect<InvokeSuccess<string, Schema.Json>, InvokeError | Schema.SchemaError>;\n readonly decodeAgentChannelDefinitionSettings: AgentChannelRuntime.Interface[\"decodeDefinitionSettings\"];\n readonly decodeAgentChannelDeploymentSettings: AgentChannelRuntime.Interface[\"decodeDeploymentSettings\"];\n readonly getAgentChannel: AgentChannelRuntime.Interface[\"get\"];\n readonly checkAccessAgentChannel: AgentChannelRuntime.Interface[\"checkAccess\"];\n readonly executeAgentChannel: AgentChannelRuntime.Interface[\"execute\"];\n readonly invoke: (request: RuntimeInvokeRequest) => Effect.Effect<InvokeSuccess, InvokeError>;\n readonly activateTrigger: (\n request: RuntimeWebhookActivationRequest,\n ) => Effect.Effect<Trigger.ActivateSuccess, unknown>;\n readonly deactivateTrigger: (\n request: RuntimeWebhookActivationRequest,\n ) => Effect.Effect<Trigger.DeactivateSuccess, unknown>;\n readonly verifyTrigger: (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.VerifySuccess, unknown>;\n readonly parseTrigger: (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.EmittedEventsSuccess<string, \"parse\">, unknown>;\n readonly pollTrigger: (\n request: RuntimeTriggerLifecycleRequest,\n ) => Effect.Effect<Trigger.EmittedEventsSuccess<string, \"poll\">, unknown>;\n readonly getAuthMethod: (\n request: AuthMethodRequest,\n ) => Effect.Effect<AuthMethod.Any, AuthMethodNotFoundError>;\n // TODO(live-schema-validation): expose live action/trigger schema decoders by capability version.\n // Server authoring/runtime must validate against SDK declarations, not JSON Schema projections.\n readonly decodeAuthMethodSetup: (\n request: DecodeAuthMethodSetupRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly prepareAuthMethod: (\n request: PrepareAuthMethodRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly prepareOAuth2Tokens: (\n request: PrepareOAuth2TokensRequest,\n ) => Effect.Effect<unknown, AuthMethodExecutionError>;\n readonly refreshAuthMethod: (\n request: RefreshAuthMethodRequest,\n ) => Effect.Effect<unknown | undefined, AuthMethodExecutionError>;\n readonly resolveAuthMethod: (\n request: ResolveAuthMethodRequest,\n ) => Effect.Effect<AuthMethodBinding.Binding, AuthMethodExecutionError>;\n readonly allowedModelIdsFor: (providerId: string) => AiProvider.AllowedModelIds | undefined;\n readonly resolveAiModelConfig: (\n request: ResolveAiModelConfigRequest,\n ) => Effect.Effect<AiProvider.RuntimeConfig, AiModelConfigError>;\n readonly resolveSandboxAccess: (\n request: ResolveAuthMethodRequest,\n ) => Effect.Effect<ResolvedSandboxAccess, SandboxAccessError>;\n}\n\n/**\n * Effect service provided by {@link toLayer}.\n *\n * @since 0.0.0\n * @category services\n */\nexport class Service extends Context.Service<Service, RuntimeService>()(\n \"@dual-os/sdk/Dual/Service\",\n) {}\n\nexport type RuntimeRequirementsFor<P extends Plugin.Any> =\n | AgentChannelRuntime.Requirements<P>\n | (P extends Plugin.Any ? PluginRequirements<P, PluginActions<P>> : never);\n\ntype AuthProvider = Plugin.Any | AiProvider.Any;\n\ntype AuthMethodFor<Providers extends AuthProvider> = Providers[\"authMethods\"][number];\n\ntype AuthMethodSetupDecodeRequirements<Method extends AuthMethod.Any> =\n AuthMethod.SetupSchema<Method> extends Schema.Top\n ? Schema.Codec.DecodingServices<AuthMethod.SetupSchema<Method>>\n : never;\n\ntype AuthMethodInputDecodeRequirements<Method extends AuthMethod.Any> =\n AuthMethod.InputSchema<Method> extends Schema.Top\n ? Schema.Codec.DecodingServices<AuthMethod.InputSchema<Method>>\n : never;\n\ntype AuthMethodExecutionRequirementsFor<Providers extends AuthProvider> =\n AuthMethodFor<Providers> extends infer Method\n ? Method extends AuthMethod.Any\n ?\n | AuthMethod.Requirements<Method>\n | AuthMethodSetupDecodeRequirements<Method>\n | AuthMethodInputDecodeRequirements<Method>\n | Schema.Codec.DecodingServices<AuthMethod.MaterialSchema<Method>>\n | Schema.Codec.DecodingServices<AuthMethod.ValueSchema<Method>>\n | Schema.Codec.EncodingServices<AuthMethod.MaterialSchema<Method>>\n | Schema.Codec.EncodingServices<AuthMethod.ValueSchema<Method>>\n | (AuthMethod.SetupSchema<Method> extends Schema.Top\n ? Schema.Codec.EncodingServices<AuthMethod.SetupSchema<Method>>\n : never)\n : never\n : never;\n\n/**\n * Requirements still needed by {@link toLayer} for an app.\n *\n * Hosts (the server, a worker, a test harness) never know an app's concrete\n * implementations: they talk to it exclusively through the generic\n * {@link Service} layer. App-specific dependencies — a plugin's API client, an\n * auth hook's token service — are discharged where they are known, at the\n * plugin or app definition (the `Exclude<..., LayerOutput>` below cancels\n * them). Only what the definition did not discharge surfaces here,\n * generically, and the host entrypoint forces it to `never` before anything\n * runs.\n *\n * @since 0.0.0\n * @category type-level\n */\nexport type ToLayerRequirements<A extends AnyApp> =\n A extends App<\n infer P extends Plugin.Any,\n infer LayerOutput,\n any,\n infer LayerRequirements,\n infer AiProviders extends readonly AiProvider.Any[]\n >\n ?\n | LayerRequirements\n | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n | Exclude<AuthMethodExecutionRequirementsFor<P | AiProviders[number]>, LayerOutput>\n : never;\n\n/**\n * Layer-construction errors surfaced by {@link toLayer} for an app.\n *\n * @since 0.0.0\n * @category type-level\n */\nexport type ToLayerError<A extends AnyApp> =\n A extends App<any, any, infer LayerError, any, any> ? LayerError : never;\n\n/**\n * Turn an {@link App} into a runtime Effect service layer.\n *\n * @since 0.0.0\n * @category layers\n */\nexport const toLayer = <\n const P extends Plugin.Any,\n LayerOutput,\n LayerError,\n LayerRequirements,\n const AiProviders extends readonly AiProvider.Any[],\n>(\n app: App<P, LayerOutput, LayerError, LayerRequirements, AiProviders>,\n): Layer.Layer<\n Service,\n LayerError,\n | LayerRequirements\n | Exclude<RuntimeRequirementsFor<P>, LayerOutput>\n | Exclude<AuthMethodExecutionRequirementsFor<P | AiProviders[number]>, LayerOutput>\n> => {\n const fullAuthMethodId = (providerId: string, method: AuthMethod.Any): string =>\n `${providerId}/${method.identifier}`;\n\n const findAuthMethod = (\n providerId: string,\n authMethodId: string,\n ): Effect.Effect<AuthMethod.Any, AuthMethodNotFoundError> => {\n const provider =\n pluginOf(app, providerId) ??\n app.aiProviders.find(candidate => AiProvider.registryId(candidate.identifier) === providerId);\n const method = provider?.authMethods.find(\n candidate =>\n candidate.identifier === authMethodId ||\n fullAuthMethodId(providerId, candidate) === authMethodId,\n );\n\n return method === undefined\n ? Effect.fail(new AuthMethodNotFoundError({ authMethodId, providerId }))\n : Effect.succeed(method);\n };\n\n const serviceLayer = Layer.effect(\n Service,\n Effect.gen(function* () {\n const channels = yield* AgentChannelRuntime.Service;\n const context = yield* Effect.context<\n RuntimeRequirementsFor<P> | AuthMethodExecutionRequirementsFor<P | AiProviders[number]>\n >();\n\n const appContext = indexGroups(context);\n\n const provideRuntimeContext = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(Effect.updateContext(input => Context.merge(appContext, input)));\n\n // Requirements are satisfied by the context captured at layer build time;\n // the cast erases them so service methods expose closed effects.\n const runWithCapturedAppContext = <A, E>(\n effect: Effect.Effect<A, E, unknown>,\n ): Effect.Effect<A, E> => provideRuntimeContext(effect) as never;\n\n const getAuthMethod = (request: AuthMethodRequest) =>\n findAuthMethod(request.providerId, request.authMethodId);\n\n const getTrigger = (request: RuntimeTriggerLifecycleRequest) => {\n const resolved = resolveRuntimeTrigger(\n app.plugins,\n request.triggerId,\n request.triggerVersion,\n );\n return resolved === undefined ||\n (request.pluginKey !== undefined && resolved.providerId !== request.pluginKey)\n ? Effect.fail(new TriggerNotFoundError({ triggerId: request.triggerId }))\n : Effect.succeed(resolved);\n };\n\n const triggerLifecycleRequest = (\n request: RuntimeTriggerLifecycleRequest,\n ): Trigger.LifecycleRequest => ({\n config: request.config,\n ...(request.state === undefined ? {} : { state: request.state }),\n ...(request.connectionId === undefined ? {} : { connectionId: request.connectionId }),\n ...(request.context === undefined ? {} : { context: request.context }),\n });\n\n const webhookActivationRequest = (\n request: RuntimeWebhookActivationRequest,\n ): Trigger.WebhookActivationRequest => ({\n ...triggerLifecycleRequest(request),\n webhookUrl: request.webhookUrl,\n });\n\n // A host can pass the raw body as text; handlers verify signatures over its bytes.\n const webhookTriggerLifecycleRequest = (\n request: RuntimeWebhookTriggerLifecycleRequest,\n ): Trigger.WebhookExecutionRequest => ({\n ...webhookActivationRequest(request),\n request: Predicate.isString(request.request.rawBody)\n ? { ...request.request, rawBody: new TextEncoder().encode(request.request.rawBody) }\n : request.request,\n });\n\n const activateTrigger = (request: RuntimeWebhookActivationRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.activate(entry, webhookActivationRequest(request));\n }),\n );\n\n const deactivateTrigger = (request: RuntimeWebhookActivationRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.deactivate(entry, webhookActivationRequest(request));\n }),\n );\n\n const verifyTrigger = (request: RuntimeWebhookTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.verify(entry, webhookTriggerLifecycleRequest(request));\n }),\n );\n\n const parseTrigger = (request: RuntimeWebhookTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.parse(entry, webhookTriggerLifecycleRequest(request));\n }),\n );\n\n const pollTrigger = (request: RuntimeTriggerLifecycleRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const entry = yield* getTrigger(request);\n return yield* Trigger.poll(entry, triggerLifecycleRequest(request));\n }),\n );\n\n const decodeAuthMethodSetup = (request: DecodeAuthMethodSetupRequest) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method => {\n if (request.encoding === \"json\" && method.setup !== undefined) {\n return Schema.decodeUnknownEffect(Schema.toCodecJson(method.setup))(request.setup);\n }\n return AuthMethodExecution.decodeSetup(method, request.setup);\n }),\n ),\n );\n\n const withAuthMethodSetup = <A, E, R>(\n request: DecodeAuthMethodSetupRequest,\n execute: (\n method: AuthMethod.Any,\n setup: AuthMethod.Setup<AuthMethod.Any>,\n ) => Effect.Effect<A, E, R>,\n ) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method =>\n AuthMethodExecution.decodeSetup(method, request.setup).pipe(\n Effect.flatMap(setup => execute(method, setup)),\n ),\n ),\n ),\n );\n\n const prepareAuthMethod = (request: PrepareAuthMethodRequest) =>\n withAuthMethodSetup(request, (method, setup) =>\n AuthMethodExecution.prepare(method, request.input, { setup }),\n );\n\n const prepareOAuth2Tokens = (request: PrepareOAuth2TokensRequest) =>\n withAuthMethodSetup(request, (method, setup) =>\n AuthMethodExecution.prepareOAuth2Tokens(method, request.tokens, { setup }),\n );\n\n const refreshAuthMethod = (request: RefreshAuthMethodRequest) =>\n runWithCapturedAppContext(\n getAuthMethod(request).pipe(\n Effect.flatMap(method =>\n AuthMethodExecution.decodeSetup(method, request.setup).pipe(\n Effect.flatMap(setup =>\n AuthMethodExecution.refreshUnknown(method, request.material, {\n minValidityMs: request.minValidityMs,\n now: request.now,\n reason: request.reason,\n setup,\n }),\n ),\n ),\n ),\n ),\n );\n\n const resolveAuthMethod = (request: ResolveAuthMethodRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const method = yield* getAuthMethod(request);\n const setup = yield* decodeAuthMethodSetup(request);\n const value =\n request.encoding === \"json\"\n ? yield* AuthMethodExecution.resolveDecoded(\n method,\n yield* Schema.decodeUnknownEffect(Schema.toCodecJson(method.material))(\n request.material,\n ),\n { setup },\n )\n : yield* AuthMethodExecution.resolve(method, request.material, { setup });\n return AuthMethodBinding.makeBinding({\n connectionId: undefined,\n method,\n providerId: request.providerId,\n value,\n });\n }),\n );\n\n const resolveAiModelConfig = (request: ResolveAiModelConfigRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const provider = app.aiProviders.find(\n candidate => AiProvider.registryId(candidate.identifier) === request.providerId,\n );\n if (provider?.resolveRuntimeConfig === undefined) {\n return yield* new AiProviderRuntimeNotConfiguredError({\n providerId: request.providerId,\n });\n }\n const binding = yield* resolveAuthMethod(request);\n const allowed = provider.allowedModelIds?.(request.material);\n if (allowed !== undefined && !allowed.includes(request.model.id)) {\n return yield* new AiModelNotAllowedError({\n modelId: request.model.id,\n providerId: request.providerId,\n });\n }\n // SAFETY: the resolver belongs to this provider and the binding was\n // resolved from the same provider's declared auth-method list.\n const resolveRuntimeConfig =\n provider.resolveRuntimeConfig as AiProvider.RuntimeConfigResolver<\n readonly AuthMethod.Any[]\n >;\n return yield* Schema.decodeUnknownEffect(AiProvider.RuntimeConfig)(\n resolveRuntimeConfig({ binding, model: request.model }),\n );\n }),\n );\n\n const resolveSandboxAccess = (request: ResolveAuthMethodRequest) =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const access = pluginOf(app, request.providerId)?.sandboxAccess;\n if (access === undefined) {\n return yield* new SandboxAccessNotDeclaredError({ providerId: request.providerId });\n }\n const context = authRuntimeContext(yield* resolveAuthMethod(request));\n // Declared origins compare as URL origins, so `https://GHES.example:443` matches requests.\n const origins = Array.map(\n access.origins(context),\n origin => Result.getOrUndefined(Url.fromString(origin))?.origin ?? origin,\n );\n const authorize = (outgoing: HttpClientRequest.HttpClientRequest) => {\n const url = Result.getOrUndefined(Url.fromString(outgoing.url));\n const refused = new SandboxRequestNotAllowedError({\n origin: url?.origin ?? outgoing.url,\n path: url?.pathname ?? \"\",\n providerId: request.providerId,\n });\n if (url === undefined || !origins.includes(url.origin)) return Effect.fail(refused);\n return Effect.fromOption(access.authorize(outgoing, context), () => refused);\n };\n return { authorize, origins } satisfies ResolvedSandboxAccess;\n }),\n );\n\n return Service.of({\n activateTrigger,\n checkAccessAgentChannel: channels.checkAccess,\n deactivateTrigger,\n decodeAgentChannelDefinitionSettings: channels.decodeDefinitionSettings,\n decodeAgentChannelDeploymentSettings: channels.decodeDeploymentSettings,\n decodeAuthMethodSetup,\n executeAgentChannel: channels.execute,\n executeAuthJson: request =>\n runWithCapturedAppContext(\n pipe(\n getAuthMethod(request),\n Effect.flatMap(method => AuthMethodExecution.executeJson(method, request)),\n ),\n ),\n getAgentChannel: channels.get,\n getAuthMethod,\n invoke: request => runWithCapturedAppContext(invokeRaw(app, request)),\n invokeJson: request =>\n runWithCapturedAppContext(\n Effect.gen(function* () {\n const result = yield* invokeRaw(app, request, true);\n return {\n ...result,\n data: yield* Schema.decodeUnknownEffect(Schema.Json)(result.data),\n };\n }),\n ),\n parseTrigger,\n pollTrigger,\n prepareAuthMethod,\n prepareOAuth2Tokens,\n refreshAuthMethod,\n allowedModelIdsFor: providerId =>\n app.aiProviders.find(\n provider => AiProvider.registryId(provider.identifier) === providerId,\n )?.allowedModelIds,\n resolveAiModelConfig,\n resolveAuthMethod,\n resolveSandboxAccess,\n verifyTrigger,\n });\n }),\n );\n\n return serviceLayer.pipe(\n Layer.provide(AgentChannelRuntime.layer(app.plugins.map(installation => installation.plugin))),\n Layer.provide(app.layer),\n );\n};\n\nexport * as DualRuntime from \"./DualRuntime.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,MAAa,WACX,QACA,aAC2B;CAAE;CAAQ;AAAQ;;;;;;;;AAS/C,MAAa,cACX,QACA,UAAU,aAQT;CACC,aAAa,CAAC;CACd,YAAY,OAAO;CACnB,OAAO,OAAO;CACd,SAAS,CAAC,QAAQ,QAAQ,OAAO,CAAC;AACpC;;;;;;;AAQF,MAAa,QAAQ,gBAAsE;CACzF,aAAa,CAAC;CACd;CACA,OAAO,MAAM;CACb,SAAS,CAAC;AACZ;AAkEA,SAAS,WAAW,KAAa,SAAyC;CACxE,MAAM,OAAO,IAAI,IAAI,MAAM,IAAI,IAAI,UAAS,iBAAgB,aAAa,OAAO,UAAU,CAAC;CAC3F,KAAK,MAAM,CAAC,WAAW,SAAS;EAC9B,IAAI,KAAK,IAAI,OAAO,UAAU,GAC5B,MAAM,IAAI,sBAAsB;GAC9B,WAAW;GACX,mBAAmB;GACnB,YAAY,OAAO;GACnB,iBAAiB,IAAI;GACrB,WAAW;EACb,CAAC;EAEH,KAAK,IAAI,OAAO,UAAU;CAC5B;CACA,OAAO;EACL,GAAG;EACH,OAAO,MAAM,OAAO,SAAS,IAAI,QAAQ,OAAO,CA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I,YAAY,MACd,aAAYhB,WAAsB,SAAS,UAAU,MAAM,UAC7D,CAAC,EAAE;GACL;GACA;GACA;GACA;EACF,CAAC;CACH,CAAC,CAGe,CAAC,CAAC,KAClB,MAAM,QAAQiB,MAA0B,IAAI,QAAQ,KAAI,iBAAgB,aAAa,MAAM,CAAC,CAAC,GAC7F,MAAM,QAAQ,IAAI,KAAK,CACzB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dual-os/sdk",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "license": "UNLICENSED",
5
5
  "files": [
6
6
  "dist/**/*.js",
@@ -1,6 +1,6 @@
1
1
  /** Provider-neutral external Agent Channel contracts. @since 0.0.0 */
2
2
  import type { Context, Effect, Pipeable, SchemaAST } from "effect";
3
- import { Match, Predicate, Schema } from "effect";
3
+ import { Match, Option, Predicate, Schema } from "effect";
4
4
 
5
5
  import * as AuthMethod from "./AuthMethod.ts";
6
6
  import { Files } from "./Files.ts";
@@ -43,7 +43,11 @@ export const Features = Schema.Struct({
43
43
  operations: Schema.optionalKey(Schema.Array(OperationKind)),
44
44
  /** Whether `read_context` returns the conversation's earlier messages. */
45
45
  readContext: Schema.optionalKey(Schema.Boolean),
46
+ /** Whether `read_sender` names a sender its messages do not; requires `senderDetails`. */
47
+ readSender: Schema.optionalKey(Schema.Boolean),
46
48
  replies: Schema.Boolean,
49
+ /** Whether messages and context messages may name their sender beyond `senderKey`. */
50
+ senderDetails: Schema.optionalKey(Schema.Boolean),
47
51
  /** Maximum age of the original responding input before preparation and delivery. */
48
52
  responseWindowMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
49
53
  threads: Schema.Boolean,
@@ -151,6 +155,55 @@ export const Timestamp = Schema.String.check(
151
155
  }),
152
156
  );
153
157
  export const VerifiedIdentity = Schema.Struct({ conversation: Destination, senderKey: Key });
158
+ const DisplayText = Schema.NonEmptyString.check(
159
+ Schema.isMaxLength(256),
160
+ Schema.isPattern(/^[^\p{Cc}]+$/u),
161
+ );
162
+ const SenderEmail = Schema.NonEmptyString.check(
163
+ Schema.isMaxLength(320),
164
+ Schema.isPattern(/^[^\s@\p{Cc}]+@[^\s@\p{Cc}]+$/u),
165
+ );
166
+ /** What a provider says about a sender besides `senderKey`, the ID to act on; none grants. */
167
+ export const SenderDetails = Schema.Struct({
168
+ /** An address the provider lists for the sender. */
169
+ senderEmail: Schema.optionalKey(SenderEmail),
170
+ /** The name others mention the sender by, such as a username, without a leading `@`. */
171
+ senderHandle: Schema.optionalKey(DisplayText),
172
+ senderName: Schema.optionalKey(DisplayText),
173
+ });
174
+ export type SenderDetails = typeof SenderDetails.Type;
175
+ // Whole characters only, so a cut never splits a surrogate pair.
176
+ const clip = (text: string, max: number) => {
177
+ let kept = "";
178
+ for (const character of text) {
179
+ if (kept.length + character.length > max) break;
180
+ kept += character;
181
+ }
182
+ return kept;
183
+ };
184
+ const display = (value: string | null | undefined) =>
185
+ Option.liftPredicate(
186
+ clip((value ?? "").replace(/\p{Cc}+/gu, " ").trim(), 256).trim(),
187
+ text => text !== "",
188
+ );
189
+ /**
190
+ * Sender details from a provider's raw values: names trimmed, without control characters and cut
191
+ * to 256 characters, a handle without its leading `@`; an empty value or an invalid email is left out.
192
+ */
193
+ export const senderDetails = (values: {
194
+ readonly email?: string | null | undefined;
195
+ readonly handle?: string | null | undefined;
196
+ readonly name?: string | null | undefined;
197
+ }): SenderDetails => {
198
+ const email = Option.liftPredicate((values.email ?? "").trim(), Schema.is(SenderEmail));
199
+ const handle = display((values.handle ?? "").replace(/^@+/u, ""));
200
+ const name = display(values.name);
201
+ return {
202
+ ...Option.match(email, { onNone: () => ({}), onSome: senderEmail => ({ senderEmail }) }),
203
+ ...Option.match(handle, { onNone: () => ({}), onSome: senderHandle => ({ senderHandle }) }),
204
+ ...Option.match(name, { onNone: () => ({}), onSome: senderName => ({ senderName }) }),
205
+ };
206
+ };
154
207
  export type VerifiedIdentity = typeof VerifiedIdentity.Type;
155
208
  export const AccessOutcome = Schema.Struct({ decision: Schema.Literals(["allow", "deny"]) });
156
209
  export type AccessOutcome = typeof AccessOutcome.Type;
@@ -158,7 +211,7 @@ export const Verification = Schema.Struct({ verified: Schema.Literal(true) });
158
211
  export type Verification = typeof Verification.Type;
159
212
  export const Exposure = Schema.Literals(["webhook", "host"]);
160
213
  export const RequiredChecks = Schema.Tuple([Schema.Literal("access")]);
161
- export const Message = Schema.Struct({
214
+ const messageFields = {
162
215
  content: Content,
163
216
  conversation: Destination,
164
217
  eventKey: Key,
@@ -168,7 +221,11 @@ export const Message = Schema.Struct({
168
221
  respond: Schema.Boolean,
169
222
  senderKey: Key,
170
223
  timestamp: Timestamp,
171
- });
224
+ };
225
+ /** Published contracts of versions without `senderDetails` keep this shape. */
226
+ const KeyedMessage = Schema.Struct(messageFields);
227
+ /** A message; sender details only where a version declares `senderDetails`. */
228
+ export const Message = Schema.Struct({ ...messageFields, ...SenderDetails.fields });
172
229
  export const DeliveryUpdate = Schema.Struct({
173
230
  deliveryKey: Key,
174
231
  deliveryUpdateKey: Key,
@@ -199,6 +256,7 @@ export const Stop = Schema.Struct({
199
256
  });
200
257
  export const Event = Schema.Union([Message, Echo, DeliveryUpdate, Stop]);
201
258
  export type Event = typeof Event.Type;
259
+ const KeyedEvent = Schema.Union([KeyedMessage, Echo, DeliveryUpdate, Stop]);
202
260
 
203
261
  /** The reactions every provider can show. Each provider maps them to its own emoji. */
204
262
  export const Reaction = Schema.Literals([
@@ -297,14 +355,31 @@ const contextMessageFields = {
297
355
  text: Text,
298
356
  timestamp: Timestamp,
299
357
  };
300
- /** Published contracts of versions without both `assets` and `readContext` keep this shape. */
301
- const TextContextMessage = Schema.Struct(contextMessageFields);
302
- /** A message read back from history; `assets` only where a version declares assets and context. */
358
+ const contextAssets = {
359
+ assets: Schema.optionalKey(Schema.Array(Asset).check(Schema.isMaxLength(20))),
360
+ };
361
+ const contextSender = {
362
+ senderEmail: SenderDetails.fields.senderEmail,
363
+ senderHandle: SenderDetails.fields.senderHandle,
364
+ };
365
+ /** A message read back from history; each optional group only where its features allow it. */
303
366
  export const ContextMessage = Schema.Struct({
304
367
  ...contextMessageFields,
305
- assets: Schema.optionalKey(Schema.Array(Asset).check(Schema.isMaxLength(20))),
368
+ ...contextAssets,
369
+ ...contextSender,
306
370
  });
307
371
  export type ContextMessage = typeof ContextMessage.Type;
372
+ // Published contracts keep the shape their features had before each optional field existed.
373
+ const TextContextMessage = Schema.Struct(contextMessageFields);
374
+ const AssetContextMessage = Schema.Struct({ ...contextMessageFields, ...contextAssets });
375
+ const SenderContextMessage = Schema.Struct({ ...contextMessageFields, ...contextSender });
376
+ const contextMessageFor = (features: Features) => {
377
+ const sender = features.senderDetails === true;
378
+ if (features.assets && features.readContext === true) {
379
+ return sender ? ContextMessage : AssetContextMessage;
380
+ }
381
+ return sender ? SenderContextMessage : TextContextMessage;
382
+ };
308
383
 
309
384
  /** Decoded originals are limited separately by the host; ordinary command JSON stays bounded. */
310
385
  export const AssetFile = Files.File.check(
@@ -395,7 +470,9 @@ const installedResultSchema = <State extends Schema.Top>(state: State, features?
395
470
  ...operation,
396
471
  verified: Schema.Literal(true),
397
472
  deniedEventKeys: Schema.optionalKey(Schema.Array(Key).check(Schema.isMaxLength(100))),
398
- events: Schema.Array(Event).check(Schema.isMaxLength(100)),
473
+ events: Schema.Array(
474
+ features === undefined || features.senderDetails === true ? Event : KeyedEvent,
475
+ ).check(Schema.isMaxLength(100)),
399
476
  response: Schema.optionalKey(WebhookResponse),
400
477
  /** A provider-native setup challenge or ping proved the configured ingress. */
401
478
  activationProof: Schema.optionalKey(Schema.Literal("verified")),
@@ -432,9 +509,7 @@ const installedResultSchema = <State extends Schema.Top>(state: State, features?
432
509
  ...operation,
433
510
  // Without a version's features, any checked result: the host reads every version's.
434
511
  messages: Schema.Array(
435
- features === undefined || (features.assets && features.readContext === true)
436
- ? ContextMessage
437
- : TextContextMessage,
512
+ features === undefined ? ContextMessage : contextMessageFor(features),
438
513
  ).check(Schema.isMaxLength(200)),
439
514
  }),
440
515
  ]);
@@ -456,11 +531,40 @@ const readAssetResult = Schema.Struct({
456
531
  kind: Schema.Literal("read_asset"),
457
532
  operationKey: Key,
458
533
  });
459
- export const commandSchema = <State extends Schema.Top>(state: State) =>
460
- Schema.Union([installedCommandSchema(state), readAssetCommand(state)]);
534
+ /** What the provider says about the sender of `identity`, after the host checks its access. */
535
+ const readSenderCommand = <State extends Schema.Top>(state: State) =>
536
+ Schema.Struct({
537
+ extensions: Schema.optionalKey(Extensions),
538
+ identity: VerifiedIdentity,
539
+ installationKey: Key,
540
+ kind: Schema.Literal("read_sender"),
541
+ operationKey: Key,
542
+ state,
543
+ });
544
+ const readSenderResult = Schema.Struct({
545
+ ...SenderDetails.fields,
546
+ extensions: Schema.optionalKey(Extensions),
547
+ kind: Schema.Literal("read_sender"),
548
+ operationKey: Key,
549
+ senderKey: Key,
550
+ });
551
+ // Without a version's features, every command and result: the host reads every version's.
552
+ const readsSender = (features: Features | undefined) =>
553
+ features === undefined || features.readSender === true;
554
+ /** Pass a version's features to check its commands against its own contract. */
555
+ export const commandSchema = <State extends Schema.Top>(state: State, features?: Features) =>
556
+ Schema.Union([
557
+ installedCommandSchema(state),
558
+ readAssetCommand(state),
559
+ ...(readsSender(features) ? ([readSenderCommand(state)] as const) : ([] as const)),
560
+ ]);
461
561
  /** Pass a version's features to check its results against its own contract. */
462
562
  export const resultSchema = <State extends Schema.Top>(state: State, features?: Features) =>
463
- Schema.Union([installedResultSchema(state, features), readAssetResult]);
563
+ Schema.Union([
564
+ installedResultSchema(state, features),
565
+ readAssetResult,
566
+ ...(readsSender(features) ? ([readSenderResult] as const) : ([] as const)),
567
+ ]);
464
568
  export type Command<State extends Schema.Top = Schema.Unknown> = ReturnType<
465
569
  typeof commandSchema<State>
466
570
  >["Type"];
@@ -540,7 +644,7 @@ export const projectContract = (
540
644
  Object.entries(definition.extensions ?? {}).map(([key, schema]) => [key, project(schema)]),
541
645
  ),
542
646
  featuresJson: definition.features,
543
- operationInputSchemaJson: project(commandSchema(definition.state)),
647
+ operationInputSchemaJson: project(commandSchema(definition.state, definition.features)),
544
648
  operationOutputSchemaJson: project(resultSchema(definition.state, definition.features)),
545
649
  requiredChecks: definition.requiredChecks,
546
650
  stateSchemaJson: project(definition.state),
@@ -689,7 +793,9 @@ const DefinitionSchema = Schema.Struct({
689
793
  operations.includes("present_outcome") &&
690
794
  new Set(operations).size === operations.length &&
691
795
  // A long text arrives as messages before its outcome.
692
- (features.maxTextLength === undefined || operations.includes("create_message"))
796
+ (features.maxTextLength === undefined || operations.includes("create_message")) &&
797
+ // What a read finds about a sender, its messages may carry too.
798
+ (features.readSender !== true || features.senderDetails === true)
693
799
  );
694
800
  }),
695
801
  );
@@ -415,6 +415,12 @@ export const layer = <P extends Plugin.Any>(
415
415
  ) {
416
416
  return yield* fail("unsupported_feature");
417
417
  }
418
+ if (
419
+ (command.kind === "read_asset" && !definition.features.assets) ||
420
+ (command.kind === "read_sender" && definition.features.readSender !== true)
421
+ ) {
422
+ return yield* fail("unsupported_feature");
423
+ }
418
424
  const handler = Option.fromNullishOr(
419
425
  findHandler(
420
426
  context,
@@ -436,6 +442,7 @@ export const layer = <P extends Plugin.Any>(
436
442
  const kind = command.kind;
437
443
  const deliveryKey = command.kind === "deliver" ? command.deliveryKey : undefined;
438
444
  const assetKey = command.kind === "read_asset" ? command.asset.assetKey : undefined;
445
+ const senderKey = command.kind === "read_sender" ? command.identity.senderKey : undefined;
439
446
  const adapterContext = {
440
447
  definitionSettings,
441
448
  deploymentSettings,
@@ -458,8 +465,8 @@ export const layer = <P extends Plugin.Any>(
458
465
  "invalid_result",
459
466
  );
460
467
  }
461
- if (command.kind === "read_asset") {
462
- if (!definition.features.assets) return yield* fail("unsupported_feature");
468
+ // A read on behalf of a sender acts for that sender, so the sender must have access.
469
+ if (command.kind === "read_asset" || command.kind === "read_sender") {
463
470
  const decision = yield* decodeData(
464
471
  AgentChannel.AccessOutcome,
465
472
  yield* invokeHandler(
@@ -491,7 +498,8 @@ export const layer = <P extends Plugin.Any>(
491
498
  result.kind !== kind ||
492
499
  result.operationKey !== operationKey ||
493
500
  (result.kind === "deliver" && result.deliveryKey !== deliveryKey) ||
494
- (result.kind === "read_asset" && result.assetKey !== assetKey)
501
+ (result.kind === "read_asset" && result.assetKey !== assetKey) ||
502
+ (result.kind === "read_sender" && result.senderKey !== senderKey)
495
503
  ) {
496
504
  return yield* fail("invalid_result");
497
505
  }
package/src/AiProvider.ts CHANGED
@@ -35,9 +35,13 @@ export interface Any extends Pipeable.Pipeable {
35
35
  readonly homepageUrl: string | undefined;
36
36
  readonly docsUrl: string | undefined;
37
37
  readonly authMethods: readonly AuthMethod.Any[];
38
+ readonly allowedModelIds?: AllowedModelIds | undefined;
38
39
  readonly resolveRuntimeConfig: unknown;
39
40
  }
40
41
 
42
+ /** Projects allowed model IDs from stored credential material. Undefined permits every catalog model. */
43
+ export type AllowedModelIds = (material: unknown) => readonly string[] | undefined;
44
+
41
45
  /** @since 0.0.0 @category models */
42
46
  export const RuntimeConfig = Schema.Struct({
43
47
  apiKey: Schema.optional(Schema.String),
@@ -76,6 +80,7 @@ export interface AiProviderOptions<Identifier extends string = string> {
76
80
  readonly categories?: readonly Category[];
77
81
  readonly homepageUrl?: string;
78
82
  readonly docsUrl?: string;
83
+ readonly allowedModelIds?: AllowedModelIds;
79
84
  }
80
85
 
81
86
  /** @since 0.0.0 @category models */
@@ -94,6 +99,7 @@ export interface AiProvider<
94
99
  readonly homepageUrl: string | undefined;
95
100
  readonly docsUrl: string | undefined;
96
101
  readonly authMethods: AuthMethods;
102
+ readonly allowedModelIds?: AllowedModelIds | undefined;
97
103
  readonly resolveRuntimeConfig: RuntimeConfigResolver<AuthMethods> | undefined;
98
104
  }
99
105
 
@@ -112,6 +118,7 @@ const optionsFromProvider = (provider: Any): AiProviderOptions => ({
112
118
  ...(provider.categories.length === 0 ? {} : { categories: provider.categories }),
113
119
  ...(provider.homepageUrl === undefined ? {} : { homepageUrl: provider.homepageUrl }),
114
120
  ...(provider.docsUrl === undefined ? {} : { docsUrl: provider.docsUrl }),
121
+ ...(provider.allowedModelIds === undefined ? {} : { allowedModelIds: provider.allowedModelIds }),
115
122
  });
116
123
 
117
124
  const Proto = { ...PipeableProto, [TypeId]: TypeId };
@@ -125,6 +132,7 @@ const makeProvider = <Identifier extends string, AuthMethods extends readonly Au
125
132
  assertNoDuplicateAuthMethodIdentifiers(options.identifier, authMethods);
126
133
 
127
134
  return Object.assign(Object.create(Proto), {
135
+ allowedModelIds: options.allowedModelIds,
128
136
  authMethods,
129
137
  categories: options.categories ?? [],
130
138
  description: options.description,
@@ -159,6 +167,14 @@ const withOption = <P extends AiProvider<any, any>>(
159
167
  provider.resolveRuntimeConfig,
160
168
  ) as P;
161
169
 
170
+ /** @since 0.0.0 @category combinators */
171
+ export const withAllowedModelIds: {
172
+ (resolve: AllowedModelIds): <Self extends Any>(provider: Self) => Self;
173
+ <Self extends Any>(provider: Self, resolve: AllowedModelIds): Self;
174
+ } = Func.dual(2, (provider: AiProvider<any, any>, allowedModelIds: AllowedModelIds) =>
175
+ withOption(provider, { allowedModelIds }),
176
+ );
177
+
162
178
  /** @since 0.0.0 @category combinators */
163
179
  export const withName: {
164
180
  (name: string): <P extends AiProvider<any, any>>(provider: P) => P;
@@ -588,7 +588,15 @@ export class AiProviderRuntimeNotConfiguredError extends Schema.TaggedError<AiPr
588
588
  { providerId: Schema.String },
589
589
  ) {}
590
590
 
591
- export type AiModelConfigError = AuthMethodExecutionError | AiProviderRuntimeNotConfiguredError;
591
+ export class AiModelNotAllowedError extends Schema.TaggedError<AiModelNotAllowedError>()(
592
+ "AiModelNotAllowedError",
593
+ { modelId: Schema.String, providerId: Schema.String },
594
+ ) {}
595
+
596
+ export type AiModelConfigError =
597
+ | AuthMethodExecutionError
598
+ | AiProviderRuntimeNotConfiguredError
599
+ | AiModelNotAllowedError;
592
600
 
593
601
  /** Raised when a provider declares no sandbox access. */
594
602
  export class SandboxAccessNotDeclaredError extends Schema.TaggedError<SandboxAccessNotDeclaredError>()(
@@ -666,6 +674,7 @@ export interface RuntimeService {
666
674
  readonly resolveAuthMethod: (
667
675
  request: ResolveAuthMethodRequest,
668
676
  ) => Effect.Effect<AuthMethodBinding.Binding, AuthMethodExecutionError>;
677
+ readonly allowedModelIdsFor: (providerId: string) => AiProvider.AllowedModelIds | undefined;
669
678
  readonly resolveAiModelConfig: (
670
679
  request: ResolveAiModelConfigRequest,
671
680
  ) => Effect.Effect<AiProvider.RuntimeConfig, AiModelConfigError>;
@@ -992,6 +1001,13 @@ export const toLayer = <
992
1001
  });
993
1002
  }
994
1003
  const binding = yield* resolveAuthMethod(request);
1004
+ const allowed = provider.allowedModelIds?.(request.material);
1005
+ if (allowed !== undefined && !allowed.includes(request.model.id)) {
1006
+ return yield* new AiModelNotAllowedError({
1007
+ modelId: request.model.id,
1008
+ providerId: request.providerId,
1009
+ });
1010
+ }
995
1011
  // SAFETY: the resolver belongs to this provider and the binding was
996
1012
  // resolved from the same provider's declared auth-method list.
997
1013
  const resolveRuntimeConfig =
@@ -1064,6 +1080,10 @@ export const toLayer = <
1064
1080
  prepareAuthMethod,
1065
1081
  prepareOAuth2Tokens,
1066
1082
  refreshAuthMethod,
1083
+ allowedModelIdsFor: providerId =>
1084
+ app.aiProviders.find(
1085
+ provider => AiProvider.registryId(provider.identifier) === providerId,
1086
+ )?.allowedModelIds,
1067
1087
  resolveAiModelConfig,
1068
1088
  resolveAuthMethod,
1069
1089
  resolveSandboxAccess,