@open-mercato/ai-assistant 0.11.1-develop.8305.1.6a9c271838 → 0.11.1-develop.8317.1.dde3d38b64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/ai_assistant/lib/agent-policy.js.map +2 -2
- package/dist/modules/ai_assistant/lib/agent-runtime.js +7 -6
- package/dist/modules/ai_assistant/lib/agent-runtime.js.map +2 -2
- package/dist/modules/ai_assistant/lib/agent-tools.js +18 -5
- package/dist/modules/ai_assistant/lib/agent-tools.js.map +2 -2
- package/package.json +6 -6
- package/src/modules/ai_assistant/lib/__tests__/agent-runtime-object-channel.test.ts +51 -2
- package/src/modules/ai_assistant/lib/__tests__/agent-tool.test.ts +79 -1
- package/src/modules/ai_assistant/lib/__tests__/agent-tools.test.ts +99 -0
- package/src/modules/ai_assistant/lib/__tests__/direct-execution-approval-paths.test.ts +26 -0
- package/src/modules/ai_assistant/lib/agent-policy.ts +4 -2
- package/src/modules/ai_assistant/lib/agent-runtime.ts +8 -3
- package/src/modules/ai_assistant/lib/agent-tools.ts +27 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/ai_assistant/lib/agent-runtime.ts"],
|
|
4
|
-
"sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { randomUUID } from 'node:crypto'\nimport { createContainer } from 'awilix'\nimport type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n GenerateObjectResult,\n GenerateTextResult,\n LanguageModel,\n PrepareStepFunction,\n PrepareStepResult,\n StreamObjectResult,\n StreamTextResult,\n ToolSet,\n UIMessage,\n ToolLoopAgentSettings,\n} from 'ai'\nimport {\n convertToModelMessages,\n generateObject,\n generateText,\n hasToolCall,\n Output,\n stepCountIs,\n streamObject,\n streamText,\n Experimental_Agent as ToolLoopAgent,\n} from 'ai'\nimport type { StopCondition } from 'ai'\nimport type { ZodTypeAny } from 'zod'\nimport { createModelFactory, resolveAllowRuntimeOverride } from './model-factory'\nimport type {\n AiAgentCallObserver,\n AiAgentCallSettings,\n AiAgentRunTraceOptions,\n} from './agent-call-contract'\nimport { mergeCallSettings, toSdkCallSettings } from './agent-call-contract'\nimport {\n buildObjectResponseFormat,\n composeCallObservers,\n createModelCallObserverHooks,\n createSynthesizedModelCall,\n describeLanguageModel,\n isLightweightCallObserver,\n notifyPromptResolved,\n observeStreamedObjectEnd,\n readSynthesizedResultMetadata,\n type ModelCallObserverHooks,\n} from './agent-call-observer'\nimport { resolveAllowlistedBaseurl } from './baseurl-allowlist'\nimport { reportAiAssistantError } from './report-ai-assistant-error'\nimport { computeEndUserIdentifier } from '@open-mercato/shared/lib/ai/safety-identifier'\nimport { llmProviderRegistry } from './llm-registry'\nimport type { EnvLookup } from '@open-mercato/shared/lib/ai/llm-provider'\nimport {\n AiModerationBlockedError,\n AiModerationUnavailableError,\n type ModerationService,\n} from './moderation'\nimport {\n isModerationActive,\n resolveModerationPolicy,\n shouldFailClosed,\n} from './moderation-policy'\nimport { recordModerationFlag } from './moderation-flag-recorder'\nimport type {\n AiAgentDefinition,\n AiAgentLoopConfig,\n AiAgentPageContextInput,\n AiAgentStructuredOutput,\n LoopStepRecord,\n LoopTrace,\n} from './ai-agent-definition'\nimport type {\n AiChatRequestContext,\n AiResolvedAttachmentPart,\n} from './attachment-bridge-types'\nimport {\n resolveAiAgentTools,\n AgentPolicyError,\n desanitizeToolNameForDisplay,\n sanitizeToolNameForModel,\n} from './agent-tools'\nimport { resolveEffectiveMutationPolicy } from './agent-policy'\nimport { resolveAgentRunMutationPolicyOverride } from './agent-channel-policy'\nimport type { McpMutationMode } from './mcp-exposure'\nimport type { AiPendingActionChannel } from './pending-action-types'\nimport { toolRegistry } from './tool-registry'\nimport {\n attachmentPartsToUiFileParts,\n resolveAttachmentPartsForAgent,\n summarizeAttachmentPartsForPrompt,\n} from './attachment-parts'\nimport { AiAgentPromptOverrideRepository } from '../data/repositories/AiAgentPromptOverrideRepository'\nimport { AiAgentMutationPolicyOverrideRepository } from '../data/repositories/AiAgentMutationPolicyOverrideRepository'\nimport { AiAgentRuntimeOverrideRepository } from '../data/repositories/AiAgentRuntimeOverrideRepository'\nimport { AiTenantModelAllowlistRepository } from '../data/repositories/AiTenantModelAllowlistRepository'\nimport type { TenantAllowlistSnapshot } from './model-allowlist'\nimport { composeSystemPromptWithOverride } from './prompt-override-merge'\nimport { extractStepMeta, extractStepToolCalls } from './loop-step-extraction'\nimport type { RawStepEvent, ToolCallTimings } from './loop-step-extraction'\nimport { isAgentTaskPlanEnabled } from './agent-registry'\nimport { createAgentRunCapture, stopWhenKinds } from './agent-run-capture'\nimport type { AgentRunLoopParams, AgentRunModelSource } from './agent-run-recorder'\nimport { isKnownMutationPolicy } from './agent-policy'\nimport type { AiAgentMutationPolicy } from './ai-agent-definition'\nimport { recordTokenUsage } from './token-usage-recorder'\nimport { injectTaskPlanIntoStream } from './task-plan-stream'\nimport { TASK_PLAN_RUNTIME_PROMPT_SECTION } from './task-plan-labels'\n\nconst logger = createLogger('ai_assistant').child({ component: 'agent-runtime' })\n\nexport interface AgentRequestPageContext {\n pageId?: string | null\n entityType?: string | null\n recordId?: string | null\n [key: string]: unknown\n}\n\nexport interface RunAiAgentTextInput {\n agentId: string\n messages: UIMessage[]\n attachmentIds?: string[]\n pageContext?: AgentRequestPageContext\n debug?: boolean\n /**\n * Phase 1 exposes the caller-supplied auth context directly on the helper\n * input. Phase 4 may wrap this behind a thinner public API once a global\n * request-context resolver exists. Helpers running inside the HTTP\n * dispatcher receive the same `AiChatRequestContext` used by `checkAgentPolicy`.\n */\n authContext: AiChatRequestContext\n /**\n * Optional per-call model id override that wins over `agent.defaultModel`.\n * The production model-factory extraction lives in Step 5.1; this Step\n * accepts a literal model id string so the Phase 1 runtime already honors\n * `agent.defaultModel` without inventing a new indirection layer.\n */\n modelOverride?: string\n /**\n * Optional request-time provider override. When non-empty, wins for the\n * provider axis at the same priority as `modelOverride` for the model axis.\n * A value that does not match any registered provider id is silently ignored.\n *\n * Phase 1 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n providerOverride?: string\n /**\n * Optional per-call base URL override. Wins over every other source in the\n * baseURL resolution chain. Intended for programmatic callers only \u2014 the\n * HTTP query-param baseUrl and the AI_RUNTIME_BASEURL_ALLOWLIST arrive in\n * Phase 4a and MUST NOT be exposed here.\n *\n * Phase 2 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n baseUrlOverride?: string\n /**\n * Per-request HTTP dispatcher override (query params `?provider=`, `?model=`,\n * `?baseUrl=`). Validated by the dispatcher route before being forwarded\n * here. Wins over tenantOverride and all lower-priority sources when\n * `agent.allowRuntimeOverride !== false`.\n *\n * Phase 4a of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n requestOverride?: {\n providerId?: string | null\n modelId?: string | null\n baseURL?: string | null\n }\n /**\n * Optional DI container used by `resolvePageContext` callbacks. When omitted\n * and the agent declares a `resolvePageContext`, hydration is skipped with a\n * warning (callbacks that need database/DI cannot run safely without one).\n */\n container?: AwilixContainer\n /**\n * Stable per-conversation id that ties every turn of a chat together for\n * token-usage correlation and pending-action idempotency (Phase 6.2).\n *\n * When omitted the server generates one and echoes it on the SSE `done`\n * event so the client can persist it for subsequent turns. Callers that\n * supply a value from a previous turn will have their usage rows grouped\n * under the same `session_id` in the token-usage tables.\n *\n * Phase 6.2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n sessionId?: string | null\n /**\n * @deprecated Use `sessionId` instead. This alias was the original name of\n * the same field; both names are accepted for one minor release to let\n * callers migrate without a hard cut. `sessionId` takes precedence when both\n * are provided.\n */\n conversationId?: string | null\n /**\n * Optional per-call loop config override. Fields set here win over the\n * agent's `loop` declaration and the tenant DB override. The override is\n * gated by `agent.loop?.allowRuntimeOverride ?? true` \u2014 agents that pin\n * a loop policy for correctness reasons can set `allowRuntimeOverride: false`\n * to reject any per-call override with `AgentPolicyError` code\n * `loop_runtime_override_disabled`.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n loop?: Partial<AiAgentLoopConfig>\n /**\n * Optional escape-hatch callback that receives the fully prepared AI SDK\n * options bag and must return the SDK result (either from `streamText` or\n * `generateText`). When supplied, the wrapper still enforces every policy\n * guardrail (features, tool allowlist, mutation approval, model factory,\n * prompt composition, attachment bridging) and then hands control to this\n * callback instead of calling `streamText` directly.\n *\n * The callback MUST pass `stopWhen` and `prepareStep` through to the AI SDK\n * call \u2014 dropping either one disables the agent's loop policy or mutation\n * approval guards respectively. See `agents.mdx` \u00A7\"Option B\" for the full\n * contract and what you lose when fields are omitted.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n generateText?: (\n options: PreparedAiSdkOptions,\n ) => Promise<\n | GenerateTextResult<ToolSet, Record<string, unknown>, never>\n | StreamTextResult<ToolSet, Record<string, unknown>, never>\n >\n /**\n * When `true`, the runtime appends a `loop-finish` SSE event to the\n * response stream after the AI SDK stream closes. The event payload is the\n * serialized `LoopTrace` for the turn (agent id, turn id, per-step records,\n * stop reason, total duration, total usage).\n *\n * Consumed by `useAiChat` to populate `lastLoopTrace` and by the playground\n * debug panel to render the per-turn trace via `LoopTracePanel`.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n emitLoopTrace?: boolean\n /**\n * Model-call contract fields (spec `2026-10-21-chat-run-tracing-and-citations` \u00A76).\n * `runId` pins the run identifier, `trace` controls run persistence and\n * channel attribution, `callSettings` are merged over the agent's\n * `modelSettings` key by key, and `observe` receives per-call events.\n */\n runId?: string\n trace?: AiAgentRunTraceOptions\n callSettings?: AiAgentCallSettings\n observe?: AiAgentCallObserver\n}\n\n/**\n * The wrapper default loop config used when neither the caller, tenant, agent,\n * nor legacy maxSteps supplies any config. Chat mode defaults to `{ maxSteps: 10 }`\n * to ensure tool-using agents can loop; object mode defaults to an empty config\n * (single structured-output call, no explicit step cap).\n */\nconst WRAPPER_DEFAULT_LOOP_CHAT: AiAgentLoopConfig = { maxSteps: 10 }\nconst WRAPPER_DEFAULT_LOOP_OBJECT: AiAgentLoopConfig = {}\n\n/**\n * Named loop-budget preset values for `?loopBudget=<preset>` query param.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport type AiAgentLoopBudgetPreset = 'tight' | 'default' | 'loose'\n\n/**\n * Maps a `loopBudget` preset name to the corresponding `AiAgentLoopBudget`\n * triple. `'default'` returns `undefined` (no override \u2014 agent default applies).\n * Values are pinned per spec \u00A7\"loopBudget preset values (Phase 4)\".\n */\nexport function resolveLoopBudgetPreset(\n preset: AiAgentLoopBudgetPreset,\n): Partial<AiAgentLoopConfig> | undefined {\n switch (preset) {\n case 'tight':\n return { maxSteps: 3, budget: { maxToolCalls: 3, maxWallClockMs: 10_000, maxTokens: 50_000 } }\n case 'loose':\n return { maxSteps: 20, budget: { maxToolCalls: 20, maxWallClockMs: 120_000, maxTokens: 500_000 } }\n case 'default':\n return undefined\n }\n}\n\nconst SSE_ENCODER = new TextEncoder()\n\nexport type TextRunStreamOutcome = {\n status: 'completed' | 'failed' | 'aborted'\n error: { code: string; message: string } | null\n}\n\ntype StreamOutcomeScanner = {\n push(chunk: Uint8Array): void\n outcome(): TextRunStreamOutcome\n}\n\nfunction readStreamPartOutcome(line: string): TextRunStreamOutcome | null {\n if (!line.startsWith('data:')) return null\n if (!line.includes('\"type\":\"error\"') && !line.includes('\"type\":\"abort\"')) return null\n try {\n const parsed = JSON.parse(line.slice('data:'.length).trim()) as { type?: unknown; errorText?: unknown }\n if (parsed.type === 'error') {\n const message = typeof parsed.errorText === 'string' ? parsed.errorText : ''\n return { status: 'failed', error: { code: 'stream_error', message } }\n }\n if (parsed.type === 'abort') return { status: 'aborted', error: null }\n } catch {\n return null\n }\n return null\n}\n\nfunction createStreamOutcomeScanner(): StreamOutcomeScanner {\n const decoder = new TextDecoder()\n let pending = ''\n let current: TextRunStreamOutcome = { status: 'completed', error: null }\n function consume(line: string): void {\n const parsed = readStreamPartOutcome(line)\n if (!parsed) return\n if (current.status === 'failed') return\n current = parsed\n }\n return {\n push(chunk) {\n pending += decoder.decode(chunk, { stream: true })\n const lines = pending.split('\\n')\n pending = lines.pop() ?? ''\n for (const line of lines) consume(line)\n },\n outcome() {\n if (pending.length > 0) {\n consume(pending)\n pending = ''\n }\n return current\n },\n }\n}\n\ntype StreamFinalizeOptions = {\n emitLoopTrace: boolean\n finalizeLoopTrace: () => LoopTrace\n abortSignal?: AbortSignal\n onSettled?: (outcome: TextRunStreamOutcome, trace: LoopTrace) => Promise<unknown>\n}\n\n/**\n * Wraps a streaming `Response` with a post-stream finalize hook. When\n * `emitLoopTrace` is set, a typed `loop-finish` SSE event carrying the\n * serialized `LoopTrace` is appended after the AI SDK stream closes. The\n * optional `onSettled` hook runs after the client stream is closed, so it never\n * holds the response open.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`; generalized by\n * spec `2026-10-21-chat-run-tracing-and-citations` \u00A72.\n */\nasync function cancelReaderQuietly(reader: ReadableStreamDefaultReader<Uint8Array>, reason: unknown): Promise<void> {\n try {\n await reader.cancel(reason)\n } catch {\n return\n }\n}\n\nfunction appendLoopFinishToStream(baseResponse: Response, options: StreamFinalizeOptions): Response {\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n const writer = writable.getWriter()\n const scanner = options.onSettled ? createStreamOutcomeScanner() : null\n\n async function pump(): Promise<void> {\n let outcome: TextRunStreamOutcome = { status: 'completed', error: null }\n let trace: LoopTrace | null = null\n let downstreamClosed = false\n const writeDownstream = async (chunk: Uint8Array): Promise<void> => {\n try {\n await writer.write(chunk)\n } catch (error) {\n downstreamClosed = true\n throw error\n }\n }\n if (!baseResponse.body) {\n await writer.close()\n } else {\n const reader = baseResponse.body.getReader()\n writer.closed.catch((reason: unknown) => {\n downstreamClosed = true\n void cancelReaderQuietly(reader, reason)\n })\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n scanner?.push(value)\n await writeDownstream(value)\n }\n if (downstreamClosed) throw new Error('[internal] downstream stream closed')\n trace = options.finalizeLoopTrace()\n if (options.emitLoopTrace) {\n const eventLine = `data: ${JSON.stringify({ type: 'loop-finish', trace })}\\n\\n`\n await writeDownstream(SSE_ENCODER.encode(eventLine))\n }\n if (scanner) outcome = scanner.outcome()\n if (outcome.status === 'completed' && options.abortSignal?.aborted === true) {\n outcome = { status: 'aborted', error: null }\n }\n } catch (error) {\n await cancelReaderQuietly(reader, error)\n const aborted =\n downstreamClosed ||\n options.abortSignal?.aborted === true ||\n (error instanceof Error && error.name === 'AbortError') ||\n (scanner !== null && scanner.outcome().status === 'aborted')\n outcome = aborted\n ? { status: 'aborted', error: null }\n : { status: 'failed', error: { code: 'stream_error', message: error instanceof Error ? error.message : String(error) } }\n } finally {\n reader.releaseLock()\n await writer.close().catch(() => undefined)\n }\n }\n if (options.onSettled) {\n try {\n await options.onSettled(outcome, trace ?? options.finalizeLoopTrace())\n } catch (error) {\n logger.warn('Run finalize hook failed; stream already delivered', { err: error })\n reportAiAssistantError(error, 'ai_assistant.agent_run_finalize_failed')\n }\n }\n }\n\n void pump()\n return new Response(readable, {\n status: baseResponse.status,\n headers: baseResponse.headers,\n })\n}\n\n/**\n * The fully prepared options bag handed to the `runAiAgentText({ generateText })`\n * escape-hatch callback. Callers receive a complete set of wrapper-composed\n * loop primitives so they can forward them to `streamText` / `generateText`.\n *\n * SECURITY CONTRACT: callers MUST forward `prepareStep` to the AI SDK call.\n * Dropping it removes the per-step tool-allowlist re-check and the mutation-\n * approval wrapping. Dropping `stopWhen` removes the agent's loop policy and\n * the R3 step-count fallback.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport interface PreparedAiSdkOptions {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n tools: ToolSet\n system: string\n messages: Awaited<ReturnType<typeof convertToModelMessages>>\n /** Alias kept for SDK compat \u2014 equals `stopWhen` array's effective maxSteps. */\n maxSteps: number\n /**\n * Wrapper-composed stop conditions (R3 mitigated: always ends with\n * `stepCountIs(maxSteps)`). MUST be forwarded to the SDK call.\n */\n stopWhen: StopCondition<ToolSet>[]\n /**\n * Wrapper-owned `PrepareStepFunction` that re-asserts the tool allowlist and\n * mutation-approval wrapping per step. SECURITY-CRITICAL: callers MUST\n * forward this to the SDK call or they lose mutation-approval guarantees.\n */\n prepareStep: PrepareStepFunction<ToolSet>\n /** Wrapper trace aggregator chained with the agent's `onStepFinish` hook. */\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n onStepStart: AiAgentLoopConfig['onStepStart']\n onToolCallStart: AiAgentLoopConfig['onToolCallStart']\n onToolCallFinish: AiAgentLoopConfig['onToolCallFinish']\n experimental_repairToolCall: AiAgentLoopConfig['repairToolCall']\n activeTools: AiAgentLoopConfig['activeTools']\n toolChoice: AiAgentLoopConfig['toolChoice']\n /**\n * Pre-wired to the per-turn `AbortController` used by budget enforcement\n * (Phase 3). Forward to the SDK call so budget limits can abort in-flight\n * requests. May be `undefined` when budget enforcement is not yet active\n * (Phases 0\u20132); the SDK treats `undefined` the same as no signal.\n */\n abortSignal: AbortSignal | undefined\n /**\n * Finalizes the per-turn `LoopTrace` and returns it. Callers that use the\n * `generateText` escape-hatch SHOULD call this after the SDK call resolves so\n * the trace is available for logging or SSE emission.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n finalizeLoopTrace: () => LoopTrace\n /**\n * Present only when `agent.executionEngine === 'tool-loop-agent'`. Callers\n * can invoke `agent.generate(...)` / `agent.stream(...)` directly with their\n * own `providerOptions` as an escape-hatch \u2014 the `ToolLoopAgent` instance is\n * already wired with the wrapper-owned `prepareStep`, `stopWhen`, and\n * `onStepFinish` at construction.\n *\n * Phase 5 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n toolLoopAgent?: ToolLoopAgent<never, ToolSet>\n /**\n * Provider-specific `providerOptions` fragment carrying the mapped end-user\n * safety identifier (e.g. OpenAI `safety_identifier`). Present only when an\n * identifier was derived and the resolved provider supports the mapping.\n * Callers using the `generateText` escape-hatch MUST forward it to the SDK\n * call so the identifier reaches the provider.\n *\n * Spec `2026-06-04-ai-input-moderation-and-safety-identifiers`.\n */\n providerOptions?: Record<string, unknown>\n /**\n * Effective call settings (agent `modelSettings` merged with per-call\n * `callSettings`). Present only when at least one setting is declared.\n * `providerOptions` above already carries the merged provider options.\n */\n callSettings?: AiAgentCallSettings\n /**\n * AI SDK call-level hooks that feed `input.observe` with one start/end event\n * per model call. Present only when an observer with model-call handlers is\n * supplied. Callers SHOULD forward both to the SDK call.\n */\n onLanguageModelCallStart?: ModelCallObserverHooks['onLanguageModelCallStart']\n onLanguageModelCallEnd?: ModelCallObserverHooks['onLanguageModelCallEnd']\n}\n\ntype ToolLoopAgentSettingsWithModelCallHooks = ToolLoopAgentSettings<never, ToolSet> & Partial<ModelCallObserverHooks>\n\n/**\n * The fully prepared options bag handed to the `runAiAgentObject({ generateObject })`\n * escape-hatch callback. Object-mode subset \u2014 chat-only fields are absent.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport interface PreparedAiSdkObjectOptions {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n system: string\n messages: Awaited<ReturnType<typeof convertToModelMessages>>\n schemaName: string\n schema: unknown\n maxSteps: number | undefined\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n onStepStart: AiAgentLoopConfig['onStepStart']\n abortSignal: AbortSignal | undefined\n /**\n * Effective call settings (agent `modelSettings` merged with per-call\n * `callSettings`). Present only when at least one setting is declared.\n * Callers SHOULD spread them into the SDK call.\n */\n callSettings?: AiAgentCallSettings\n}\n\n/**\n * Guards the per-call loop override against agents that have opted out of\n * runtime overrides by setting `loop.allowRuntimeOverride: false`.\n *\n * Throws `AgentPolicyError` with code `loop_runtime_override_disabled` when\n * the agent has opted out and a caller override was supplied.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nfunction assertLoopRuntimeOverrideAllowed(\n agent: AiAgentDefinition,\n callerLoop: Partial<AiAgentLoopConfig> | undefined,\n): void {\n if (!callerLoop) return\n const allowed = agent.loop?.allowRuntimeOverride ?? true\n if (!allowed) {\n throw new AgentPolicyError(\n 'loop_runtime_override_disabled',\n `Agent \"${agent.id}\" has disabled per-call loop overrides (loop.allowRuntimeOverride: false). Remove the loop override to proceed.`,\n )\n }\n}\n\n/**\n * Reads `<MODULE>_AI_LOOP_*` env shorthands for the given module id.\n * Returns a partial `AiAgentLoopConfig` containing only the axes that are\n * explicitly set in the environment. Missing or malformed values are silently\n * ignored (fail-open \u2014 env vars are a best-effort static deployment mechanism).\n *\n * Supported variables (Phase 3 of spec\n * `2026-04-28-ai-agents-agentic-loop-controls`):\n *\n * - `<MODULE>_AI_LOOP_MAX_STEPS` \u2014 maps to `loop.maxSteps`\n * - `<MODULE>_AI_LOOP_MAX_WALL_CLOCK_MS` \u2014 maps to `loop.budget.maxWallClockMs`\n * - `<MODULE>_AI_LOOP_MAX_TOKENS` \u2014 maps to `loop.budget.maxTokens`\n */\nfunction readModuleLoopEnv(moduleId: string): Partial<AiAgentLoopConfig> {\n const prefix = moduleId.toUpperCase()\n const partial: Partial<AiAgentLoopConfig> = {}\n\n const maxStepsRaw = process.env[`${prefix}_AI_LOOP_MAX_STEPS`]\n if (maxStepsRaw) {\n const parsed = parseInt(maxStepsRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) partial.maxSteps = parsed\n }\n\n const maxWallClockRaw = process.env[`${prefix}_AI_LOOP_MAX_WALL_CLOCK_MS`]\n const maxTokensRaw = process.env[`${prefix}_AI_LOOP_MAX_TOKENS`]\n\n if (maxWallClockRaw || maxTokensRaw) {\n const budgetPartial: AiAgentLoopConfig['budget'] = {}\n if (maxWallClockRaw) {\n const parsed = parseInt(maxWallClockRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) budgetPartial.maxWallClockMs = parsed\n }\n if (maxTokensRaw) {\n const parsed = parseInt(maxTokensRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) budgetPartial.maxTokens = parsed\n }\n if (Object.keys(budgetPartial).length > 0) partial.budget = budgetPartial\n }\n\n return partial\n}\n\n/**\n * Resolves the effective loop config for a turn by walking the precedence\n * chain (highest first):\n *\n * 1. `callerLoop` \u2014 per-call `runAiAgentText({ loop })` override (Phase 1).\n * 2. Tenant override row \u2014 NOT yet implemented in DB; always `undefined` here.\n * // TODO(Phase 1782-3): hydrate loop columns from ai_agent_runtime_overrides\n * 3. `<MODULE>_AI_LOOP_*` env shorthands (Phase 3) \u2014 only MAX_STEPS,\n * MAX_WALL_CLOCK_MS, MAX_TOKENS. Lower precedence than DB override but higher\n * than the agent's code-declared defaults.\n * 4. `agent.loop` \u2014 agent's declarative loop config.\n * 5. `agent.maxSteps` (deprecated alias) \u2014 mapped to `{ maxSteps: agent.maxSteps }`.\n * 6. `wrapperDefault` \u2014 the wrapper's hardcoded fallback.\n *\n * Each source contributes only the fields it sets explicitly; fields absent at\n * a higher-priority source fall through to a lower-priority one. The merge is\n * performed left-to-right with higher-priority sources winning field-by-field.\n *\n * Throws `AgentPolicyError` code `loop_runtime_override_disabled` when the\n * agent opts out of per-call overrides and a caller loop was supplied.\n *\n * Phase 0 + Phase 1 + Phase 3 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function resolveEffectiveLoopConfig(\n agent: AiAgentDefinition,\n callerLoop?: Partial<AiAgentLoopConfig> | undefined,\n wrapperDefault?: AiAgentLoopConfig,\n): AiAgentLoopConfig {\n assertLoopRuntimeOverrideAllowed(agent, callerLoop)\n\n const effectiveDefault = wrapperDefault ?? WRAPPER_DEFAULT_LOOP_CHAT\n\n // Build base from lowest-priority: wrapper default \u2192 legacy maxSteps \u2192 agent.loop\n const legacyMaxSteps: AiAgentLoopConfig | undefined =\n typeof agent.maxSteps === 'number' && agent.maxSteps > 0 && !agent.loop\n ? { maxSteps: agent.maxSteps }\n : undefined\n\n const base: AiAgentLoopConfig = {\n ...effectiveDefault,\n ...(legacyMaxSteps ?? {}),\n ...(agent.loop ?? {}),\n }\n\n // Phase 3 \u2014 env shorthands at priority 3 (above agent.loop, below DB override).\n // TODO(Phase 1782-3): hydrate loop columns from ai_agent_runtime_overrides\n // and merge tenantOverride here at priority #2 (above envOverride).\n const envOverride = readModuleLoopEnv(agent.moduleId)\n const withEnv: AiAgentLoopConfig = {\n ...base,\n ...envOverride,\n ...(envOverride.budget != null\n ? { budget: { ...(base.budget ?? {}), ...envOverride.budget } }\n : {}),\n }\n\n const withCaller: AiAgentLoopConfig = callerLoop\n ? { ...withEnv, ...callerLoop }\n : withEnv\n\n // Phase 3 \u2014 kill switch: when disabled is set to true, force maxSteps: 1 so the\n // agent executes as a single model call with no tool looping. All other loop config\n // is preserved (budget, etc.) but the step cap wins.\n if (withCaller.disabled === true) {\n return { ...withCaller, maxSteps: 1 }\n }\n\n return withCaller\n}\n\n/**\n * The reason a budget limit was hit, exposed on `LoopAbortReason` (Phase 3).\n */\nexport type LoopBudgetAbortReason =\n | 'budget-tool-calls'\n | 'budget-wall-clock'\n | 'budget-tokens'\n\n/**\n * Tracks per-turn budget usage and aborts the run when any limit is exceeded.\n *\n * Usage:\n * 1. Construct with the loop budget and the turn's `AbortController`.\n * 2. Call `wire(onStepFinish)` to get a composed `onStepFinish` that feeds\n * usage data into the enforcer on every completed step.\n * 3. The enforcer calls `abortController.abort()` with a typed\n * `LoopBudgetAbortReason` when a limit is hit.\n *\n * Phase 3 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport class BudgetEnforcer {\n private toolCallsUsed = 0\n private tokensUsed = 0\n readonly turnStartMs: number\n abortReason: LoopBudgetAbortReason | null = null\n\n constructor(\n private readonly budget: AiAgentLoopConfig['budget'],\n private readonly abortController: AbortController,\n ) {\n this.turnStartMs = Date.now()\n }\n\n get hasActiveBudget(): boolean {\n const b = this.budget\n return (\n b !== undefined &&\n (b.maxToolCalls !== undefined || b.maxWallClockMs !== undefined || b.maxTokens !== undefined)\n )\n }\n\n recordStep(usage: { inputTokens?: number; outputTokens?: number; toolCalls?: number }): void {\n if (!this.budget) return\n this.toolCallsUsed += usage.toolCalls ?? 0\n this.tokensUsed += (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0)\n this.checkLimits()\n }\n\n private checkLimits(): void {\n const b = this.budget\n if (!b) return\n\n if (b.maxToolCalls !== undefined && this.toolCallsUsed >= b.maxToolCalls) {\n this.abort('budget-tool-calls')\n return\n }\n\n const elapsedMs = Date.now() - this.turnStartMs\n if (b.maxWallClockMs !== undefined && elapsedMs >= b.maxWallClockMs) {\n this.abort('budget-wall-clock')\n return\n }\n\n if (b.maxTokens !== undefined && this.tokensUsed >= b.maxTokens) {\n this.abort('budget-tokens')\n }\n }\n\n private abort(reason: LoopBudgetAbortReason): void {\n if (this.abortReason !== null) return\n this.abortReason = reason\n logger.info('Budget exceeded \u2014 aborting turn', {\n reason,\n toolCalls: this.toolCallsUsed,\n tokens: this.tokensUsed,\n elapsedMs: Date.now() - this.turnStartMs,\n })\n this.abortController.abort(reason)\n }\n\n wire(\n userOnStepFinish: AiAgentLoopConfig['onStepFinish'],\n ): AiAgentLoopConfig['onStepFinish'] {\n if (!this.hasActiveBudget) return userOnStepFinish\n return async (event) => {\n this.recordStep({\n inputTokens: event.usage?.inputTokens,\n outputTokens: event.usage?.outputTokens,\n toolCalls: event.toolCalls?.length,\n })\n if (userOnStepFinish) {\n try {\n await userOnStepFinish(event)\n } catch (err) {\n logger.error('User onStepFinish threw; ignoring', { err })\n }\n }\n }\n }\n}\n\n/**\n * Builds a wrapper-owned `onStepFinish` collector that aggregates per-step\n * usage and tool-call data into a `LoopTrace` object. The collector chains\n * the user's `onStepFinish` after it aggregates (exceptions from the user's\n * hook are caught and logged but do not abort the turn).\n *\n * Returns both the wired `onStepFinish` hook and a `finalize()` function that\n * resolves the `LoopTrace` once the turn is complete. The `budgetEnforcer`\n * is already wired into `onStepFinish` at a lower layer \u2014 this collector sits\n * above it.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function buildLoopTraceCollector(\n agentId: string,\n sessionId: string,\n turnId: string,\n userOnStepFinish: AiAgentLoopConfig['onStepFinish'],\n toolCallTimings?: ToolCallTimings,\n): {\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n finalize: (abortReason: LoopBudgetAbortReason | null) => LoopTrace\n} {\n const turnStartMs = Date.now()\n const steps: LoopStepRecord[] = []\n\n const onStepFinish: AiAgentLoopConfig['onStepFinish'] = async (event) => {\n const stepIndex = steps.length\n const rawEvent = event as unknown as RawStepEvent\n const toolCalls: LoopStepRecord['toolCalls'] = extractStepToolCalls(rawEvent, toolCallTimings).map(\n (extracted) => ({\n ...(extracted.toolCallId ? { toolCallId: extracted.toolCallId } : {}),\n toolName: desanitizeToolNameForDisplay(extracted.toolName),\n args: extracted.args,\n result: extracted.result,\n error: extracted.error,\n repairAttempted: extracted.repairAttempted,\n durationMs: extracted.durationMs ?? 0,\n }),\n )\n\n const stepMeta = extractStepMeta(rawEvent)\n const textDelta = stepMeta.text\n const finishReason = stepMeta.finishReason as LoopStepRecord['finishReason']\n const modelId = stepMeta.modelId\n\n steps.push({\n stepIndex,\n modelId,\n toolCalls,\n textDelta,\n usage: {\n inputTokens: stepMeta.usage.inputTokens,\n outputTokens: stepMeta.usage.outputTokens,\n },\n finishReason,\n })\n\n if (userOnStepFinish) {\n try {\n await userOnStepFinish(event)\n } catch (err) {\n logger.error('User onStepFinish in LoopTrace collector threw; ignoring', { err })\n }\n }\n }\n\n function finalize(abortReason: LoopBudgetAbortReason | null): LoopTrace {\n const totalDurationMs = Date.now() - turnStartMs\n const totalUsage = steps.reduce(\n (acc, step) => ({\n inputTokens: acc.inputTokens + step.usage.inputTokens,\n outputTokens: acc.outputTokens + step.usage.outputTokens,\n }),\n { inputTokens: 0, outputTokens: 0 },\n )\n\n let stopReason: LoopTrace['stopReason'] = 'finish-reason'\n if (abortReason === 'budget-tool-calls') stopReason = 'budget-tool-calls'\n else if (abortReason === 'budget-wall-clock') stopReason = 'budget-wall-clock'\n else if (abortReason === 'budget-tokens') stopReason = 'budget-tokens'\n\n return {\n agentId,\n sessionId,\n turnId,\n steps,\n stopReason,\n totalDurationMs,\n totalUsage,\n }\n }\n\n return { onStepFinish, finalize }\n}\n\n/**\n * Translates serializable `AiAgentLoopStopCondition` items into the Vercel AI\n * SDK `StopCondition` array ready to pass to `streamText` / `generateText`.\n *\n * The wrapper ALWAYS appends `stepCountIs(maxSteps ?? 10)` as the final item\n * in the returned array (R3 mitigation). This guarantees that a misconfigured\n * `hasToolCall` for a non-existent tool can never cause an infinite loop\n * because the SDK treats `stopWhen` arrays with OR semantics \u2014 the step-count\n * fallback will always trip eventually.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function translateStopConditions(\n loopConfig: AiAgentLoopConfig,\n mapToolName: (toolName: string) => string = (toolName) => toolName,\n): StopCondition<ToolSet>[] {\n const effectiveMaxSteps = loopConfig.maxSteps ?? 10\n const userConditions: StopCondition<ToolSet>[] = []\n\n const rawStopWhen = loopConfig.stopWhen\n if (rawStopWhen) {\n const items = Array.isArray(rawStopWhen) ? rawStopWhen : [rawStopWhen]\n for (const item of items) {\n if (item.kind === 'stepCount') {\n userConditions.push(stepCountIs(item.count))\n } else if (item.kind === 'hasToolCall') {\n userConditions.push(hasToolCall(mapToolName(item.toolName)))\n } else if (item.kind === 'custom') {\n userConditions.push(item.stop as StopCondition<ToolSet>)\n }\n }\n }\n\n // Always append the hard step-count fallback (R3 mitigation).\n return [...userConditions, stepCountIs(effectiveMaxSteps)]\n}\n\n/**\n * Security-critical merge of the wrapper-owned step override with the user's\n * `prepareStep` return value.\n *\n * Guarantees (R1 mitigation \u2014 preserving the mutation-approval contract):\n * 1. Any `tools` map returned by the user is intersected with `toolRegistry`\n * (the policy-gated, mutation-approval-wrapped map). If the user returned\n * a raw mutation handler, the merged map points at the wrapped one.\n * 2. Any `activeTools` returned by the user is intersected with\n * `agent.allowedTools`. Out-of-set names are dropped with a single\n * `loop:active_tools_filtered` warning.\n * 3. A user-returned `tools` map that contains a mutation tool pointing at the\n * raw handler (not the wrapped one) is rejected with\n * `AgentPolicyError` code `loop_violates_mutation_policy`.\n * 4. Non-policy fields (`model`, `toolChoice`, `system`, `messages`) from the\n * user override are honored as-is.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n *\n * ai-sdk 6.0.177 dropped the `tools` field from `PrepareStepResult`, so the\n * map is no longer consumed by `streamText` / `generateText`. We still inspect\n * any `tools` map that a caller passes via a type-asserted result \u2014 even\n * though the SDK ignores it \u2014 to keep the defense-in-depth guard and the\n * existing test contract (R1 mitigation #3) intact.\n */\ntype StepOverrideWithTools = NonNullable<PrepareStepResult<ToolSet>> & {\n tools?: Record<string, unknown>\n}\n\nfunction normalizeAllowedToolNameForAgent(\n toolName: string,\n agent: AiAgentDefinition,\n): string | null {\n if (agent.allowedTools.includes(toolName)) return toolName\n const dottedName = desanitizeToolNameForDisplay(toolName)\n return agent.allowedTools.includes(dottedName) ? dottedName : null\n}\n\nexport function mergeStepOverrides(\n wrapperOverride: PrepareStepResult<ToolSet>,\n userOverride: PrepareStepResult<ToolSet> | undefined | null,\n agent: AiAgentDefinition,\n wrappedToolRegistry: Record<string, unknown>,\n): PrepareStepResult<ToolSet> {\n if (!userOverride) return wrapperOverride\n\n const merged: StepOverrideWithTools = { ...(wrapperOverride as StepOverrideWithTools) }\n const userWithTools = userOverride as StepOverrideWithTools\n\n if (userOverride.model !== undefined) {\n merged.model = userOverride.model\n }\n if (userOverride.toolChoice !== undefined) {\n merged.toolChoice = userOverride.toolChoice\n }\n\n if (userOverride.activeTools !== undefined) {\n const filtered = userOverride.activeTools.flatMap((name) => {\n const normalized = normalizeAllowedToolNameForAgent(name, agent)\n const allowed = normalized !== null\n if (!allowed) {\n logger.warn('loop:active_tools_filtered \u2014 tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })\n }\n return normalized ? [normalized] : []\n })\n merged.activeTools = filtered\n }\n\n if (userWithTools.tools !== undefined) {\n const userTools = userWithTools.tools\n const mergedTools: Record<string, unknown> = {}\n\n for (const [toolKey, userHandler] of Object.entries(userTools)) {\n const wrappedHandler = wrappedToolRegistry[toolKey]\n if (!wrappedHandler) {\n logger.warn('mergeStepOverrides \u2014 tool from user prepareStep is not in the wrapper tool registry; dropping', { toolName: toolKey })\n continue\n }\n if (userHandler !== wrappedHandler) {\n const toolDef = toolRegistry.getTool(\n toolKey.replace(/__/g, '.'),\n ) as { isMutation?: boolean } | undefined\n if (toolDef?.isMutation === true) {\n throw new AgentPolicyError(\n 'loop_violates_mutation_policy',\n `User prepareStep returned a tools map with raw (unwrapped) mutation handler for \"${toolKey}\". This bypasses the mutation-approval gate and is rejected.`,\n )\n }\n }\n mergedTools[toolKey] = wrappedHandler\n }\n merged.tools = mergedTools\n }\n\n return merged\n}\n\nfunction mapPrepareStepResultForModel(\n result: PrepareStepResult<ToolSet>,\n wrappedTools: Record<string, unknown>,\n): PrepareStepResult<ToolSet> {\n if (!result?.activeTools) return result\n const activeTools = result.activeTools\n .map((toolName) => sanitizeToolNameForModel(toolName))\n .filter((toolName) => wrappedTools[toolName] !== undefined)\n return { ...result, activeTools }\n}\n\nfunction mapToolChoiceForModel(\n toolChoice: AiAgentLoopConfig['toolChoice'],\n): AiAgentLoopConfig['toolChoice'] {\n if (!toolChoice || typeof toolChoice !== 'object' || toolChoice.type !== 'tool') {\n return toolChoice\n }\n return {\n ...toolChoice,\n toolName: sanitizeToolNameForModel(toolChoice.toolName),\n } as AiAgentLoopConfig['toolChoice']\n}\n\nfunction mapActiveToolsForModel(\n activeTools: string[] | undefined,\n wrappedTools: Record<string, unknown>,\n): string[] | undefined {\n if (!activeTools) return undefined\n return activeTools\n .map((toolName) => sanitizeToolNameForModel(toolName))\n .filter((toolName) => wrappedTools[toolName] !== undefined)\n}\n\n/**\n * Builds the wrapper-owned `PrepareStepFunction` that enforces the tool\n * allowlist and mutation-approval contract on every step, then composes\n * the user's `prepareStep` on top via `mergeStepOverrides`.\n *\n * This is the SECURITY-CRITICAL function for Phase 0. The wrapper `prepareStep`\n * ensures:\n * - Tool active-set is always a subset of `effectiveLoop.activeTools ?? agent.allowedTools`.\n * - Mutation tools always point at the prepareMutation-wrapped handlers.\n * - User's `prepareStep` return value cannot smuggle raw mutation handlers.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function buildWrapperPrepareStep(\n agent: AiAgentDefinition,\n effectiveLoop: AiAgentLoopConfig,\n wrappedTools: Record<string, unknown>,\n): PrepareStepFunction<ToolSet> {\n return async (state) => {\n const wrapperOverride: PrepareStepResult<ToolSet> = {}\n\n if (effectiveLoop.activeTools && effectiveLoop.activeTools.length > 0) {\n wrapperOverride.activeTools = effectiveLoop.activeTools.flatMap((name) => {\n const normalized = normalizeAllowedToolNameForAgent(name, agent)\n const allowed = normalized !== null\n if (!allowed) {\n logger.warn('loop:active_tools_filtered \u2014 tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })\n }\n return normalized ? [normalized] : []\n })\n }\n\n if (effectiveLoop.prepareStep) {\n let userOverride: PrepareStepResult<ToolSet> | undefined | null\n try {\n userOverride = await effectiveLoop.prepareStep(state)\n } catch (error) {\n logger.error('User prepareStep threw; ignoring user override', { agentId: agent.id, err: error })\n return mapPrepareStepResultForModel(wrapperOverride, wrappedTools)\n }\n return mapPrepareStepResultForModel(\n mergeStepOverrides(wrapperOverride, userOverride, agent, wrappedTools),\n wrappedTools,\n )\n }\n\n return mapPrepareStepResultForModel(wrapperOverride, wrappedTools)\n }\n}\n\n/**\n * Validates that a loop config does not set any primitives that are\n * unsupported by the object-mode SDK path (`generateObject` / `streamObject`).\n *\n * Object mode accepts ONLY: `maxSteps`, `budget`, `onStepFinish`,\n * `onStepStart`, `allowRuntimeOverride`. The remaining fields\n * (`prepareStep`, `repairToolCall`, `stopWhen`, `activeTools`,\n * `toolChoice`) are chat-only and will never reach `generateObject`.\n *\n * Throws `AgentPolicyError` code `loop_unsupported_in_object_mode` if any\n * unsupported field is set. This provides an explicit, actionable error\n * rather than a silent no-op.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function assertLoopObjectModeCompatible(loopConfig: Partial<AiAgentLoopConfig>): void {\n const unsupportedFields: string[] = []\n\n if (loopConfig.prepareStep !== undefined) unsupportedFields.push('prepareStep')\n if (loopConfig.repairToolCall !== undefined) unsupportedFields.push('repairToolCall')\n if (loopConfig.stopWhen !== undefined) unsupportedFields.push('stopWhen')\n if (loopConfig.activeTools !== undefined) unsupportedFields.push('activeTools')\n if (loopConfig.toolChoice !== undefined) unsupportedFields.push('toolChoice')\n\n if (unsupportedFields.length > 0) {\n throw new AgentPolicyError(\n 'loop_unsupported_in_object_mode',\n `Object-mode agents do not support these loop primitives: ${unsupportedFields.join(', ')}. Use runAiAgentText for agents that require these loop controls.`,\n )\n }\n}\n\ninterface ResolvedAgentModel {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n modelId: string\n providerId: string\n /**\n * Provider-specific `providerOptions` fragment carrying the mapped end-user\n * safety identifier (undefined when no identifier or no provider mapping).\n */\n providerOptions?: Record<string, unknown>\n /** Whether the resolved chat provider supports input moderation. */\n supportsInputModeration: boolean\n /** Resolved base URL (if any), reused by the moderation endpoint call. */\n baseURL?: string\n /** Which resolution source won, mapped onto the run trace `modelSource`. */\n source?: string\n}\n\nfunction toAgentRunModelSource(source: string | undefined): AgentRunModelSource {\n if (source === 'request_override' || source === 'caller_override') return 'request'\n if (source === 'tenant_override') return 'runtime-override'\n if (source === 'agent_default') return 'agent'\n return 'default'\n}\n\nfunction listMutationToolNames(toolNames: string[]): Set<string> {\n const mutationToolNames = new Set<string>()\n for (const toolName of toolNames) {\n const registered = toolRegistry.getTool(toolName) as { isMutation?: boolean } | undefined\n if (registered?.isMutation === true) mutationToolNames.add(toolName)\n }\n return mutationToolNames\n}\n\nfunction listRunToolNames(tools: Record<string, unknown> | undefined): string[] {\n return Object.keys(tools ?? {}).map((toolName) => desanitizeToolNameForDisplay(toolName))\n}\n\nfunction buildRunLoopParams(\n loop: AiAgentLoopConfig,\n modelSource: AgentRunModelSource,\n): AgentRunLoopParams {\n return {\n maxSteps: loop.maxSteps ?? null,\n toolChoice: loop.toolChoice,\n budget: loop.budget,\n activeTools: loop.activeTools ?? null,\n stopWhenKinds: stopWhenKinds(loop.stopWhen),\n allowRuntimeOverride: loop.allowRuntimeOverride ?? null,\n modelSource,\n }\n}\n\nfunction joinStepText(steps: LoopStepRecord[]): string | null {\n const text = steps.map((step) => step.textDelta ?? '').join('')\n return text.length > 0 ? text : null\n}\n\nfunction serializeObjectOutput(value: unknown): string | null {\n if (value === undefined || value === null) return null\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value)\n } catch {\n return null\n }\n}\n\nfunction resolveAgentModel(\n agent: AiAgentDefinition,\n modelOverride: string | undefined,\n providerOverride: string | undefined,\n container: AwilixContainer | undefined,\n baseUrlOverride?: string,\n tenantOverride?: { providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null,\n requestOverride?: { providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null,\n tenantAllowlist?: TenantAllowlistSnapshot | null,\n endUserIdentifier?: string,\n): ResolvedAgentModel {\n const effectiveContainer = container ?? createContainer()\n const resolution = createModelFactory(effectiveContainer).resolveModel({\n moduleId: agent.moduleId,\n agentDefaultModel: agent.defaultModel,\n agentDefaultProvider: agent.defaultProvider,\n agentDefaultBaseUrl: agent.defaultBaseUrl,\n callerOverride: modelOverride,\n providerOverride,\n baseUrlOverride,\n allowRuntimeOverride: resolveAllowRuntimeOverride(agent),\n tenantOverride: tenantOverride ?? undefined,\n requestOverride: requestOverride ?? undefined,\n tenantAllowlist: tenantAllowlist ?? null,\n endUserIdentifier,\n })\n return {\n model: resolution.model as LanguageModel,\n experimental_download: resolution.download,\n modelId: resolution.modelId,\n providerId: resolution.providerId,\n providerOptions: resolution.providerOptions,\n supportsInputModeration: resolution.supportsInputModeration === true,\n baseURL: resolution.baseURL,\n source: resolution.source,\n }\n}\n\n/**\n * Concatenates the text parts of the most recent user message. Only the new\n * user turn is moderated (prior history was screened on its own turn). Returns\n * an empty string when there is no user message or no text content.\n */\nexport function extractLatestUserText(messages: UIMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const raw = messages[index] as unknown as {\n role?: string\n content?: string\n parts?: Array<{ type?: string; text?: string }>\n }\n if (raw.role !== 'user') continue\n if (Array.isArray(raw.parts)) {\n return raw.parts\n .filter((part) => part?.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text as string)\n .join('\\n')\n }\n return typeof raw.content === 'string' ? raw.content : ''\n }\n return ''\n}\n\nexport interface InputModerationGateParams {\n untrustedInput?: boolean\n supportsInputModeration: boolean\n userText: string\n service: ModerationService | null\n /**\n * Lazy resolver for the moderation provider's API key. Invoked only when the\n * gate actually proceeds (policy active, provider supports moderation, text\n * non-empty, service present) \u2014 so callers never pay for (or fail on) key\n * resolution on the common skip paths.\n */\n resolveApiKey: () => string | null\n baseURL?: string\n moderationModel?: string\n perAgentOverride?: boolean | null\n tenantWideOverride?: boolean | null\n env?: EnvLookup\n /**\n * Best-effort side effect invoked with the flagged categories right before\n * the gate throws {@link AiModerationBlockedError}. Phase 3 wires the audit\n * insert + event emit here; it MUST NOT throw (failures are swallowed by the\n * caller) and MUST NOT block the rejection.\n */\n onFlagged?: (categories: Record<string, { flagged: boolean; score: number }>) => void | Promise<void>\n}\n\n/**\n * Pre-loop input moderation gate. Runs the moderation check for the current\n * user turn before the model call. Decoupled from the registry/container so it\n * is unit-testable: the caller resolves the {@link ModerationService} and API\n * key. Throws {@link AiModerationBlockedError} when flagged; honors\n * fail-closed (enforced) vs fail-open (opt-in) on endpoint unavailability.\n */\nexport async function runInputModerationGate(params: InputModerationGateParams): Promise<void> {\n const policy = resolveModerationPolicy({\n untrustedInput: params.untrustedInput,\n perAgentOverride: params.perAgentOverride,\n tenantWideOverride: params.tenantWideOverride,\n env: params.env,\n })\n if (!isModerationActive(policy)) return\n // The resolved chat provider has no moderation endpoint \u2014 rely on its own\n // server-side filtering and skip the gate.\n if (!params.supportsInputModeration) return\n const text = params.userText.trim()\n if (!text) return\n\n const failClosed = shouldFailClosed(policy)\n const failOpenOrThrow = (reason: string, error?: unknown): void => {\n if (failClosed) {\n if (error instanceof AiModerationUnavailableError) throw error\n throw new AiModerationUnavailableError(reason, error)\n }\n logger.warn('Input moderation unavailable; failing open for opt-in surface', { reason })\n }\n\n if (!params.service) {\n return failOpenOrThrow('moderation service is not available in the container')\n }\n const apiKey = params.resolveApiKey()\n if (!apiKey) {\n return failOpenOrThrow('no API key available for the moderation provider')\n }\n\n let result\n try {\n result = await params.service.checkInput({\n text,\n apiKey,\n baseURL: params.baseURL,\n model: params.moderationModel,\n })\n } catch (error) {\n if (error instanceof AiModerationUnavailableError) {\n return failOpenOrThrow(error.message, error)\n }\n throw error\n }\n\n if (result.flagged) {\n if (params.onFlagged) {\n try {\n await params.onFlagged(result.categories)\n } catch (error) {\n logger.error('Moderation flag side effect failed (rejection still applies)', { err: error })\n }\n }\n throw new AiModerationBlockedError(result.categories)\n }\n}\n\n/**\n * Compute the tenant-salted end-user safety identifier for a chat turn,\n * best-effort. Returns undefined (never throws) so a derivation failure \u2014 e.g.\n * a missing base secret in a misconfigured environment \u2014 degrades to \"no\n * identifier attached\" instead of breaking the chat. Failures are logged.\n */\nfunction resolveEndUserIdentifier(authContext: AiChatRequestContext): string | undefined {\n try {\n return computeEndUserIdentifier(authContext.tenantId, authContext.userId)\n } catch (error) {\n logger.warn('Failed to derive end-user safety identifier', { err: error })\n return undefined\n }\n}\n\nasync function resolveTenantAllowlistSnapshot(\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<TenantAllowlistSnapshot | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiTenantModelAllowlistRepository(em)\n return await repo.getSnapshot({\n tenantId,\n organizationId: organizationId ?? null,\n })\n } catch (error) {\n logger.warn('Tenant allowlist lookup failed; falling back to env-only enforcement', { err: error })\n return null\n }\n}\n\n/**\n * Composes the effective system prompt for a run. When the agent declares a\n * `resolvePageContext` callback AND the incoming request carries both\n * `entityType` and `recordId`, the callback is invoked and its return value\n * is appended to `agent.systemPrompt`. Throwing callbacks are caught and\n * logged without failing the request \u2014 the spec allows hydration to be\n * best-effort until Step 5.2 wires a stricter contract.\n *\n * `userId` identifies the authenticated caller and is forwarded to the callback\n * so it can authorize user-scoped hydration. It MUST come from the server-side\n * auth context \u2014 `pageContext` is browser-supplied and is never read for it.\n * The parameter is trailing and optional so existing five-argument callers keep\n * working; they simply hand the resolver no verified identity.\n */\nexport async function composeSystemPrompt(\n agent: AiAgentDefinition,\n pageContext: AgentRequestPageContext | undefined,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n userId?: string | null,\n): Promise<string> {\n const composed = await composeSystemPromptWithMeta(\n agent,\n pageContext,\n container,\n tenantId,\n organizationId,\n userId,\n )\n return composed.prompt\n}\n\nexport type PromptOverrideReference = { id: string; version: number }\n\nexport type AgentRunPromptContext = {\n systemPrompt: string\n promptOverride: PromptOverrideReference | null\n pageContextHydrated: boolean\n attachmentCount: number\n provider: string | null\n modelId: string | null\n}\n\nasync function reportPromptResolved(\n observe: AiAgentCallObserver | undefined,\n agentId: string,\n runContext: AgentRunPromptContext,\n): Promise<void> {\n await notifyPromptResolved(observe, {\n agentId,\n systemPrompt: runContext.systemPrompt,\n promptOverride: runContext.promptOverride,\n pageContextHydrated: runContext.pageContextHydrated,\n attachmentCount: runContext.attachmentCount,\n provider: runContext.provider,\n modelId: runContext.modelId,\n })\n}\n\nexport type ComposedSystemPromptWithMeta = {\n prompt: string\n promptOverride: PromptOverrideReference | null\n pageContextHydrated: boolean\n}\n\nexport async function composeSystemPromptWithMeta(\n agent: AiAgentDefinition,\n pageContext: AgentRequestPageContext | undefined,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n userId?: string | null,\n): Promise<ComposedSystemPromptWithMeta> {\n const resolvedBase = await resolveSystemPromptWithOverrideMeta(\n agent,\n container,\n tenantId,\n organizationId,\n )\n const baseFromOverride = resolvedBase.prompt\n const unhydrated: ComposedSystemPromptWithMeta = {\n prompt: baseFromOverride,\n promptOverride: resolvedBase.override,\n pageContextHydrated: false,\n }\n const resolve = agent.resolvePageContext\n if (!resolve) return unhydrated\n const entityType = pageContext?.entityType\n const recordId = pageContext?.recordId\n if (typeof entityType !== 'string' || entityType.length === 0) return unhydrated\n if (typeof recordId !== 'string' || recordId.length === 0) return unhydrated\n if (!container) {\n logger.warn('Agent declares resolvePageContext but no container was passed to runAiAgentText; skipping hydration', { agentId: agent.id })\n return unhydrated\n }\n const hydrationInput: AiAgentPageContextInput = {\n entityType,\n recordId,\n container,\n tenantId,\n organizationId,\n userId: userId ?? null,\n }\n try {\n const hydrated = await resolve(hydrationInput)\n if (typeof hydrated === 'string' && hydrated.trim().length > 0) {\n return { ...unhydrated, prompt: `${baseFromOverride}\\n\\n${hydrated}`, pageContextHydrated: true }\n }\n } catch (error) {\n logger.error('resolvePageContext failed; continuing without hydration', { agentId: agent.id, err: error })\n }\n return unhydrated\n}\n\n/**\n * Fetches the latest tenant-scoped prompt override for `agent` (if any) and\n * layers it onto the built-in `systemPrompt` via the additive merge helper.\n *\n * BC + fail-open: every failure mode \u2014 missing container, missing `em`\n * registration, repository throw, missing migration \u2014 is logged at `warn`\n * and falls back to `agent.systemPrompt`. A chat turn MUST never fail on\n * override lookup (per Step 5.3 spec: \"If the repo call throws, log and\n * fall back to the built-in prompt \u2014 never fail the chat request\").\n */\nexport async function resolveSystemPromptWithOverrideMeta(\n agent: AiAgentDefinition,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<{ prompt: string; override: PromptOverrideReference | null }> {\n const base = agent.systemPrompt\n const fallback = { prompt: base, override: null }\n if (!tenantId || !container) return fallback\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return fallback\n try {\n const repo = new AiAgentPromptOverrideRepository(em)\n const latest = await repo.getLatest(agent.id, {\n tenantId,\n organizationId: organizationId ?? null,\n })\n if (!latest || !latest.sections || Object.keys(latest.sections).length === 0) {\n return fallback\n }\n return {\n prompt: composeSystemPromptWithOverride(base, { sections: latest.sections }),\n override: { id: latest.id, version: latest.version },\n }\n } catch (error) {\n logger.warn('Prompt-override lookup failed; falling back to built-in prompt', { agentId: agent.id, err: error })\n return fallback\n }\n}\n\n/**\n * Looks up the tenant-scoped `mutationPolicy` override for `agentId` (Step\n * 5.4). Fails SAFE: any repo error, missing container, missing `em`\n * registration, or corrupt enum value returns `null`, which causes the\n * runtime to fall back to the agent's code-declared policy. A chat turn\n * MUST never fail on override lookup.\n */\nasync function resolveMutationPolicyOverride(\n agentId: string,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<AiAgentMutationPolicy | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiAgentMutationPolicyOverrideRepository(em)\n const row = await repo.get(agentId, { tenantId, organizationId: organizationId ?? null })\n if (!row) return null\n const raw = row.mutationPolicy\n if (!isKnownMutationPolicy(raw)) {\n logger.warn('Ignoring corrupt mutationPolicy override row; falling back to code-declared policy', { agentId, policy: raw })\n return null\n }\n return raw\n } catch (error) {\n logger.warn('mutationPolicy override lookup failed; falling back to code-declared policy', { agentId, err: error })\n \n return null\n }\n}\n\n/**\n * Looks up the per-tenant AI runtime override (provider / model / baseURL) for\n * the given agent (Phase 4a of spec\n * `2026-04-27-ai-agents-provider-model-baseurl-overrides`).\n *\n * Mirrors the fail-open contract of {@link resolveMutationPolicyOverride}: any\n * error \u2014 missing container, missing `em`, repository throw, missing migration\n * \u2014 is logged at `warn` level and returns null so the model factory falls\n * through to lower-priority sources. A chat turn MUST never fail on override\n * lookup.\n */\nasync function resolveRuntimeModelOverride(\n agentId: string,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<{ providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiAgentRuntimeOverrideRepository(em)\n const row = await repo.getDefault({\n tenantId,\n organizationId: organizationId ?? null,\n agentId,\n })\n if (!row) return null\n const baseURL = resolveAllowlistedBaseurl(row.baseUrl)\n if (!baseURL && row.baseUrl?.trim()) {\n logger.warn('Stored AI runtime baseURL is not allowed by AI_RUNTIME_BASEURL_ALLOWLIST; ignoring it', {\n agentId,\n tenantId,\n organizationId,\n })\n }\n return {\n providerId: row.providerId ?? null,\n modelId: row.modelId ?? null,\n baseURL,\n }\n } catch (error) {\n logger.warn('Runtime model override lookup failed; falling back to lower-priority sources', { agentId, err: error })\n return null\n }\n}\n\n/**\n * Resolves the per-agent and tenant-wide `input_moderation` override values for\n * the moderation policy precedence. Best-effort and fail-open (returns nulls on\n * any error so the gate falls back to the env default). Returns the two values\n * separately because the precedence treats per-agent and tenant-wide as\n * distinct steps.\n */\nasync function resolveModerationOverrideValues(\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n agentId: string,\n): Promise<{ perAgentOverride: boolean | null; tenantWideOverride: boolean | null }> {\n const empty = { perAgentOverride: null, tenantWideOverride: null }\n if (!tenantId || !container) return empty\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return empty\n try {\n const repo = new AiAgentRuntimeOverrideRepository(em)\n const [agentRow, tenantRow] = await Promise.all([\n repo.getExact({ tenantId, organizationId: organizationId ?? null, agentId }),\n repo.getDefault({ tenantId, organizationId: organizationId ?? null, agentId: null }),\n ])\n return {\n perAgentOverride: agentRow?.inputModeration ?? null,\n tenantWideOverride: tenantRow?.inputModeration ?? null,\n }\n } catch (error) {\n logger.warn('Moderation override lookup failed; falling back to env default', { agentId, err: error })\n return empty\n }\n}\n\n/**\n * Normalizes simple `{ role, content }` chat messages into the AI SDK\n * `UIMessage` shape that `convertToModelMessages` requires. When the\n * incoming message already carries a `parts` array it is left untouched;\n * otherwise a single `TextUIPart` is synthesized from `content`.\n */\nfunction ensureUiMessageShape(messages: UIMessage[]): UIMessage[] {\n return messages.map((message, index) => {\n const raw = message as unknown as { id?: string; role?: string; content?: string; parts?: unknown[] }\n if (Array.isArray(raw.parts) && raw.parts.length > 0) {\n // Already has parts \u2014 only ensure `id` is present\n return { ...message, id: raw.id ?? `msg-${index}` } as UIMessage\n }\n const textContent = typeof raw.content === 'string' ? raw.content : ''\n return {\n id: raw.id ?? `msg-${index}`,\n role: raw.role ?? 'user',\n parts: [{ type: 'text', text: textContent }],\n } as unknown as UIMessage\n })\n}\n\n/**\n * Appends AI SDK v6 `FileUIPart` entries to the last user message in the\n * request so resolved attachment bytes / signed URLs reach the model. Pure\n * helper so chat-mode and object-mode share identical behavior \u2014 any\n * divergence here breaks the Step 3.6 parity contract.\n */\nfunction attachAttachmentsToMessages(\n messages: UIMessage[],\n parts: readonly AiResolvedAttachmentPart[],\n): UIMessage[] {\n if (parts.length === 0) return messages\n const fileParts = attachmentPartsToUiFileParts(parts)\n if (fileParts.length === 0) return messages\n const next = messages.slice()\n let lastUserIndex = -1\n for (let index = next.length - 1; index >= 0; index -= 1) {\n const candidate = next[index] as unknown as { role?: string }\n if (candidate?.role === 'user') {\n lastUserIndex = index\n break\n }\n }\n if (lastUserIndex === -1) {\n next.push({\n id: 'ai-runtime-attachments',\n role: 'user',\n parts: fileParts as unknown as UIMessage['parts'],\n } as unknown as UIMessage)\n return next\n }\n const source = next[lastUserIndex] as unknown as { parts?: unknown[] }\n const existingParts = Array.isArray(source.parts) ? source.parts : []\n next[lastUserIndex] = {\n ...(next[lastUserIndex] as object),\n parts: [...existingParts, ...fileParts],\n } as UIMessage\n return next\n}\n\nfunction appendAttachmentSummary(\n systemPrompt: string,\n parts: readonly AiResolvedAttachmentPart[],\n): string {\n const summary = summarizeAttachmentPartsForPrompt(parts)\n if (!summary) return systemPrompt\n return `${systemPrompt}\\n\\n${summary}`\n}\n\n/**\n * Builds a runtime \"MUTATION POLICY (RUNTIME)\" block describing the\n * EFFECTIVE policy for this turn \u2014 what the model should expect when it\n * calls each whitelisted mutation tool. Generated dynamically because:\n *\n * - the agent's static prompt cannot know which per-tenant override is\n * in force (`destructive-confirm-required` flips most writes to\n * run-direct) and would otherwise mislead the operator with stale\n * \"this requires approval\" copy;\n * - the per-tool `isDestructive` flag determines whether each\n * whitelisted write goes through the approval card or runs inline.\n *\n * Without this block, the model parrots its hardcoded \"always route\n * through the approval card\" prompt language and tells the user \"your\n * change is awaiting approval\" when in fact the dispatcher already\n * applied the change directly. The injected block flips the model to\n * report results accurately (\"applied\", \"pending your approval\", or\n * \"blocked because read-only\") tool-by-tool.\n */\nfunction buildRuntimeMutationPolicySection(\n agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },\n mutationPolicyOverride: string | null,\n): string | null {\n const effective = resolveEffectiveMutationPolicy(\n (agent.mutationPolicy ?? null) as never,\n (mutationPolicyOverride ?? null) as never,\n agent.id,\n )\n const lines: string[] = []\n lines.push('MUTATION POLICY (RUNTIME)')\n lines.push(`Declared agent policy: ${agent.mutationPolicy ?? 'read-only'}.`)\n if (mutationPolicyOverride && mutationPolicyOverride !== agent.mutationPolicy) {\n lines.push(`Tenant override active: ${mutationPolicyOverride}.`)\n }\n lines.push(`Effective policy: ${effective}.`)\n\n // Bucket the agent's allowlisted tools into \"gated\" / \"direct\" / \"conditional\"\n // / \"blocked\" so the model can phrase outcomes correctly per tool.\n // `conditional` covers tools whose `isDestructive` is a predicate function:\n // their gate-vs-direct decision depends on the per-call input (e.g.\n // `customers.manage_deal_comment` gates only its delete branch under\n // `destructive-confirm-required`).\n const direct: string[] = []\n const gated: string[] = []\n const conditional: string[] = []\n const blocked: string[] = []\n for (const toolName of agent.allowedTools) {\n const tool = toolRegistry.getTool(toolName) as\n | { isMutation?: boolean; isDestructive?: boolean | ((input: unknown) => boolean) }\n | undefined\n if (!tool || tool.isMutation !== true) continue\n if (effective === 'read-only') {\n blocked.push(toolName)\n continue\n }\n if (effective === 'confirm-required') {\n gated.push(toolName)\n continue\n }\n // destructive-confirm-required\n if (typeof tool.isDestructive === 'function') {\n conditional.push(toolName)\n } else if (tool.isDestructive === true) {\n gated.push(toolName)\n } else {\n direct.push(toolName)\n }\n }\n\n if (\n direct.length === 0 &&\n gated.length === 0 &&\n conditional.length === 0 &&\n blocked.length === 0\n ) {\n // Read-only agent with no mutation tools \u2014 no runtime policy block needed.\n return null\n }\n if (direct.length > 0) {\n lines.push('')\n lines.push(\n `Tools that WILL RUN DIRECTLY (no approval card, no pending action) under the effective policy: ${direct.join(', ')}.`,\n )\n lines.push(\n 'When you call any of these and the call returns successfully, the change has ALREADY BEEN APPLIED. Report it in the past tense (\"Updated \u2026\", \"Added \u2026\", \"Created \u2026\"). Do NOT tell the operator the action is \"pending your approval\" or \"awaiting confirmation\" \u2014 that would be a false statement under the current policy.',\n )\n }\n if (gated.length > 0) {\n lines.push('')\n lines.push(\n `Tools that REQUIRE APPROVAL under the effective policy: ${gated.join(', ')}.`,\n )\n lines.push(\n 'When you call any of these, the dispatcher returns an \"awaiting confirmation\" envelope and renders an inline approval card. Tell the operator the change is pending their confirmation; do NOT claim it has been applied.',\n )\n }\n if (conditional.length > 0) {\n lines.push('')\n lines.push(\n `Tools whose approval requirement DEPENDS ON THE INPUT under the effective policy: ${conditional.join(', ')}.`,\n )\n lines.push(\n 'These multi-operation tools gate ONLY the destructive branches (typically `operation: \"delete\"` or similar). Read the tool result envelope: if it carries `status: \"pending-confirmation\"` then the change is pending \u2014 tell the operator it needs their approval. If it carries direct success data, the change has ALREADY BEEN APPLIED \u2014 report it in the past tense. Never assume one branch behaves like another.',\n )\n }\n if (blocked.length > 0) {\n lines.push('')\n lines.push(\n `Tools that are BLOCKED under the effective policy (read-only): ${blocked.join(', ')}.`,\n )\n lines.push(\n 'Calls to these tools are refused before the handler runs. Do not attempt them; instead direct the operator to the matching backoffice page or to switch the tenant policy if they have permission.',\n )\n }\n lines.push('')\n lines.push(\n 'This RUNTIME policy block always wins over any conflicting \"approval card\" language earlier in the prompt \u2014 the static prompt is written for the most restrictive case but real behavior depends on the per-call policy described here.',\n )\n return lines.join('\\n')\n}\n\nfunction appendRuntimeMutationPolicy(\n systemPrompt: string,\n agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },\n mutationPolicyOverride: string | null,\n): string {\n const block = buildRuntimeMutationPolicySection(agent, mutationPolicyOverride)\n if (!block) return systemPrompt\n return `${systemPrompt}\\n\\n${block}`\n}\n\nfunction appendRuntimeTaskPlanPrompt(systemPrompt: string, agent: Pick<AiAgentDefinition, 'taskPlan'>): string {\n if (!isAgentTaskPlanEnabled(agent)) return systemPrompt\n return `${systemPrompt}\\n\\n${TASK_PLAN_RUNTIME_PROMPT_SECTION}`\n}\n\n/**\n * Server-side helper that runs an Open Mercato agent in chat mode via the\n * Vercel AI SDK and returns a streaming `Response` ready to be emitted from a\n * route handler. Shares the same policy gate and tool resolution path as the\n * HTTP dispatcher \u2014 a caller using this helper can never bypass the agent's\n * `requiredFeatures`, `allowedTools`, `executionMode`, or `mutationPolicy`.\n *\n * Attachment-to-model conversion (Step 3.7): resolved\n * {@link AiResolvedAttachmentPart}s are materialized inline as AI SDK v6\n * `FileUIPart` entries on the last user message (images/PDFs) and as a\n * structured `[ATTACHMENTS]` block appended to the system prompt (text\n * extracts + metadata-only summaries). The existing `attachmentIds`\n * pass-through into `resolveAiAgentTools` is preserved \u2014 Step 3.6 parity\n * invariant #7 still holds.\n */\nexport async function runAiAgentText(input: RunAiAgentTextInput): Promise<Response> {\n const [mutationPolicyOverride, tenantRuntimeOverride, tenantAllowlistSnapshot] = await Promise.all([\n resolveMutationPolicyOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveRuntimeModelOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveTenantAllowlistSnapshot(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n ])\n // Phase 6.2 \u2014 resolve the effective session id. `sessionId` takes precedence\n // over the deprecated `conversationId` alias. When neither is supplied, a\n // fresh UUID is generated server-side so token-usage rows and pending-action\n // idempotency hashes are always correlated within the same session.\n const effectiveSessionId = (input.sessionId ?? input.conversationId) || randomUUID()\n\n const { agent, tools, toolCallTimings } = await resolveAiAgentTools({\n agentId: input.agentId,\n authContext: input.authContext,\n pageContext: input.pageContext,\n attachmentIds: input.attachmentIds,\n mutationPolicyOverride,\n container: input.container,\n conversationId: effectiveSessionId,\n })\n\n const resolvedAttachments = await resolveAttachmentPartsForAgent({\n agent,\n attachmentIds: input.attachmentIds,\n authContext: input.authContext,\n container: input.container,\n })\n\n const composedPrompt = await composeSystemPromptWithMeta(\n agent,\n input.pageContext,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n input.authContext.userId,\n )\n const systemPrompt = appendRuntimeMutationPolicy(\n appendRuntimeTaskPlanPrompt(appendAttachmentSummary(composedPrompt.prompt, resolvedAttachments), agent),\n agent,\n mutationPolicyOverride,\n )\n\n const resolvedModel = resolveAgentModel(\n agent,\n input.modelOverride,\n input.providerOverride,\n input.container,\n input.baseUrlOverride,\n tenantRuntimeOverride,\n input.requestOverride,\n tenantAllowlistSnapshot,\n resolveEndUserIdentifier(input.authContext),\n )\n const { model } = resolvedModel\n const runId = input.runId ?? randomUUID()\n const turnId = randomUUID()\n const runToolNames = listRunToolNames(tools)\n const runCapture = createAgentRunCapture({\n container: input.container,\n trace: input.trace,\n runId,\n agent,\n authContext: input.authContext,\n executionMode: 'chat',\n effectiveMutationPolicy: resolveEffectiveMutationPolicy(agent.mutationPolicy, mutationPolicyOverride, agent.id),\n toolNames: runToolNames,\n mutationToolNames: listMutationToolNames(runToolNames),\n conversationId: effectiveSessionId,\n turnId,\n apiKeyId: null,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n baseUrl: resolvedModel.baseURL,\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n })\n const observe = composeCallObservers(input.observe, runCapture?.observer)\n const runPromptContext: AgentRunPromptContext = {\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n pageContextHydrated: composedPrompt.pageContextHydrated,\n attachmentCount: resolvedAttachments.length,\n provider: resolvedModel.providerId ?? null,\n modelId: resolvedModel.modelId ?? null,\n }\n await reportPromptResolved(observe, agent.id, runPromptContext)\n const effectiveCallSettings = mergeCallSettings(agent.modelSettings, input.callSettings)\n const hasCallSettings = Object.keys(effectiveCallSettings).length > 0\n const sdkCallSettings = toSdkCallSettings(effectiveCallSettings, resolvedModel.providerOptions)\n const { providerOptions: modelProviderOptions, ...sdkCallSettingsWithoutProviderOptions } = sdkCallSettings\n const modelCallHooks = createModelCallObserverHooks(observe, {\n agentId: agent.id,\n providerOptions: modelProviderOptions,\n })\n const normalizedMessages = ensureUiMessageShape(input.messages)\n\n // Pre-loop input moderation gate (spec 2026-06-04). Runs before the model\n // call on enabled/enforced surfaces where the provider supports moderation.\n // Throws AiModerationBlockedError (flagged) or AiModerationUnavailableError\n // (enforced + outage); both are surfaced by the SSE error path.\n let moderationService: ModerationService | null = null\n try {\n moderationService = input.container?.resolve<ModerationService>('moderationService') ?? null\n } catch {\n moderationService = null\n }\n // Read tenant overrides only when the provider can moderate and the agent is\n // not already enforced (untrustedInput short-circuits to enforced) \u2014 avoids a\n // DB round-trip on the common skip paths.\n const moderationOverrides =\n resolvedModel.supportsInputModeration && agent.untrustedInput !== true\n ? await resolveModerationOverrideValues(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n agent.id,\n )\n : { perAgentOverride: null, tenantWideOverride: null }\n await runInputModerationGate({\n untrustedInput: agent.untrustedInput,\n supportsInputModeration: resolvedModel.supportsInputModeration,\n perAgentOverride: moderationOverrides.perAgentOverride,\n tenantWideOverride: moderationOverrides.tenantWideOverride,\n userText: extractLatestUserText(normalizedMessages),\n service: moderationService,\n resolveApiKey: () => llmProviderRegistry.get(resolvedModel.providerId)?.resolveApiKey() ?? null,\n baseURL: resolvedModel.baseURL,\n moderationModel: process.env.OM_AI_MODERATION_MODEL,\n onFlagged: (categories) =>\n recordModerationFlag(\n {\n tenantId: input.authContext.tenantId,\n organizationId: input.authContext.organizationId,\n agentId: agent.id,\n userId: input.authContext.userId,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n categories,\n },\n input.container,\n ),\n })\n\n const hydratedMessages = attachAttachmentsToMessages(normalizedMessages, resolvedAttachments)\n const modelMessages = await convertToModelMessages(hydratedMessages)\n\n const effectiveLoop = resolveEffectiveLoopConfig(agent, input.loop, WRAPPER_DEFAULT_LOOP_CHAT)\n const stopConditions = translateStopConditions(effectiveLoop, sanitizeToolNameForModel)\n const wrapperPrepareStep = buildWrapperPrepareStep(agent, effectiveLoop, tools)\n const sdkActiveTools = mapActiveToolsForModel(effectiveLoop.activeTools, tools)\n const sdkToolChoice = mapToolChoiceForModel(effectiveLoop.toolChoice)\n\n // Phase 3 + Phase 4 \u2014 budget enforcement + LoopTrace collection.\n // Layer order (outer \u2192 inner):\n // budgetEnforcer.wire(traceOnStepFinish) \u2192 traceOnStepFinish calls userOnStepFinish\n // The trace collector builds the per-turn LoopTrace; the budget enforcer\n // aborts via AbortController when any limit is exceeded.\n const loopTraceCollector = buildLoopTraceCollector(\n agent.id,\n effectiveSessionId,\n turnId,\n effectiveLoop.onStepFinish,\n toolCallTimings,\n )\n const abortController = new AbortController()\n const budgetEnforcer = new BudgetEnforcer(effectiveLoop.budget, abortController)\n const tracedOnStepFinish = budgetEnforcer.wire(loopTraceCollector.onStepFinish)\n\n // Phase 6.3 \u2014 wire the token-usage recorder into the wrapper-owned onStepFinish.\n // The recorder fires AFTER the trace collector so modelId is already in the trace.\n // It is invoked as void (detached) and MUST NEVER throw per R12.\n // resolvedModel is already computed above (model, modelId, providerId).\n\n let currentStepIndex = 0\n const wiredOnStepFinish: AiAgentLoopConfig['onStepFinish'] = async (event) => {\n const capturedStepIndex = currentStepIndex\n currentStepIndex += 1\n\n if (tracedOnStepFinish) {\n await tracedOnStepFinish(event)\n }\n runCapture?.recordStep(event)\n if (input.container) {\n const rawEvent = event as unknown as {\n usage?: { inputTokens?: number; outputTokens?: number; cachedInputTokens?: number; reasoningTokens?: number }\n finishReason?: string\n }\n void recordTokenUsage(\n {\n authContext: input.authContext,\n agentId: agent.id,\n moduleId: agent.moduleId,\n sessionId: effectiveSessionId,\n turnId,\n stepIndex: capturedStepIndex,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n usage: {\n inputTokens: rawEvent.usage?.inputTokens,\n outputTokens: rawEvent.usage?.outputTokens,\n cachedInputTokens: rawEvent.usage?.cachedInputTokens,\n reasoningTokens: rawEvent.usage?.reasoningTokens,\n },\n finishReason: rawEvent.finishReason,\n loopAbortReason: budgetEnforcer.abortReason ?? undefined,\n },\n input.container,\n )\n }\n }\n\n let wallClockTimer: ReturnType<typeof setTimeout> | undefined\n if (effectiveLoop.budget?.maxWallClockMs) {\n wallClockTimer = setTimeout(() => {\n budgetEnforcer.recordStep({ toolCalls: 0 })\n }, effectiveLoop.budget.maxWallClockMs)\n }\n\n // Phase 5 \u2014 construct ToolLoopAgent when executionEngine === 'tool-loop-agent'.\n // The agent is built ONCE per turn (not pooled) with:\n // - model + tools from the wrapper-resolved registry\n // - stopWhen wired at construction (ToolLoopAgentSettings field)\n // - prepareStep wired at construction (NOT via prepareCall \u2014 it is not in\n // prepareCall's Pick list per spec \u00A7Phase 5 correction)\n // - onStepFinish wired at construction (budget + trace collector)\n // - prepareCall used only for per-turn narrowing of model/tools/stopWhen/\n // activeTools/providerOptions (per spec \u00A7Phase 5 correction)\n let builtToolLoopAgent: ToolLoopAgent<never, ToolSet> | undefined\n if (agent.executionEngine === 'tool-loop-agent') {\n const agentSettings: ToolLoopAgentSettingsWithModelCallHooks = {\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n instructions: systemPrompt,\n tools: tools as ToolSet,\n stopWhen: stopConditions,\n prepareStep: wrapperPrepareStep,\n onStepFinish: wiredOnStepFinish,\n ...(effectiveLoop.repairToolCall !== undefined\n ? { experimental_repairToolCall: effectiveLoop.repairToolCall }\n : {}),\n ...(sdkActiveTools !== undefined ? { activeTools: sdkActiveTools } : {}),\n ...(sdkToolChoice !== undefined ? { toolChoice: sdkToolChoice } : {}),\n ...sdkCallSettingsWithoutProviderOptions,\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions as never } : {}),\n ...(modelCallHooks ?? {}),\n }\n builtToolLoopAgent = new ToolLoopAgent<never, ToolSet>(agentSettings)\n }\n\n const preparedOptions: PreparedAiSdkOptions = {\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n tools,\n system: systemPrompt,\n messages: modelMessages,\n maxSteps: effectiveLoop.maxSteps ?? 10,\n stopWhen: stopConditions,\n prepareStep: wrapperPrepareStep,\n onStepFinish: wiredOnStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n onToolCallStart: effectiveLoop.onToolCallStart,\n onToolCallFinish: effectiveLoop.onToolCallFinish,\n experimental_repairToolCall: effectiveLoop.repairToolCall,\n activeTools: sdkActiveTools,\n toolChoice: sdkToolChoice,\n abortSignal: abortController.signal,\n finalizeLoopTrace: () => ({ ...loopTraceCollector.finalize(budgetEnforcer.abortReason), runId }),\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions } : {}),\n ...(hasCallSettings ? { callSettings: effectiveCallSettings } : {}),\n ...(builtToolLoopAgent !== undefined ? { toolLoopAgent: builtToolLoopAgent } : {}),\n ...(modelCallHooks ?? {}),\n }\n\n // Phase 1 of `2026-05-13-ai-chat-visible-task-plan` \u2014 every chat-mode\n // response stream is wrapped in a task-plan injector. The injector is\n // additive and keyed by the per-turn `turnId` so old clients that ignore\n // unknown chunks keep working; current clients render only agent-authored\n // plan rows and leave raw lifecycle progress in the tool-call details.\n const taskPlanId = `turn_${turnId}`\n\n const settleTextRun = async (\n status: 'completed' | 'failed' | 'aborted',\n trace: LoopTrace,\n error?: unknown,\n ): Promise<void> => {\n if (!runCapture) return\n try {\n await runCapture.settle({\n status,\n loopParams: buildRunLoopParams(effectiveLoop, toAgentRunModelSource(resolvedModel.source)),\n inputText: extractLatestUserText(normalizedMessages) || null,\n steps: trace.steps,\n stopReason: status === 'aborted' && trace.stopReason === 'finish-reason' ? 'abort' : trace.stopReason,\n outputText: joinStepText(trace.steps),\n ...(error !== undefined && error !== null ? { error } : {}),\n })\n } catch (settleError) {\n logger.warn('Run settle failed; ignoring', { err: settleError })\n reportAiAssistantError(settleError, 'ai_assistant.agent_run_settle_failed')\n }\n }\n\n const dispatchTextStream = async (): Promise<Response> => {\n if (input.generateText) {\n try {\n const callbackResult = await input.generateText(preparedOptions)\n const baseResponse = (callbackResult as StreamTextResult<ToolSet, Record<string, unknown>, never>).toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n } finally {\n if (wallClockTimer !== undefined) clearTimeout(wallClockTimer)\n }\n }\n\n // Phase 5 \u2014 engine dispatch: tool-loop-agent path vs default stream-text path.\n if (builtToolLoopAgent !== undefined) {\n // `ToolLoopAgent.stream` dispatches via the agent's own prepareCall/prepareStep\n // pipeline. prepareStep is already wired at construction (security-critical),\n // and so is `onStepFinish` \u2014 passing it here too makes the SDK merge both\n // wirings without dedup, so the budget enforcer and the loop trace would count\n // every step twice and abort the turn before the final answer (#5042).\n const agentStreamResult = await builtToolLoopAgent.stream({\n messages: modelMessages,\n abortSignal: abortController.signal,\n })\n if (wallClockTimer !== undefined) {\n const clearTimer = () => clearTimeout(wallClockTimer!)\n Promise.resolve(agentStreamResult.consumeStream()).then(clearTimer, clearTimer)\n }\n const baseResponse = agentStreamResult.toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n }\n\n // Default stream-text path (executionEngine === 'stream-text' or unset).\n const result = streamText({\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n tools,\n stopWhen: stopConditions as never,\n prepareStep: wrapperPrepareStep as never,\n onStepFinish: wiredOnStepFinish as never,\n experimental_onStepStart: effectiveLoop.onStepStart as never,\n experimental_onToolCallStart: effectiveLoop.onToolCallStart as never,\n experimental_onToolCallFinish: effectiveLoop.onToolCallFinish as never,\n experimental_repairToolCall: effectiveLoop.repairToolCall as never,\n ...(sdkActiveTools !== undefined ? { activeTools: sdkActiveTools } : {}),\n ...(sdkToolChoice !== undefined ? { toolChoice: sdkToolChoice } : {}),\n ...sdkCallSettingsWithoutProviderOptions,\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions as never } : {}),\n ...(modelCallHooks ?? {}),\n abortSignal: abortController.signal,\n })\n if (wallClockTimer !== undefined) {\n const clearTimer = () => clearTimeout(wallClockTimer!)\n Promise.resolve(result.consumeStream()).then(clearTimer, clearTimer)\n }\n const baseResponse = result.toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n }\n\n let streamResponse: Response\n try {\n streamResponse = await dispatchTextStream()\n } catch (error) {\n void settleTextRun(\n abortController.signal.aborted ? 'aborted' : 'failed',\n preparedOptions.finalizeLoopTrace(),\n error,\n )\n throw error\n }\n if (!input.emitLoopTrace && !runCapture) return streamResponse\n return appendLoopFinishToStream(streamResponse, {\n emitLoopTrace: input.emitLoopTrace === true,\n finalizeLoopTrace: preparedOptions.finalizeLoopTrace,\n abortSignal: abortController.signal,\n ...(runCapture\n ? { onSettled: (outcome: TextRunStreamOutcome, trace: LoopTrace) => settleTextRun(outcome.status, trace, outcome.error) }\n : {}),\n })\n}\n\n/**\n * Runtime override for the structured-output schema used by {@link runAiAgentObject}.\n * When the agent itself declares no `output` block, the caller MUST supply this;\n * otherwise the helper rejects with {@link AgentPolicyError} code\n * `execution_mode_not_supported`.\n */\nexport interface RunAiAgentObjectOutputOverride<TSchema = ZodTypeAny> {\n schemaName: string\n schema: TSchema\n /**\n * `'generate'` (default) calls AI SDK `generateObject` and resolves to the\n * parsed object. `'stream'` calls `streamObject` and returns the SDK's\n * streaming handle so callers can consume partial objects / text deltas.\n */\n mode?: 'generate' | 'stream'\n}\n\nexport interface RunAiAgentObjectInput<TSchema = ZodTypeAny> {\n agentId: string\n /**\n * Accepts either a bare user prompt (wrapped as `[{ role: 'user', content }]`)\n * or a prebuilt `UIMessage[]` array \u2014 matches the source spec's\n * `RunAiAgentObjectInput` contract (\u00A71149\u20131160).\n */\n input: string | UIMessage[]\n attachmentIds?: string[]\n pageContext?: AgentRequestPageContext\n /**\n * Same Phase-1 shim as {@link RunAiAgentTextInput.authContext}. Required until\n * a global request-context resolver lands (Phase 4).\n */\n authContext: AiChatRequestContext\n modelOverride?: string\n /**\n * Optional request-time provider override. When non-empty, wins for the\n * provider axis at the same priority as `modelOverride` for the model axis.\n *\n * Phase 1 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n providerOverride?: string\n /**\n * Optional per-call base URL override. Wins over every other source in the\n * baseURL resolution chain. Intended for programmatic callers only \u2014 the\n * HTTP query-param baseUrl and the AI_RUNTIME_BASEURL_ALLOWLIST arrive in\n * Phase 4a and MUST NOT be exposed here.\n *\n * Phase 2 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n baseUrlOverride?: string\n /**\n * Per-request HTTP dispatcher override (query params `?provider=`, `?model=`,\n * `?baseUrl=`). Validated by the dispatcher route before being forwarded\n * here. Wins over tenantOverride and all lower-priority sources when\n * `agent.allowRuntimeOverride !== false`.\n *\n * Phase 4a of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n requestOverride?: {\n providerId?: string | null\n modelId?: string | null\n baseURL?: string | null\n }\n output?: RunAiAgentObjectOutputOverride<TSchema>\n /**\n * Opt-in: run the agent as a READ-ONLY tool loop that finalizes into the\n * structured-output schema, instead of the toolless `generateObject` call.\n *\n * When `true` AND the agent resolves at least one tool, the runtime dispatches\n * via `generateText({ tools, output: Output.object({ schema }) })`\n * so the model can call its allowlisted tools to gather data before emitting\n * the structured object. The mutation-approval gate (`buildWrapperPrepareStep`)\n * is wired identically to chat mode, and read-only agents already have every\n * `isMutation: true` tool stripped \u2014 so this never enables a direct write.\n *\n * When `false`/omitted (or no tools resolve) the existing toolless\n * `generateObject`/`streamObject` path runs unchanged.\n */\n enableTools?: boolean\n debug?: boolean\n container?: AwilixContainer\n /**\n * Optional stable per-run session id for token-usage correlation.\n * Object-mode runs are single-turn by definition but the session id lets\n * callers group multiple object runs together for reporting.\n *\n * Phase 6.2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n sessionId?: string | null\n /**\n * Optional per-call loop config override for object mode. Only the\n * object-safe subset is accepted: `maxSteps`, `budget`, `onStepFinish`,\n * `onStepStart`, and `allowRuntimeOverride`. Providing any chat-only\n * field (`prepareStep`, `repairToolCall`, `stopWhen`, `activeTools`,\n * `toolChoice`) throws `AgentPolicyError` code\n * `loop_unsupported_in_object_mode`.\n *\n * Exception: `prepareStep` is honoured on the `enableTools` tool-loop branch,\n * composed under the wrapper-owned `prepareStep` exactly like chat mode (the\n * caller's value replaces `agent.loop.prepareStep`). When `enableTools` is set\n * but no tools resolve, the caller's `prepareStep` is dropped with a warning\n * instead of failing the run; without `enableTools` it still throws.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n loop?: Pick<\n AiAgentLoopConfig,\n 'maxSteps' | 'budget' | 'onStepFinish' | 'onStepStart' | 'allowRuntimeOverride' | 'prepareStep'\n >\n /**\n * Optional escape-hatch callback receiving the fully prepared object-mode\n * options bag. When supplied the wrapper still enforces all policy guardrails\n * and then delegates the actual SDK call to this function. The callback MUST\n * return a value compatible with `GenerateObjectResult` or `StreamObjectResult`.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n generateObject?: (\n options: PreparedAiSdkObjectOptions,\n ) => Promise<GenerateObjectResult<unknown> | StreamObjectResult<unknown, unknown, unknown>>\n /**\n * Surface the run is invoked on behalf of. Defaults to `'agent'` (today's\n * behaviour). An MCP / tools-api caller passes its channel and server\n * `mutationMode`: `direct` / `deny` force the run read-only, `approval`\n * keeps the agent's own policy and queues its writes as pending actions\n * stamped with the channel, `apiKeyId` and `correlationId` (spec\n * `2026-10-21-mcp-tool-exposure-parity-and-audit` \u00A73.1).\n */\n channel?: AiPendingActionChannel\n mutationMode?: McpMutationMode\n apiKeyId?: string | null\n correlationId?: string | null\n /**\n * Model-call contract fields (spec `2026-10-21-chat-run-tracing-and-citations` \u00A76).\n * `runId` pins the run identifier, `trace` controls run persistence and\n * channel attribution, `callSettings` are merged over the agent's\n * `modelSettings` key by key, and `observe` receives per-call events.\n */\n runId?: string\n trace?: AiAgentRunTraceOptions\n callSettings?: AiAgentCallSettings\n observe?: AiAgentCallObserver\n /** Caller-owned signal; aborting it aborts the run's model calls. */\n abortSignal?: AbortSignal\n}\n\nexport type RunAiAgentObjectGenerateResult<TSchema> = {\n mode: 'generate'\n object: TSchema\n finishReason?: string\n usage?: { inputTokens?: number; outputTokens?: number }\n /**\n * Per-step records from the read-only tool loop, in the same\n * {@link LoopStepRecord} shape the chat path's LoopTrace collector produces.\n * Present only on the `enableTools` tool-loop branch; the toolless\n * `generateObject`/`streamObject` paths never set it. Additive \u2014 consumed by\n * the agent-orchestrator native runtime for per-step trace capture (spec\n * `2026-07-07-lightweight-agent-runtime` Phase 1).\n */\n steps?: LoopStepRecord[]\n /**\n * Ids of the pending actions the run's mutation tools queued for approval.\n * Present only when at least one was created.\n */\n pendingActionIds?: string[]\n /**\n * Provider warnings of the toolless `generateObject` call (e.g. an\n * `unsupported` setting the provider dropped). The tool-loop branch reports\n * them per step through `loop.onStepFinish` instead. Additive.\n */\n warnings?: AiAgentCallWarning[]\n /** Run identifier the call is traced under (`ai_agent_runs.id`). */\n runId?: string\n}\n\nexport type AiAgentCallWarning = { type: string; feature?: string; details?: string; message?: string }\n\nfunction readCallWarnings(result: unknown): AiAgentCallWarning[] | undefined {\n const warnings = (result as { warnings?: unknown } | null)?.warnings\n if (!Array.isArray(warnings) || warnings.length === 0) return undefined\n return warnings.filter(\n (warning): warning is AiAgentCallWarning =>\n Boolean(warning) && typeof warning === 'object' && typeof (warning as { type?: unknown }).type === 'string',\n )\n}\n\nexport type RunAiAgentObjectStreamResult<TSchema> = {\n mode: 'stream'\n /** Full parsed object once the stream completes. */\n object: Promise<TSchema>\n /** Async iterator of partial (progressively hydrated) objects. */\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n /** Async iterator of the raw text deltas the model emitted. */\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n /** Run identifier the call is traced under (`ai_agent_runs.id`). */\n runId?: string\n}\n\nexport type RunAiAgentObjectResult<TSchema> =\n | RunAiAgentObjectGenerateResult<TSchema>\n | RunAiAgentObjectStreamResult<TSchema>\n\nfunction linkCallerAbortSignal(signal: AbortSignal | undefined, controller: AbortController): void {\n if (!signal) return\n if (signal.aborted) {\n controller.abort(signal.reason)\n return\n }\n signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true })\n}\n\nfunction normalizeObjectMessages(input: string | UIMessage[]): UIMessage[] {\n if (typeof input === 'string') {\n return [\n {\n id: 'user-input',\n role: 'user',\n parts: [{ type: 'text', text: input }],\n } as unknown as UIMessage,\n ]\n }\n return input\n}\n\nfunction resolveStructuredOutput<TSchema>(\n agent: AiAgentDefinition,\n override: RunAiAgentObjectOutputOverride<TSchema> | undefined,\n): { schemaName: string; schema: unknown; mode: 'generate' | 'stream' } {\n if (override) {\n return {\n schemaName: override.schemaName,\n schema: override.schema as unknown,\n mode: override.mode ?? 'generate',\n }\n }\n const declared = agent.output as AiAgentStructuredOutput | undefined\n if (!declared) {\n throw new AgentPolicyError(\n 'execution_mode_not_supported',\n `Agent \"${agent.id}\" does not declare a structured-output schema; pass runAiAgentObject({ output }) or declare agent.output.`,\n )\n }\n return {\n schemaName: declared.schemaName,\n schema: declared.schema as unknown,\n mode: declared.mode ?? 'generate',\n }\n}\n\n/**\n * Server-side helper that runs an Open Mercato agent in structured-output mode\n * via the Vercel AI SDK. Shares the same policy gate, tool resolution path,\n * system-prompt composition, and model resolution as {@link runAiAgentText} \u2014\n * object-mode and chat-mode CANNOT diverge.\n *\n * Attachment-to-model conversion (Step 3.7): resolved\n * {@link AiResolvedAttachmentPart}s are materialized inline as AI SDK v6\n * `FileUIPart` entries on the last user message (images/PDFs) and as a\n * structured `[ATTACHMENTS]` block appended to the system prompt (text\n * extracts + metadata-only summaries). Matches {@link runAiAgentText} byte-\n * for-byte so the Step 3.6 parity contract is preserved.\n */\nexport async function runAiAgentObject<TSchema = unknown>(\n input: RunAiAgentObjectInput<TSchema>,\n): Promise<RunAiAgentObjectResult<TSchema>> {\n const [mutationPolicyOverride, tenantRuntimeOverride, tenantAllowlistSnapshot] = await Promise.all([\n resolveMutationPolicyOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveRuntimeModelOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveTenantAllowlistSnapshot(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n ])\n const { agent, tools, pendingActionIds, toolCallTimings } = await resolveAiAgentTools({\n agentId: input.agentId,\n authContext: input.authContext,\n pageContext: input.pageContext,\n attachmentIds: input.attachmentIds,\n requestedExecutionMode: 'object',\n mutationPolicyOverride,\n container: input.container,\n channel: input.channel,\n mutationMode: input.mutationMode,\n apiKeyId: input.apiKeyId,\n correlationId: input.correlationId,\n })\n const runMutationPolicyOverride = resolveAgentRunMutationPolicyOverride({\n channel: input.channel,\n mutationMode: input.mutationMode,\n declaredPolicy: agent.mutationPolicy,\n tenantOverride: mutationPolicyOverride,\n canQueueMutations: typeof input.container !== 'undefined',\n })\n\n const resolvedOutput = resolveStructuredOutput(agent, input.output)\n\n const resolvedAttachments = await resolveAttachmentPartsForAgent({\n agent,\n attachmentIds: input.attachmentIds,\n authContext: input.authContext,\n container: input.container,\n })\n\n const composedPrompt = await composeSystemPromptWithMeta(\n agent,\n input.pageContext,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n input.authContext.userId,\n )\n const systemPrompt = appendRuntimeMutationPolicy(\n appendRuntimeTaskPlanPrompt(appendAttachmentSummary(composedPrompt.prompt, resolvedAttachments), agent),\n agent,\n runMutationPolicyOverride,\n )\n\n const resolvedObjectModel = resolveAgentModel(\n agent,\n input.modelOverride,\n input.providerOverride,\n input.container,\n input.baseUrlOverride,\n tenantRuntimeOverride,\n input.requestOverride,\n tenantAllowlistSnapshot,\n )\n const { model } = resolvedObjectModel\n const objectRunId = input.runId ?? randomUUID()\n const effectiveObjectSessionId = input.sessionId ?? randomUUID()\n const objectTurnId = randomUUID()\n const objectToolNames = listRunToolNames(tools)\n const objectRunCapture = createAgentRunCapture({\n container: input.container,\n trace: input.trace,\n runId: objectRunId,\n agent,\n authContext: input.authContext,\n executionMode: 'object',\n effectiveMutationPolicy: resolveEffectiveMutationPolicy(agent.mutationPolicy, runMutationPolicyOverride, agent.id),\n toolNames: objectToolNames,\n mutationToolNames: listMutationToolNames(objectToolNames),\n conversationId: input.sessionId ?? null,\n turnId: objectTurnId,\n apiKeyId: input.apiKeyId ?? null,\n fallbackCorrelationId: input.correlationId ?? null,\n providerId: resolvedObjectModel.providerId,\n modelId: resolvedObjectModel.modelId,\n baseUrl: resolvedObjectModel.baseURL,\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n })\n const objectObserve = composeCallObservers(input.observe, objectRunCapture?.observer)\n const runPromptContext: AgentRunPromptContext = {\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n pageContextHydrated: composedPrompt.pageContextHydrated,\n attachmentCount: resolvedAttachments.length,\n provider: resolvedObjectModel.providerId ?? null,\n modelId: resolvedObjectModel.modelId ?? null,\n }\n await reportPromptResolved(objectObserve, agent.id, runPromptContext)\n const effectiveCallSettings = mergeCallSettings(agent.modelSettings, input.callSettings)\n const hasCallSettings = Object.keys(effectiveCallSettings).length > 0\n const { providerOptions: objectProviderOptions, ...objectCallSettings } = toSdkCallSettings(effectiveCallSettings)\n const sdkCallSettings = {\n ...objectCallSettings,\n ...(objectProviderOptions !== undefined ? { providerOptions: objectProviderOptions as never } : {}),\n }\n const normalizedMessages = ensureUiMessageShape(normalizeObjectMessages(input.input))\n const hydratedMessages = attachAttachmentsToMessages(\n normalizedMessages,\n resolvedAttachments,\n )\n const modelMessages = await convertToModelMessages(hydratedMessages)\n const objectResponseFormat = objectObserve && !isLightweightCallObserver(objectObserve)\n ? buildObjectResponseFormat(resolvedOutput.schemaName, resolvedOutput.schema)\n : undefined\n\n const abortController = new AbortController()\n linkCallerAbortSignal(input.abortSignal, abortController)\n const objectInputText = extractLatestUserText(normalizedMessages) || null\n const objectModelSource = toAgentRunModelSource(resolvedObjectModel.source)\n let objectRunLoop: AiAgentLoopConfig = {}\n const objectToolLoop: { trace: ReturnType<typeof buildLoopTraceCollector> | null } = { trace: null }\n\n const settleObjectRun = async (\n status: 'completed' | 'failed' | 'aborted',\n details: {\n steps: LoopStepRecord[]\n object?: unknown\n finishReason?: string | null\n usage?: { inputTokens?: number; outputTokens?: number } | null\n error?: unknown\n },\n ): Promise<void> => {\n if (!objectRunCapture) return\n try {\n await objectRunCapture.settle({\n status,\n loopParams: buildRunLoopParams(objectRunLoop, objectModelSource),\n inputText: objectInputText,\n steps: details.steps,\n stopReason: status === 'aborted' ? 'abort' : status === 'completed' ? 'finish-reason' : null,\n finishReason: details.finishReason ?? null,\n outputText: serializeObjectOutput(details.object),\n usage: details.usage ?? null,\n ...(details.error !== undefined ? { error: details.error } : {}),\n })\n } catch (settleError) {\n logger.warn('Run settle failed; ignoring', { err: settleError })\n reportAiAssistantError(settleError, 'ai_assistant.agent_run_settle_failed')\n }\n }\n\n const synthesizeObjectStep = (\n finishReason: string | undefined,\n usage: { inputTokens?: number; outputTokens?: number } | undefined,\n ): LoopStepRecord[] => {\n objectRunCapture?.recordStep({ finishReason, usage })\n return [\n {\n stepIndex: 0,\n modelId: resolvedObjectModel.modelId,\n toolCalls: [],\n textDelta: '',\n usage: { inputTokens: usage?.inputTokens ?? 0, outputTokens: usage?.outputTokens ?? 0 },\n finishReason: (finishReason ?? 'stop') as LoopStepRecord['finishReason'],\n },\n ]\n }\n\n const dispatchObjectRun = async (): Promise<RunAiAgentObjectResult<TSchema>> => {\n // Read-only tool-loop path (opt-in via `enableTools`). When the agent resolves\n // tools, run a `generateText` loop that finalizes into the output schema via\n // `experimental_output`, so the model can read through its allowlisted tools\n // before proposing. The mutation gate + stop conditions are wired exactly as in\n // chat mode; read-only agents have mutation tools stripped, so no direct write\n // is ever possible. Falls through to `generateObject` when no tools resolve.\n const resolvedToolNames = Object.keys((tools ?? {}) as ToolSet)\n // Degrading to a single-shot call is a legitimate fallback, but it silently\n // changes what the agent CAN do \u2014 an agent whose prompt says \"validate your\n // draft with the tool before returning\" is now being asked to obey an\n // instruction it has no way to follow. Say so, loudly, once per turn.\n if (input.enableTools && resolvedToolNames.length === 0) {\n logger.warn(\n 'Agent requested a tool loop but no tools resolved; falling back to a single-shot generateObject',\n {\n agentId: agent.id,\n allowedTools: agent.allowedTools,\n },\n )\n }\n if (input.enableTools && resolvedToolNames.length > 0) {\n const toolLoopConfig = resolveEffectiveLoopConfig(agent, input.loop, WRAPPER_DEFAULT_LOOP_CHAT)\n const toolStopConditions = translateStopConditions(toolLoopConfig, sanitizeToolNameForModel)\n const toolWrapperPrepareStep = buildWrapperPrepareStep(agent, toolLoopConfig, tools)\n // Per-step exposure (native-runtime spec Phase 1, additive): aggregate the\n // AI SDK's step records through the same collector the chat path uses and\n // forward the caller's `loop.onStepFinish` \u2014 previously silently dropped on\n // this branch. Callers that pass no `loop.onStepFinish` observe identical\n // behavior plus the optional `steps` field on the result.\n objectRunLoop = toolLoopConfig\n const toolLoopTrace = buildLoopTraceCollector(\n agent.id,\n effectiveObjectSessionId,\n objectTurnId,\n toolLoopConfig.onStepFinish,\n toolCallTimings,\n )\n objectToolLoop.trace = toolLoopTrace\n const toolLoopOnStepFinish: AiAgentLoopConfig['onStepFinish'] = objectRunCapture\n ? async (event) => {\n await toolLoopTrace.onStepFinish?.(event)\n objectRunCapture.recordStep(event)\n }\n : toolLoopTrace.onStepFinish\n const toolLoopModelCallHooks = createModelCallObserverHooks(objectObserve, {\n agentId: agent.id,\n providerOptions: objectProviderOptions,\n responseFormat: objectResponseFormat,\n })\n const toolResult = await generateText({\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n tools,\n stopWhen: toolStopConditions as never,\n prepareStep: toolWrapperPrepareStep as never,\n onStepFinish: toolLoopOnStepFinish as never,\n output: Output.object({ schema: resolvedOutput.schema as never }),\n ...sdkCallSettings,\n ...(toolLoopModelCallHooks ?? {}),\n abortSignal: abortController.signal,\n })\n return {\n mode: 'generate',\n object: (toolResult as unknown as { output: TSchema }).output,\n finishReason: (toolResult as { finishReason?: string }).finishReason,\n usage: {\n inputTokens: toolResult.usage?.inputTokens,\n outputTokens: toolResult.usage?.outputTokens,\n },\n steps: toolLoopTrace.finalize(null).steps,\n ...(pendingActionIds.length > 0 ? { pendingActionIds: [...pendingActionIds] } : {}),\n }\n }\n\n let toollessLoop = input.loop\n if (toollessLoop?.prepareStep && input.enableTools) {\n logger.warn('Caller prepareStep dropped: the tool loop fell back to a toolless generateObject', {\n agentId: agent.id,\n })\n toollessLoop = { ...toollessLoop, prepareStep: undefined }\n }\n if (toollessLoop) {\n assertLoopObjectModeCompatible(toollessLoop)\n }\n const effectiveLoop = resolveEffectiveLoopConfig(agent, toollessLoop, WRAPPER_DEFAULT_LOOP_OBJECT)\n objectRunLoop = effectiveLoop\n\n const preparedObjectOptions: PreparedAiSdkObjectOptions = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schemaName: resolvedOutput.schemaName,\n schema: resolvedOutput.schema,\n maxSteps: effectiveLoop.maxSteps,\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n abortSignal: abortController.signal,\n ...(hasCallSettings ? { callSettings: effectiveCallSettings } : {}),\n }\n\n const modelDescriptor = describeLanguageModel(model, {\n provider: resolvedObjectModel.providerId,\n modelId: resolvedObjectModel.modelId,\n })\n const synthesizedModelCall = createSynthesizedModelCall(objectObserve, {\n agentId: agent.id,\n provider: modelDescriptor.provider,\n modelId: modelDescriptor.modelId,\n system: systemPrompt,\n messages: modelMessages,\n responseFormat: objectResponseFormat,\n callSettings: effectiveCallSettings,\n callerManaged: Boolean(input.generateObject),\n })\n await synthesizedModelCall?.start()\n\n if (input.generateObject) {\n const callbackResult = await input.generateObject(preparedObjectOptions)\n const typedResult = callbackResult as unknown as Record<string, unknown>\n if ('partialObjectStream' in typedResult) {\n const streamResult = typedResult as {\n object: Promise<TSchema>\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n }\n observeStreamedObjectEnd(synthesizedModelCall, streamResult)\n return {\n mode: 'stream',\n object: streamResult.object,\n partialObjectStream: streamResult.partialObjectStream,\n textStream: streamResult.textStream,\n finishReason: streamResult.finishReason,\n usage: streamResult.usage,\n }\n }\n const genResult = typedResult as { object: unknown; finishReason?: string; usage?: { inputTokens?: number; outputTokens?: number } }\n await synthesizedModelCall?.end(readSynthesizedResultMetadata(typedResult))\n const genWarnings = readCallWarnings(typedResult)\n return {\n mode: 'generate',\n object: genResult.object as TSchema,\n finishReason: genResult.finishReason,\n usage: genResult.usage,\n ...(genWarnings ? { warnings: genWarnings } : {}),\n }\n }\n\n if (resolvedOutput.mode === 'stream') {\n const streamArgs = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schema: resolvedOutput.schema as never,\n schemaName: resolvedOutput.schemaName,\n ...(effectiveLoop.maxSteps !== undefined ? { maxSteps: effectiveLoop.maxSteps } : {}),\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n ...sdkCallSettings,\n abortSignal: abortController.signal,\n } as Parameters<typeof streamObject>[0]\n const result = streamObject(streamArgs) as unknown as {\n object: Promise<TSchema>\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n }\n observeStreamedObjectEnd(synthesizedModelCall, result)\n return {\n mode: 'stream',\n object: result.object,\n partialObjectStream: result.partialObjectStream,\n textStream: result.textStream,\n finishReason: result.finishReason,\n usage: result.usage,\n }\n }\n\n const generateArgs = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schema: resolvedOutput.schema as never,\n schemaName: resolvedOutput.schemaName,\n ...(effectiveLoop.maxSteps !== undefined ? { maxSteps: effectiveLoop.maxSteps } : {}),\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n ...sdkCallSettings,\n abortSignal: abortController.signal,\n } as Parameters<typeof generateObject>[0]\n\n const result = await generateObject(generateArgs)\n await synthesizedModelCall?.end(readSynthesizedResultMetadata(result))\n const resultWarnings = readCallWarnings(result)\n return {\n mode: 'generate',\n object: (result as { object: unknown }).object as TSchema,\n finishReason: (result as { finishReason?: string }).finishReason,\n usage: (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage,\n ...(resultWarnings ? { warnings: resultWarnings } : {}),\n }\n }\n\n let objectResult: RunAiAgentObjectResult<TSchema>\n try {\n objectResult = await dispatchObjectRun()\n } catch (error) {\n void settleObjectRun(abortController.signal.aborted ? 'aborted' : 'failed', {\n steps: objectToolLoop.trace ? objectToolLoop.trace.finalize(null).steps : [],\n error,\n })\n throw error\n }\n\n if (objectResult.mode === 'generate') {\n void settleObjectRun('completed', {\n steps: objectResult.steps ?? synthesizeObjectStep(objectResult.finishReason, objectResult.usage),\n object: objectResult.object,\n finishReason: objectResult.finishReason ?? null,\n usage: objectResult.usage ?? null,\n })\n return { ...objectResult, runId: objectRunId }\n }\n\n if (objectRunCapture) {\n const streamed = objectResult\n void Promise.resolve(streamed.object).then(\n async (value) => {\n const [finishReason, usage] = await Promise.all([\n Promise.resolve(streamed.finishReason).catch(() => undefined),\n Promise.resolve(streamed.usage).catch(() => undefined),\n ])\n await settleObjectRun('completed', {\n steps: synthesizeObjectStep(finishReason, usage),\n object: value,\n finishReason: finishReason ?? null,\n usage: usage ?? null,\n })\n },\n async (error: unknown) => {\n await settleObjectRun(abortController.signal.aborted ? 'aborted' : 'failed', { steps: [], error })\n },\n )\n }\n return { ...objectResult, runId: objectRunId }\n}\n\nexport { AgentPolicyError }\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAehC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAsB;AAAA,OACjB;AAGP,SAAS,oBAAoB,mCAAmC;AAMhE,SAAS,mBAAmB,yBAAyB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iCAAiC;AAC1C,SAAS,8BAA8B;AACvC,SAAS,gCAAgC;AACzC,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AAarC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sCAAsC;AAC/C,SAAS,6CAA6C;AAGtD,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AAChD,SAAS,+CAA+C;AACxD,SAAS,wCAAwC;AACjD,SAAS,wCAAwC;AAEjD,SAAS,uCAAuC;AAChD,SAAS,iBAAiB,4BAA4B;AAEtD,SAAS,8BAA8B;AACvC,SAAS,uBAAuB,qBAAqB;AAErD,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAEjD,MAAM,SAAS,aAAa,cAAc,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAkJhF,MAAM,4BAA+C,EAAE,UAAU,GAAG;AACpE,MAAM,8BAA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a,SAAS;AAAA,IAC/B,CAAC;AACD,WAAO,EAAE,GAAG,cAAc,OAAO,YAAY;AAAA,EAC/C;AAEA,MAAI,kBAAkB;AACpB,UAAM,WAAW;AACjB,SAAK,QAAQ,QAAQ,SAAS,MAAM,EAAE;AAAA,MACpC,OAAO,UAAU;AACf,cAAM,CAAC,cAAc,KAAK,IAAI,MAAM,QAAQ,IAAI;AAAA,UAC9C,QAAQ,QAAQ,SAAS,YAAY,EAAE,MAAM,MAAM,MAAS;AAAA,UAC5D,QAAQ,QAAQ,SAAS,KAAK,EAAE,MAAM,MAAM,MAAS;AAAA,QACvD,CAAC;AACD,cAAM,gBAAgB,aAAa;AAAA,UACjC,OAAO,qBAAqB,cAAc,KAAK;AAAA,UAC/C,QAAQ;AAAA,UACR,cAAc,gBAAgB;AAAA,UAC9B,OAAO,SAAS;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,MACA,OAAO,UAAmB;AACxB,cAAM,gBAAgB,gBAAgB,OAAO,UAAU,YAAY,UAAU,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC;AAAA,MACnG;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,GAAG,cAAc,OAAO,YAAY;AAC/C;",
|
|
4
|
+
"sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { randomUUID } from 'node:crypto'\nimport { createContainer } from 'awilix'\nimport type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n GenerateObjectResult,\n GenerateTextResult,\n LanguageModel,\n PrepareStepFunction,\n PrepareStepResult,\n StreamObjectResult,\n StreamTextResult,\n ToolSet,\n UIMessage,\n ToolLoopAgentSettings,\n} from 'ai'\nimport {\n convertToModelMessages,\n generateObject,\n generateText,\n hasToolCall,\n Output,\n stepCountIs,\n streamObject,\n streamText,\n Experimental_Agent as ToolLoopAgent,\n} from 'ai'\nimport type { StopCondition } from 'ai'\nimport type { ZodTypeAny } from 'zod'\nimport { createModelFactory, resolveAllowRuntimeOverride } from './model-factory'\nimport type {\n AiAgentCallObserver,\n AiAgentCallSettings,\n AiAgentRunTraceOptions,\n} from './agent-call-contract'\nimport { mergeCallSettings, toSdkCallSettings } from './agent-call-contract'\nimport {\n buildObjectResponseFormat,\n composeCallObservers,\n createModelCallObserverHooks,\n createSynthesizedModelCall,\n describeLanguageModel,\n isLightweightCallObserver,\n notifyPromptResolved,\n observeStreamedObjectEnd,\n readSynthesizedResultMetadata,\n type ModelCallObserverHooks,\n} from './agent-call-observer'\nimport { resolveAllowlistedBaseurl } from './baseurl-allowlist'\nimport { reportAiAssistantError } from './report-ai-assistant-error'\nimport { computeEndUserIdentifier } from '@open-mercato/shared/lib/ai/safety-identifier'\nimport { llmProviderRegistry } from './llm-registry'\nimport type { EnvLookup } from '@open-mercato/shared/lib/ai/llm-provider'\nimport {\n AiModerationBlockedError,\n AiModerationUnavailableError,\n type ModerationService,\n} from './moderation'\nimport {\n isModerationActive,\n resolveModerationPolicy,\n shouldFailClosed,\n} from './moderation-policy'\nimport { recordModerationFlag } from './moderation-flag-recorder'\nimport type {\n AiAgentDefinition,\n AiAgentLoopConfig,\n AiAgentPageContextInput,\n AiAgentStructuredOutput,\n LoopStepRecord,\n LoopTrace,\n} from './ai-agent-definition'\nimport type {\n AiChatRequestContext,\n AiResolvedAttachmentPart,\n} from './attachment-bridge-types'\nimport {\n resolveAiAgentTools,\n AgentPolicyError,\n desanitizeToolNameForDisplay,\n sanitizeToolNameForModel,\n} from './agent-tools'\nimport { resolveEffectiveMutationPolicy } from './agent-policy'\nimport { resolveAgentRunMutationPolicyOverride } from './agent-channel-policy'\nimport type { McpMutationMode } from './mcp-exposure'\nimport type { AiPendingActionChannel } from './pending-action-types'\nimport { toolRegistry } from './tool-registry'\nimport {\n attachmentPartsToUiFileParts,\n resolveAttachmentPartsForAgent,\n summarizeAttachmentPartsForPrompt,\n} from './attachment-parts'\nimport { AiAgentPromptOverrideRepository } from '../data/repositories/AiAgentPromptOverrideRepository'\nimport { AiAgentMutationPolicyOverrideRepository } from '../data/repositories/AiAgentMutationPolicyOverrideRepository'\nimport { AiAgentRuntimeOverrideRepository } from '../data/repositories/AiAgentRuntimeOverrideRepository'\nimport { AiTenantModelAllowlistRepository } from '../data/repositories/AiTenantModelAllowlistRepository'\nimport type { TenantAllowlistSnapshot } from './model-allowlist'\nimport { composeSystemPromptWithOverride } from './prompt-override-merge'\nimport { extractStepMeta, extractStepToolCalls } from './loop-step-extraction'\nimport type { RawStepEvent, ToolCallTimings } from './loop-step-extraction'\nimport { isAgentTaskPlanEnabled } from './agent-registry'\nimport { createAgentRunCapture, stopWhenKinds } from './agent-run-capture'\nimport type { AgentRunLoopParams, AgentRunModelSource } from './agent-run-recorder'\nimport { isKnownMutationPolicy } from './agent-policy'\nimport type { AiAgentMutationPolicy } from './ai-agent-definition'\nimport { recordTokenUsage } from './token-usage-recorder'\nimport { injectTaskPlanIntoStream } from './task-plan-stream'\nimport { TASK_PLAN_RUNTIME_PROMPT_SECTION } from './task-plan-labels'\n\nconst logger = createLogger('ai_assistant').child({ component: 'agent-runtime' })\n\nexport interface AgentRequestPageContext {\n pageId?: string | null\n entityType?: string | null\n recordId?: string | null\n [key: string]: unknown\n}\n\nexport interface RunAiAgentTextInput {\n agentId: string\n messages: UIMessage[]\n attachmentIds?: string[]\n pageContext?: AgentRequestPageContext\n debug?: boolean\n /**\n * Phase 1 exposes the caller-supplied auth context directly on the helper\n * input. Phase 4 may wrap this behind a thinner public API once a global\n * request-context resolver exists. Helpers running inside the HTTP\n * dispatcher receive the same `AiChatRequestContext` used by `checkAgentPolicy`.\n */\n authContext: AiChatRequestContext\n /**\n * Optional per-call model id override that wins over `agent.defaultModel`.\n * The production model-factory extraction lives in Step 5.1; this Step\n * accepts a literal model id string so the Phase 1 runtime already honors\n * `agent.defaultModel` without inventing a new indirection layer.\n */\n modelOverride?: string\n /**\n * Optional request-time provider override. When non-empty, wins for the\n * provider axis at the same priority as `modelOverride` for the model axis.\n * A value that does not match any registered provider id is silently ignored.\n *\n * Phase 1 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n providerOverride?: string\n /**\n * Optional per-call base URL override. Wins over every other source in the\n * baseURL resolution chain. Intended for programmatic callers only \u2014 the\n * HTTP query-param baseUrl and the AI_RUNTIME_BASEURL_ALLOWLIST arrive in\n * Phase 4a and MUST NOT be exposed here.\n *\n * Phase 2 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n baseUrlOverride?: string\n /**\n * Per-request HTTP dispatcher override (query params `?provider=`, `?model=`,\n * `?baseUrl=`). Validated by the dispatcher route before being forwarded\n * here. Wins over tenantOverride and all lower-priority sources when\n * `agent.allowRuntimeOverride !== false`.\n *\n * Phase 4a of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n requestOverride?: {\n providerId?: string | null\n modelId?: string | null\n baseURL?: string | null\n }\n /**\n * Optional DI container used by `resolvePageContext` callbacks. When omitted\n * and the agent declares a `resolvePageContext`, hydration is skipped with a\n * warning (callbacks that need database/DI cannot run safely without one).\n */\n container?: AwilixContainer\n /**\n * Stable per-conversation id that ties every turn of a chat together for\n * token-usage correlation and pending-action idempotency (Phase 6.2).\n *\n * When omitted the server generates one and echoes it on the SSE `done`\n * event so the client can persist it for subsequent turns. Callers that\n * supply a value from a previous turn will have their usage rows grouped\n * under the same `session_id` in the token-usage tables.\n *\n * Phase 6.2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n sessionId?: string | null\n /**\n * @deprecated Use `sessionId` instead. This alias was the original name of\n * the same field; both names are accepted for one minor release to let\n * callers migrate without a hard cut. `sessionId` takes precedence when both\n * are provided.\n */\n conversationId?: string | null\n /**\n * Optional per-call loop config override. Fields set here win over the\n * agent's `loop` declaration and the tenant DB override. The override is\n * gated by `agent.loop?.allowRuntimeOverride ?? true` \u2014 agents that pin\n * a loop policy for correctness reasons can set `allowRuntimeOverride: false`\n * to reject any per-call override with `AgentPolicyError` code\n * `loop_runtime_override_disabled`.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n loop?: Partial<AiAgentLoopConfig>\n /**\n * Optional escape-hatch callback that receives the fully prepared AI SDK\n * options bag and must return the SDK result (either from `streamText` or\n * `generateText`). When supplied, the wrapper still enforces every policy\n * guardrail (features, tool allowlist, mutation approval, model factory,\n * prompt composition, attachment bridging) and then hands control to this\n * callback instead of calling `streamText` directly.\n *\n * The callback MUST pass `stopWhen` and `prepareStep` through to the AI SDK\n * call \u2014 dropping either one disables the agent's loop policy or mutation\n * approval guards respectively. See `agents.mdx` \u00A7\"Option B\" for the full\n * contract and what you lose when fields are omitted.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n generateText?: (\n options: PreparedAiSdkOptions,\n ) => Promise<\n | GenerateTextResult<ToolSet, Record<string, unknown>, never>\n | StreamTextResult<ToolSet, Record<string, unknown>, never>\n >\n /**\n * When `true`, the runtime appends a `loop-finish` SSE event to the\n * response stream after the AI SDK stream closes. The event payload is the\n * serialized `LoopTrace` for the turn (agent id, turn id, per-step records,\n * stop reason, total duration, total usage).\n *\n * Consumed by `useAiChat` to populate `lastLoopTrace` and by the playground\n * debug panel to render the per-turn trace via `LoopTracePanel`.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n emitLoopTrace?: boolean\n /**\n * Model-call contract fields (spec `2026-10-21-chat-run-tracing-and-citations` \u00A76).\n * `runId` pins the run identifier, `trace` controls run persistence and\n * channel attribution, `callSettings` are merged over the agent's\n * `modelSettings` key by key, and `observe` receives per-call events.\n */\n runId?: string\n trace?: AiAgentRunTraceOptions\n callSettings?: AiAgentCallSettings\n observe?: AiAgentCallObserver\n}\n\n/**\n * The wrapper default loop config used when neither the caller, tenant, agent,\n * nor legacy maxSteps supplies any config. Chat mode defaults to `{ maxSteps: 10 }`\n * to ensure tool-using agents can loop; object mode defaults to an empty config\n * (single structured-output call, no explicit step cap).\n */\nconst WRAPPER_DEFAULT_LOOP_CHAT: AiAgentLoopConfig = { maxSteps: 10 }\nconst WRAPPER_DEFAULT_LOOP_OBJECT: AiAgentLoopConfig = {}\n\n/**\n * Named loop-budget preset values for `?loopBudget=<preset>` query param.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport type AiAgentLoopBudgetPreset = 'tight' | 'default' | 'loose'\n\n/**\n * Maps a `loopBudget` preset name to the corresponding `AiAgentLoopBudget`\n * triple. `'default'` returns `undefined` (no override \u2014 agent default applies).\n * Values are pinned per spec \u00A7\"loopBudget preset values (Phase 4)\".\n */\nexport function resolveLoopBudgetPreset(\n preset: AiAgentLoopBudgetPreset,\n): Partial<AiAgentLoopConfig> | undefined {\n switch (preset) {\n case 'tight':\n return { maxSteps: 3, budget: { maxToolCalls: 3, maxWallClockMs: 10_000, maxTokens: 50_000 } }\n case 'loose':\n return { maxSteps: 20, budget: { maxToolCalls: 20, maxWallClockMs: 120_000, maxTokens: 500_000 } }\n case 'default':\n return undefined\n }\n}\n\nconst SSE_ENCODER = new TextEncoder()\n\nexport type TextRunStreamOutcome = {\n status: 'completed' | 'failed' | 'aborted'\n error: { code: string; message: string } | null\n}\n\ntype StreamOutcomeScanner = {\n push(chunk: Uint8Array): void\n outcome(): TextRunStreamOutcome\n}\n\nfunction readStreamPartOutcome(line: string): TextRunStreamOutcome | null {\n if (!line.startsWith('data:')) return null\n if (!line.includes('\"type\":\"error\"') && !line.includes('\"type\":\"abort\"')) return null\n try {\n const parsed = JSON.parse(line.slice('data:'.length).trim()) as { type?: unknown; errorText?: unknown }\n if (parsed.type === 'error') {\n const message = typeof parsed.errorText === 'string' ? parsed.errorText : ''\n return { status: 'failed', error: { code: 'stream_error', message } }\n }\n if (parsed.type === 'abort') return { status: 'aborted', error: null }\n } catch {\n return null\n }\n return null\n}\n\nfunction createStreamOutcomeScanner(): StreamOutcomeScanner {\n const decoder = new TextDecoder()\n let pending = ''\n let current: TextRunStreamOutcome = { status: 'completed', error: null }\n function consume(line: string): void {\n const parsed = readStreamPartOutcome(line)\n if (!parsed) return\n if (current.status === 'failed') return\n current = parsed\n }\n return {\n push(chunk) {\n pending += decoder.decode(chunk, { stream: true })\n const lines = pending.split('\\n')\n pending = lines.pop() ?? ''\n for (const line of lines) consume(line)\n },\n outcome() {\n if (pending.length > 0) {\n consume(pending)\n pending = ''\n }\n return current\n },\n }\n}\n\ntype StreamFinalizeOptions = {\n emitLoopTrace: boolean\n finalizeLoopTrace: () => LoopTrace\n abortSignal?: AbortSignal\n onSettled?: (outcome: TextRunStreamOutcome, trace: LoopTrace) => Promise<unknown>\n}\n\n/**\n * Wraps a streaming `Response` with a post-stream finalize hook. When\n * `emitLoopTrace` is set, a typed `loop-finish` SSE event carrying the\n * serialized `LoopTrace` is appended after the AI SDK stream closes. The\n * optional `onSettled` hook runs after the client stream is closed, so it never\n * holds the response open.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`; generalized by\n * spec `2026-10-21-chat-run-tracing-and-citations` \u00A72.\n */\nasync function cancelReaderQuietly(reader: ReadableStreamDefaultReader<Uint8Array>, reason: unknown): Promise<void> {\n try {\n await reader.cancel(reason)\n } catch {\n return\n }\n}\n\nfunction appendLoopFinishToStream(baseResponse: Response, options: StreamFinalizeOptions): Response {\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n const writer = writable.getWriter()\n const scanner = options.onSettled ? createStreamOutcomeScanner() : null\n\n async function pump(): Promise<void> {\n let outcome: TextRunStreamOutcome = { status: 'completed', error: null }\n let trace: LoopTrace | null = null\n let downstreamClosed = false\n const writeDownstream = async (chunk: Uint8Array): Promise<void> => {\n try {\n await writer.write(chunk)\n } catch (error) {\n downstreamClosed = true\n throw error\n }\n }\n if (!baseResponse.body) {\n await writer.close()\n } else {\n const reader = baseResponse.body.getReader()\n writer.closed.catch((reason: unknown) => {\n downstreamClosed = true\n void cancelReaderQuietly(reader, reason)\n })\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n scanner?.push(value)\n await writeDownstream(value)\n }\n if (downstreamClosed) throw new Error('[internal] downstream stream closed')\n trace = options.finalizeLoopTrace()\n if (options.emitLoopTrace) {\n const eventLine = `data: ${JSON.stringify({ type: 'loop-finish', trace })}\\n\\n`\n await writeDownstream(SSE_ENCODER.encode(eventLine))\n }\n if (scanner) outcome = scanner.outcome()\n if (outcome.status === 'completed' && options.abortSignal?.aborted === true) {\n outcome = { status: 'aborted', error: null }\n }\n } catch (error) {\n await cancelReaderQuietly(reader, error)\n const aborted =\n downstreamClosed ||\n options.abortSignal?.aborted === true ||\n (error instanceof Error && error.name === 'AbortError') ||\n (scanner !== null && scanner.outcome().status === 'aborted')\n outcome = aborted\n ? { status: 'aborted', error: null }\n : { status: 'failed', error: { code: 'stream_error', message: error instanceof Error ? error.message : String(error) } }\n } finally {\n reader.releaseLock()\n await writer.close().catch(() => undefined)\n }\n }\n if (options.onSettled) {\n try {\n await options.onSettled(outcome, trace ?? options.finalizeLoopTrace())\n } catch (error) {\n logger.warn('Run finalize hook failed; stream already delivered', { err: error })\n reportAiAssistantError(error, 'ai_assistant.agent_run_finalize_failed')\n }\n }\n }\n\n void pump()\n return new Response(readable, {\n status: baseResponse.status,\n headers: baseResponse.headers,\n })\n}\n\n/**\n * The fully prepared options bag handed to the `runAiAgentText({ generateText })`\n * escape-hatch callback. Callers receive a complete set of wrapper-composed\n * loop primitives so they can forward them to `streamText` / `generateText`.\n *\n * SECURITY CONTRACT: callers MUST forward `prepareStep` to the AI SDK call.\n * Dropping it removes the per-step tool-allowlist re-check and the mutation-\n * approval wrapping. Dropping `stopWhen` removes the agent's loop policy and\n * the R3 step-count fallback.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport interface PreparedAiSdkOptions {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n tools: ToolSet\n system: string\n messages: Awaited<ReturnType<typeof convertToModelMessages>>\n /** Alias kept for SDK compat \u2014 equals `stopWhen` array's effective maxSteps. */\n maxSteps: number\n /**\n * Wrapper-composed stop conditions (R3 mitigated: always ends with\n * `stepCountIs(maxSteps)`). MUST be forwarded to the SDK call.\n */\n stopWhen: StopCondition<ToolSet>[]\n /**\n * Wrapper-owned `PrepareStepFunction` that re-asserts the tool allowlist and\n * mutation-approval wrapping per step. SECURITY-CRITICAL: callers MUST\n * forward this to the SDK call or they lose mutation-approval guarantees.\n */\n prepareStep: PrepareStepFunction<ToolSet>\n /** Wrapper trace aggregator chained with the agent's `onStepFinish` hook. */\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n onStepStart: AiAgentLoopConfig['onStepStart']\n onToolCallStart: AiAgentLoopConfig['onToolCallStart']\n onToolCallFinish: AiAgentLoopConfig['onToolCallFinish']\n experimental_repairToolCall: AiAgentLoopConfig['repairToolCall']\n activeTools: AiAgentLoopConfig['activeTools']\n toolChoice: AiAgentLoopConfig['toolChoice']\n /**\n * Pre-wired to the per-turn `AbortController` used by budget enforcement\n * (Phase 3). Forward to the SDK call so budget limits can abort in-flight\n * requests. May be `undefined` when budget enforcement is not yet active\n * (Phases 0\u20132); the SDK treats `undefined` the same as no signal.\n */\n abortSignal: AbortSignal | undefined\n /**\n * Finalizes the per-turn `LoopTrace` and returns it. Callers that use the\n * `generateText` escape-hatch SHOULD call this after the SDK call resolves so\n * the trace is available for logging or SSE emission.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n finalizeLoopTrace: () => LoopTrace\n /**\n * Present only when `agent.executionEngine === 'tool-loop-agent'`. Callers\n * can invoke `agent.generate(...)` / `agent.stream(...)` directly with their\n * own `providerOptions` as an escape-hatch \u2014 the `ToolLoopAgent` instance is\n * already wired with the wrapper-owned `prepareStep`, `stopWhen`, and\n * `onStepFinish` at construction.\n *\n * Phase 5 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n toolLoopAgent?: ToolLoopAgent<never, ToolSet>\n /**\n * Provider-specific `providerOptions` fragment carrying the mapped end-user\n * safety identifier (e.g. OpenAI `safety_identifier`). Present only when an\n * identifier was derived and the resolved provider supports the mapping.\n * Callers using the `generateText` escape-hatch MUST forward it to the SDK\n * call so the identifier reaches the provider.\n *\n * Spec `2026-06-04-ai-input-moderation-and-safety-identifiers`.\n */\n providerOptions?: Record<string, unknown>\n /**\n * Effective call settings (agent `modelSettings` merged with per-call\n * `callSettings`). Present only when at least one setting is declared.\n * `providerOptions` above already carries the merged provider options.\n */\n callSettings?: AiAgentCallSettings\n /**\n * AI SDK call-level hooks that feed `input.observe` with one start/end event\n * per model call. Present only when an observer with model-call handlers is\n * supplied. Callers SHOULD forward both to the SDK call.\n */\n onLanguageModelCallStart?: ModelCallObserverHooks['onLanguageModelCallStart']\n onLanguageModelCallEnd?: ModelCallObserverHooks['onLanguageModelCallEnd']\n}\n\ntype ToolLoopAgentSettingsWithModelCallHooks = ToolLoopAgentSettings<never, ToolSet> & Partial<ModelCallObserverHooks>\n\n/**\n * The fully prepared options bag handed to the `runAiAgentObject({ generateObject })`\n * escape-hatch callback. Object-mode subset \u2014 chat-only fields are absent.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport interface PreparedAiSdkObjectOptions {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n system: string\n messages: Awaited<ReturnType<typeof convertToModelMessages>>\n schemaName: string\n schema: unknown\n maxSteps: number | undefined\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n onStepStart: AiAgentLoopConfig['onStepStart']\n abortSignal: AbortSignal | undefined\n /**\n * Effective call settings (agent `modelSettings` merged with per-call\n * `callSettings`). Present only when at least one setting is declared.\n * Callers SHOULD spread them into the SDK call.\n */\n callSettings?: AiAgentCallSettings\n}\n\n/**\n * Guards the per-call loop override against agents that have opted out of\n * runtime overrides by setting `loop.allowRuntimeOverride: false`.\n *\n * Throws `AgentPolicyError` with code `loop_runtime_override_disabled` when\n * the agent has opted out and a caller override was supplied.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nfunction assertLoopRuntimeOverrideAllowed(\n agent: AiAgentDefinition,\n callerLoop: Partial<AiAgentLoopConfig> | undefined,\n): void {\n if (!callerLoop) return\n const allowed = agent.loop?.allowRuntimeOverride ?? true\n if (!allowed) {\n throw new AgentPolicyError(\n 'loop_runtime_override_disabled',\n `Agent \"${agent.id}\" has disabled per-call loop overrides (loop.allowRuntimeOverride: false). Remove the loop override to proceed.`,\n )\n }\n}\n\n/**\n * Reads `<MODULE>_AI_LOOP_*` env shorthands for the given module id.\n * Returns a partial `AiAgentLoopConfig` containing only the axes that are\n * explicitly set in the environment. Missing or malformed values are silently\n * ignored (fail-open \u2014 env vars are a best-effort static deployment mechanism).\n *\n * Supported variables (Phase 3 of spec\n * `2026-04-28-ai-agents-agentic-loop-controls`):\n *\n * - `<MODULE>_AI_LOOP_MAX_STEPS` \u2014 maps to `loop.maxSteps`\n * - `<MODULE>_AI_LOOP_MAX_WALL_CLOCK_MS` \u2014 maps to `loop.budget.maxWallClockMs`\n * - `<MODULE>_AI_LOOP_MAX_TOKENS` \u2014 maps to `loop.budget.maxTokens`\n */\nfunction readModuleLoopEnv(moduleId: string): Partial<AiAgentLoopConfig> {\n const prefix = moduleId.toUpperCase()\n const partial: Partial<AiAgentLoopConfig> = {}\n\n const maxStepsRaw = process.env[`${prefix}_AI_LOOP_MAX_STEPS`]\n if (maxStepsRaw) {\n const parsed = parseInt(maxStepsRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) partial.maxSteps = parsed\n }\n\n const maxWallClockRaw = process.env[`${prefix}_AI_LOOP_MAX_WALL_CLOCK_MS`]\n const maxTokensRaw = process.env[`${prefix}_AI_LOOP_MAX_TOKENS`]\n\n if (maxWallClockRaw || maxTokensRaw) {\n const budgetPartial: AiAgentLoopConfig['budget'] = {}\n if (maxWallClockRaw) {\n const parsed = parseInt(maxWallClockRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) budgetPartial.maxWallClockMs = parsed\n }\n if (maxTokensRaw) {\n const parsed = parseInt(maxTokensRaw.trim(), 10)\n if (!isNaN(parsed) && parsed > 0) budgetPartial.maxTokens = parsed\n }\n if (Object.keys(budgetPartial).length > 0) partial.budget = budgetPartial\n }\n\n return partial\n}\n\n/**\n * Resolves the effective loop config for a turn by walking the precedence\n * chain (highest first):\n *\n * 1. `callerLoop` \u2014 per-call `runAiAgentText({ loop })` override (Phase 1).\n * 2. Tenant override row \u2014 NOT yet implemented in DB; always `undefined` here.\n * // TODO(Phase 1782-3): hydrate loop columns from ai_agent_runtime_overrides\n * 3. `<MODULE>_AI_LOOP_*` env shorthands (Phase 3) \u2014 only MAX_STEPS,\n * MAX_WALL_CLOCK_MS, MAX_TOKENS. Lower precedence than DB override but higher\n * than the agent's code-declared defaults.\n * 4. `agent.loop` \u2014 agent's declarative loop config.\n * 5. `agent.maxSteps` (deprecated alias) \u2014 mapped to `{ maxSteps: agent.maxSteps }`.\n * 6. `wrapperDefault` \u2014 the wrapper's hardcoded fallback.\n *\n * Each source contributes only the fields it sets explicitly; fields absent at\n * a higher-priority source fall through to a lower-priority one. The merge is\n * performed left-to-right with higher-priority sources winning field-by-field.\n *\n * Throws `AgentPolicyError` code `loop_runtime_override_disabled` when the\n * agent opts out of per-call overrides and a caller loop was supplied.\n *\n * Phase 0 + Phase 1 + Phase 3 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function resolveEffectiveLoopConfig(\n agent: AiAgentDefinition,\n callerLoop?: Partial<AiAgentLoopConfig> | undefined,\n wrapperDefault?: AiAgentLoopConfig,\n): AiAgentLoopConfig {\n assertLoopRuntimeOverrideAllowed(agent, callerLoop)\n\n const effectiveDefault = wrapperDefault ?? WRAPPER_DEFAULT_LOOP_CHAT\n\n // Build base from lowest-priority: wrapper default \u2192 legacy maxSteps \u2192 agent.loop\n const legacyMaxSteps: AiAgentLoopConfig | undefined =\n typeof agent.maxSteps === 'number' && agent.maxSteps > 0 && !agent.loop\n ? { maxSteps: agent.maxSteps }\n : undefined\n\n const base: AiAgentLoopConfig = {\n ...effectiveDefault,\n ...(legacyMaxSteps ?? {}),\n ...(agent.loop ?? {}),\n }\n\n // Phase 3 \u2014 env shorthands at priority 3 (above agent.loop, below DB override).\n // TODO(Phase 1782-3): hydrate loop columns from ai_agent_runtime_overrides\n // and merge tenantOverride here at priority #2 (above envOverride).\n const envOverride = readModuleLoopEnv(agent.moduleId)\n const withEnv: AiAgentLoopConfig = {\n ...base,\n ...envOverride,\n ...(envOverride.budget != null\n ? { budget: { ...(base.budget ?? {}), ...envOverride.budget } }\n : {}),\n }\n\n const withCaller: AiAgentLoopConfig = callerLoop\n ? { ...withEnv, ...callerLoop }\n : withEnv\n\n // Phase 3 \u2014 kill switch: when disabled is set to true, force maxSteps: 1 so the\n // agent executes as a single model call with no tool looping. All other loop config\n // is preserved (budget, etc.) but the step cap wins.\n if (withCaller.disabled === true) {\n return { ...withCaller, maxSteps: 1 }\n }\n\n return withCaller\n}\n\n/**\n * The reason a budget limit was hit, exposed on `LoopAbortReason` (Phase 3).\n */\nexport type LoopBudgetAbortReason =\n | 'budget-tool-calls'\n | 'budget-wall-clock'\n | 'budget-tokens'\n\n/**\n * Tracks per-turn budget usage and aborts the run when any limit is exceeded.\n *\n * Usage:\n * 1. Construct with the loop budget and the turn's `AbortController`.\n * 2. Call `wire(onStepFinish)` to get a composed `onStepFinish` that feeds\n * usage data into the enforcer on every completed step.\n * 3. The enforcer calls `abortController.abort()` with a typed\n * `LoopBudgetAbortReason` when a limit is hit.\n *\n * Phase 3 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport class BudgetEnforcer {\n private toolCallsUsed = 0\n private tokensUsed = 0\n readonly turnStartMs: number\n abortReason: LoopBudgetAbortReason | null = null\n\n constructor(\n private readonly budget: AiAgentLoopConfig['budget'],\n private readonly abortController: AbortController,\n ) {\n this.turnStartMs = Date.now()\n }\n\n get hasActiveBudget(): boolean {\n const b = this.budget\n return (\n b !== undefined &&\n (b.maxToolCalls !== undefined || b.maxWallClockMs !== undefined || b.maxTokens !== undefined)\n )\n }\n\n recordStep(usage: { inputTokens?: number; outputTokens?: number; toolCalls?: number }): void {\n if (!this.budget) return\n this.toolCallsUsed += usage.toolCalls ?? 0\n this.tokensUsed += (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0)\n this.checkLimits()\n }\n\n private checkLimits(): void {\n const b = this.budget\n if (!b) return\n\n if (b.maxToolCalls !== undefined && this.toolCallsUsed >= b.maxToolCalls) {\n this.abort('budget-tool-calls')\n return\n }\n\n const elapsedMs = Date.now() - this.turnStartMs\n if (b.maxWallClockMs !== undefined && elapsedMs >= b.maxWallClockMs) {\n this.abort('budget-wall-clock')\n return\n }\n\n if (b.maxTokens !== undefined && this.tokensUsed >= b.maxTokens) {\n this.abort('budget-tokens')\n }\n }\n\n private abort(reason: LoopBudgetAbortReason): void {\n if (this.abortReason !== null) return\n this.abortReason = reason\n logger.info('Budget exceeded \u2014 aborting turn', {\n reason,\n toolCalls: this.toolCallsUsed,\n tokens: this.tokensUsed,\n elapsedMs: Date.now() - this.turnStartMs,\n })\n this.abortController.abort(reason)\n }\n\n wire(\n userOnStepFinish: AiAgentLoopConfig['onStepFinish'],\n ): AiAgentLoopConfig['onStepFinish'] {\n if (!this.hasActiveBudget) return userOnStepFinish\n return async (event) => {\n this.recordStep({\n inputTokens: event.usage?.inputTokens,\n outputTokens: event.usage?.outputTokens,\n toolCalls: event.toolCalls?.length,\n })\n if (userOnStepFinish) {\n try {\n await userOnStepFinish(event)\n } catch (err) {\n logger.error('User onStepFinish threw; ignoring', { err })\n }\n }\n }\n }\n}\n\n/**\n * Builds a wrapper-owned `onStepFinish` collector that aggregates per-step\n * usage and tool-call data into a `LoopTrace` object. The collector chains\n * the user's `onStepFinish` after it aggregates (exceptions from the user's\n * hook are caught and logged but do not abort the turn).\n *\n * Returns both the wired `onStepFinish` hook and a `finalize()` function that\n * resolves the `LoopTrace` once the turn is complete. The `budgetEnforcer`\n * is already wired into `onStepFinish` at a lower layer \u2014 this collector sits\n * above it.\n *\n * Phase 4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function buildLoopTraceCollector(\n agentId: string,\n sessionId: string,\n turnId: string,\n userOnStepFinish: AiAgentLoopConfig['onStepFinish'],\n toolCallTimings?: ToolCallTimings,\n): {\n onStepFinish: AiAgentLoopConfig['onStepFinish']\n finalize: (abortReason: LoopBudgetAbortReason | null) => LoopTrace\n} {\n const turnStartMs = Date.now()\n const steps: LoopStepRecord[] = []\n\n const onStepFinish: AiAgentLoopConfig['onStepFinish'] = async (event) => {\n const stepIndex = steps.length\n const rawEvent = event as unknown as RawStepEvent\n const toolCalls: LoopStepRecord['toolCalls'] = extractStepToolCalls(rawEvent, toolCallTimings).map(\n (extracted) => ({\n ...(extracted.toolCallId ? { toolCallId: extracted.toolCallId } : {}),\n toolName: desanitizeToolNameForDisplay(extracted.toolName),\n args: extracted.args,\n result: extracted.result,\n error: extracted.error,\n repairAttempted: extracted.repairAttempted,\n durationMs: extracted.durationMs ?? 0,\n }),\n )\n\n const stepMeta = extractStepMeta(rawEvent)\n const textDelta = stepMeta.text\n const finishReason = stepMeta.finishReason as LoopStepRecord['finishReason']\n const modelId = stepMeta.modelId\n\n steps.push({\n stepIndex,\n modelId,\n toolCalls,\n textDelta,\n usage: {\n inputTokens: stepMeta.usage.inputTokens,\n outputTokens: stepMeta.usage.outputTokens,\n },\n finishReason,\n })\n\n if (userOnStepFinish) {\n try {\n await userOnStepFinish(event)\n } catch (err) {\n logger.error('User onStepFinish in LoopTrace collector threw; ignoring', { err })\n }\n }\n }\n\n function finalize(abortReason: LoopBudgetAbortReason | null): LoopTrace {\n const totalDurationMs = Date.now() - turnStartMs\n const totalUsage = steps.reduce(\n (acc, step) => ({\n inputTokens: acc.inputTokens + step.usage.inputTokens,\n outputTokens: acc.outputTokens + step.usage.outputTokens,\n }),\n { inputTokens: 0, outputTokens: 0 },\n )\n\n let stopReason: LoopTrace['stopReason'] = 'finish-reason'\n if (abortReason === 'budget-tool-calls') stopReason = 'budget-tool-calls'\n else if (abortReason === 'budget-wall-clock') stopReason = 'budget-wall-clock'\n else if (abortReason === 'budget-tokens') stopReason = 'budget-tokens'\n\n return {\n agentId,\n sessionId,\n turnId,\n steps,\n stopReason,\n totalDurationMs,\n totalUsage,\n }\n }\n\n return { onStepFinish, finalize }\n}\n\n/**\n * Translates serializable `AiAgentLoopStopCondition` items into the Vercel AI\n * SDK `StopCondition` array ready to pass to `streamText` / `generateText`.\n *\n * The wrapper ALWAYS appends `stepCountIs(maxSteps ?? 10)` as the final item\n * in the returned array (R3 mitigation). This guarantees that a misconfigured\n * `hasToolCall` for a non-existent tool can never cause an infinite loop\n * because the SDK treats `stopWhen` arrays with OR semantics \u2014 the step-count\n * fallback will always trip eventually.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function translateStopConditions(\n loopConfig: AiAgentLoopConfig,\n mapToolName: (toolName: string) => string = (toolName) => toolName,\n): StopCondition<ToolSet>[] {\n const effectiveMaxSteps = loopConfig.maxSteps ?? 10\n const userConditions: StopCondition<ToolSet>[] = []\n\n const rawStopWhen = loopConfig.stopWhen\n if (rawStopWhen) {\n const items = Array.isArray(rawStopWhen) ? rawStopWhen : [rawStopWhen]\n for (const item of items) {\n if (item.kind === 'stepCount') {\n userConditions.push(stepCountIs(item.count))\n } else if (item.kind === 'hasToolCall') {\n userConditions.push(hasToolCall(mapToolName(item.toolName)))\n } else if (item.kind === 'custom') {\n userConditions.push(item.stop as StopCondition<ToolSet>)\n }\n }\n }\n\n // Always append the hard step-count fallback (R3 mitigation).\n return [...userConditions, stepCountIs(effectiveMaxSteps)]\n}\n\n/**\n * Security-critical merge of the wrapper-owned step override with the user's\n * `prepareStep` return value.\n *\n * Guarantees (R1 mitigation \u2014 preserving the mutation-approval contract):\n * 1. Any `tools` map returned by the user is intersected with `toolRegistry`\n * (the policy-gated, mutation-approval-wrapped map). If the user returned\n * a raw mutation handler, the merged map points at the wrapped one.\n * 2. Any `activeTools` returned by the user is intersected with\n * `agent.allowedTools`. Out-of-set names are dropped with a single\n * `loop:active_tools_filtered` warning.\n * 3. A user-returned `tools` map that contains a mutation tool pointing at the\n * raw handler (not the wrapped one) is rejected with\n * `AgentPolicyError` code `loop_violates_mutation_policy`.\n * 4. Non-policy fields (`model`, `toolChoice`, `system`, `messages`) from the\n * user override are honored as-is.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n *\n * ai-sdk 6.0.177 dropped the `tools` field from `PrepareStepResult`, so the\n * map is no longer consumed by `streamText` / `generateText`. We still inspect\n * any `tools` map that a caller passes via a type-asserted result \u2014 even\n * though the SDK ignores it \u2014 to keep the defense-in-depth guard and the\n * existing test contract (R1 mitigation #3) intact.\n */\ntype StepOverrideWithTools = NonNullable<PrepareStepResult<ToolSet>> & {\n tools?: Record<string, unknown>\n}\n\nfunction normalizeAllowedToolNameForAgent(\n toolName: string,\n agent: AiAgentDefinition,\n): string | null {\n if (agent.allowedTools.includes(toolName)) return toolName\n const dottedName = desanitizeToolNameForDisplay(toolName)\n return agent.allowedTools.includes(dottedName) ? dottedName : null\n}\n\nexport function mergeStepOverrides(\n wrapperOverride: PrepareStepResult<ToolSet>,\n userOverride: PrepareStepResult<ToolSet> | undefined | null,\n agent: AiAgentDefinition,\n wrappedToolRegistry: Record<string, unknown>,\n): PrepareStepResult<ToolSet> {\n if (!userOverride) return wrapperOverride\n\n const merged: StepOverrideWithTools = { ...(wrapperOverride as StepOverrideWithTools) }\n const userWithTools = userOverride as StepOverrideWithTools\n\n if (userOverride.model !== undefined) {\n merged.model = userOverride.model\n }\n if (userOverride.toolChoice !== undefined) {\n merged.toolChoice = userOverride.toolChoice\n }\n\n if (userOverride.activeTools !== undefined) {\n const filtered = userOverride.activeTools.flatMap((name) => {\n const normalized = normalizeAllowedToolNameForAgent(name, agent)\n const allowed = normalized !== null\n if (!allowed) {\n logger.warn('loop:active_tools_filtered \u2014 tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })\n }\n return normalized ? [normalized] : []\n })\n merged.activeTools = filtered\n }\n\n if (userWithTools.tools !== undefined) {\n const userTools = userWithTools.tools\n const mergedTools: Record<string, unknown> = {}\n\n for (const [toolKey, userHandler] of Object.entries(userTools)) {\n const wrappedHandler = wrappedToolRegistry[toolKey]\n if (!wrappedHandler) {\n logger.warn('mergeStepOverrides \u2014 tool from user prepareStep is not in the wrapper tool registry; dropping', { toolName: toolKey })\n continue\n }\n if (userHandler !== wrappedHandler) {\n const toolDef = toolRegistry.getTool(\n toolKey.replace(/__/g, '.'),\n ) as { isMutation?: boolean } | undefined\n if (toolDef?.isMutation === true) {\n throw new AgentPolicyError(\n 'loop_violates_mutation_policy',\n `User prepareStep returned a tools map with raw (unwrapped) mutation handler for \"${toolKey}\". This bypasses the mutation-approval gate and is rejected.`,\n )\n }\n }\n mergedTools[toolKey] = wrappedHandler\n }\n merged.tools = mergedTools\n }\n\n return merged\n}\n\nfunction mapPrepareStepResultForModel(\n result: PrepareStepResult<ToolSet>,\n wrappedTools: Record<string, unknown>,\n): PrepareStepResult<ToolSet> {\n if (!result?.activeTools) return result\n const activeTools = result.activeTools\n .map((toolName) => sanitizeToolNameForModel(toolName))\n .filter((toolName) => wrappedTools[toolName] !== undefined)\n return { ...result, activeTools }\n}\n\nfunction mapToolChoiceForModel(\n toolChoice: AiAgentLoopConfig['toolChoice'],\n): AiAgentLoopConfig['toolChoice'] {\n if (!toolChoice || typeof toolChoice !== 'object' || toolChoice.type !== 'tool') {\n return toolChoice\n }\n return {\n ...toolChoice,\n toolName: sanitizeToolNameForModel(toolChoice.toolName),\n } as AiAgentLoopConfig['toolChoice']\n}\n\nfunction mapActiveToolsForModel(\n activeTools: string[] | undefined,\n wrappedTools: Record<string, unknown>,\n): string[] | undefined {\n if (!activeTools) return undefined\n return activeTools\n .map((toolName) => sanitizeToolNameForModel(toolName))\n .filter((toolName) => wrappedTools[toolName] !== undefined)\n}\n\n/**\n * Builds the wrapper-owned `PrepareStepFunction` that enforces the tool\n * allowlist and mutation-approval contract on every step, then composes\n * the user's `prepareStep` on top via `mergeStepOverrides`.\n *\n * This is the SECURITY-CRITICAL function for Phase 0. The wrapper `prepareStep`\n * ensures:\n * - Tool active-set is always a subset of `effectiveLoop.activeTools ?? agent.allowedTools`.\n * - Mutation tools always point at the prepareMutation-wrapped handlers.\n * - User's `prepareStep` return value cannot smuggle raw mutation handlers.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function buildWrapperPrepareStep(\n agent: AiAgentDefinition,\n effectiveLoop: AiAgentLoopConfig,\n wrappedTools: Record<string, unknown>,\n): PrepareStepFunction<ToolSet> {\n return async (state) => {\n const wrapperOverride: PrepareStepResult<ToolSet> = {}\n\n if (effectiveLoop.activeTools && effectiveLoop.activeTools.length > 0) {\n wrapperOverride.activeTools = effectiveLoop.activeTools.flatMap((name) => {\n const normalized = normalizeAllowedToolNameForAgent(name, agent)\n const allowed = normalized !== null\n if (!allowed) {\n logger.warn('loop:active_tools_filtered \u2014 tool not in agent allowedTools; dropping from activeTools', { toolName: name, agentId: agent.id })\n }\n return normalized ? [normalized] : []\n })\n }\n\n if (effectiveLoop.prepareStep) {\n let userOverride: PrepareStepResult<ToolSet> | undefined | null\n try {\n userOverride = await effectiveLoop.prepareStep(state)\n } catch (error) {\n logger.error('User prepareStep threw; ignoring user override', { agentId: agent.id, err: error })\n return mapPrepareStepResultForModel(wrapperOverride, wrappedTools)\n }\n return mapPrepareStepResultForModel(\n mergeStepOverrides(wrapperOverride, userOverride, agent, wrappedTools),\n wrappedTools,\n )\n }\n\n return mapPrepareStepResultForModel(wrapperOverride, wrappedTools)\n }\n}\n\n/**\n * Validates that a loop config does not set any primitives that are\n * unsupported by the object-mode SDK path (`generateObject` / `streamObject`).\n *\n * Object mode accepts ONLY: `maxSteps`, `budget`, `onStepFinish`,\n * `onStepStart`, `allowRuntimeOverride`. The remaining fields\n * (`prepareStep`, `repairToolCall`, `stopWhen`, `activeTools`,\n * `toolChoice`) are chat-only and will never reach `generateObject`.\n *\n * Throws `AgentPolicyError` code `loop_unsupported_in_object_mode` if any\n * unsupported field is set. This provides an explicit, actionable error\n * rather than a silent no-op.\n *\n * Phase 0 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport function assertLoopObjectModeCompatible(loopConfig: Partial<AiAgentLoopConfig>): void {\n const unsupportedFields: string[] = []\n\n if (loopConfig.prepareStep !== undefined) unsupportedFields.push('prepareStep')\n if (loopConfig.repairToolCall !== undefined) unsupportedFields.push('repairToolCall')\n if (loopConfig.stopWhen !== undefined) unsupportedFields.push('stopWhen')\n if (loopConfig.activeTools !== undefined) unsupportedFields.push('activeTools')\n if (loopConfig.toolChoice !== undefined) unsupportedFields.push('toolChoice')\n\n if (unsupportedFields.length > 0) {\n throw new AgentPolicyError(\n 'loop_unsupported_in_object_mode',\n `Object-mode agents do not support these loop primitives: ${unsupportedFields.join(', ')}. Use runAiAgentText for agents that require these loop controls.`,\n )\n }\n}\n\ninterface ResolvedAgentModel {\n model: LanguageModel\n experimental_download?: import('ai').Experimental_DownloadFunction\n modelId: string\n providerId: string\n /**\n * Provider-specific `providerOptions` fragment carrying the mapped end-user\n * safety identifier (undefined when no identifier or no provider mapping).\n */\n providerOptions?: Record<string, unknown>\n /** Whether the resolved chat provider supports input moderation. */\n supportsInputModeration: boolean\n /** Resolved base URL (if any), reused by the moderation endpoint call. */\n baseURL?: string\n /** Which resolution source won, mapped onto the run trace `modelSource`. */\n source?: string\n}\n\nfunction toAgentRunModelSource(source: string | undefined): AgentRunModelSource {\n if (source === 'request_override' || source === 'caller_override') return 'request'\n if (source === 'tenant_override') return 'runtime-override'\n if (source === 'agent_default') return 'agent'\n return 'default'\n}\n\nfunction listMutationToolNames(toolNames: string[]): Set<string> {\n const mutationToolNames = new Set<string>()\n for (const toolName of toolNames) {\n const registered = toolRegistry.getTool(toolName) as { isMutation?: boolean } | undefined\n if (registered?.isMutation === true) mutationToolNames.add(toolName)\n }\n return mutationToolNames\n}\n\nfunction listRunToolNames(tools: Record<string, unknown> | undefined): string[] {\n return Object.keys(tools ?? {}).map((toolName) => desanitizeToolNameForDisplay(toolName))\n}\n\nfunction buildRunLoopParams(\n loop: AiAgentLoopConfig,\n modelSource: AgentRunModelSource,\n): AgentRunLoopParams {\n return {\n maxSteps: loop.maxSteps ?? null,\n toolChoice: loop.toolChoice,\n budget: loop.budget,\n activeTools: loop.activeTools ?? null,\n stopWhenKinds: stopWhenKinds(loop.stopWhen),\n allowRuntimeOverride: loop.allowRuntimeOverride ?? null,\n modelSource,\n }\n}\n\nfunction joinStepText(steps: LoopStepRecord[]): string | null {\n const text = steps.map((step) => step.textDelta ?? '').join('')\n return text.length > 0 ? text : null\n}\n\nfunction serializeObjectOutput(value: unknown): string | null {\n if (value === undefined || value === null) return null\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value)\n } catch {\n return null\n }\n}\n\nfunction resolveAgentModel(\n agent: AiAgentDefinition,\n modelOverride: string | undefined,\n providerOverride: string | undefined,\n container: AwilixContainer | undefined,\n baseUrlOverride?: string,\n tenantOverride?: { providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null,\n requestOverride?: { providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null,\n tenantAllowlist?: TenantAllowlistSnapshot | null,\n endUserIdentifier?: string,\n): ResolvedAgentModel {\n const effectiveContainer = container ?? createContainer()\n const resolution = createModelFactory(effectiveContainer).resolveModel({\n moduleId: agent.moduleId,\n agentDefaultModel: agent.defaultModel,\n agentDefaultProvider: agent.defaultProvider,\n agentDefaultBaseUrl: agent.defaultBaseUrl,\n callerOverride: modelOverride,\n providerOverride,\n baseUrlOverride,\n allowRuntimeOverride: resolveAllowRuntimeOverride(agent),\n tenantOverride: tenantOverride ?? undefined,\n requestOverride: requestOverride ?? undefined,\n tenantAllowlist: tenantAllowlist ?? null,\n endUserIdentifier,\n })\n return {\n model: resolution.model as LanguageModel,\n experimental_download: resolution.download,\n modelId: resolution.modelId,\n providerId: resolution.providerId,\n providerOptions: resolution.providerOptions,\n supportsInputModeration: resolution.supportsInputModeration === true,\n baseURL: resolution.baseURL,\n source: resolution.source,\n }\n}\n\n/**\n * Concatenates the text parts of the most recent user message. Only the new\n * user turn is moderated (prior history was screened on its own turn). Returns\n * an empty string when there is no user message or no text content.\n */\nexport function extractLatestUserText(messages: UIMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const raw = messages[index] as unknown as {\n role?: string\n content?: string\n parts?: Array<{ type?: string; text?: string }>\n }\n if (raw.role !== 'user') continue\n if (Array.isArray(raw.parts)) {\n return raw.parts\n .filter((part) => part?.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text as string)\n .join('\\n')\n }\n return typeof raw.content === 'string' ? raw.content : ''\n }\n return ''\n}\n\nexport interface InputModerationGateParams {\n untrustedInput?: boolean\n supportsInputModeration: boolean\n userText: string\n service: ModerationService | null\n /**\n * Lazy resolver for the moderation provider's API key. Invoked only when the\n * gate actually proceeds (policy active, provider supports moderation, text\n * non-empty, service present) \u2014 so callers never pay for (or fail on) key\n * resolution on the common skip paths.\n */\n resolveApiKey: () => string | null\n baseURL?: string\n moderationModel?: string\n perAgentOverride?: boolean | null\n tenantWideOverride?: boolean | null\n env?: EnvLookup\n /**\n * Best-effort side effect invoked with the flagged categories right before\n * the gate throws {@link AiModerationBlockedError}. Phase 3 wires the audit\n * insert + event emit here; it MUST NOT throw (failures are swallowed by the\n * caller) and MUST NOT block the rejection.\n */\n onFlagged?: (categories: Record<string, { flagged: boolean; score: number }>) => void | Promise<void>\n}\n\n/**\n * Pre-loop input moderation gate. Runs the moderation check for the current\n * user turn before the model call. Decoupled from the registry/container so it\n * is unit-testable: the caller resolves the {@link ModerationService} and API\n * key. Throws {@link AiModerationBlockedError} when flagged; honors\n * fail-closed (enforced) vs fail-open (opt-in) on endpoint unavailability.\n */\nexport async function runInputModerationGate(params: InputModerationGateParams): Promise<void> {\n const policy = resolveModerationPolicy({\n untrustedInput: params.untrustedInput,\n perAgentOverride: params.perAgentOverride,\n tenantWideOverride: params.tenantWideOverride,\n env: params.env,\n })\n if (!isModerationActive(policy)) return\n // The resolved chat provider has no moderation endpoint \u2014 rely on its own\n // server-side filtering and skip the gate.\n if (!params.supportsInputModeration) return\n const text = params.userText.trim()\n if (!text) return\n\n const failClosed = shouldFailClosed(policy)\n const failOpenOrThrow = (reason: string, error?: unknown): void => {\n if (failClosed) {\n if (error instanceof AiModerationUnavailableError) throw error\n throw new AiModerationUnavailableError(reason, error)\n }\n logger.warn('Input moderation unavailable; failing open for opt-in surface', { reason })\n }\n\n if (!params.service) {\n return failOpenOrThrow('moderation service is not available in the container')\n }\n const apiKey = params.resolveApiKey()\n if (!apiKey) {\n return failOpenOrThrow('no API key available for the moderation provider')\n }\n\n let result\n try {\n result = await params.service.checkInput({\n text,\n apiKey,\n baseURL: params.baseURL,\n model: params.moderationModel,\n })\n } catch (error) {\n if (error instanceof AiModerationUnavailableError) {\n return failOpenOrThrow(error.message, error)\n }\n throw error\n }\n\n if (result.flagged) {\n if (params.onFlagged) {\n try {\n await params.onFlagged(result.categories)\n } catch (error) {\n logger.error('Moderation flag side effect failed (rejection still applies)', { err: error })\n }\n }\n throw new AiModerationBlockedError(result.categories)\n }\n}\n\n/**\n * Compute the tenant-salted end-user safety identifier for a chat turn,\n * best-effort. Returns undefined (never throws) so a derivation failure \u2014 e.g.\n * a missing base secret in a misconfigured environment \u2014 degrades to \"no\n * identifier attached\" instead of breaking the chat. Failures are logged.\n */\nfunction resolveEndUserIdentifier(authContext: AiChatRequestContext): string | undefined {\n try {\n return computeEndUserIdentifier(authContext.tenantId, authContext.userId)\n } catch (error) {\n logger.warn('Failed to derive end-user safety identifier', { err: error })\n return undefined\n }\n}\n\nasync function resolveTenantAllowlistSnapshot(\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<TenantAllowlistSnapshot | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiTenantModelAllowlistRepository(em)\n return await repo.getSnapshot({\n tenantId,\n organizationId: organizationId ?? null,\n })\n } catch (error) {\n logger.warn('Tenant allowlist lookup failed; falling back to env-only enforcement', { err: error })\n return null\n }\n}\n\n/**\n * Composes the effective system prompt for a run. When the agent declares a\n * `resolvePageContext` callback AND the incoming request carries both\n * `entityType` and `recordId`, the callback is invoked and its return value\n * is appended to `agent.systemPrompt`. Throwing callbacks are caught and\n * logged without failing the request \u2014 the spec allows hydration to be\n * best-effort until Step 5.2 wires a stricter contract.\n *\n * `userId` identifies the authenticated caller and is forwarded to the callback\n * so it can authorize user-scoped hydration. It MUST come from the server-side\n * auth context \u2014 `pageContext` is browser-supplied and is never read for it.\n * The parameter is trailing and optional so existing five-argument callers keep\n * working; they simply hand the resolver no verified identity.\n */\nexport async function composeSystemPrompt(\n agent: AiAgentDefinition,\n pageContext: AgentRequestPageContext | undefined,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n userId?: string | null,\n): Promise<string> {\n const composed = await composeSystemPromptWithMeta(\n agent,\n pageContext,\n container,\n tenantId,\n organizationId,\n userId,\n )\n return composed.prompt\n}\n\nexport type PromptOverrideReference = { id: string; version: number }\n\nexport type AgentRunPromptContext = {\n systemPrompt: string\n promptOverride: PromptOverrideReference | null\n pageContextHydrated: boolean\n attachmentCount: number\n provider: string | null\n modelId: string | null\n}\n\nasync function reportPromptResolved(\n observe: AiAgentCallObserver | undefined,\n agentId: string,\n runContext: AgentRunPromptContext,\n): Promise<void> {\n await notifyPromptResolved(observe, {\n agentId,\n systemPrompt: runContext.systemPrompt,\n promptOverride: runContext.promptOverride,\n pageContextHydrated: runContext.pageContextHydrated,\n attachmentCount: runContext.attachmentCount,\n provider: runContext.provider,\n modelId: runContext.modelId,\n })\n}\n\nexport type ComposedSystemPromptWithMeta = {\n prompt: string\n promptOverride: PromptOverrideReference | null\n pageContextHydrated: boolean\n}\n\nexport async function composeSystemPromptWithMeta(\n agent: AiAgentDefinition,\n pageContext: AgentRequestPageContext | undefined,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n userId?: string | null,\n): Promise<ComposedSystemPromptWithMeta> {\n const resolvedBase = await resolveSystemPromptWithOverrideMeta(\n agent,\n container,\n tenantId,\n organizationId,\n )\n const baseFromOverride = resolvedBase.prompt\n const unhydrated: ComposedSystemPromptWithMeta = {\n prompt: baseFromOverride,\n promptOverride: resolvedBase.override,\n pageContextHydrated: false,\n }\n const resolve = agent.resolvePageContext\n if (!resolve) return unhydrated\n const entityType = pageContext?.entityType\n const recordId = pageContext?.recordId\n if (typeof entityType !== 'string' || entityType.length === 0) return unhydrated\n if (typeof recordId !== 'string' || recordId.length === 0) return unhydrated\n if (!container) {\n logger.warn('Agent declares resolvePageContext but no container was passed to runAiAgentText; skipping hydration', { agentId: agent.id })\n return unhydrated\n }\n const hydrationInput: AiAgentPageContextInput = {\n entityType,\n recordId,\n container,\n tenantId,\n organizationId,\n userId: userId ?? null,\n }\n try {\n const hydrated = await resolve(hydrationInput)\n if (typeof hydrated === 'string' && hydrated.trim().length > 0) {\n return { ...unhydrated, prompt: `${baseFromOverride}\\n\\n${hydrated}`, pageContextHydrated: true }\n }\n } catch (error) {\n logger.error('resolvePageContext failed; continuing without hydration', { agentId: agent.id, err: error })\n }\n return unhydrated\n}\n\n/**\n * Fetches the latest tenant-scoped prompt override for `agent` (if any) and\n * layers it onto the built-in `systemPrompt` via the additive merge helper.\n *\n * BC + fail-open: every failure mode \u2014 missing container, missing `em`\n * registration, repository throw, missing migration \u2014 is logged at `warn`\n * and falls back to `agent.systemPrompt`. A chat turn MUST never fail on\n * override lookup (per Step 5.3 spec: \"If the repo call throws, log and\n * fall back to the built-in prompt \u2014 never fail the chat request\").\n */\nexport async function resolveSystemPromptWithOverrideMeta(\n agent: AiAgentDefinition,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<{ prompt: string; override: PromptOverrideReference | null }> {\n const base = agent.systemPrompt\n const fallback = { prompt: base, override: null }\n if (!tenantId || !container) return fallback\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return fallback\n try {\n const repo = new AiAgentPromptOverrideRepository(em)\n const latest = await repo.getLatest(agent.id, {\n tenantId,\n organizationId: organizationId ?? null,\n })\n if (!latest || !latest.sections || Object.keys(latest.sections).length === 0) {\n return fallback\n }\n return {\n prompt: composeSystemPromptWithOverride(base, { sections: latest.sections }),\n override: { id: latest.id, version: latest.version },\n }\n } catch (error) {\n logger.warn('Prompt-override lookup failed; falling back to built-in prompt', { agentId: agent.id, err: error })\n return fallback\n }\n}\n\n/**\n * Looks up the tenant-scoped `mutationPolicy` override for `agentId` (Step\n * 5.4). Fails SAFE: any repo error, missing container, missing `em`\n * registration, or corrupt enum value returns `null`, which causes the\n * runtime to fall back to the agent's code-declared policy. A chat turn\n * MUST never fail on override lookup.\n */\nasync function resolveMutationPolicyOverride(\n agentId: string,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<AiAgentMutationPolicy | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiAgentMutationPolicyOverrideRepository(em)\n const row = await repo.get(agentId, { tenantId, organizationId: organizationId ?? null })\n if (!row) return null\n const raw = row.mutationPolicy\n if (!isKnownMutationPolicy(raw)) {\n logger.warn('Ignoring corrupt mutationPolicy override row; falling back to code-declared policy', { agentId, policy: raw })\n return null\n }\n return raw\n } catch (error) {\n logger.warn('mutationPolicy override lookup failed; falling back to code-declared policy', { agentId, err: error })\n \n return null\n }\n}\n\n/**\n * Looks up the per-tenant AI runtime override (provider / model / baseURL) for\n * the given agent (Phase 4a of spec\n * `2026-04-27-ai-agents-provider-model-baseurl-overrides`).\n *\n * Mirrors the fail-open contract of {@link resolveMutationPolicyOverride}: any\n * error \u2014 missing container, missing `em`, repository throw, missing migration\n * \u2014 is logged at `warn` level and returns null so the model factory falls\n * through to lower-priority sources. A chat turn MUST never fail on override\n * lookup.\n */\nasync function resolveRuntimeModelOverride(\n agentId: string,\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<{ providerId?: string | null; modelId?: string | null; baseURL?: string | null } | null> {\n if (!tenantId || !container) return null\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return null\n try {\n const repo = new AiAgentRuntimeOverrideRepository(em)\n const row = await repo.getDefault({\n tenantId,\n organizationId: organizationId ?? null,\n agentId,\n })\n if (!row) return null\n const baseURL = resolveAllowlistedBaseurl(row.baseUrl)\n if (!baseURL && row.baseUrl?.trim()) {\n logger.warn('Stored AI runtime baseURL is not allowed by AI_RUNTIME_BASEURL_ALLOWLIST; ignoring it', {\n agentId,\n tenantId,\n organizationId,\n })\n }\n return {\n providerId: row.providerId ?? null,\n modelId: row.modelId ?? null,\n baseURL,\n }\n } catch (error) {\n logger.warn('Runtime model override lookup failed; falling back to lower-priority sources', { agentId, err: error })\n return null\n }\n}\n\n/**\n * Resolves the per-agent and tenant-wide `input_moderation` override values for\n * the moderation policy precedence. Best-effort and fail-open (returns nulls on\n * any error so the gate falls back to the env default). Returns the two values\n * separately because the precedence treats per-agent and tenant-wide as\n * distinct steps.\n */\nasync function resolveModerationOverrideValues(\n container: AwilixContainer | undefined,\n tenantId: string | null,\n organizationId: string | null,\n agentId: string,\n): Promise<{ perAgentOverride: boolean | null; tenantWideOverride: boolean | null }> {\n const empty = { perAgentOverride: null, tenantWideOverride: null }\n if (!tenantId || !container) return empty\n let em: EntityManager | null = null\n try {\n em = container.resolve<EntityManager>('em')\n } catch {\n em = null\n }\n if (!em) return empty\n try {\n const repo = new AiAgentRuntimeOverrideRepository(em)\n const [agentRow, tenantRow] = await Promise.all([\n repo.getExact({ tenantId, organizationId: organizationId ?? null, agentId }),\n repo.getDefault({ tenantId, organizationId: organizationId ?? null, agentId: null }),\n ])\n return {\n perAgentOverride: agentRow?.inputModeration ?? null,\n tenantWideOverride: tenantRow?.inputModeration ?? null,\n }\n } catch (error) {\n logger.warn('Moderation override lookup failed; falling back to env default', { agentId, err: error })\n return empty\n }\n}\n\n/**\n * Normalizes simple `{ role, content }` chat messages into the AI SDK\n * `UIMessage` shape that `convertToModelMessages` requires. When the\n * incoming message already carries a `parts` array it is left untouched;\n * otherwise a single `TextUIPart` is synthesized from `content`.\n */\nfunction ensureUiMessageShape(messages: UIMessage[]): UIMessage[] {\n return messages.map((message, index) => {\n const raw = message as unknown as { id?: string; role?: string; content?: string; parts?: unknown[] }\n if (Array.isArray(raw.parts) && raw.parts.length > 0) {\n // Already has parts \u2014 only ensure `id` is present\n return { ...message, id: raw.id ?? `msg-${index}` } as UIMessage\n }\n const textContent = typeof raw.content === 'string' ? raw.content : ''\n return {\n id: raw.id ?? `msg-${index}`,\n role: raw.role ?? 'user',\n parts: [{ type: 'text', text: textContent }],\n } as unknown as UIMessage\n })\n}\n\n/**\n * Appends AI SDK v6 `FileUIPart` entries to the last user message in the\n * request so resolved attachment bytes / signed URLs reach the model. Pure\n * helper so chat-mode and object-mode share identical behavior \u2014 any\n * divergence here breaks the Step 3.6 parity contract.\n */\nfunction attachAttachmentsToMessages(\n messages: UIMessage[],\n parts: readonly AiResolvedAttachmentPart[],\n): UIMessage[] {\n if (parts.length === 0) return messages\n const fileParts = attachmentPartsToUiFileParts(parts)\n if (fileParts.length === 0) return messages\n const next = messages.slice()\n let lastUserIndex = -1\n for (let index = next.length - 1; index >= 0; index -= 1) {\n const candidate = next[index] as unknown as { role?: string }\n if (candidate?.role === 'user') {\n lastUserIndex = index\n break\n }\n }\n if (lastUserIndex === -1) {\n next.push({\n id: 'ai-runtime-attachments',\n role: 'user',\n parts: fileParts as unknown as UIMessage['parts'],\n } as unknown as UIMessage)\n return next\n }\n const source = next[lastUserIndex] as unknown as { parts?: unknown[] }\n const existingParts = Array.isArray(source.parts) ? source.parts : []\n next[lastUserIndex] = {\n ...(next[lastUserIndex] as object),\n parts: [...existingParts, ...fileParts],\n } as UIMessage\n return next\n}\n\nfunction appendAttachmentSummary(\n systemPrompt: string,\n parts: readonly AiResolvedAttachmentPart[],\n): string {\n const summary = summarizeAttachmentPartsForPrompt(parts)\n if (!summary) return systemPrompt\n return `${systemPrompt}\\n\\n${summary}`\n}\n\n/**\n * Builds a runtime \"MUTATION POLICY (RUNTIME)\" block describing the\n * EFFECTIVE policy for this turn \u2014 what the model should expect when it\n * calls each whitelisted mutation tool. Generated dynamically because:\n *\n * - the agent's static prompt cannot know which per-tenant override is\n * in force (`destructive-confirm-required` flips most writes to\n * run-direct) and would otherwise mislead the operator with stale\n * \"this requires approval\" copy;\n * - the per-tool `isDestructive` flag determines whether each\n * whitelisted write goes through the approval card or runs inline.\n *\n * Without this block, the model parrots its hardcoded \"always route\n * through the approval card\" prompt language and tells the user \"your\n * change is awaiting approval\" when in fact the dispatcher already\n * applied the change directly. The injected block flips the model to\n * report results accurately (\"applied\", \"pending your approval\", or\n * \"blocked because read-only\") tool-by-tool.\n */\nfunction buildRuntimeMutationPolicySection(\n agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },\n mutationPolicyOverride: string | null,\n channel: AiPendingActionChannel = 'agent',\n): string | null {\n const effective = resolveEffectiveMutationPolicy(\n (agent.mutationPolicy ?? null) as never,\n (mutationPolicyOverride ?? null) as never,\n agent.id,\n )\n const lines: string[] = []\n lines.push('MUTATION POLICY (RUNTIME)')\n lines.push(`Declared agent policy: ${agent.mutationPolicy ?? 'read-only'}.`)\n if (mutationPolicyOverride && mutationPolicyOverride !== agent.mutationPolicy) {\n lines.push(`Tenant override active: ${mutationPolicyOverride}.`)\n }\n lines.push(`Effective policy: ${effective}.`)\n\n // Bucket the agent's allowlisted tools into \"gated\" / \"direct\" / \"conditional\"\n // / \"blocked\" so the model can phrase outcomes correctly per tool.\n // `conditional` covers tools whose `isDestructive` is a predicate function:\n // their gate-vs-direct decision depends on the per-call input (e.g.\n // `customers.manage_deal_comment` gates only its delete branch under\n // `destructive-confirm-required`).\n const direct: string[] = []\n const gated: string[] = []\n const conditional: string[] = []\n const blocked: string[] = []\n for (const toolName of agent.allowedTools) {\n const tool = toolRegistry.getTool(toolName) as\n | { isMutation?: boolean; isDestructive?: boolean | ((input: unknown) => boolean) }\n | undefined\n if (!tool || tool.isMutation !== true) continue\n if (effective === 'read-only') {\n blocked.push(toolName)\n continue\n }\n if (effective === 'confirm-required' || channel !== 'agent') {\n gated.push(toolName)\n continue\n }\n // destructive-confirm-required\n if (typeof tool.isDestructive === 'function') {\n conditional.push(toolName)\n } else if (tool.isDestructive === true) {\n gated.push(toolName)\n } else {\n direct.push(toolName)\n }\n }\n\n if (\n direct.length === 0 &&\n gated.length === 0 &&\n conditional.length === 0 &&\n blocked.length === 0\n ) {\n // Read-only agent with no mutation tools \u2014 no runtime policy block needed.\n return null\n }\n if (direct.length > 0) {\n lines.push('')\n lines.push(\n `Tools that WILL RUN DIRECTLY (no approval card, no pending action) under the effective policy: ${direct.join(', ')}.`,\n )\n lines.push(\n 'When you call any of these and the call returns successfully, the change has ALREADY BEEN APPLIED. Report it in the past tense (\"Updated \u2026\", \"Added \u2026\", \"Created \u2026\"). Do NOT tell the operator the action is \"pending your approval\" or \"awaiting confirmation\" \u2014 that would be a false statement under the current policy.',\n )\n }\n if (gated.length > 0) {\n lines.push('')\n lines.push(\n `Tools that REQUIRE APPROVAL under the effective policy: ${gated.join(', ')}.`,\n )\n lines.push(\n channel === 'agent'\n ? 'When you call any of these, the dispatcher returns an \"awaiting confirmation\" envelope and renders an inline approval card. Tell the operator the change is pending their confirmation; do NOT claim it has been applied.'\n : 'When you call any of these, the change is queued as a pending action and the dispatcher returns an \"awaiting confirmation\" envelope. It will NOT run until it is approved on the Pending AI actions page. Report it as pending approval; do NOT claim it has been applied.',\n )\n }\n if (conditional.length > 0) {\n lines.push('')\n lines.push(\n `Tools whose approval requirement DEPENDS ON THE INPUT under the effective policy: ${conditional.join(', ')}.`,\n )\n lines.push(\n 'These multi-operation tools gate ONLY the destructive branches (typically `operation: \"delete\"` or similar). Read the tool result envelope: if it carries `status: \"pending-confirmation\"` then the change is pending \u2014 tell the operator it needs their approval. If it carries direct success data, the change has ALREADY BEEN APPLIED \u2014 report it in the past tense. Never assume one branch behaves like another.',\n )\n }\n if (blocked.length > 0) {\n lines.push('')\n lines.push(\n `Tools that are BLOCKED under the effective policy (read-only): ${blocked.join(', ')}.`,\n )\n lines.push(\n 'Calls to these tools are refused before the handler runs. Do not attempt them; instead direct the operator to the matching backoffice page or to switch the tenant policy if they have permission.',\n )\n }\n lines.push('')\n lines.push(\n 'This RUNTIME policy block always wins over any conflicting \"approval card\" language earlier in the prompt \u2014 the static prompt is written for the most restrictive case but real behavior depends on the per-call policy described here.',\n )\n return lines.join('\\n')\n}\n\nfunction appendRuntimeMutationPolicy(\n systemPrompt: string,\n agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },\n mutationPolicyOverride: string | null,\n channel?: AiPendingActionChannel,\n): string {\n const block = buildRuntimeMutationPolicySection(agent, mutationPolicyOverride, channel)\n if (!block) return systemPrompt\n return `${systemPrompt}\\n\\n${block}`\n}\n\nfunction appendRuntimeTaskPlanPrompt(systemPrompt: string, agent: Pick<AiAgentDefinition, 'taskPlan'>): string {\n if (!isAgentTaskPlanEnabled(agent)) return systemPrompt\n return `${systemPrompt}\\n\\n${TASK_PLAN_RUNTIME_PROMPT_SECTION}`\n}\n\n/**\n * Server-side helper that runs an Open Mercato agent in chat mode via the\n * Vercel AI SDK and returns a streaming `Response` ready to be emitted from a\n * route handler. Shares the same policy gate and tool resolution path as the\n * HTTP dispatcher \u2014 a caller using this helper can never bypass the agent's\n * `requiredFeatures`, `allowedTools`, `executionMode`, or `mutationPolicy`.\n *\n * Attachment-to-model conversion (Step 3.7): resolved\n * {@link AiResolvedAttachmentPart}s are materialized inline as AI SDK v6\n * `FileUIPart` entries on the last user message (images/PDFs) and as a\n * structured `[ATTACHMENTS]` block appended to the system prompt (text\n * extracts + metadata-only summaries). The existing `attachmentIds`\n * pass-through into `resolveAiAgentTools` is preserved \u2014 Step 3.6 parity\n * invariant #7 still holds.\n */\nexport async function runAiAgentText(input: RunAiAgentTextInput): Promise<Response> {\n const [mutationPolicyOverride, tenantRuntimeOverride, tenantAllowlistSnapshot] = await Promise.all([\n resolveMutationPolicyOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveRuntimeModelOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveTenantAllowlistSnapshot(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n ])\n // Phase 6.2 \u2014 resolve the effective session id. `sessionId` takes precedence\n // over the deprecated `conversationId` alias. When neither is supplied, a\n // fresh UUID is generated server-side so token-usage rows and pending-action\n // idempotency hashes are always correlated within the same session.\n const effectiveSessionId = (input.sessionId ?? input.conversationId) || randomUUID()\n\n const { agent, tools, toolCallTimings } = await resolveAiAgentTools({\n agentId: input.agentId,\n authContext: input.authContext,\n pageContext: input.pageContext,\n attachmentIds: input.attachmentIds,\n mutationPolicyOverride,\n container: input.container,\n conversationId: effectiveSessionId,\n })\n\n const resolvedAttachments = await resolveAttachmentPartsForAgent({\n agent,\n attachmentIds: input.attachmentIds,\n authContext: input.authContext,\n container: input.container,\n })\n\n const composedPrompt = await composeSystemPromptWithMeta(\n agent,\n input.pageContext,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n input.authContext.userId,\n )\n const systemPrompt = appendRuntimeMutationPolicy(\n appendRuntimeTaskPlanPrompt(appendAttachmentSummary(composedPrompt.prompt, resolvedAttachments), agent),\n agent,\n mutationPolicyOverride,\n )\n\n const resolvedModel = resolveAgentModel(\n agent,\n input.modelOverride,\n input.providerOverride,\n input.container,\n input.baseUrlOverride,\n tenantRuntimeOverride,\n input.requestOverride,\n tenantAllowlistSnapshot,\n resolveEndUserIdentifier(input.authContext),\n )\n const { model } = resolvedModel\n const runId = input.runId ?? randomUUID()\n const turnId = randomUUID()\n const runToolNames = listRunToolNames(tools)\n const runCapture = createAgentRunCapture({\n container: input.container,\n trace: input.trace,\n runId,\n agent,\n authContext: input.authContext,\n executionMode: 'chat',\n effectiveMutationPolicy: resolveEffectiveMutationPolicy(agent.mutationPolicy, mutationPolicyOverride, agent.id),\n toolNames: runToolNames,\n mutationToolNames: listMutationToolNames(runToolNames),\n conversationId: effectiveSessionId,\n turnId,\n apiKeyId: null,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n baseUrl: resolvedModel.baseURL,\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n })\n const observe = composeCallObservers(input.observe, runCapture?.observer)\n const runPromptContext: AgentRunPromptContext = {\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n pageContextHydrated: composedPrompt.pageContextHydrated,\n attachmentCount: resolvedAttachments.length,\n provider: resolvedModel.providerId ?? null,\n modelId: resolvedModel.modelId ?? null,\n }\n await reportPromptResolved(observe, agent.id, runPromptContext)\n const effectiveCallSettings = mergeCallSettings(agent.modelSettings, input.callSettings)\n const hasCallSettings = Object.keys(effectiveCallSettings).length > 0\n const sdkCallSettings = toSdkCallSettings(effectiveCallSettings, resolvedModel.providerOptions)\n const { providerOptions: modelProviderOptions, ...sdkCallSettingsWithoutProviderOptions } = sdkCallSettings\n const modelCallHooks = createModelCallObserverHooks(observe, {\n agentId: agent.id,\n providerOptions: modelProviderOptions,\n })\n const normalizedMessages = ensureUiMessageShape(input.messages)\n\n // Pre-loop input moderation gate (spec 2026-06-04). Runs before the model\n // call on enabled/enforced surfaces where the provider supports moderation.\n // Throws AiModerationBlockedError (flagged) or AiModerationUnavailableError\n // (enforced + outage); both are surfaced by the SSE error path.\n let moderationService: ModerationService | null = null\n try {\n moderationService = input.container?.resolve<ModerationService>('moderationService') ?? null\n } catch {\n moderationService = null\n }\n // Read tenant overrides only when the provider can moderate and the agent is\n // not already enforced (untrustedInput short-circuits to enforced) \u2014 avoids a\n // DB round-trip on the common skip paths.\n const moderationOverrides =\n resolvedModel.supportsInputModeration && agent.untrustedInput !== true\n ? await resolveModerationOverrideValues(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n agent.id,\n )\n : { perAgentOverride: null, tenantWideOverride: null }\n await runInputModerationGate({\n untrustedInput: agent.untrustedInput,\n supportsInputModeration: resolvedModel.supportsInputModeration,\n perAgentOverride: moderationOverrides.perAgentOverride,\n tenantWideOverride: moderationOverrides.tenantWideOverride,\n userText: extractLatestUserText(normalizedMessages),\n service: moderationService,\n resolveApiKey: () => llmProviderRegistry.get(resolvedModel.providerId)?.resolveApiKey() ?? null,\n baseURL: resolvedModel.baseURL,\n moderationModel: process.env.OM_AI_MODERATION_MODEL,\n onFlagged: (categories) =>\n recordModerationFlag(\n {\n tenantId: input.authContext.tenantId,\n organizationId: input.authContext.organizationId,\n agentId: agent.id,\n userId: input.authContext.userId,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n categories,\n },\n input.container,\n ),\n })\n\n const hydratedMessages = attachAttachmentsToMessages(normalizedMessages, resolvedAttachments)\n const modelMessages = await convertToModelMessages(hydratedMessages)\n\n const effectiveLoop = resolveEffectiveLoopConfig(agent, input.loop, WRAPPER_DEFAULT_LOOP_CHAT)\n const stopConditions = translateStopConditions(effectiveLoop, sanitizeToolNameForModel)\n const wrapperPrepareStep = buildWrapperPrepareStep(agent, effectiveLoop, tools)\n const sdkActiveTools = mapActiveToolsForModel(effectiveLoop.activeTools, tools)\n const sdkToolChoice = mapToolChoiceForModel(effectiveLoop.toolChoice)\n\n // Phase 3 + Phase 4 \u2014 budget enforcement + LoopTrace collection.\n // Layer order (outer \u2192 inner):\n // budgetEnforcer.wire(traceOnStepFinish) \u2192 traceOnStepFinish calls userOnStepFinish\n // The trace collector builds the per-turn LoopTrace; the budget enforcer\n // aborts via AbortController when any limit is exceeded.\n const loopTraceCollector = buildLoopTraceCollector(\n agent.id,\n effectiveSessionId,\n turnId,\n effectiveLoop.onStepFinish,\n toolCallTimings,\n )\n const abortController = new AbortController()\n const budgetEnforcer = new BudgetEnforcer(effectiveLoop.budget, abortController)\n const tracedOnStepFinish = budgetEnforcer.wire(loopTraceCollector.onStepFinish)\n\n // Phase 6.3 \u2014 wire the token-usage recorder into the wrapper-owned onStepFinish.\n // The recorder fires AFTER the trace collector so modelId is already in the trace.\n // It is invoked as void (detached) and MUST NEVER throw per R12.\n // resolvedModel is already computed above (model, modelId, providerId).\n\n let currentStepIndex = 0\n const wiredOnStepFinish: AiAgentLoopConfig['onStepFinish'] = async (event) => {\n const capturedStepIndex = currentStepIndex\n currentStepIndex += 1\n\n if (tracedOnStepFinish) {\n await tracedOnStepFinish(event)\n }\n runCapture?.recordStep(event)\n if (input.container) {\n const rawEvent = event as unknown as {\n usage?: { inputTokens?: number; outputTokens?: number; cachedInputTokens?: number; reasoningTokens?: number }\n finishReason?: string\n }\n void recordTokenUsage(\n {\n authContext: input.authContext,\n agentId: agent.id,\n moduleId: agent.moduleId,\n sessionId: effectiveSessionId,\n turnId,\n stepIndex: capturedStepIndex,\n providerId: resolvedModel.providerId,\n modelId: resolvedModel.modelId,\n usage: {\n inputTokens: rawEvent.usage?.inputTokens,\n outputTokens: rawEvent.usage?.outputTokens,\n cachedInputTokens: rawEvent.usage?.cachedInputTokens,\n reasoningTokens: rawEvent.usage?.reasoningTokens,\n },\n finishReason: rawEvent.finishReason,\n loopAbortReason: budgetEnforcer.abortReason ?? undefined,\n },\n input.container,\n )\n }\n }\n\n let wallClockTimer: ReturnType<typeof setTimeout> | undefined\n if (effectiveLoop.budget?.maxWallClockMs) {\n wallClockTimer = setTimeout(() => {\n budgetEnforcer.recordStep({ toolCalls: 0 })\n }, effectiveLoop.budget.maxWallClockMs)\n }\n\n // Phase 5 \u2014 construct ToolLoopAgent when executionEngine === 'tool-loop-agent'.\n // The agent is built ONCE per turn (not pooled) with:\n // - model + tools from the wrapper-resolved registry\n // - stopWhen wired at construction (ToolLoopAgentSettings field)\n // - prepareStep wired at construction (NOT via prepareCall \u2014 it is not in\n // prepareCall's Pick list per spec \u00A7Phase 5 correction)\n // - onStepFinish wired at construction (budget + trace collector)\n // - prepareCall used only for per-turn narrowing of model/tools/stopWhen/\n // activeTools/providerOptions (per spec \u00A7Phase 5 correction)\n let builtToolLoopAgent: ToolLoopAgent<never, ToolSet> | undefined\n if (agent.executionEngine === 'tool-loop-agent') {\n const agentSettings: ToolLoopAgentSettingsWithModelCallHooks = {\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n instructions: systemPrompt,\n tools: tools as ToolSet,\n stopWhen: stopConditions,\n prepareStep: wrapperPrepareStep,\n onStepFinish: wiredOnStepFinish,\n ...(effectiveLoop.repairToolCall !== undefined\n ? { experimental_repairToolCall: effectiveLoop.repairToolCall }\n : {}),\n ...(sdkActiveTools !== undefined ? { activeTools: sdkActiveTools } : {}),\n ...(sdkToolChoice !== undefined ? { toolChoice: sdkToolChoice } : {}),\n ...sdkCallSettingsWithoutProviderOptions,\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions as never } : {}),\n ...(modelCallHooks ?? {}),\n }\n builtToolLoopAgent = new ToolLoopAgent<never, ToolSet>(agentSettings)\n }\n\n const preparedOptions: PreparedAiSdkOptions = {\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n tools,\n system: systemPrompt,\n messages: modelMessages,\n maxSteps: effectiveLoop.maxSteps ?? 10,\n stopWhen: stopConditions,\n prepareStep: wrapperPrepareStep,\n onStepFinish: wiredOnStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n onToolCallStart: effectiveLoop.onToolCallStart,\n onToolCallFinish: effectiveLoop.onToolCallFinish,\n experimental_repairToolCall: effectiveLoop.repairToolCall,\n activeTools: sdkActiveTools,\n toolChoice: sdkToolChoice,\n abortSignal: abortController.signal,\n finalizeLoopTrace: () => ({ ...loopTraceCollector.finalize(budgetEnforcer.abortReason), runId }),\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions } : {}),\n ...(hasCallSettings ? { callSettings: effectiveCallSettings } : {}),\n ...(builtToolLoopAgent !== undefined ? { toolLoopAgent: builtToolLoopAgent } : {}),\n ...(modelCallHooks ?? {}),\n }\n\n // Phase 1 of `2026-05-13-ai-chat-visible-task-plan` \u2014 every chat-mode\n // response stream is wrapped in a task-plan injector. The injector is\n // additive and keyed by the per-turn `turnId` so old clients that ignore\n // unknown chunks keep working; current clients render only agent-authored\n // plan rows and leave raw lifecycle progress in the tool-call details.\n const taskPlanId = `turn_${turnId}`\n\n const settleTextRun = async (\n status: 'completed' | 'failed' | 'aborted',\n trace: LoopTrace,\n error?: unknown,\n ): Promise<void> => {\n if (!runCapture) return\n try {\n await runCapture.settle({\n status,\n loopParams: buildRunLoopParams(effectiveLoop, toAgentRunModelSource(resolvedModel.source)),\n inputText: extractLatestUserText(normalizedMessages) || null,\n steps: trace.steps,\n stopReason: status === 'aborted' && trace.stopReason === 'finish-reason' ? 'abort' : trace.stopReason,\n outputText: joinStepText(trace.steps),\n ...(error !== undefined && error !== null ? { error } : {}),\n })\n } catch (settleError) {\n logger.warn('Run settle failed; ignoring', { err: settleError })\n reportAiAssistantError(settleError, 'ai_assistant.agent_run_settle_failed')\n }\n }\n\n const dispatchTextStream = async (): Promise<Response> => {\n if (input.generateText) {\n try {\n const callbackResult = await input.generateText(preparedOptions)\n const baseResponse = (callbackResult as StreamTextResult<ToolSet, Record<string, unknown>, never>).toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n } finally {\n if (wallClockTimer !== undefined) clearTimeout(wallClockTimer)\n }\n }\n\n // Phase 5 \u2014 engine dispatch: tool-loop-agent path vs default stream-text path.\n if (builtToolLoopAgent !== undefined) {\n // `ToolLoopAgent.stream` dispatches via the agent's own prepareCall/prepareStep\n // pipeline. prepareStep is already wired at construction (security-critical),\n // and so is `onStepFinish` \u2014 passing it here too makes the SDK merge both\n // wirings without dedup, so the budget enforcer and the loop trace would count\n // every step twice and abort the turn before the final answer (#5042).\n const agentStreamResult = await builtToolLoopAgent.stream({\n messages: modelMessages,\n abortSignal: abortController.signal,\n })\n if (wallClockTimer !== undefined) {\n const clearTimer = () => clearTimeout(wallClockTimer!)\n Promise.resolve(agentStreamResult.consumeStream()).then(clearTimer, clearTimer)\n }\n const baseResponse = agentStreamResult.toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n }\n\n // Default stream-text path (executionEngine === 'stream-text' or unset).\n const result = streamText({\n model,\n ...(resolvedModel.experimental_download ? { experimental_download: resolvedModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n tools,\n stopWhen: stopConditions as never,\n prepareStep: wrapperPrepareStep as never,\n onStepFinish: wiredOnStepFinish as never,\n experimental_onStepStart: effectiveLoop.onStepStart as never,\n experimental_onToolCallStart: effectiveLoop.onToolCallStart as never,\n experimental_onToolCallFinish: effectiveLoop.onToolCallFinish as never,\n experimental_repairToolCall: effectiveLoop.repairToolCall as never,\n ...(sdkActiveTools !== undefined ? { activeTools: sdkActiveTools } : {}),\n ...(sdkToolChoice !== undefined ? { toolChoice: sdkToolChoice } : {}),\n ...sdkCallSettingsWithoutProviderOptions,\n ...(modelProviderOptions !== undefined ? { providerOptions: modelProviderOptions as never } : {}),\n ...(modelCallHooks ?? {}),\n abortSignal: abortController.signal,\n })\n if (wallClockTimer !== undefined) {\n const clearTimer = () => clearTimeout(wallClockTimer!)\n Promise.resolve(result.consumeStream()).then(clearTimer, clearTimer)\n }\n const baseResponse = result.toUIMessageStreamResponse({\n sendReasoning: true,\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n },\n })\n return injectTaskPlanIntoStream(baseResponse, taskPlanId)\n }\n\n let streamResponse: Response\n try {\n streamResponse = await dispatchTextStream()\n } catch (error) {\n void settleTextRun(\n abortController.signal.aborted ? 'aborted' : 'failed',\n preparedOptions.finalizeLoopTrace(),\n error,\n )\n throw error\n }\n if (!input.emitLoopTrace && !runCapture) return streamResponse\n return appendLoopFinishToStream(streamResponse, {\n emitLoopTrace: input.emitLoopTrace === true,\n finalizeLoopTrace: preparedOptions.finalizeLoopTrace,\n abortSignal: abortController.signal,\n ...(runCapture\n ? { onSettled: (outcome: TextRunStreamOutcome, trace: LoopTrace) => settleTextRun(outcome.status, trace, outcome.error) }\n : {}),\n })\n}\n\n/**\n * Runtime override for the structured-output schema used by {@link runAiAgentObject}.\n * When the agent itself declares no `output` block, the caller MUST supply this;\n * otherwise the helper rejects with {@link AgentPolicyError} code\n * `execution_mode_not_supported`.\n */\nexport interface RunAiAgentObjectOutputOverride<TSchema = ZodTypeAny> {\n schemaName: string\n schema: TSchema\n /**\n * `'generate'` (default) calls AI SDK `generateObject` and resolves to the\n * parsed object. `'stream'` calls `streamObject` and returns the SDK's\n * streaming handle so callers can consume partial objects / text deltas.\n */\n mode?: 'generate' | 'stream'\n}\n\nexport interface RunAiAgentObjectInput<TSchema = ZodTypeAny> {\n agentId: string\n /**\n * Accepts either a bare user prompt (wrapped as `[{ role: 'user', content }]`)\n * or a prebuilt `UIMessage[]` array \u2014 matches the source spec's\n * `RunAiAgentObjectInput` contract (\u00A71149\u20131160).\n */\n input: string | UIMessage[]\n attachmentIds?: string[]\n pageContext?: AgentRequestPageContext\n /**\n * Same Phase-1 shim as {@link RunAiAgentTextInput.authContext}. Required until\n * a global request-context resolver lands (Phase 4).\n */\n authContext: AiChatRequestContext\n modelOverride?: string\n /**\n * Optional request-time provider override. When non-empty, wins for the\n * provider axis at the same priority as `modelOverride` for the model axis.\n *\n * Phase 1 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n providerOverride?: string\n /**\n * Optional per-call base URL override. Wins over every other source in the\n * baseURL resolution chain. Intended for programmatic callers only \u2014 the\n * HTTP query-param baseUrl and the AI_RUNTIME_BASEURL_ALLOWLIST arrive in\n * Phase 4a and MUST NOT be exposed here.\n *\n * Phase 2 of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n baseUrlOverride?: string\n /**\n * Per-request HTTP dispatcher override (query params `?provider=`, `?model=`,\n * `?baseUrl=`). Validated by the dispatcher route before being forwarded\n * here. Wins over tenantOverride and all lower-priority sources when\n * `agent.allowRuntimeOverride !== false`.\n *\n * Phase 4a of spec `2026-04-27-ai-agents-provider-model-baseurl-overrides`.\n */\n requestOverride?: {\n providerId?: string | null\n modelId?: string | null\n baseURL?: string | null\n }\n output?: RunAiAgentObjectOutputOverride<TSchema>\n /**\n * Opt-in: run the agent as a READ-ONLY tool loop that finalizes into the\n * structured-output schema, instead of the toolless `generateObject` call.\n *\n * When `true` AND the agent resolves at least one tool, the runtime dispatches\n * via `generateText({ tools, output: Output.object({ schema }) })`\n * so the model can call its allowlisted tools to gather data before emitting\n * the structured object. The mutation-approval gate (`buildWrapperPrepareStep`)\n * is wired identically to chat mode, and read-only agents already have every\n * `isMutation: true` tool stripped \u2014 so this never enables a direct write.\n *\n * When `false`/omitted (or no tools resolve) the existing toolless\n * `generateObject`/`streamObject` path runs unchanged.\n */\n enableTools?: boolean\n debug?: boolean\n container?: AwilixContainer\n /**\n * Optional stable per-run session id for token-usage correlation.\n * Object-mode runs are single-turn by definition but the session id lets\n * callers group multiple object runs together for reporting.\n *\n * Phase 6.2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n sessionId?: string | null\n /**\n * Optional per-call loop config override for object mode. Only the\n * object-safe subset is accepted: `maxSteps`, `budget`, `onStepFinish`,\n * `onStepStart`, and `allowRuntimeOverride`. Providing any chat-only\n * field (`prepareStep`, `repairToolCall`, `stopWhen`, `activeTools`,\n * `toolChoice`) throws `AgentPolicyError` code\n * `loop_unsupported_in_object_mode`.\n *\n * Exception: `prepareStep` is honoured on the `enableTools` tool-loop branch,\n * composed under the wrapper-owned `prepareStep` exactly like chat mode (the\n * caller's value replaces `agent.loop.prepareStep`). When `enableTools` is set\n * but no tools resolve, the caller's `prepareStep` is dropped with a warning\n * instead of failing the run; without `enableTools` it still throws.\n *\n * Phase 1 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n loop?: Pick<\n AiAgentLoopConfig,\n 'maxSteps' | 'budget' | 'onStepFinish' | 'onStepStart' | 'allowRuntimeOverride' | 'prepareStep'\n >\n /**\n * Optional escape-hatch callback receiving the fully prepared object-mode\n * options bag. When supplied the wrapper still enforces all policy guardrails\n * and then delegates the actual SDK call to this function. The callback MUST\n * return a value compatible with `GenerateObjectResult` or `StreamObjectResult`.\n *\n * Phase 2 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\n generateObject?: (\n options: PreparedAiSdkObjectOptions,\n ) => Promise<GenerateObjectResult<unknown> | StreamObjectResult<unknown, unknown, unknown>>\n /**\n * Surface the run is invoked on behalf of. Defaults to `'agent'` (today's\n * behaviour). An MCP / tools-api caller passes its channel and server\n * `mutationMode`: `direct` / `deny` force the run read-only, `approval`\n * keeps the agent's own policy and queues its writes as pending actions\n * stamped with the channel, `apiKeyId` and `correlationId` (spec\n * `2026-10-21-mcp-tool-exposure-parity-and-audit` \u00A73.1).\n */\n channel?: AiPendingActionChannel\n mutationMode?: McpMutationMode\n apiKeyId?: string | null\n correlationId?: string | null\n /**\n * Model-call contract fields (spec `2026-10-21-chat-run-tracing-and-citations` \u00A76).\n * `runId` pins the run identifier, `trace` controls run persistence and\n * channel attribution, `callSettings` are merged over the agent's\n * `modelSettings` key by key, and `observe` receives per-call events.\n */\n runId?: string\n trace?: AiAgentRunTraceOptions\n callSettings?: AiAgentCallSettings\n observe?: AiAgentCallObserver\n /** Caller-owned signal; aborting it aborts the run's model calls. */\n abortSignal?: AbortSignal\n}\n\nexport type RunAiAgentObjectGenerateResult<TSchema> = {\n mode: 'generate'\n object: TSchema\n finishReason?: string\n usage?: { inputTokens?: number; outputTokens?: number }\n /**\n * Per-step records from the read-only tool loop, in the same\n * {@link LoopStepRecord} shape the chat path's LoopTrace collector produces.\n * Present only on the `enableTools` tool-loop branch; the toolless\n * `generateObject`/`streamObject` paths never set it. Additive \u2014 consumed by\n * the agent-orchestrator native runtime for per-step trace capture (spec\n * `2026-07-07-lightweight-agent-runtime` Phase 1).\n */\n steps?: LoopStepRecord[]\n /**\n * Ids of the pending actions the run's mutation tools queued for approval.\n * Present only when at least one was created.\n */\n pendingActionIds?: string[]\n /**\n * Provider warnings of the toolless `generateObject` call (e.g. an\n * `unsupported` setting the provider dropped). The tool-loop branch reports\n * them per step through `loop.onStepFinish` instead. Additive.\n */\n warnings?: AiAgentCallWarning[]\n /** Run identifier the call is traced under (`ai_agent_runs.id`). */\n runId?: string\n}\n\nexport type AiAgentCallWarning = { type: string; feature?: string; details?: string; message?: string }\n\nfunction readCallWarnings(result: unknown): AiAgentCallWarning[] | undefined {\n const warnings = (result as { warnings?: unknown } | null)?.warnings\n if (!Array.isArray(warnings) || warnings.length === 0) return undefined\n return warnings.filter(\n (warning): warning is AiAgentCallWarning =>\n Boolean(warning) && typeof warning === 'object' && typeof (warning as { type?: unknown }).type === 'string',\n )\n}\n\nexport type RunAiAgentObjectStreamResult<TSchema> = {\n mode: 'stream'\n /** Full parsed object once the stream completes. */\n object: Promise<TSchema>\n /** Async iterator of partial (progressively hydrated) objects. */\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n /** Async iterator of the raw text deltas the model emitted. */\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n /** Run identifier the call is traced under (`ai_agent_runs.id`). */\n runId?: string\n}\n\nexport type RunAiAgentObjectResult<TSchema> =\n | RunAiAgentObjectGenerateResult<TSchema>\n | RunAiAgentObjectStreamResult<TSchema>\n\nfunction linkCallerAbortSignal(signal: AbortSignal | undefined, controller: AbortController): void {\n if (!signal) return\n if (signal.aborted) {\n controller.abort(signal.reason)\n return\n }\n signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true })\n}\n\nfunction normalizeObjectMessages(input: string | UIMessage[]): UIMessage[] {\n if (typeof input === 'string') {\n return [\n {\n id: 'user-input',\n role: 'user',\n parts: [{ type: 'text', text: input }],\n } as unknown as UIMessage,\n ]\n }\n return input\n}\n\nfunction resolveStructuredOutput<TSchema>(\n agent: AiAgentDefinition,\n override: RunAiAgentObjectOutputOverride<TSchema> | undefined,\n): { schemaName: string; schema: unknown; mode: 'generate' | 'stream' } {\n if (override) {\n return {\n schemaName: override.schemaName,\n schema: override.schema as unknown,\n mode: override.mode ?? 'generate',\n }\n }\n const declared = agent.output as AiAgentStructuredOutput | undefined\n if (!declared) {\n throw new AgentPolicyError(\n 'execution_mode_not_supported',\n `Agent \"${agent.id}\" does not declare a structured-output schema; pass runAiAgentObject({ output }) or declare agent.output.`,\n )\n }\n return {\n schemaName: declared.schemaName,\n schema: declared.schema as unknown,\n mode: declared.mode ?? 'generate',\n }\n}\n\n/**\n * Server-side helper that runs an Open Mercato agent in structured-output mode\n * via the Vercel AI SDK. Shares the same policy gate, tool resolution path,\n * system-prompt composition, and model resolution as {@link runAiAgentText} \u2014\n * object-mode and chat-mode CANNOT diverge.\n *\n * Attachment-to-model conversion (Step 3.7): resolved\n * {@link AiResolvedAttachmentPart}s are materialized inline as AI SDK v6\n * `FileUIPart` entries on the last user message (images/PDFs) and as a\n * structured `[ATTACHMENTS]` block appended to the system prompt (text\n * extracts + metadata-only summaries). Matches {@link runAiAgentText} byte-\n * for-byte so the Step 3.6 parity contract is preserved.\n */\nexport async function runAiAgentObject<TSchema = unknown>(\n input: RunAiAgentObjectInput<TSchema>,\n): Promise<RunAiAgentObjectResult<TSchema>> {\n const [mutationPolicyOverride, tenantRuntimeOverride, tenantAllowlistSnapshot] = await Promise.all([\n resolveMutationPolicyOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveRuntimeModelOverride(\n input.agentId,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n resolveTenantAllowlistSnapshot(\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n ),\n ])\n const { agent, tools, pendingActionIds, toolCallTimings } = await resolveAiAgentTools({\n agentId: input.agentId,\n authContext: input.authContext,\n pageContext: input.pageContext,\n attachmentIds: input.attachmentIds,\n requestedExecutionMode: 'object',\n mutationPolicyOverride,\n container: input.container,\n channel: input.channel,\n mutationMode: input.mutationMode,\n apiKeyId: input.apiKeyId,\n correlationId: input.correlationId,\n })\n const runMutationPolicyOverride = resolveAgentRunMutationPolicyOverride({\n channel: input.channel,\n mutationMode: input.mutationMode,\n declaredPolicy: agent.mutationPolicy,\n tenantOverride: mutationPolicyOverride,\n canQueueMutations: typeof input.container !== 'undefined',\n })\n\n const resolvedOutput = resolveStructuredOutput(agent, input.output)\n\n const resolvedAttachments = await resolveAttachmentPartsForAgent({\n agent,\n attachmentIds: input.attachmentIds,\n authContext: input.authContext,\n container: input.container,\n })\n\n const composedPrompt = await composeSystemPromptWithMeta(\n agent,\n input.pageContext,\n input.container,\n input.authContext.tenantId,\n input.authContext.organizationId,\n input.authContext.userId,\n )\n const systemPrompt = appendRuntimeMutationPolicy(\n appendRuntimeTaskPlanPrompt(appendAttachmentSummary(composedPrompt.prompt, resolvedAttachments), agent),\n agent,\n runMutationPolicyOverride,\n input.channel,\n )\n\n const resolvedObjectModel = resolveAgentModel(\n agent,\n input.modelOverride,\n input.providerOverride,\n input.container,\n input.baseUrlOverride,\n tenantRuntimeOverride,\n input.requestOverride,\n tenantAllowlistSnapshot,\n )\n const { model } = resolvedObjectModel\n const objectRunId = input.runId ?? randomUUID()\n const effectiveObjectSessionId = input.sessionId ?? randomUUID()\n const objectTurnId = randomUUID()\n const objectToolNames = listRunToolNames(tools)\n const objectRunCapture = createAgentRunCapture({\n container: input.container,\n trace: input.trace,\n runId: objectRunId,\n agent,\n authContext: input.authContext,\n executionMode: 'object',\n effectiveMutationPolicy: resolveEffectiveMutationPolicy(agent.mutationPolicy, runMutationPolicyOverride, agent.id),\n toolNames: objectToolNames,\n mutationToolNames: listMutationToolNames(objectToolNames),\n conversationId: input.sessionId ?? null,\n turnId: objectTurnId,\n apiKeyId: input.apiKeyId ?? null,\n fallbackCorrelationId: input.correlationId ?? null,\n providerId: resolvedObjectModel.providerId,\n modelId: resolvedObjectModel.modelId,\n baseUrl: resolvedObjectModel.baseURL,\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n })\n const objectObserve = composeCallObservers(input.observe, objectRunCapture?.observer)\n const runPromptContext: AgentRunPromptContext = {\n systemPrompt,\n promptOverride: composedPrompt.promptOverride,\n pageContextHydrated: composedPrompt.pageContextHydrated,\n attachmentCount: resolvedAttachments.length,\n provider: resolvedObjectModel.providerId ?? null,\n modelId: resolvedObjectModel.modelId ?? null,\n }\n await reportPromptResolved(objectObserve, agent.id, runPromptContext)\n const effectiveCallSettings = mergeCallSettings(agent.modelSettings, input.callSettings)\n const hasCallSettings = Object.keys(effectiveCallSettings).length > 0\n const { providerOptions: objectProviderOptions, ...objectCallSettings } = toSdkCallSettings(effectiveCallSettings)\n const sdkCallSettings = {\n ...objectCallSettings,\n ...(objectProviderOptions !== undefined ? { providerOptions: objectProviderOptions as never } : {}),\n }\n const normalizedMessages = ensureUiMessageShape(normalizeObjectMessages(input.input))\n const hydratedMessages = attachAttachmentsToMessages(\n normalizedMessages,\n resolvedAttachments,\n )\n const modelMessages = await convertToModelMessages(hydratedMessages)\n const objectResponseFormat = objectObserve && !isLightweightCallObserver(objectObserve)\n ? buildObjectResponseFormat(resolvedOutput.schemaName, resolvedOutput.schema)\n : undefined\n\n const abortController = new AbortController()\n linkCallerAbortSignal(input.abortSignal, abortController)\n const objectInputText = extractLatestUserText(normalizedMessages) || null\n const objectModelSource = toAgentRunModelSource(resolvedObjectModel.source)\n let objectRunLoop: AiAgentLoopConfig = {}\n const objectToolLoop: { trace: ReturnType<typeof buildLoopTraceCollector> | null } = { trace: null }\n\n const settleObjectRun = async (\n status: 'completed' | 'failed' | 'aborted',\n details: {\n steps: LoopStepRecord[]\n object?: unknown\n finishReason?: string | null\n usage?: { inputTokens?: number; outputTokens?: number } | null\n error?: unknown\n },\n ): Promise<void> => {\n if (!objectRunCapture) return\n try {\n await objectRunCapture.settle({\n status,\n loopParams: buildRunLoopParams(objectRunLoop, objectModelSource),\n inputText: objectInputText,\n steps: details.steps,\n stopReason: status === 'aborted' ? 'abort' : status === 'completed' ? 'finish-reason' : null,\n finishReason: details.finishReason ?? null,\n outputText: serializeObjectOutput(details.object),\n usage: details.usage ?? null,\n ...(details.error !== undefined ? { error: details.error } : {}),\n })\n } catch (settleError) {\n logger.warn('Run settle failed; ignoring', { err: settleError })\n reportAiAssistantError(settleError, 'ai_assistant.agent_run_settle_failed')\n }\n }\n\n const synthesizeObjectStep = (\n finishReason: string | undefined,\n usage: { inputTokens?: number; outputTokens?: number } | undefined,\n ): LoopStepRecord[] => {\n objectRunCapture?.recordStep({ finishReason, usage })\n return [\n {\n stepIndex: 0,\n modelId: resolvedObjectModel.modelId,\n toolCalls: [],\n textDelta: '',\n usage: { inputTokens: usage?.inputTokens ?? 0, outputTokens: usage?.outputTokens ?? 0 },\n finishReason: (finishReason ?? 'stop') as LoopStepRecord['finishReason'],\n },\n ]\n }\n\n const dispatchObjectRun = async (): Promise<RunAiAgentObjectResult<TSchema>> => {\n // Read-only tool-loop path (opt-in via `enableTools`). When the agent resolves\n // tools, run a `generateText` loop that finalizes into the output schema via\n // `experimental_output`, so the model can read through its allowlisted tools\n // before proposing. The mutation gate + stop conditions are wired exactly as in\n // chat mode; read-only agents have mutation tools stripped, so no direct write\n // is ever possible. Falls through to `generateObject` when no tools resolve.\n const resolvedToolNames = Object.keys((tools ?? {}) as ToolSet)\n // Degrading to a single-shot call is a legitimate fallback, but it silently\n // changes what the agent CAN do \u2014 an agent whose prompt says \"validate your\n // draft with the tool before returning\" is now being asked to obey an\n // instruction it has no way to follow. Say so, loudly, once per turn.\n if (input.enableTools && resolvedToolNames.length === 0) {\n logger.warn(\n 'Agent requested a tool loop but no tools resolved; falling back to a single-shot generateObject',\n {\n agentId: agent.id,\n allowedTools: agent.allowedTools,\n },\n )\n }\n if (input.enableTools && resolvedToolNames.length > 0) {\n const toolLoopConfig = resolveEffectiveLoopConfig(agent, input.loop, WRAPPER_DEFAULT_LOOP_CHAT)\n const toolStopConditions = translateStopConditions(toolLoopConfig, sanitizeToolNameForModel)\n const toolWrapperPrepareStep = buildWrapperPrepareStep(agent, toolLoopConfig, tools)\n // Per-step exposure (native-runtime spec Phase 1, additive): aggregate the\n // AI SDK's step records through the same collector the chat path uses and\n // forward the caller's `loop.onStepFinish` \u2014 previously silently dropped on\n // this branch. Callers that pass no `loop.onStepFinish` observe identical\n // behavior plus the optional `steps` field on the result.\n objectRunLoop = toolLoopConfig\n const toolLoopTrace = buildLoopTraceCollector(\n agent.id,\n effectiveObjectSessionId,\n objectTurnId,\n toolLoopConfig.onStepFinish,\n toolCallTimings,\n )\n objectToolLoop.trace = toolLoopTrace\n const toolLoopOnStepFinish: AiAgentLoopConfig['onStepFinish'] = objectRunCapture\n ? async (event) => {\n await toolLoopTrace.onStepFinish?.(event)\n objectRunCapture.recordStep(event)\n }\n : toolLoopTrace.onStepFinish\n const toolLoopModelCallHooks = createModelCallObserverHooks(objectObserve, {\n agentId: agent.id,\n providerOptions: objectProviderOptions,\n responseFormat: objectResponseFormat,\n })\n const toolResult = await generateText({\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n tools,\n stopWhen: toolStopConditions as never,\n prepareStep: toolWrapperPrepareStep as never,\n onStepFinish: toolLoopOnStepFinish as never,\n output: Output.object({ schema: resolvedOutput.schema as never }),\n ...sdkCallSettings,\n ...(toolLoopModelCallHooks ?? {}),\n abortSignal: abortController.signal,\n })\n return {\n mode: 'generate',\n object: (toolResult as unknown as { output: TSchema }).output,\n finishReason: (toolResult as { finishReason?: string }).finishReason,\n usage: {\n inputTokens: toolResult.usage?.inputTokens,\n outputTokens: toolResult.usage?.outputTokens,\n },\n steps: toolLoopTrace.finalize(null).steps,\n ...(pendingActionIds.length > 0 ? { pendingActionIds: [...pendingActionIds] } : {}),\n }\n }\n\n let toollessLoop = input.loop\n if (toollessLoop?.prepareStep && input.enableTools) {\n logger.warn('Caller prepareStep dropped: the tool loop fell back to a toolless generateObject', {\n agentId: agent.id,\n })\n toollessLoop = { ...toollessLoop, prepareStep: undefined }\n }\n if (toollessLoop) {\n assertLoopObjectModeCompatible(toollessLoop)\n }\n const effectiveLoop = resolveEffectiveLoopConfig(agent, toollessLoop, WRAPPER_DEFAULT_LOOP_OBJECT)\n objectRunLoop = effectiveLoop\n\n const preparedObjectOptions: PreparedAiSdkObjectOptions = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schemaName: resolvedOutput.schemaName,\n schema: resolvedOutput.schema,\n maxSteps: effectiveLoop.maxSteps,\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n abortSignal: abortController.signal,\n ...(hasCallSettings ? { callSettings: effectiveCallSettings } : {}),\n }\n\n const modelDescriptor = describeLanguageModel(model, {\n provider: resolvedObjectModel.providerId,\n modelId: resolvedObjectModel.modelId,\n })\n const synthesizedModelCall = createSynthesizedModelCall(objectObserve, {\n agentId: agent.id,\n provider: modelDescriptor.provider,\n modelId: modelDescriptor.modelId,\n system: systemPrompt,\n messages: modelMessages,\n responseFormat: objectResponseFormat,\n callSettings: effectiveCallSettings,\n callerManaged: Boolean(input.generateObject),\n })\n await synthesizedModelCall?.start()\n\n if (input.generateObject) {\n const callbackResult = await input.generateObject(preparedObjectOptions)\n const typedResult = callbackResult as unknown as Record<string, unknown>\n if ('partialObjectStream' in typedResult) {\n const streamResult = typedResult as {\n object: Promise<TSchema>\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n }\n observeStreamedObjectEnd(synthesizedModelCall, streamResult)\n return {\n mode: 'stream',\n object: streamResult.object,\n partialObjectStream: streamResult.partialObjectStream,\n textStream: streamResult.textStream,\n finishReason: streamResult.finishReason,\n usage: streamResult.usage,\n }\n }\n const genResult = typedResult as { object: unknown; finishReason?: string; usage?: { inputTokens?: number; outputTokens?: number } }\n await synthesizedModelCall?.end(readSynthesizedResultMetadata(typedResult))\n const genWarnings = readCallWarnings(typedResult)\n return {\n mode: 'generate',\n object: genResult.object as TSchema,\n finishReason: genResult.finishReason,\n usage: genResult.usage,\n ...(genWarnings ? { warnings: genWarnings } : {}),\n }\n }\n\n if (resolvedOutput.mode === 'stream') {\n const streamArgs = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schema: resolvedOutput.schema as never,\n schemaName: resolvedOutput.schemaName,\n ...(effectiveLoop.maxSteps !== undefined ? { maxSteps: effectiveLoop.maxSteps } : {}),\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n ...sdkCallSettings,\n abortSignal: abortController.signal,\n } as Parameters<typeof streamObject>[0]\n const result = streamObject(streamArgs) as unknown as {\n object: Promise<TSchema>\n partialObjectStream: AsyncIterable<Partial<TSchema>>\n textStream: AsyncIterable<string>\n finishReason?: Promise<string | undefined>\n usage?: Promise<{ inputTokens?: number; outputTokens?: number } | undefined>\n }\n observeStreamedObjectEnd(synthesizedModelCall, result)\n return {\n mode: 'stream',\n object: result.object,\n partialObjectStream: result.partialObjectStream,\n textStream: result.textStream,\n finishReason: result.finishReason,\n usage: result.usage,\n }\n }\n\n const generateArgs = {\n model,\n ...(resolvedObjectModel.experimental_download ? { experimental_download: resolvedObjectModel.experimental_download } : {}),\n system: systemPrompt,\n messages: modelMessages,\n schema: resolvedOutput.schema as never,\n schemaName: resolvedOutput.schemaName,\n ...(effectiveLoop.maxSteps !== undefined ? { maxSteps: effectiveLoop.maxSteps } : {}),\n onStepFinish: effectiveLoop.onStepFinish,\n onStepStart: effectiveLoop.onStepStart,\n ...sdkCallSettings,\n abortSignal: abortController.signal,\n } as Parameters<typeof generateObject>[0]\n\n const result = await generateObject(generateArgs)\n await synthesizedModelCall?.end(readSynthesizedResultMetadata(result))\n const resultWarnings = readCallWarnings(result)\n return {\n mode: 'generate',\n object: (result as { object: unknown }).object as TSchema,\n finishReason: (result as { finishReason?: string }).finishReason,\n usage: (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage,\n ...(resultWarnings ? { warnings: resultWarnings } : {}),\n }\n }\n\n let objectResult: RunAiAgentObjectResult<TSchema>\n try {\n objectResult = await dispatchObjectRun()\n } catch (error) {\n void settleObjectRun(abortController.signal.aborted ? 'aborted' : 'failed', {\n steps: objectToolLoop.trace ? objectToolLoop.trace.finalize(null).steps : [],\n error,\n })\n throw error\n }\n\n if (objectResult.mode === 'generate') {\n void settleObjectRun('completed', {\n steps: objectResult.steps ?? synthesizeObjectStep(objectResult.finishReason, objectResult.usage),\n object: objectResult.object,\n finishReason: objectResult.finishReason ?? null,\n usage: objectResult.usage ?? null,\n })\n return { ...objectResult, runId: objectRunId }\n }\n\n if (objectRunCapture) {\n const streamed = objectResult\n void Promise.resolve(streamed.object).then(\n async (value) => {\n const [finishReason, usage] = await Promise.all([\n Promise.resolve(streamed.finishReason).catch(() => undefined),\n Promise.resolve(streamed.usage).catch(() => undefined),\n ])\n await settleObjectRun('completed', {\n steps: synthesizeObjectStep(finishReason, usage),\n object: value,\n finishReason: finishReason ?? null,\n usage: usage ?? null,\n })\n },\n async (error: unknown) => {\n await settleObjectRun(abortController.signal.aborted ? 'aborted' : 'failed', { steps: [], error })\n },\n )\n }\n return { ...objectResult, runId: objectRunId }\n}\n\nexport { AgentPolicyError }\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAehC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAsB;AAAA,OACjB;AAGP,SAAS,oBAAoB,mCAAmC;AAMhE,SAAS,mBAAmB,yBAAyB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iCAAiC;AAC1C,SAAS,8BAA8B;AACvC,SAAS,gCAAgC;AACzC,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B;AAarC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sCAAsC;AAC/C,SAAS,6CAA6C;AAGtD,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AAChD,SAAS,+CAA+C;AACxD,SAAS,wCAAwC;AACjD,SAAS,wCAAwC;AAEjD,SAAS,uCAAuC;AAChD,SAAS,iBAAiB,4BAA4B;AAEtD,SAAS,8BAA8B;AACvC,SAAS,uBAAuB,qBAAqB;AAErD,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AACzC,SA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