@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.
@@ -64,7 +64,7 @@ function formatToolResult(result) {
64
64
  return String(result);
65
65
  }
66
66
  }
67
- function buildToolHandlerContext(ctx, container, tool) {
67
+ function buildToolHandlerContext(ctx, container, tool, channelContext) {
68
68
  return {
69
69
  tenantId: ctx.tenantId,
70
70
  organizationId: ctx.organizationId,
@@ -72,7 +72,13 @@ function buildToolHandlerContext(ctx, container, tool) {
72
72
  container: container ?? void 0,
73
73
  userFeatures: ctx.features,
74
74
  isSuperAdmin: ctx.isSuperAdmin,
75
- ...tool ? { tool } : {}
75
+ ...tool ? { tool } : {},
76
+ ...channelContext ? {
77
+ channel: channelContext.channel,
78
+ ...channelContext.mutationMode ? { mutationMode: channelContext.mutationMode } : {},
79
+ apiKeyId: channelContext.apiKeyId,
80
+ correlationId: channelContext.correlationId
81
+ } : {}
76
82
  };
77
83
  }
78
84
  function formatPendingActionToolResult(agent, tool, pendingActionId, expiresAt, reused, status, executionResult) {
@@ -110,9 +116,9 @@ function readExecuteToolCallId(options) {
110
116
  const toolCallId = options?.toolCallId;
111
117
  return typeof toolCallId === "string" && toolCallId.length > 0 ? toolCallId : null;
112
118
  }
113
- function adaptToolToAiSdk(tool, ctx, mutation, container, effectiveMutationPolicy, toolCallTimings) {
119
+ function adaptToolToAiSdk(tool, ctx, mutation, container, effectiveMutationPolicy, toolCallTimings, channelContext) {
114
120
  const safeSchema = toSafeZodSchema(tool.inputSchema);
115
- const handlerContext = buildToolHandlerContext(ctx, container, tool);
121
+ const handlerContext = buildToolHandlerContext(ctx, container, tool, channelContext);
116
122
  const runToolCall = async (args, toolCallId) => {
117
123
  const replayDecision = resolveToolReplayDecision({
118
124
  toolName: tool.name,
@@ -130,6 +136,7 @@ function adaptToolToAiSdk(tool, ctx, mutation, container, effectiveMutationPolic
130
136
  }
131
137
  const requiresApprovalNow = (() => {
132
138
  if (!mutation) return false;
139
+ if (mutation.channel !== "agent") return true;
133
140
  if (effectiveMutationPolicy === "confirm-required") return true;
134
141
  if (effectiveMutationPolicy === "destructive-confirm-required") {
135
142
  return resolveIsDestructive(mutation.tool.isDestructive, args);
@@ -301,7 +308,13 @@ async function resolveAiAgentTools(input) {
301
308
  mutationOptions,
302
309
  input.container,
303
310
  effectiveMutationPolicy,
304
- toolCallTimings
311
+ toolCallTimings,
312
+ {
313
+ channel,
314
+ mutationMode: input.mutationMode,
315
+ apiKeyId: input.apiKeyId ?? null,
316
+ correlationId: input.correlationId ?? null
317
+ }
305
318
  );
306
319
  } catch (error) {
307
320
  logger.error("Failed to adapt tool for agent", { toolName, agentId: agent.id, err: error });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/agent-tools.ts"],
4
- "sourcesContent": ["import { shouldIsolateModelFactoryTools, withModelFactoryToolScope } from './model-factory-context'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { dynamicTool, type Tool } from 'ai'\nimport type { AwilixContainer } from 'awilix'\nimport type { ZodType } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport type { AiChatRequestContext, AiUiPart } from './attachment-bridge-types'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionStatus,\n} from './pending-action-types'\nimport { getAgent, loadAgentRegistry } from './agent-registry'\nimport {\n checkAgentPolicy,\n resolveEffectiveMutationPolicy,\n type AgentPolicyDenyCode,\n} from './agent-policy'\nimport { toolRegistry } from './tool-registry'\nimport { toSafeZodSchema } from './schema-utils'\nimport { createToolUiPartBuffer, mergeUiPartsIntoToolResult } from './tool-ui-parts'\nimport { prepareMutation } from './prepare-mutation'\nimport { resolveAgentRunMutationPolicyOverride } from './agent-channel-policy'\nimport type { McpMutationMode } from './mcp-exposure'\nimport type { AiPendingActionChannel } from './pending-action-types'\nimport type { ToolCallTiming, ToolCallTimings } from './loop-step-extraction'\nimport {\n buildRecordedToolFixture,\n emitRecordedToolFixture,\n resolveToolReplayDecision,\n withToolReplayContext,\n} from './llm-adapters/tool-replay-context'\nimport { resolveStagedToolInput } from './tool-input'\nimport { hasRequiredFeatures } from './auth'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Error thrown by `resolveAiAgentTools` (and downstream `runAiAgentText`) when\n * the agent-level policy check denies a request. Carries the structured deny\n * code so HTTP dispatchers can map it to a stable status and JSON body.\n */\nexport class AgentPolicyError extends Error {\n readonly code: AgentPolicyDenyCode\n\n constructor(code: AgentPolicyDenyCode, message: string) {\n super(message)\n this.name = 'AgentPolicyError'\n this.code = code\n }\n}\n\nexport interface ResolveAiAgentToolsInput {\n agentId: string\n authContext: AiChatRequestContext\n pageContext?: Record<string, unknown>\n attachmentIds?: string[]\n /**\n * Execution mode the caller intends to run the agent in. Defaults to\n * `'chat'` to preserve the existing chat dispatcher contract. Object-mode\n * callers (see `runAiAgentObject`) MUST pass `'object'` so the policy gate\n * can reject chat-only agents early with `execution_mode_not_supported`.\n */\n requestedExecutionMode?: 'chat' | 'object'\n /**\n * Optional tenant-scoped mutation-policy DOWNGRADE. When supplied, the\n * effective policy evaluated by `checkAgentPolicy` is the most restrictive\n * of `{ agent.mutationPolicy, mutationPolicyOverride }`. Escalation is\n * rejected at the route layer; this helper trusts callers to pass only\n * values produced by the override repository.\n */\n mutationPolicyOverride?: AiAgentMutationPolicy | null\n /**\n * DI container used by the `prepareMutation` tool-call wrapper (Step 5.6).\n * When present AND the agent's effective mutation policy is non-read-only,\n * `isMutation: true` tools are intercepted: the runtime creates an\n * `AiPendingAction` row and enqueues a `mutation-preview-card` UI part in\n * the returned {@link ResolvedAgentTools.uiPartQueue} instead of running the\n * tool's handler. When absent, mutation tools degrade-gracefully to the\n * pre-5.6 pass-through adapter \u2014 existing read-only agents are unaffected.\n */\n container?: AwilixContainer\n /**\n * Optional chat-turn correlation id used when hashing the\n * `AiPendingAction.idempotencyKey` so retries of the same mutation collapse\n * to a single row. The chat dispatcher supplies the OpenCode / AI SDK turn\n * id here; when omitted the hash falls back to `null` which still preserves\n * per-tenant/org uniqueness within the TTL window.\n */\n conversationId?: string | null\n /**\n * Surface the agent runs on behalf of. Defaults to `'agent'` (today's\n * behaviour). For `'mcp'` / `'tools-api'` the `mutationMode` decides the\n * effective policy via {@link resolveAgentRunMutationPolicyOverride} and\n * pending actions are stamped with the channel.\n */\n channel?: AiPendingActionChannel\n mutationMode?: McpMutationMode\n apiKeyId?: string | null\n correlationId?: string | null\n}\n\n/**\n * Queue of UI parts the mutation-preview wrapper accumulates during a turn.\n * The chat/object dispatcher flushes these on the next emission boundary\n * (spec \u00A79 allows either direct streaming or this queue pattern \u2014 we ship the\n * queue in Step 5.6 and the chat dispatcher will drain it in Step 5.10 when\n * the `mutation-preview-card` component registers). BC: callers that ignore\n * the field are unaffected.\n */\nexport interface AiUiPartQueue {\n /** Pushed by the mutation wrapper; drained by the dispatcher in order. */\n enqueue: (part: AiUiPart) => void\n drain: () => AiUiPart[]\n size: () => number\n}\n\nfunction createAiUiPartQueue(): AiUiPartQueue {\n const buffer: AiUiPart[] = []\n return {\n enqueue: (part) => {\n buffer.push(part)\n },\n drain: () => {\n const snapshot = buffer.slice()\n buffer.length = 0\n return snapshot\n },\n size: () => buffer.length,\n }\n}\n\nexport interface ResolvedAgentTools {\n agent: AiAgentDefinition\n tools: Record<string, Tool<unknown, unknown>>\n /**\n * Per-request UI-part queue the chat dispatcher drains between streamText\n * chunks (Step 5.10 contract). Always present; empty when no mutation-tool\n * calls fire during the turn.\n */\n uiPartQueue: AiUiPartQueue\n /**\n * Ids of the `AiPendingAction` rows created by the mutation wrapper during\n * the run, in call order. Empty when no mutation was queued.\n */\n pendingActionIds: string[]\n /**\n * Per-run start/end wall-clock timestamps (`Date.now()`) of every tool\n * execution, keyed by the AI SDK `toolCallId`. Filled as tools run; read by\n * `extractStepToolCalls` to compute `durationMs`. Calls without a\n * `toolCallId` are not recorded.\n */\n toolCallTimings: ToolCallTimings\n}\n\nfunction toPolicyAuthContext(ctx: AiChatRequestContext): {\n userFeatures: string[]\n isSuperAdmin: boolean\n} {\n return {\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n }\n}\n\n/**\n * Sanitize a dotted tool name (e.g. `search.hybrid_search`) into a format\n * accepted by all major LLM providers. OpenAI requires tool names to match\n * `^[a-zA-Z0-9_-]+$`; dots are replaced with double underscores (`__`).\n * Anthropic and Google accept both formats, so this is safe across providers.\n */\nexport function sanitizeToolNameForModel(name: string): string {\n return name.replace(/\\./g, '__')\n}\n\nexport function desanitizeToolNameForDisplay(name: string): string {\n return name.replace(/__/g, '.')\n}\n\nfunction formatToolResult(result: unknown): string {\n if (result === null || result === undefined) return 'No result returned'\n if (typeof result === 'string') return result\n if (typeof result === 'number' || typeof result === 'boolean') return String(result)\n try {\n return JSON.stringify(result, null, 2)\n } catch {\n return String(result)\n }\n}\n\nfunction buildToolHandlerContext(\n ctx: AiChatRequestContext,\n container?: AwilixContainer,\n tool?: AiToolDefinition,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: (container ?? undefined) as unknown as McpToolContext['container'],\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n ...(tool ? { tool } : {}),\n }\n}\n\ninterface MutationInterceptorOptions {\n agent: AiAgentDefinition\n tool: AiToolDefinition\n container: AwilixContainer\n ctx: AiChatRequestContext\n mutationPolicyOverride: AiAgentMutationPolicy | null\n conversationId: string | null\n uiPartQueue: AiUiPartQueue\n channel: AiPendingActionChannel\n apiKeyId: string | null\n correlationId: string | null\n pendingActionIds: string[]\n}\n\nfunction formatPendingActionToolResult(\n agent: AiAgentDefinition,\n tool: AiToolDefinition,\n pendingActionId: string,\n expiresAt: Date,\n reused: boolean,\n status: AiPendingActionStatus,\n executionResult: AiPendingActionExecutionResult | null,\n): string {\n // A reused `confirmed`/`executing` row means this exact mutation already\n // ran (or is running) under the same idempotency key \u2014 tell the model so\n // it does not resubmit, instead of always claiming a fresh approval is\n // pending (issue #7550).\n if (reused && (status === 'confirmed' || status === 'executing')) {\n const resultStatus = status === 'executing' ? 'executing' : 'already-executed'\n return formatToolResult({\n status: resultStatus,\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n executionResult: executionResult ?? null,\n message:\n resultStatus === 'executing'\n ? `Mutation \"${tool.name}\" is already executing from a prior confirmed call. Do NOT submit it again; wait for the result.`\n : `Mutation \"${tool.name}\" already ran for this input (idempotency key reused). Do NOT submit it again \u2014 see executionResult for the prior outcome.`,\n })\n }\n return formatToolResult({\n status: 'pending-confirmation',\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n expiresAt: expiresAt.toISOString(),\n message: `Awaiting user confirmation for mutation \"${tool.name}\". The action will NOT run until the user approves it.`,\n })\n}\n\n/**\n * Per-call gating decision for the destructive-confirm-required policy.\n * Honors a static boolean OR a predicate evaluated against the actual\n * tool-call args, so a multi-operation tool (e.g.\n * `customers.manage_deal_comment` with `operation: 'create' | 'update'\n * | 'delete'`) can gate only its destructive branches without being\n * split into multiple tools.\n */\nfunction resolveIsDestructive(\n isDestructive: boolean | ((input: unknown) => boolean) | undefined,\n args: unknown,\n): boolean {\n if (typeof isDestructive === 'function') {\n try {\n return isDestructive(args) === true\n } catch {\n // If the predicate throws (e.g. unexpected input shape), default to\n // gating \u2014 fail-safe for destructive policy.\n return true\n }\n }\n return isDestructive === true\n}\n\nfunction readExecuteToolCallId(options: { toolCallId?: unknown } | undefined): string | null {\n const toolCallId = options?.toolCallId\n return typeof toolCallId === 'string' && toolCallId.length > 0 ? toolCallId : null\n}\n\nfunction adaptToolToAiSdk(\n tool: AiToolDefinition,\n ctx: AiChatRequestContext,\n mutation: MutationInterceptorOptions | null,\n container: AwilixContainer | undefined,\n effectiveMutationPolicy: 'read-only' | 'confirm-required' | 'destructive-confirm-required' | undefined,\n toolCallTimings: Map<string, ToolCallTiming>,\n): Tool<unknown, unknown> {\n const safeSchema = toSafeZodSchema(tool.inputSchema as ZodType)\n const handlerContext = buildToolHandlerContext(ctx, container, tool)\n const runToolCall = async (args: unknown, toolCallId: string | null): Promise<string> => {\n const replayDecision = resolveToolReplayDecision({\n toolName: tool.name,\n args,\n isMutation: tool.isMutation === true,\n toolCallId,\n authorized: hasRequiredFeatures(tool.requiredFeatures, ctx.features, ctx.isSuperAdmin),\n })\n if (replayDecision.kind === 'replay') {\n const recordedError = replayDecision.fixture.error\n if (recordedError) {\n throw new Error(`Tool \"${tool.name}\" failed: ${recordedError.message}`)\n }\n return formatToolResult(replayDecision.fixture.output)\n }\n // Per-call gating decision. Under `destructive-confirm-required`,\n // tools with a predicate `isDestructive(args)` may flip per call \u2014\n // e.g. comment delete gates while comment create runs direct.\n const requiresApprovalNow = (() => {\n if (!mutation) return false\n if (effectiveMutationPolicy === 'confirm-required') return true\n if (effectiveMutationPolicy === 'destructive-confirm-required') {\n return resolveIsDestructive(mutation.tool.isDestructive, args)\n }\n return false\n })()\n if (mutation && requiresApprovalNow) {\n try {\n const toolCallArgs =\n args && typeof args === 'object' && !Array.isArray(args)\n ? { ...(args as Record<string, unknown>) }\n : {}\n const stagedInput = resolveStagedToolInput(tool.inputSchema, toolCallArgs)\n if (!stagedInput.success) {\n throw new Error(stagedInput.error)\n }\n const { uiPart, pendingAction, reused } = await prepareMutation(\n {\n agent: mutation.agent,\n tool: mutation.tool,\n toolCallArgs: stagedInput.input,\n conversationId: mutation.conversationId,\n mutationPolicyOverride: mutation.mutationPolicyOverride,\n channel: mutation.channel,\n apiKeyId: mutation.apiKeyId,\n correlationId: mutation.correlationId,\n },\n {\n tenantId: mutation.ctx.tenantId,\n organizationId: mutation.ctx.organizationId,\n userId: mutation.ctx.userId,\n features: mutation.ctx.features,\n isSuperAdmin: mutation.ctx.isSuperAdmin,\n container: mutation.container,\n },\n )\n mutation.uiPartQueue.enqueue(uiPart)\n mutation.pendingActionIds.push(pendingAction.id)\n return formatPendingActionToolResult(\n mutation.agent,\n mutation.tool,\n pendingAction.id,\n pendingAction.expiresAt,\n reused,\n pendingAction.status,\n pendingAction.executionResult ?? null,\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(\n `Tool \"${tool.name}\" could not be prepared for confirmation: ${message}`,\n )\n }\n }\n try {\n // Create a fresh container per tool call so the EM is never stale.\n const freshContainer = await createRequestContainer()\n const uiPartBuffer = createToolUiPartBuffer()\n const freshContext: McpToolContext = {\n ...handlerContext,\n container: freshContainer as unknown as McpToolContext['container'],\n uiParts: { enqueue: uiPartBuffer.enqueue },\n }\n const { executeTool } = await import('./tool-executor')\n const execute = () => executeTool(tool.name, args, freshContext)\n const execResult = replayDecision.kind === 'record' && shouldIsolateModelFactoryTools()\n ? await withToolReplayContext({ mode: 'record', sink: () => undefined }, () => withModelFactoryToolScope(execute))\n : await execute()\n if (!execResult.success) {\n throw new Error(execResult.error || 'Tool execution failed')\n }\n const output = mergeUiPartsIntoToolResult(execResult.result, uiPartBuffer.drain())\n if (replayDecision.kind === 'record') {\n emitRecordedToolFixture(replayDecision.sink, buildRecordedToolFixture(replayDecision.call, { output }))\n }\n return formatToolResult(output)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (replayDecision.kind === 'record') {\n emitRecordedToolFixture(replayDecision.sink, buildRecordedToolFixture(replayDecision.call, { error: message }))\n }\n throw new Error(`Tool \"${tool.name}\" failed: ${message}`)\n }\n }\n return dynamicTool({\n description: tool.description,\n inputSchema: safeSchema,\n execute: async (args: unknown, options?: { toolCallId?: unknown }) => {\n const toolCallId = readExecuteToolCallId(options)\n if (!toolCallId) return runToolCall(args, null)\n const timing: ToolCallTiming = { startedAt: Date.now() }\n toolCallTimings.set(toolCallId, timing)\n try {\n return await runToolCall(args, toolCallId)\n } finally {\n timing.endedAt = Date.now()\n }\n },\n })\n}\n\n/**\n * Resolves the agent's whitelisted tools into an AI SDK `tools` map, enforcing\n * the same policy gate as the HTTP dispatcher. Throws {@link AgentPolicyError}\n * on agent-level deny; tool-level denies are skipped with a logger warning\n * because the agent author whitelisted a tool the caller is not currently\n * permitted to execute (deterministic non-failure \u2014 the remaining tools still\n * reach the model).\n */\nexport async function resolveAiAgentTools(\n input: ResolveAiAgentToolsInput,\n): Promise<ResolvedAgentTools> {\n await loadAgentRegistry()\n // The agent registry alone is not enough: the policy gate below resolves\n // every allowlisted name against the TOOL registry, and rejects what it\n // cannot find as `tool_unknown`. Loading it here \u2014 rather than in the half\n // dozen entry points that happened to remember \u2014 is what makes an agent's\n // allowlist mean the same thing on every path.\n try {\n const { ensureModuleToolsLoaded } = await import('./tool-loader')\n await ensureModuleToolsLoaded()\n } catch (error) {\n // A registry that failed to load leaves the agent toolless, which the\n // caller already handles; it must not take the whole turn down.\n logger.error('Could not load module tools; agent will resolve to its known tools only', {\n agentId: input.agentId,\n err: error,\n })\n }\n\n const policyAuth = toPolicyAuthContext(input.authContext)\n const channel = input.channel ?? 'agent'\n const mutationPolicyOverride = resolveAgentRunMutationPolicyOverride({\n channel,\n mutationMode: input.mutationMode,\n declaredPolicy: getAgent(input.agentId)?.mutationPolicy,\n tenantOverride: input.mutationPolicyOverride,\n canQueueMutations: typeof input.container !== 'undefined',\n })\n const agentDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n requestedExecutionMode: input.requestedExecutionMode ?? 'chat',\n mutationPolicyOverride,\n })\n if (!agentDecision.ok) {\n throw new AgentPolicyError(agentDecision.code, agentDecision.message)\n }\n\n const { agent } = agentDecision\n const tools: Record<string, Tool<unknown, unknown>> = {}\n const uiPartQueue = createAiUiPartQueue()\n const pendingActionIds: string[] = []\n const toolCallTimings = new Map<string, ToolCallTiming>()\n const effectiveMutationPolicy = resolveEffectiveMutationPolicy(\n agent.mutationPolicy,\n mutationPolicyOverride,\n agent.id,\n )\n const canInterceptMutations =\n effectiveMutationPolicy !== 'read-only' && typeof input.container !== 'undefined'\n\n for (const toolName of agent.allowedTools) {\n const toolDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n toolName,\n mutationPolicyOverride,\n })\n if (!toolDecision.ok) {\n logger.warn('Skipping tool for agent', { toolName, agentId: agent.id, reason: toolDecision.message })\n continue\n }\n\n const record = (toolDecision.tool ?? toolRegistry.getTool(toolName)) as\n | AiToolDefinition\n | undefined\n if (!record) {\n logger.warn('Tool vanished from registry between policy checks; skipping', { toolName })\n continue\n }\n\n try {\n // For any mutation tool whose policy isn't read-only, prepare the\n // interceptor options once. The actual gate-vs-run-direct decision\n // happens at call time inside `adaptToolToAiSdk` because under\n // `destructive-confirm-required` `isDestructive` may be a predicate\n // evaluated against the per-call args (e.g. a multi-operation\n // tool with `operation: 'create' | 'update' | 'delete'` gates only\n // the destructive branch).\n const mutationOptions: MutationInterceptorOptions | null =\n record.isMutation === true && canInterceptMutations && input.container\n ? {\n agent,\n tool: record,\n container: input.container,\n ctx: input.authContext,\n mutationPolicyOverride,\n conversationId: input.conversationId ?? null,\n uiPartQueue,\n channel,\n apiKeyId: input.apiKeyId ?? null,\n correlationId: input.correlationId ?? null,\n pendingActionIds,\n }\n : null\n // Sanitize tool name for model API compatibility: OpenAI requires\n // names matching ^[a-zA-Z0-9_-]+$ (no dots). Replace dots with\n // double underscores so `search.hybrid_search` becomes\n // `search__hybrid_search`. The AI SDK uses the record key as the\n // tool name sent to the model; the original dotted name stays on\n // the `tool` object for logging and prepareMutation hashing.\n const modelSafeToolName = sanitizeToolNameForModel(toolName)\n tools[modelSafeToolName] = adaptToolToAiSdk(\n record,\n input.authContext,\n mutationOptions,\n input.container,\n effectiveMutationPolicy,\n toolCallTimings,\n )\n } catch (error) {\n logger.error('Failed to adapt tool for agent', { toolName, agentId: agent.id, err: error })\n }\n }\n\n return { agent, tools, uiPartQueue, pend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AkB;AAAA,QACxC;AAAA,QACA;AAAA,QACA,UAAU,MAAM,YAAY;AAAA,QAC5B,eAAe,MAAM,iBAAiB;AAAA,QACtC;AAAA,MACF,IACA;AAON,YAAM,oBAAoB,yBAAyB,QAAQ;AAC3D,YAAM,iBAAiB,IAAI;AAAA,QACzB;AAAA,QACA,MAAM;AAAA,QACN;AAAA,QACA,MAAM;AAAA,QACN;AAAA,QACA;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,aAAO,MAAM,kCAAkC,EAAE,UAAU,SAAS,MAAM,IAAI,KAAK,MAAM,CAAC;AAAA,IAC5F;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,OAAO,aAAa,kBAAkB,gBAAgB;AACxE;",
4
+ "sourcesContent": ["import { shouldIsolateModelFactoryTools, withModelFactoryToolScope } from './model-factory-context'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { dynamicTool, type Tool } from 'ai'\nimport type { AwilixContainer } from 'awilix'\nimport type { ZodType } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport type { AiChatRequestContext, AiUiPart } from './attachment-bridge-types'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionStatus,\n} from './pending-action-types'\nimport { getAgent, loadAgentRegistry } from './agent-registry'\nimport {\n checkAgentPolicy,\n resolveEffectiveMutationPolicy,\n type AgentPolicyDenyCode,\n} from './agent-policy'\nimport { toolRegistry } from './tool-registry'\nimport { toSafeZodSchema } from './schema-utils'\nimport { createToolUiPartBuffer, mergeUiPartsIntoToolResult } from './tool-ui-parts'\nimport { prepareMutation } from './prepare-mutation'\nimport { resolveAgentRunMutationPolicyOverride } from './agent-channel-policy'\nimport type { McpMutationMode } from './mcp-exposure'\nimport type { AiPendingActionChannel } from './pending-action-types'\nimport type { ToolCallTiming, ToolCallTimings } from './loop-step-extraction'\nimport {\n buildRecordedToolFixture,\n emitRecordedToolFixture,\n resolveToolReplayDecision,\n withToolReplayContext,\n} from './llm-adapters/tool-replay-context'\nimport { resolveStagedToolInput } from './tool-input'\nimport { hasRequiredFeatures } from './auth'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Error thrown by `resolveAiAgentTools` (and downstream `runAiAgentText`) when\n * the agent-level policy check denies a request. Carries the structured deny\n * code so HTTP dispatchers can map it to a stable status and JSON body.\n */\nexport class AgentPolicyError extends Error {\n readonly code: AgentPolicyDenyCode\n\n constructor(code: AgentPolicyDenyCode, message: string) {\n super(message)\n this.name = 'AgentPolicyError'\n this.code = code\n }\n}\n\nexport interface ResolveAiAgentToolsInput {\n agentId: string\n authContext: AiChatRequestContext\n pageContext?: Record<string, unknown>\n attachmentIds?: string[]\n /**\n * Execution mode the caller intends to run the agent in. Defaults to\n * `'chat'` to preserve the existing chat dispatcher contract. Object-mode\n * callers (see `runAiAgentObject`) MUST pass `'object'` so the policy gate\n * can reject chat-only agents early with `execution_mode_not_supported`.\n */\n requestedExecutionMode?: 'chat' | 'object'\n /**\n * Optional tenant-scoped mutation-policy DOWNGRADE. When supplied, the\n * effective policy evaluated by `checkAgentPolicy` is the most restrictive\n * of `{ agent.mutationPolicy, mutationPolicyOverride }`. Escalation is\n * rejected at the route layer; this helper trusts callers to pass only\n * values produced by the override repository.\n */\n mutationPolicyOverride?: AiAgentMutationPolicy | null\n /**\n * DI container used by the `prepareMutation` tool-call wrapper (Step 5.6).\n * When present AND the agent's effective mutation policy is non-read-only,\n * `isMutation: true` tools are intercepted: the runtime creates an\n * `AiPendingAction` row and enqueues a `mutation-preview-card` UI part in\n * the returned {@link ResolvedAgentTools.uiPartQueue} instead of running the\n * tool's handler. When absent, mutation tools degrade-gracefully to the\n * pre-5.6 pass-through adapter \u2014 existing read-only agents are unaffected.\n */\n container?: AwilixContainer\n /**\n * Optional chat-turn correlation id used when hashing the\n * `AiPendingAction.idempotencyKey` so retries of the same mutation collapse\n * to a single row. The chat dispatcher supplies the OpenCode / AI SDK turn\n * id here; when omitted the hash falls back to `null` which still preserves\n * per-tenant/org uniqueness within the TTL window.\n */\n conversationId?: string | null\n /**\n * Surface the agent runs on behalf of. Defaults to `'agent'` (today's\n * behaviour). For `'mcp'` / `'tools-api'` the `mutationMode` decides the\n * effective policy via {@link resolveAgentRunMutationPolicyOverride} and\n * pending actions are stamped with the channel.\n */\n channel?: AiPendingActionChannel\n mutationMode?: McpMutationMode\n apiKeyId?: string | null\n correlationId?: string | null\n}\n\n/**\n * Queue of UI parts the mutation-preview wrapper accumulates during a turn.\n * The chat/object dispatcher flushes these on the next emission boundary\n * (spec \u00A79 allows either direct streaming or this queue pattern \u2014 we ship the\n * queue in Step 5.6 and the chat dispatcher will drain it in Step 5.10 when\n * the `mutation-preview-card` component registers). BC: callers that ignore\n * the field are unaffected.\n */\nexport interface AiUiPartQueue {\n /** Pushed by the mutation wrapper; drained by the dispatcher in order. */\n enqueue: (part: AiUiPart) => void\n drain: () => AiUiPart[]\n size: () => number\n}\n\nfunction createAiUiPartQueue(): AiUiPartQueue {\n const buffer: AiUiPart[] = []\n return {\n enqueue: (part) => {\n buffer.push(part)\n },\n drain: () => {\n const snapshot = buffer.slice()\n buffer.length = 0\n return snapshot\n },\n size: () => buffer.length,\n }\n}\n\nexport interface ResolvedAgentTools {\n agent: AiAgentDefinition\n tools: Record<string, Tool<unknown, unknown>>\n /**\n * Per-request UI-part queue the chat dispatcher drains between streamText\n * chunks (Step 5.10 contract). Always present; empty when no mutation-tool\n * calls fire during the turn.\n */\n uiPartQueue: AiUiPartQueue\n /**\n * Ids of the `AiPendingAction` rows created by the mutation wrapper during\n * the run, in call order. Empty when no mutation was queued.\n */\n pendingActionIds: string[]\n /**\n * Per-run start/end wall-clock timestamps (`Date.now()`) of every tool\n * execution, keyed by the AI SDK `toolCallId`. Filled as tools run; read by\n * `extractStepToolCalls` to compute `durationMs`. Calls without a\n * `toolCallId` are not recorded.\n */\n toolCallTimings: ToolCallTimings\n}\n\nfunction toPolicyAuthContext(ctx: AiChatRequestContext): {\n userFeatures: string[]\n isSuperAdmin: boolean\n} {\n return {\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n }\n}\n\n/**\n * Sanitize a dotted tool name (e.g. `search.hybrid_search`) into a format\n * accepted by all major LLM providers. OpenAI requires tool names to match\n * `^[a-zA-Z0-9_-]+$`; dots are replaced with double underscores (`__`).\n * Anthropic and Google accept both formats, so this is safe across providers.\n */\nexport function sanitizeToolNameForModel(name: string): string {\n return name.replace(/\\./g, '__')\n}\n\nexport function desanitizeToolNameForDisplay(name: string): string {\n return name.replace(/__/g, '.')\n}\n\nfunction formatToolResult(result: unknown): string {\n if (result === null || result === undefined) return 'No result returned'\n if (typeof result === 'string') return result\n if (typeof result === 'number' || typeof result === 'boolean') return String(result)\n try {\n return JSON.stringify(result, null, 2)\n } catch {\n return String(result)\n }\n}\n\ninterface ToolHandlerChannelContext {\n channel: AiPendingActionChannel\n mutationMode?: McpMutationMode\n apiKeyId: string | null\n correlationId: string | null\n}\n\nfunction buildToolHandlerContext(\n ctx: AiChatRequestContext,\n container?: AwilixContainer,\n tool?: AiToolDefinition,\n channelContext?: ToolHandlerChannelContext,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: (container ?? undefined) as unknown as McpToolContext['container'],\n userFeatures: ctx.features,\n isSuperAdmin: ctx.isSuperAdmin,\n ...(tool ? { tool } : {}),\n ...(channelContext\n ? {\n channel: channelContext.channel,\n ...(channelContext.mutationMode ? { mutationMode: channelContext.mutationMode } : {}),\n apiKeyId: channelContext.apiKeyId,\n correlationId: channelContext.correlationId,\n }\n : {}),\n }\n}\n\ninterface MutationInterceptorOptions {\n agent: AiAgentDefinition\n tool: AiToolDefinition\n container: AwilixContainer\n ctx: AiChatRequestContext\n mutationPolicyOverride: AiAgentMutationPolicy | null\n conversationId: string | null\n uiPartQueue: AiUiPartQueue\n channel: AiPendingActionChannel\n apiKeyId: string | null\n correlationId: string | null\n pendingActionIds: string[]\n}\n\nfunction formatPendingActionToolResult(\n agent: AiAgentDefinition,\n tool: AiToolDefinition,\n pendingActionId: string,\n expiresAt: Date,\n reused: boolean,\n status: AiPendingActionStatus,\n executionResult: AiPendingActionExecutionResult | null,\n): string {\n // A reused `confirmed`/`executing` row means this exact mutation already\n // ran (or is running) under the same idempotency key \u2014 tell the model so\n // it does not resubmit, instead of always claiming a fresh approval is\n // pending (issue #7550).\n if (reused && (status === 'confirmed' || status === 'executing')) {\n const resultStatus = status === 'executing' ? 'executing' : 'already-executed'\n return formatToolResult({\n status: resultStatus,\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n executionResult: executionResult ?? null,\n message:\n resultStatus === 'executing'\n ? `Mutation \"${tool.name}\" is already executing from a prior confirmed call. Do NOT submit it again; wait for the result.`\n : `Mutation \"${tool.name}\" already ran for this input (idempotency key reused). Do NOT submit it again \u2014 see executionResult for the prior outcome.`,\n })\n }\n return formatToolResult({\n status: 'pending-confirmation',\n agentId: agent.id,\n toolName: tool.name,\n pendingActionId,\n expiresAt: expiresAt.toISOString(),\n message: `Awaiting user confirmation for mutation \"${tool.name}\". The action will NOT run until the user approves it.`,\n })\n}\n\n/**\n * Per-call gating decision for the destructive-confirm-required policy.\n * Honors a static boolean OR a predicate evaluated against the actual\n * tool-call args, so a multi-operation tool (e.g.\n * `customers.manage_deal_comment` with `operation: 'create' | 'update'\n * | 'delete'`) can gate only its destructive branches without being\n * split into multiple tools.\n */\nfunction resolveIsDestructive(\n isDestructive: boolean | ((input: unknown) => boolean) | undefined,\n args: unknown,\n): boolean {\n if (typeof isDestructive === 'function') {\n try {\n return isDestructive(args) === true\n } catch {\n // If the predicate throws (e.g. unexpected input shape), default to\n // gating \u2014 fail-safe for destructive policy.\n return true\n }\n }\n return isDestructive === true\n}\n\nfunction readExecuteToolCallId(options: { toolCallId?: unknown } | undefined): string | null {\n const toolCallId = options?.toolCallId\n return typeof toolCallId === 'string' && toolCallId.length > 0 ? toolCallId : null\n}\n\nfunction adaptToolToAiSdk(\n tool: AiToolDefinition,\n ctx: AiChatRequestContext,\n mutation: MutationInterceptorOptions | null,\n container: AwilixContainer | undefined,\n effectiveMutationPolicy: 'read-only' | 'confirm-required' | 'destructive-confirm-required' | undefined,\n toolCallTimings: Map<string, ToolCallTiming>,\n channelContext?: ToolHandlerChannelContext,\n): Tool<unknown, unknown> {\n const safeSchema = toSafeZodSchema(tool.inputSchema as ZodType)\n const handlerContext = buildToolHandlerContext(ctx, container, tool, channelContext)\n const runToolCall = async (args: unknown, toolCallId: string | null): Promise<string> => {\n const replayDecision = resolveToolReplayDecision({\n toolName: tool.name,\n args,\n isMutation: tool.isMutation === true,\n toolCallId,\n authorized: hasRequiredFeatures(tool.requiredFeatures, ctx.features, ctx.isSuperAdmin),\n })\n if (replayDecision.kind === 'replay') {\n const recordedError = replayDecision.fixture.error\n if (recordedError) {\n throw new Error(`Tool \"${tool.name}\" failed: ${recordedError.message}`)\n }\n return formatToolResult(replayDecision.fixture.output)\n }\n // Per-call gating decision. Under `destructive-confirm-required`,\n // tools with a predicate `isDestructive(args)` may flip per call \u2014\n // e.g. comment delete gates while comment create runs direct.\n // On `mcp` / `tools-api` a non-null `mutation` means approval mode,\n // which never runs the handler directly, so every write is gated.\n const requiresApprovalNow = (() => {\n if (!mutation) return false\n if (mutation.channel !== 'agent') return true\n if (effectiveMutationPolicy === 'confirm-required') return true\n if (effectiveMutationPolicy === 'destructive-confirm-required') {\n return resolveIsDestructive(mutation.tool.isDestructive, args)\n }\n return false\n })()\n if (mutation && requiresApprovalNow) {\n try {\n const toolCallArgs =\n args && typeof args === 'object' && !Array.isArray(args)\n ? { ...(args as Record<string, unknown>) }\n : {}\n const stagedInput = resolveStagedToolInput(tool.inputSchema, toolCallArgs)\n if (!stagedInput.success) {\n throw new Error(stagedInput.error)\n }\n const { uiPart, pendingAction, reused } = await prepareMutation(\n {\n agent: mutation.agent,\n tool: mutation.tool,\n toolCallArgs: stagedInput.input,\n conversationId: mutation.conversationId,\n mutationPolicyOverride: mutation.mutationPolicyOverride,\n channel: mutation.channel,\n apiKeyId: mutation.apiKeyId,\n correlationId: mutation.correlationId,\n },\n {\n tenantId: mutation.ctx.tenantId,\n organizationId: mutation.ctx.organizationId,\n userId: mutation.ctx.userId,\n features: mutation.ctx.features,\n isSuperAdmin: mutation.ctx.isSuperAdmin,\n container: mutation.container,\n },\n )\n mutation.uiPartQueue.enqueue(uiPart)\n mutation.pendingActionIds.push(pendingAction.id)\n return formatPendingActionToolResult(\n mutation.agent,\n mutation.tool,\n pendingAction.id,\n pendingAction.expiresAt,\n reused,\n pendingAction.status,\n pendingAction.executionResult ?? null,\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(\n `Tool \"${tool.name}\" could not be prepared for confirmation: ${message}`,\n )\n }\n }\n try {\n // Create a fresh container per tool call so the EM is never stale.\n const freshContainer = await createRequestContainer()\n const uiPartBuffer = createToolUiPartBuffer()\n const freshContext: McpToolContext = {\n ...handlerContext,\n container: freshContainer as unknown as McpToolContext['container'],\n uiParts: { enqueue: uiPartBuffer.enqueue },\n }\n const { executeTool } = await import('./tool-executor')\n const execute = () => executeTool(tool.name, args, freshContext)\n const execResult = replayDecision.kind === 'record' && shouldIsolateModelFactoryTools()\n ? await withToolReplayContext({ mode: 'record', sink: () => undefined }, () => withModelFactoryToolScope(execute))\n : await execute()\n if (!execResult.success) {\n throw new Error(execResult.error || 'Tool execution failed')\n }\n const output = mergeUiPartsIntoToolResult(execResult.result, uiPartBuffer.drain())\n if (replayDecision.kind === 'record') {\n emitRecordedToolFixture(replayDecision.sink, buildRecordedToolFixture(replayDecision.call, { output }))\n }\n return formatToolResult(output)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (replayDecision.kind === 'record') {\n emitRecordedToolFixture(replayDecision.sink, buildRecordedToolFixture(replayDecision.call, { error: message }))\n }\n throw new Error(`Tool \"${tool.name}\" failed: ${message}`)\n }\n }\n return dynamicTool({\n description: tool.description,\n inputSchema: safeSchema,\n execute: async (args: unknown, options?: { toolCallId?: unknown }) => {\n const toolCallId = readExecuteToolCallId(options)\n if (!toolCallId) return runToolCall(args, null)\n const timing: ToolCallTiming = { startedAt: Date.now() }\n toolCallTimings.set(toolCallId, timing)\n try {\n return await runToolCall(args, toolCallId)\n } finally {\n timing.endedAt = Date.now()\n }\n },\n })\n}\n\n/**\n * Resolves the agent's whitelisted tools into an AI SDK `tools` map, enforcing\n * the same policy gate as the HTTP dispatcher. Throws {@link AgentPolicyError}\n * on agent-level deny; tool-level denies are skipped with a logger warning\n * because the agent author whitelisted a tool the caller is not currently\n * permitted to execute (deterministic non-failure \u2014 the remaining tools still\n * reach the model).\n */\nexport async function resolveAiAgentTools(\n input: ResolveAiAgentToolsInput,\n): Promise<ResolvedAgentTools> {\n await loadAgentRegistry()\n // The agent registry alone is not enough: the policy gate below resolves\n // every allowlisted name against the TOOL registry, and rejects what it\n // cannot find as `tool_unknown`. Loading it here \u2014 rather than in the half\n // dozen entry points that happened to remember \u2014 is what makes an agent's\n // allowlist mean the same thing on every path.\n try {\n const { ensureModuleToolsLoaded } = await import('./tool-loader')\n await ensureModuleToolsLoaded()\n } catch (error) {\n // A registry that failed to load leaves the agent toolless, which the\n // caller already handles; it must not take the whole turn down.\n logger.error('Could not load module tools; agent will resolve to its known tools only', {\n agentId: input.agentId,\n err: error,\n })\n }\n\n const policyAuth = toPolicyAuthContext(input.authContext)\n const channel = input.channel ?? 'agent'\n const mutationPolicyOverride = resolveAgentRunMutationPolicyOverride({\n channel,\n mutationMode: input.mutationMode,\n declaredPolicy: getAgent(input.agentId)?.mutationPolicy,\n tenantOverride: input.mutationPolicyOverride,\n canQueueMutations: typeof input.container !== 'undefined',\n })\n const agentDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n requestedExecutionMode: input.requestedExecutionMode ?? 'chat',\n mutationPolicyOverride,\n })\n if (!agentDecision.ok) {\n throw new AgentPolicyError(agentDecision.code, agentDecision.message)\n }\n\n const { agent } = agentDecision\n const tools: Record<string, Tool<unknown, unknown>> = {}\n const uiPartQueue = createAiUiPartQueue()\n const pendingActionIds: string[] = []\n const toolCallTimings = new Map<string, ToolCallTiming>()\n const effectiveMutationPolicy = resolveEffectiveMutationPolicy(\n agent.mutationPolicy,\n mutationPolicyOverride,\n agent.id,\n )\n const canInterceptMutations =\n effectiveMutationPolicy !== 'read-only' && typeof input.container !== 'undefined'\n\n for (const toolName of agent.allowedTools) {\n const toolDecision = checkAgentPolicy({\n agentId: input.agentId,\n authContext: policyAuth,\n toolName,\n mutationPolicyOverride,\n })\n if (!toolDecision.ok) {\n logger.warn('Skipping tool for agent', { toolName, agentId: agent.id, reason: toolDecision.message })\n continue\n }\n\n const record = (toolDecision.tool ?? toolRegistry.getTool(toolName)) as\n | AiToolDefinition\n | undefined\n if (!record) {\n logger.warn('Tool vanished from registry between policy checks; skipping', { toolName })\n continue\n }\n\n try {\n // For any mutation tool whose policy isn't read-only, prepare the\n // interceptor options once. The actual gate-vs-run-direct decision\n // happens at call time inside `adaptToolToAiSdk` because under\n // `destructive-confirm-required` `isDestructive` may be a predicate\n // evaluated against the per-call args (e.g. a multi-operation\n // tool with `operation: 'create' | 'update' | 'delete'` gates only\n // the destructive branch).\n const mutationOptions: MutationInterceptorOptions | null =\n record.isMutation === true && canInterceptMutations && input.container\n ? {\n agent,\n tool: record,\n container: input.container,\n ctx: input.authContext,\n mutationPolicyOverride,\n conversationId: input.conversationId ?? null,\n uiPartQueue,\n channel,\n apiKeyId: input.apiKeyId ?? null,\n correlationId: input.correlationId ?? null,\n pendingActionIds,\n }\n : null\n // Sanitize tool name for model API compatibility: OpenAI requires\n // names matching ^[a-zA-Z0-9_-]+$ (no dots). Replace dots with\n // double underscores so `search.hybrid_search` becomes\n // `search__hybrid_search`. The AI SDK uses the record key as the\n // tool name sent to the model; the original dotted name stays on\n // the `tool` object for logging and prepareMutation hashing.\n const modelSafeToolName = sanitizeToolNameForModel(toolName)\n tools[modelSafeToolName] = adaptToolToAiSdk(\n record,\n input.authContext,\n mutationOptions,\n input.container,\n effectiveMutationPolicy,\n toolCallTimings,\n {\n channel,\n mutationMode: input.mutationMode,\n apiKeyId: input.apiKeyId ?? null,\n correlationId: input.correlationId ?? null,\n },\n )\n } catch (error) {\n logger.error('Failed to adapt tool for agent', { toolName, agentId: agent.id, err: error })\n }\n }\n\n return { agent, tools, uiPartQueue, pendingActionIds, toolCallTimings }\n}\n"],
5
+ "mappings": "AAAA,SAAS,gCAAgC,iCAAiC;AAC1E,SAAS,oBAAoB;AAC7B,SAAS,mBAA8B;AAGvC,SAAS,8BAA8B;AAQvC,SAAS,UAAU,yBAAyB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,wBAAwB,kCAAkC;AACnE,SAAS,uBAAuB;AAChC,SAAS,6CAA6C;AAItD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,cAAc;AAOnC,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,MAA2B,SAAiB;AACtD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAmEA,SAAS,sBAAqC;AAC5C,QAAM,SAAqB,CAAC;AAC5B,SAAO;AAAA,IACL,SAAS,CAAC,SAAS;AACjB,aAAO,KAAK,IAAI;AAAA,IAClB;AAAA,IACA,OAAO,MAAM;AACX,YAAM,WAAW,OAAO,MAAM;AAC9B,aAAO,SAAS;AAChB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,MAAM,OAAO;AAAA,EACrB;AACF;AAyBA,SAAS,oBAAoB,KAG3B;AACA,SAAO;AAAA,IACL,cAAc,IAAI;AAAA,IAClB,cAAc,IAA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.6a9c271838",
3
+ "version": "0.11.1-develop.8317.1.dde3d38b64",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -103,16 +103,16 @@
103
103
  "zod-to-json-schema": "^3.25.2"
104
104
  },
105
105
  "peerDependencies": {
106
- "@open-mercato/shared": "0.11.1-develop.8305.1.6a9c271838",
107
- "@open-mercato/ui": "0.11.1-develop.8305.1.6a9c271838",
106
+ "@open-mercato/shared": "0.11.1-develop.8317.1.dde3d38b64",
107
+ "@open-mercato/ui": "0.11.1-develop.8317.1.dde3d38b64",
108
108
  "react": "^19.0.0",
109
109
  "react-dom": "^19.0.0",
110
110
  "zod": ">=3.23.0"
111
111
  },
112
112
  "devDependencies": {
113
- "@open-mercato/cli": "0.11.1-develop.8305.1.6a9c271838",
114
- "@open-mercato/shared": "0.11.1-develop.8305.1.6a9c271838",
115
- "@open-mercato/ui": "0.11.1-develop.8305.1.6a9c271838",
113
+ "@open-mercato/cli": "0.11.1-develop.8317.1.dde3d38b64",
114
+ "@open-mercato/shared": "0.11.1-develop.8317.1.dde3d38b64",
115
+ "@open-mercato/ui": "0.11.1-develop.8317.1.dde3d38b64",
116
116
  "@types/react": "^19.2.18",
117
117
  "@types/react-dom": "^19.2.5",
118
118
  "react": "19.2.8",
@@ -58,7 +58,7 @@ const container = {
58
58
  },
59
59
  } as unknown as AwilixContainer
60
60
 
61
- function seedMutationAgent(): void {
61
+ function seedMutationAgent(mutationPolicy: AiAgentDefinition['mutationPolicy'] = 'confirm-required'): void {
62
62
  const readTool: AiToolDefinition = {
63
63
  name: 'customers.read_deal',
64
64
  description: 'read',
@@ -82,7 +82,7 @@ function seedMutationAgent(): void {
82
82
  systemPrompt: 'System prompt base.',
83
83
  executionMode: 'object',
84
84
  readOnly: false,
85
- mutationPolicy: 'confirm-required',
85
+ mutationPolicy,
86
86
  allowedTools: ['customers.read_deal', 'customers.update_deal'],
87
87
  output: { schemaName: 'Verdict', schema: outputSchema },
88
88
  }
@@ -175,6 +175,55 @@ describe('runAiAgentObject channel mutation policy (MCP parity §3.1)', () => {
175
175
  expect(result.pendingActionIds).toEqual(['pending-1'])
176
176
  })
177
177
 
178
+ it("tells the model every write is queued for a destructive-confirm-required agent on 'mcp' in 'approval' mode", async () => {
179
+ seedMutationAgent('destructive-confirm-required')
180
+ mockGenerateTextCallingUpdate()
181
+
182
+ const result = await runAiAgentObject({
183
+ agentId: 'customers.writer_agent',
184
+ input: 'judge',
185
+ authContext: baseAuth,
186
+ enableTools: true,
187
+ container,
188
+ channel: 'mcp',
189
+ mutationMode: 'approval',
190
+ })
191
+
192
+ const callArg = generateTextMock.mock.calls[0][0] as { system: string }
193
+ expect(callArg.system).toContain('Effective policy: destructive-confirm-required.')
194
+ expect(callArg.system).toContain('Tools that REQUIRE APPROVAL under the effective policy: customers.update_deal.')
195
+ expect(callArg.system).toContain('queued as a pending action')
196
+ expect(callArg.system).not.toContain('WILL RUN DIRECTLY')
197
+ expect(callArg.system).not.toContain('inline approval card')
198
+ expect(prepareMutationMock).toHaveBeenCalledTimes(1)
199
+ if (result.mode !== 'generate') throw new Error('unreachable')
200
+ expect(result.pendingActionIds).toEqual(['pending-1'])
201
+ })
202
+
203
+ it('keeps the direct-run prompt for a destructive-confirm-required agent on the agent channel', async () => {
204
+ seedMutationAgent('destructive-confirm-required')
205
+ generateTextMock.mockResolvedValue({
206
+ output: { verdict: 'ok' },
207
+ finishReason: 'stop',
208
+ usage: { inputTokens: 1, outputTokens: 1 },
209
+ })
210
+
211
+ await runAiAgentObject({
212
+ agentId: 'customers.writer_agent',
213
+ input: 'judge',
214
+ authContext: baseAuth,
215
+ enableTools: true,
216
+ container,
217
+ })
218
+
219
+ const callArg = generateTextMock.mock.calls[0][0] as { system: string }
220
+ expect(callArg.system).toContain(
221
+ 'Tools that WILL RUN DIRECTLY (no approval card, no pending action) under the effective policy: customers.update_deal.',
222
+ )
223
+ expect(callArg.system).not.toContain('REQUIRE APPROVAL')
224
+ expect(prepareMutationMock).not.toHaveBeenCalled()
225
+ })
226
+
178
227
  it('keeps default agent-channel behaviour when no channel is supplied', async () => {
179
228
  seedMutationAgent()
180
229
  mockGenerateTextCallingUpdate()
@@ -15,7 +15,30 @@ jest.mock('../agent-registry', () => ({
15
15
  getAgent: (id: string) => mockAgents.get(id),
16
16
  }))
17
17
 
18
- import { AgentPolicyError } from '../agent-tools'
18
+ jest.mock('../tool-loader', () => ({
19
+ ensureModuleToolsLoaded: async () => undefined,
20
+ }))
21
+
22
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({
23
+ createRequestContainer: async () => ({
24
+ resolve: () => {
25
+ throw new Error('not registered')
26
+ },
27
+ }),
28
+ }))
29
+
30
+ jest.mock('../tool-executor', () => ({
31
+ executeTool: async (name: string, args: unknown, context: unknown) => {
32
+ const { toolRegistry: registry } = await import('../tool-registry')
33
+ const registered = registry.getTool(name)
34
+ if (!registered) return { success: false, error: `Tool "${name}" not found` }
35
+ return { success: true, result: await registered.handler(args as never, context as never) }
36
+ },
37
+ }))
38
+
39
+ import { AgentPolicyError, resolveAiAgentTools } from '../agent-tools'
40
+ import { resolveAgentRunMutationPolicyOverride } from '../agent-channel-policy'
41
+ import { registerMcpTool, toolRegistry } from '../tool-registry'
19
42
  import { AiAgentDispatchDeniedError } from '../agent-run-dispatcher'
20
43
  import { AgentToolError } from '../agent-tool-error'
21
44
  import {
@@ -371,6 +394,61 @@ describe('defineAgentTool', () => {
371
394
  expect(dispatcher.runObject).not.toHaveBeenCalled()
372
395
  })
373
396
 
397
+ it('runs a nested agent read-only when the outer agent was called over mcp with mutations denied', async () => {
398
+ seedAgent({ mutationPolicy: 'confirm-required', readOnly: false })
399
+ mockAgents.set('catalog.outer', {
400
+ id: 'catalog.outer',
401
+ moduleId: 'catalog',
402
+ label: 'Outer',
403
+ description: 'Outer agent',
404
+ systemPrompt: 'Outer',
405
+ allowedTools: ['catalog.review_product'],
406
+ requiredFeatures: ['catalog.products.view'],
407
+ })
408
+ toolRegistry.clear()
409
+ registerMcpTool(buildTool({ requiredFeatures: ['catalog.products.view'] }), { moduleId: 'catalog' })
410
+ try {
411
+ const outer = await resolveAiAgentTools({
412
+ agentId: 'catalog.outer',
413
+ authContext: {
414
+ tenantId: 'tenant-1',
415
+ organizationId: 'org-1',
416
+ userId: 'user-1',
417
+ features: ['catalog.products.view'],
418
+ isSuperAdmin: false,
419
+ },
420
+ channel: 'mcp',
421
+ mutationMode: 'deny',
422
+ apiKeyId: 'key-1',
423
+ correlationId: 'corr-outer',
424
+ })
425
+ const nested = outer.tools.catalog__review_product as {
426
+ execute: (args: unknown, options?: unknown) => Promise<unknown>
427
+ }
428
+ await nested.execute({ input: 'Review product 42' }, { toolCallId: 'call-1', messages: [] })
429
+
430
+ expect(runAiAgentObjectMock).toHaveBeenCalledWith(
431
+ expect.objectContaining({ agentId: AGENT_ID, channel: 'mcp', mutationMode: 'deny', apiKeyId: 'key-1' }),
432
+ )
433
+ const innerRun = runAiAgentObjectMock.mock.calls[0][0] as {
434
+ channel: 'mcp'
435
+ mutationMode: 'deny'
436
+ container: unknown
437
+ }
438
+ expect(
439
+ resolveAgentRunMutationPolicyOverride({
440
+ channel: innerRun.channel,
441
+ mutationMode: innerRun.mutationMode,
442
+ declaredPolicy: 'confirm-required',
443
+ tenantOverride: null,
444
+ canQueueMutations: typeof innerRun.container !== 'undefined',
445
+ }),
446
+ ).toBe('read-only')
447
+ } finally {
448
+ toolRegistry.clear()
449
+ }
450
+ })
451
+
374
452
  it('maps tool channels to agent run channels', () => {
375
453
  expect(toAgentRunChannel('mcp')).toBe('mcp')
376
454
  expect(toAgentRunChannel('tools-api')).toBe('tools-api')
@@ -33,6 +33,8 @@ import {
33
33
  } from '../agent-registry'
34
34
  import { toolRegistry, registerMcpTool } from '../tool-registry'
35
35
  import { emitCitations } from '../citations'
36
+ import searchAiTools from '../../ai-tools/search-pack'
37
+ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
36
38
 
37
39
  jest.mock('@open-mercato/shared/lib/logger', () => {
38
40
  const mocked = {
@@ -177,6 +179,103 @@ describe('resolveAiAgentTools', () => {
177
179
  }
178
180
  })
179
181
 
182
+ it('threads channel, mutation mode, API key and correlation id into the handler context', async () => {
183
+ const seen: Array<Record<string, unknown>> = []
184
+ registerMcpTool(
185
+ makeTool({
186
+ name: 'customers.list_people',
187
+ handler: async (_input, ctx) => {
188
+ seen.push({
189
+ channel: ctx.channel,
190
+ mutationMode: ctx.mutationMode,
191
+ apiKeyId: ctx.apiKeyId,
192
+ correlationId: ctx.correlationId,
193
+ })
194
+ return { ok: true }
195
+ },
196
+ }),
197
+ { moduleId: 'customers' },
198
+ )
199
+ seedAgentRegistryForTests([
200
+ makeAgent({ id: 'customers.assistant', moduleId: 'customers', allowedTools: ['customers.list_people'] }),
201
+ ])
202
+
203
+ const result = await resolveAiAgentTools({
204
+ agentId: 'customers.assistant',
205
+ authContext: baseAuth,
206
+ channel: 'mcp',
207
+ mutationMode: 'deny',
208
+ apiKeyId: 'key-1',
209
+ correlationId: 'corr-1',
210
+ })
211
+ const tool = result.tools.customers__list_people as { execute: (args: unknown, options?: unknown) => Promise<unknown> }
212
+ await tool.execute({}, { toolCallId: 'call-1', messages: [] })
213
+
214
+ expect(seen).toEqual([{ channel: 'mcp', mutationMode: 'deny', apiKeyId: 'key-1', correlationId: 'corr-1' }])
215
+ })
216
+
217
+ it('stamps the agent channel on the handler context by default', async () => {
218
+ const seen: unknown[] = []
219
+ registerMcpTool(
220
+ makeTool({
221
+ name: 'customers.list_people',
222
+ handler: async (_input, ctx) => {
223
+ seen.push(ctx.channel)
224
+ return { ok: true }
225
+ },
226
+ }),
227
+ { moduleId: 'customers' },
228
+ )
229
+ seedAgentRegistryForTests([
230
+ makeAgent({ id: 'customers.assistant', moduleId: 'customers', allowedTools: ['customers.list_people'] }),
231
+ ])
232
+
233
+ const result = await resolveAiAgentTools({ agentId: 'customers.assistant', authContext: baseAuth })
234
+ const tool = result.tools.customers__list_people as { execute: (args: unknown, options?: unknown) => Promise<unknown> }
235
+ await tool.execute({}, { toolCallId: 'call-1', messages: [] })
236
+
237
+ expect(seen).toEqual(['agent'])
238
+ })
239
+
240
+ it.each([
241
+ { label: 'the API key when the run carries one', apiKeyId: 'key-1', expected: { sub: 'api_key:key-1', isApiKey: true, keyId: 'key-1' } },
242
+ { label: 'the user when the run has no API key', apiKeyId: undefined, expected: { sub: 'user-1', userId: 'user-1' } },
243
+ ])('runs search.hybrid_search as $label', async ({ apiKeyId, expected }) => {
244
+ const searchTool = searchAiTools.find((entry) => entry.name === 'search.hybrid_search')
245
+ if (!searchTool) throw new Error('search.hybrid_search missing')
246
+ registerMcpTool(searchTool, { moduleId: 'search' })
247
+ seedAgentRegistryForTests([
248
+ makeAgent({ id: 'customers.assistant', moduleId: 'customers', allowedTools: ['search.hybrid_search'] }),
249
+ ])
250
+ const viewers: unknown[] = []
251
+ const searchService = {
252
+ search: async (_query: string, options: { viewer?: { auth: unknown } }) => {
253
+ viewers.push(options.viewer?.auth)
254
+ return []
255
+ },
256
+ }
257
+ const searchIndexer = { getEntityConfig: () => undefined, getAllEntityConfigs: () => [] }
258
+ ;(createRequestContainer as jest.Mock).mockResolvedValueOnce({
259
+ resolve: (name: string) => {
260
+ if (name === 'searchService') return searchService
261
+ if (name === 'searchIndexer') return searchIndexer
262
+ return undefined
263
+ },
264
+ })
265
+
266
+ const result = await resolveAiAgentTools({
267
+ agentId: 'customers.assistant',
268
+ authContext: baseAuth,
269
+ ...(apiKeyId ? { channel: 'mcp' as const, mutationMode: 'approval' as const, apiKeyId } : {}),
270
+ })
271
+ const tool = result.tools.search__hybrid_search as { execute: (args: unknown, options?: unknown) => Promise<unknown> }
272
+ await tool.execute({ q: 'clause' }, { toolCallId: 'call-1', messages: [] })
273
+
274
+ expect(viewers).toHaveLength(1)
275
+ expect(viewers[0]).toMatchObject(expected)
276
+ if (apiKeyId) expect(viewers[0]).not.toHaveProperty('userId')
277
+ })
278
+
180
279
  it('skips tools the caller lacks features for and still returns the rest', async () => {
181
280
  registerMcpTool(
182
281
  makeTool({
@@ -111,6 +111,32 @@ describe('agent approval paths alongside the direct HTTP refusal', () => {
111
111
  expect(result).toEqual(expect.stringContaining('"written": true'))
112
112
  })
113
113
 
114
+ it.each(['mcp', 'tools-api'] as const)(
115
+ 'queues non-destructive writes of a destructive-confirm-required agent on %s in approval mode',
116
+ async (channel) => {
117
+ seedAgent({ mutationPolicy: 'destructive-confirm-required' })
118
+ const resolved = await resolveAiAgentTools({
119
+ agentId: 'test.assistant',
120
+ authContext,
121
+ container,
122
+ channel,
123
+ mutationMode: 'approval',
124
+ apiKeyId: 'key-1',
125
+ correlationId: 'corr-1',
126
+ })
127
+
128
+ const result = await resolved.tools.test__mutation.execute?.({ title: 'Changed' }, executionOptions)
129
+
130
+ expect(handler).not.toHaveBeenCalled()
131
+ expect(prepareMutationMock).toHaveBeenCalledWith(
132
+ expect.objectContaining({ toolCallArgs: { title: 'Changed' }, channel, apiKeyId: 'key-1', correlationId: 'corr-1' }),
133
+ expect.anything(),
134
+ )
135
+ expect(result).toEqual(expect.stringContaining('pending-confirmation'))
136
+ expect(resolved.pendingActionIds).toEqual(['action-1'])
137
+ },
138
+ )
139
+
114
140
  it.each([
115
141
  { mutationPolicyOverride: 'read-only' as const },
116
142
  { authContext: { ...authContext, features: [] } },
@@ -59,8 +59,10 @@ export interface AgentPolicyCheckInput {
59
59
  /**
60
60
  * Restrictiveness ranking of `AiAgentMutationPolicy` (most restrictive first).
61
61
  * `read-only` blocks all mutation tools. `destructive-confirm-required` forces
62
- * confirmation for every write (including non-destructive ones). `confirm-required`
63
- * is the least restrictive policy — writes go through a single confirmation.
62
+ * confirmation only for destructive writes; non-destructive writes run directly
63
+ * on the in-process agent channel (on `mcp` / `tools-api` in approval mode every
64
+ * write is still queued). `confirm-required` gates every write through a single
65
+ * confirmation.
64
66
  *
65
67
  * This ordering is load-bearing for both the runtime's effective-policy
66
68
  * computation AND the route-layer escalation guard. Changing the order is a
@@ -1774,6 +1774,7 @@ function appendAttachmentSummary(
1774
1774
  function buildRuntimeMutationPolicySection(
1775
1775
  agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },
1776
1776
  mutationPolicyOverride: string | null,
1777
+ channel: AiPendingActionChannel = 'agent',
1777
1778
  ): string | null {
1778
1779
  const effective = resolveEffectiveMutationPolicy(
1779
1780
  (agent.mutationPolicy ?? null) as never,
@@ -1807,7 +1808,7 @@ function buildRuntimeMutationPolicySection(
1807
1808
  blocked.push(toolName)
1808
1809
  continue
1809
1810
  }
1810
- if (effective === 'confirm-required') {
1811
+ if (effective === 'confirm-required' || channel !== 'agent') {
1811
1812
  gated.push(toolName)
1812
1813
  continue
1813
1814
  }
@@ -1845,7 +1846,9 @@ function buildRuntimeMutationPolicySection(
1845
1846
  `Tools that REQUIRE APPROVAL under the effective policy: ${gated.join(', ')}.`,
1846
1847
  )
1847
1848
  lines.push(
1848
- '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.',
1849
+ channel === 'agent'
1850
+ ? '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.'
1851
+ : '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.',
1849
1852
  )
1850
1853
  }
1851
1854
  if (conditional.length > 0) {
@@ -1877,8 +1880,9 @@ function appendRuntimeMutationPolicy(
1877
1880
  systemPrompt: string,
1878
1881
  agent: { id: string; mutationPolicy?: string | null; allowedTools: string[] },
1879
1882
  mutationPolicyOverride: string | null,
1883
+ channel?: AiPendingActionChannel,
1880
1884
  ): string {
1881
- const block = buildRuntimeMutationPolicySection(agent, mutationPolicyOverride)
1885
+ const block = buildRuntimeMutationPolicySection(agent, mutationPolicyOverride, channel)
1882
1886
  if (!block) return systemPrompt
1883
1887
  return `${systemPrompt}\n\n${block}`
1884
1888
  }
@@ -2646,6 +2650,7 @@ export async function runAiAgentObject<TSchema = unknown>(
2646
2650
  appendRuntimeTaskPlanPrompt(appendAttachmentSummary(composedPrompt.prompt, resolvedAttachments), agent),
2647
2651
  agent,
2648
2652
  runMutationPolicyOverride,
2653
+ input.channel,
2649
2654
  )
2650
2655
 
2651
2656
  const resolvedObjectModel = resolveAgentModel(