import type { AiAgentCallSettings, AiAgentRunChannel } from './agent-call-contract' export const AI_AGENT_RUN_DISPATCHER_DI_KEY = 'aiAgentRunDispatcher' export type AiAgentRunDispatchVia = 'route' | 'tool' export type AiAgentRunDispatchCaller = { tenantId: string organizationId: string userId: string | null apiKeyId: string | null features: string[] isSuperAdmin: boolean } export type AiAgentRunDispatchInput = { agentId: string input: unknown caller: AiAgentRunDispatchCaller channel: AiAgentRunChannel via: AiAgentRunDispatchVia correlationId: string callSettings?: AiAgentCallSettings timeoutMs: number signal?: AbortSignal } export type AiAgentRunDispatchUsage = { inputTokens?: number outputTokens?: number } export type AiAgentRunDispatchResult = { result: unknown agentRunId: string | null usage?: AiAgentRunDispatchUsage finishReason?: string | null } export interface AiAgentRunDispatcher { owns(agentId: string): boolean isAvailable(agentId: string): Promise runObject(input: AiAgentRunDispatchInput): Promise } /** * `agent_call_settings_unsupported`: the request carried call-time model settings the * agent's runtime cannot apply (an Agent Orchestrator agent on OpenCode). */ export type AiAgentDispatchDeniedCode = 'agent_invoke_denied' | 'agent_principal_missing' | 'agent_call_settings_unsupported' export class AiAgentDispatchDeniedError extends Error { readonly code: AiAgentDispatchDeniedCode readonly agentId: string constructor(code: AiAgentDispatchDeniedCode, agentId: string, message?: string) { super(message ?? `[internal] Agent dispatch denied (${code}) for agent ${agentId}`) this.name = 'AiAgentDispatchDeniedError' this.code = code this.agentId = agentId } } export function isAiAgentDispatchDeniedError(error: unknown): error is AiAgentDispatchDeniedError { return error instanceof AiAgentDispatchDeniedError } type DispatcherResolver = { resolve(name: string): T } function isAiAgentRunDispatcher(value: unknown): value is AiAgentRunDispatcher { if (!value || typeof value !== 'object') return false const candidate = value as Partial> return ( typeof candidate.owns === 'function' && typeof candidate.isAvailable === 'function' && typeof candidate.runObject === 'function' ) } export function resolveAiAgentRunDispatcher( container: DispatcherResolver | null | undefined, ): AiAgentRunDispatcher | null { if (!container) return null try { const dispatcher = container.resolve(AI_AGENT_RUN_DISPATCHER_DI_KEY) return isAiAgentRunDispatcher(dispatcher) ? dispatcher : null } catch { return null } } export type ResolveDispatchOwnerOptions = { knownLocally: boolean } export async function resolveDispatchOwner( dispatcher: AiAgentRunDispatcher | null | undefined, agentId: string, options: ResolveDispatchOwnerOptions, ): Promise { if (!dispatcher) return false if (dispatcher.owns(agentId)) return true if (options.knownLocally) return false try { return await dispatcher.isAvailable(agentId) } catch { return false } }