@open-mercato/ai-assistant 0.10.1-develop.8287.1.7313a0fe67 → 0.10.1-develop.8291.1.6ec3aee41c
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-tools.js +3 -1
- package/dist/modules/ai_assistant/lib/agent-tools.js.map +2 -2
- package/dist/modules/ai_assistant/lib/llm-adapters/tool-replay-context.js +16 -8
- package/dist/modules/ai_assistant/lib/llm-adapters/tool-replay-context.js.map +2 -2
- package/package.json +6 -6
- package/src/modules/ai_assistant/lib/__tests__/tool-replay-context.test.ts +73 -2
- package/src/modules/ai_assistant/lib/agent-tools.ts +2 -0
- package/src/modules/ai_assistant/lib/llm-adapters/tool-replay-context.ts +19 -10
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
withToolReplayContext
|
|
20
20
|
} from "./llm-adapters/tool-replay-context.js";
|
|
21
21
|
import { resolveStagedToolInput } from "./tool-input.js";
|
|
22
|
+
import { hasRequiredFeatures } from "./auth.js";
|
|
22
23
|
const logger = createLogger("ai_assistant");
|
|
23
24
|
class AgentPolicyError extends Error {
|
|
24
25
|
constructor(code, message) {
|
|
@@ -117,7 +118,8 @@ function adaptToolToAiSdk(tool, ctx, mutation, container, effectiveMutationPolic
|
|
|
117
118
|
toolName: tool.name,
|
|
118
119
|
args,
|
|
119
120
|
isMutation: tool.isMutation === true,
|
|
120
|
-
toolCallId
|
|
121
|
+
toolCallId,
|
|
122
|
+
authorized: hasRequiredFeatures(tool.requiredFeatures, ctx.features, ctx.isSuperAdmin)
|
|
121
123
|
});
|
|
122
124
|
if (replayDecision.kind === "replay") {
|
|
123
125
|
const recordedError = replayDecision.fixture.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'\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 })\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, 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;
|
|
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, 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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Q,CAAC;AACpG;AAAA,IACF;AAEA,UAAM,SAAU,aAAa,QAAQ,aAAa,QAAQ,QAAQ;AAGlE,QAAI,CAAC,QAAQ;AACX,aAAO,KAAK,+DAA+D,EAAE,SAAS,CAAC;AACvF;AAAA,IACF;AAEA,QAAI;AAQF,YAAM,kBACJ,OAAO,eAAe,QAAQ,yBAAyB,MAAM,YACzD;AAAA,QACE;AAAA,QACA,MAAM;AAAA,QACN,WAAW,MAAM;AAAA,QACjB,KAAK,MAAM;AAAA,QACX;AAAA,QACA,gBAAgB,MAAM,kBAAkB;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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -87,6 +87,22 @@ function resolveToolReplayDecision(input) {
|
|
|
87
87
|
if (!scope) return { kind: "live" };
|
|
88
88
|
const call = claimCall(scope, input.toolName, input.args, input.toolCallId);
|
|
89
89
|
const { context } = scope;
|
|
90
|
+
if (context.mode === "replay" && input.isMutation) {
|
|
91
|
+
reportMiss(context, call, "mutation_refused", "error");
|
|
92
|
+
throw new ToolReplayError(
|
|
93
|
+
"tool_replay_mutation_refused",
|
|
94
|
+
input.toolName,
|
|
95
|
+
`[internal] tool_replay_mutation_refused: mutation tool "${input.toolName}" cannot run under tool replay`
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
if (input.authorized === false) {
|
|
99
|
+
if (context.mode === "replay") reportMiss(context, call, "forbidden", "error");
|
|
100
|
+
throw new ToolReplayError(
|
|
101
|
+
"tool_replay_forbidden",
|
|
102
|
+
input.toolName,
|
|
103
|
+
`[internal] tool_replay_forbidden: insufficient permissions for tool "${input.toolName}"`
|
|
104
|
+
);
|
|
105
|
+
}
|
|
90
106
|
if (context.mode === "record") {
|
|
91
107
|
if (!input.isMutation) {
|
|
92
108
|
const mocked2 = lookupFixture(context, call);
|
|
@@ -97,14 +113,6 @@ function resolveToolReplayDecision(input) {
|
|
|
97
113
|
}
|
|
98
114
|
return { kind: "record", call, sink: context.sink };
|
|
99
115
|
}
|
|
100
|
-
if (input.isMutation) {
|
|
101
|
-
reportMiss(context, call, "mutation_refused", "error");
|
|
102
|
-
throw new ToolReplayError(
|
|
103
|
-
"tool_replay_mutation_refused",
|
|
104
|
-
input.toolName,
|
|
105
|
-
`[internal] tool_replay_mutation_refused: mutation tool "${input.toolName}" cannot run under tool replay`
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
116
|
const mocked = lookupFixture(context, call);
|
|
109
117
|
if (mocked) {
|
|
110
118
|
reportHit(context, call, "lookup");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/ai_assistant/lib/llm-adapters/tool-replay-context.ts"],
|
|
4
|
-
"sourcesContent": ["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { createHash } from 'node:crypto'\nimport { canonicalJsonStringify } from '../agent-definition-hash'\n\n/**\n * One recorded tool call. `argsKey` is the SHA-256 of the canonical JSON of\n * `args`; `occurrence` is the 0-based index of this call among earlier calls\n * with the same `(toolName, argsKey)` inside one bound context. `output` is\n * the handler result after emitted UI parts were merged, so replay reproduces\n * cards and citations exactly.\n */\nexport type ToolReplayFixture = {\n toolName: string\n argsKey: string\n args: unknown\n output: unknown\n error?: { message: string } | null\n occurrence: number\n toolCallId?: string | null\n}\n\nexport type ToolReplayMissReason = 'fixture_missing' | 'mutation_refused'\n\nexport type ToolReplayMiss = {\n toolName: string\n argsKey: string\n args: unknown\n occurrence: number\n toolCallId: string | null\n reason: ToolReplayMissReason\n resolution: 'error' | 'live'\n}\n\nexport type ToolReplayHitSource = 'lookup' | 'fixture'\n\n/**\n * Optional hooks shared by both context variants. `lookup` answers a call\n * before recorded fixtures (replay) or before the live run (record); it is\n * never consulted for an `isMutation` call. `observeHit` sees every call a\n * `lookup` or a recorded fixture answered. Both are best-effort: a throwing\n * `lookup` counts as no hit and a throwing `observeHit` is ignored.\n */\nexport type ToolReplayLookupHooks = {\n lookup?: (call: ToolReplayCall) => ToolReplayFixture | null\n observeHit?: (call: ToolReplayCall, source: ToolReplayHitSource) => void\n}\n\nexport type ToolReplayContext =\n | ({\n mode: 'replay'\n fixtures: ToolReplayFixture[]\n match: 'strict' | 'ordered'\n onMiss: 'error' | 'live'\n observeMiss?: (miss: ToolReplayMiss) => void\n } & ToolReplayLookupHooks)\n | ({\n mode: 'record'\n sink: (fixture: ToolReplayFixture) => void\n } & ToolReplayLookupHooks)\n\nexport type ToolReplayErrorCode = 'tool_fixture_missing' | 'tool_replay_mutation_refused'\n\nexport class ToolReplayError extends Error {\n readonly code: ToolReplayErrorCode\n readonly toolName: string\n\n constructor(code: ToolReplayErrorCode, toolName: string, message: string) {\n super(message)\n this.name = 'ToolReplayError'\n this.code = code\n this.toolName = toolName\n }\n}\n\ntype ToolReplayScope = {\n context: ToolReplayContext\n occurrencesByArgs: Map<string, number>\n occurrencesByTool: Map<string, number>\n}\n\nconst TOOL_REPLAY_STORAGE_KEY = Symbol.for('@open-mercato/ai-assistant/tool-replay-context')\n\ntype GlobalWithToolReplayStorage = typeof globalThis & {\n [TOOL_REPLAY_STORAGE_KEY]?: AsyncLocalStorage<ToolReplayScope>\n}\n\nfunction resolveToolReplayStorage(): AsyncLocalStorage<ToolReplayScope> {\n const scope = globalThis as GlobalWithToolReplayStorage\n if (!scope[TOOL_REPLAY_STORAGE_KEY]) {\n scope[TOOL_REPLAY_STORAGE_KEY] = new AsyncLocalStorage<ToolReplayScope>()\n }\n return scope[TOOL_REPLAY_STORAGE_KEY]\n}\n\nconst toolReplayStorage = resolveToolReplayStorage()\n\n/**\n * Binds a tool record/replay context for every agent tool call executed inside\n * `fn`. Each binding gets its own occurrence counters, so concurrent or nested\n * runs never share state. Outside a binding tool execution is unchanged.\n */\nexport function withToolReplayContext<T>(context: ToolReplayContext, fn: () => Promise<T>): Promise<T> {\n const scope: ToolReplayScope = {\n context,\n occurrencesByArgs: new Map(),\n occurrencesByTool: new Map(),\n }\n return toolReplayStorage.run(scope, fn)\n}\n\nexport function getToolReplayContext(): ToolReplayContext | null {\n return toolReplayStorage.getStore()?.context ?? null\n}\n\nexport function computeToolArgsKey(args: unknown): string {\n return createHash('sha256').update(canonicalJsonStringify(args)).digest('hex')\n}\n\nexport type ToolReplayCall = {\n toolName: string\n args: unknown\n argsKey: string\n occurrence: number\n ordinal: number\n toolCallId: string | null\n}\n\nexport type ToolReplayDecision =\n | { kind: 'live' }\n | { kind: 'replay'; fixture: ToolReplayFixture }\n | { kind: 'record'; call: ToolReplayCall; sink: (fixture: ToolReplayFixture) => void }\n | { kind: 'miss_live'; call: ToolReplayCall }\n\nfunction claimCall(scope: ToolReplayScope, toolName: string, args: unknown, toolCallId: string | null): ToolReplayCall {\n const argsKey = computeToolArgsKey(args)\n const argsCounterKey = `${toolName}\\u0000${argsKey}`\n const occurrence = scope.occurrencesByArgs.get(argsCounterKey) ?? 0\n scope.occurrencesByArgs.set(argsCounterKey, occurrence + 1)\n const ordinal = scope.occurrencesByTool.get(toolName) ?? 0\n scope.occurrencesByTool.set(toolName, ordinal + 1)\n return { toolName, args, argsKey, occurrence, ordinal, toolCallId }\n}\n\nfunction findFixture(\n context: Extract<ToolReplayContext, { mode: 'replay' }>,\n call: ToolReplayCall,\n): ToolReplayFixture | null {\n if (context.match === 'ordered') {\n const sameTool = context.fixtures.filter((fixture) => fixture.toolName === call.toolName)\n return sameTool[call.ordinal] ?? null\n }\n return (\n context.fixtures.find(\n (fixture) =>\n fixture.toolName === call.toolName &&\n fixture.argsKey === call.argsKey &&\n fixture.occurrence === call.occurrence,\n ) ?? null\n )\n}\n\nfunction lookupFixture(context: ToolReplayContext, call: ToolReplayCall): ToolReplayFixture | null {\n if (!context.lookup) return null\n try {\n return context.lookup(call) ?? null\n } catch {\n return null\n }\n}\n\nfunction reportHit(context: ToolReplayContext, call: ToolReplayCall, source: ToolReplayHitSource): void {\n if (!context.observeHit) return\n try {\n context.observeHit(call, source)\n } catch {\n return\n }\n}\n\nfunction reportMiss(\n context: Extract<ToolReplayContext, { mode: 'replay' }>,\n call: ToolReplayCall,\n reason: ToolReplayMissReason,\n resolution: 'error' | 'live',\n): void {\n if (!context.observeMiss) return\n try {\n context.observeMiss({\n toolName: call.toolName,\n argsKey: call.argsKey,\n args: call.args,\n occurrence: call.occurrence,\n toolCallId: call.toolCallId,\n reason,\n resolution,\n })\n } catch {\n return\n }\n}\n\n/**\n * Decides how the agent tool wrapper handles one call under the ambient\n * context. Replay refuses `isMutation` tools outright (a replayed run must\n * never write or queue an approval) and throws `tool_fixture_missing` on a\n * miss unless `onMiss: 'live'`, in which case the real tool runs and the miss\n * is reported through `observeMiss`.\n */\nexport function resolveToolReplayDecision(input: {\n toolName: string\n args: unknown\n isMutation: boolean\n toolCallId: string | null\n}): ToolReplayDecision {\n const scope = toolReplayStorage.getStore()\n if (!scope) return { kind: 'live' }\n const call = claimCall(scope, input.toolName, input.args, input.toolCallId)\n const { context } = scope\n if (context.mode === '
|
|
5
|
-
"mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AA4DhC,MAAM,wBAAwB,MAAM;AAAA,EAIzC,YAAY,MAA2B,UAAkB,SAAiB;AACxE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,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,YACC,QAAQ,aAAa,KAAK,YAC1B,QAAQ,YAAY,KAAK,WACzB,QAAQ,eAAe,KAAK;AAAA,EAChC,KAAK;AAET;AAEA,SAAS,cAAc,SAA4B,MAAgD;AACjG,MAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,MAAI;AACF,WAAO,QAAQ,OAAO,IAAI,KAAK;AAAA,EACjC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,SAA4B,MAAsB,QAAmC;AACtG,MAAI,CAAC,QAAQ,WAAY;AACzB,MAAI;AACF,YAAQ,WAAW,MAAM,MAAM;AAAA,EACjC,QAAQ;AACN;AAAA,EACF;AACF;AAEA,SAAS,WACP,SACA,MACA,QACA,YACM;AACN,MAAI,CAAC,QAAQ,YAAa;AAC1B,MAAI;AACF,YAAQ,YAAY;AAAA,MAClB,UAAU,KAAK;AAAA,MACf,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,YAAY,KAAK;AAAA,MACjB,YAAY,KAAK;AAAA,MACjB;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,QAAQ;AACN;AAAA,EACF;AACF;AASO,SAAS,0BAA0B,
|
|
4
|
+
"sourcesContent": ["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { createHash } from 'node:crypto'\nimport { canonicalJsonStringify } from '../agent-definition-hash'\n\n/**\n * One recorded tool call. `argsKey` is the SHA-256 of the canonical JSON of\n * `args`; `occurrence` is the 0-based index of this call among earlier calls\n * with the same `(toolName, argsKey)` inside one bound context. `output` is\n * the handler result after emitted UI parts were merged, so replay reproduces\n * cards and citations exactly.\n */\nexport type ToolReplayFixture = {\n toolName: string\n argsKey: string\n args: unknown\n output: unknown\n error?: { message: string } | null\n occurrence: number\n toolCallId?: string | null\n}\n\nexport type ToolReplayMissReason = 'fixture_missing' | 'mutation_refused' | 'forbidden'\n\nexport type ToolReplayMiss = {\n toolName: string\n argsKey: string\n args: unknown\n occurrence: number\n toolCallId: string | null\n reason: ToolReplayMissReason\n resolution: 'error' | 'live'\n}\n\nexport type ToolReplayHitSource = 'lookup' | 'fixture'\n\n/**\n * Optional hooks shared by both context variants. `lookup` answers a call\n * before recorded fixtures (replay) or before the live run (record); it is\n * never consulted for an `isMutation` call. `observeHit` sees every call a\n * `lookup` or a recorded fixture answered. Both are best-effort: a throwing\n * `lookup` counts as no hit and a throwing `observeHit` is ignored.\n */\nexport type ToolReplayLookupHooks = {\n lookup?: (call: ToolReplayCall) => ToolReplayFixture | null\n observeHit?: (call: ToolReplayCall, source: ToolReplayHitSource) => void\n}\n\nexport type ToolReplayContext =\n | ({\n mode: 'replay'\n fixtures: ToolReplayFixture[]\n match: 'strict' | 'ordered'\n onMiss: 'error' | 'live'\n observeMiss?: (miss: ToolReplayMiss) => void\n } & ToolReplayLookupHooks)\n | ({\n mode: 'record'\n sink: (fixture: ToolReplayFixture) => void\n } & ToolReplayLookupHooks)\n\nexport type ToolReplayErrorCode = 'tool_fixture_missing' | 'tool_replay_mutation_refused' | 'tool_replay_forbidden'\n\nexport class ToolReplayError extends Error {\n readonly code: ToolReplayErrorCode\n readonly toolName: string\n\n constructor(code: ToolReplayErrorCode, toolName: string, message: string) {\n super(message)\n this.name = 'ToolReplayError'\n this.code = code\n this.toolName = toolName\n }\n}\n\ntype ToolReplayScope = {\n context: ToolReplayContext\n occurrencesByArgs: Map<string, number>\n occurrencesByTool: Map<string, number>\n}\n\nconst TOOL_REPLAY_STORAGE_KEY = Symbol.for('@open-mercato/ai-assistant/tool-replay-context')\n\ntype GlobalWithToolReplayStorage = typeof globalThis & {\n [TOOL_REPLAY_STORAGE_KEY]?: AsyncLocalStorage<ToolReplayScope>\n}\n\nfunction resolveToolReplayStorage(): AsyncLocalStorage<ToolReplayScope> {\n const scope = globalThis as GlobalWithToolReplayStorage\n if (!scope[TOOL_REPLAY_STORAGE_KEY]) {\n scope[TOOL_REPLAY_STORAGE_KEY] = new AsyncLocalStorage<ToolReplayScope>()\n }\n return scope[TOOL_REPLAY_STORAGE_KEY]\n}\n\nconst toolReplayStorage = resolveToolReplayStorage()\n\n/**\n * Binds a tool record/replay context for every agent tool call executed inside\n * `fn`. Each binding gets its own occurrence counters, so concurrent or nested\n * runs never share state. Outside a binding tool execution is unchanged.\n */\nexport function withToolReplayContext<T>(context: ToolReplayContext, fn: () => Promise<T>): Promise<T> {\n const scope: ToolReplayScope = {\n context,\n occurrencesByArgs: new Map(),\n occurrencesByTool: new Map(),\n }\n return toolReplayStorage.run(scope, fn)\n}\n\nexport function getToolReplayContext(): ToolReplayContext | null {\n return toolReplayStorage.getStore()?.context ?? null\n}\n\nexport function computeToolArgsKey(args: unknown): string {\n return createHash('sha256').update(canonicalJsonStringify(args)).digest('hex')\n}\n\nexport type ToolReplayCall = {\n toolName: string\n args: unknown\n argsKey: string\n occurrence: number\n ordinal: number\n toolCallId: string | null\n}\n\nexport type ToolReplayDecision =\n | { kind: 'live' }\n | { kind: 'replay'; fixture: ToolReplayFixture }\n | { kind: 'record'; call: ToolReplayCall; sink: (fixture: ToolReplayFixture) => void }\n | { kind: 'miss_live'; call: ToolReplayCall }\n\nfunction claimCall(scope: ToolReplayScope, toolName: string, args: unknown, toolCallId: string | null): ToolReplayCall {\n const argsKey = computeToolArgsKey(args)\n const argsCounterKey = `${toolName}\\u0000${argsKey}`\n const occurrence = scope.occurrencesByArgs.get(argsCounterKey) ?? 0\n scope.occurrencesByArgs.set(argsCounterKey, occurrence + 1)\n const ordinal = scope.occurrencesByTool.get(toolName) ?? 0\n scope.occurrencesByTool.set(toolName, ordinal + 1)\n return { toolName, args, argsKey, occurrence, ordinal, toolCallId }\n}\n\nfunction findFixture(\n context: Extract<ToolReplayContext, { mode: 'replay' }>,\n call: ToolReplayCall,\n): ToolReplayFixture | null {\n if (context.match === 'ordered') {\n const sameTool = context.fixtures.filter((fixture) => fixture.toolName === call.toolName)\n return sameTool[call.ordinal] ?? null\n }\n return (\n context.fixtures.find(\n (fixture) =>\n fixture.toolName === call.toolName &&\n fixture.argsKey === call.argsKey &&\n fixture.occurrence === call.occurrence,\n ) ?? null\n )\n}\n\nfunction lookupFixture(context: ToolReplayContext, call: ToolReplayCall): ToolReplayFixture | null {\n if (!context.lookup) return null\n try {\n return context.lookup(call) ?? null\n } catch {\n return null\n }\n}\n\nfunction reportHit(context: ToolReplayContext, call: ToolReplayCall, source: ToolReplayHitSource): void {\n if (!context.observeHit) return\n try {\n context.observeHit(call, source)\n } catch {\n return\n }\n}\n\nfunction reportMiss(\n context: Extract<ToolReplayContext, { mode: 'replay' }>,\n call: ToolReplayCall,\n reason: ToolReplayMissReason,\n resolution: 'error' | 'live',\n): void {\n if (!context.observeMiss) return\n try {\n context.observeMiss({\n toolName: call.toolName,\n argsKey: call.argsKey,\n args: call.args,\n occurrence: call.occurrence,\n toolCallId: call.toolCallId,\n reason,\n resolution,\n })\n } catch {\n return\n }\n}\n\n/**\n * Decides how the agent tool wrapper handles one call under the ambient\n * context. Replay refuses `isMutation` tools outright (a replayed run must\n * never write or queue an approval) and throws `tool_fixture_missing` on a\n * miss unless `onMiss: 'live'`, in which case the real tool runs and the miss\n * is reported through `observeMiss`.\n */\nexport function resolveToolReplayDecision(input: {\n toolName: string\n args: unknown\n isMutation: boolean\n toolCallId: string | null\n authorized?: boolean\n}): ToolReplayDecision {\n const scope = toolReplayStorage.getStore()\n if (!scope) return { kind: 'live' }\n const call = claimCall(scope, input.toolName, input.args, input.toolCallId)\n const { context } = scope\n if (context.mode === 'replay' && input.isMutation) {\n reportMiss(context, call, 'mutation_refused', 'error')\n throw new ToolReplayError(\n 'tool_replay_mutation_refused',\n input.toolName,\n `[internal] tool_replay_mutation_refused: mutation tool \"${input.toolName}\" cannot run under tool replay`,\n )\n }\n if (input.authorized === false) {\n if (context.mode === 'replay') reportMiss(context, call, 'forbidden', 'error')\n throw new ToolReplayError(\n 'tool_replay_forbidden',\n input.toolName,\n `[internal] tool_replay_forbidden: insufficient permissions for tool \"${input.toolName}\"`,\n )\n }\n if (context.mode === 'record') {\n if (!input.isMutation) {\n const mocked = lookupFixture(context, call)\n if (mocked) {\n reportHit(context, call, 'lookup')\n return { kind: 'replay', fixture: mocked }\n }\n }\n return { kind: 'record', call, sink: context.sink }\n }\n const mocked = lookupFixture(context, call)\n if (mocked) {\n reportHit(context, call, 'lookup')\n return { kind: 'replay', fixture: mocked }\n }\n const fixture = findFixture(context, call)\n if (fixture) {\n reportHit(context, call, 'fixture')\n return { kind: 'replay', fixture }\n }\n if (context.onMiss === 'live') {\n reportMiss(context, call, 'fixture_missing', 'live')\n return { kind: 'miss_live', call }\n }\n reportMiss(context, call, 'fixture_missing', 'error')\n throw new ToolReplayError(\n 'tool_fixture_missing',\n input.toolName,\n `[internal] tool_fixture_missing: no recorded result for tool \"${input.toolName}\" (occurrence ${call.occurrence})`,\n )\n}\n\nexport function buildRecordedToolFixture(\n call: ToolReplayCall,\n outcome: { output: unknown } | { error: string },\n): ToolReplayFixture {\n return {\n toolName: call.toolName,\n argsKey: call.argsKey,\n args: call.args,\n output: 'output' in outcome ? outcome.output : null,\n error: 'error' in outcome ? { message: outcome.error } : null,\n occurrence: call.occurrence,\n toolCallId: call.toolCallId,\n }\n}\n\nexport function emitRecordedToolFixture(\n sink: (fixture: ToolReplayFixture) => void,\n fixture: ToolReplayFixture,\n): void {\n try {\n sink(fixture)\n } catch {\n return\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AA4DhC,MAAM,wBAAwB,MAAM;AAAA,EAIzC,YAAY,MAA2B,UAAkB,SAAiB;AACxE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAQA,MAAM,0BAA0B,uBAAO,IAAI,gDAAgD;AAM3F,SAAS,2BAA+D;AACtE,QAAM,QAAQ;AACd,MAAI,CAAC,MAAM,uBAAuB,GAAG;AACnC,UAAM,uBAAuB,IAAI,IAAI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
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
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.10.1-develop.
|
|
107
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
106
|
+
"@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
107
|
+
"@open-mercato/ui": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
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.10.1-develop.
|
|
114
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
115
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
113
|
+
"@open-mercato/cli": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
114
|
+
"@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
115
|
+
"@open-mercato/ui": "0.10.1-develop.8291.1.6ec3aee41c",
|
|
116
116
|
"@types/react": "^19.2.18",
|
|
117
117
|
"@types/react-dom": "^19.2.5",
|
|
118
118
|
"react": "19.2.8",
|
|
@@ -50,6 +50,7 @@ jest.mock('@open-mercato/shared/lib/logger', () => {
|
|
|
50
50
|
import type { AwilixContainer } from 'awilix'
|
|
51
51
|
import { z } from 'zod'
|
|
52
52
|
import type { AiAgentDefinition } from '../ai-agent-definition'
|
|
53
|
+
import type { AiChatRequestContext } from '../attachment-bridge-types'
|
|
53
54
|
import type { AiToolDefinition } from '../types'
|
|
54
55
|
import { resolveAiAgentTools } from '../agent-tools'
|
|
55
56
|
import { resetAgentRegistryForTests, seedAgentRegistryForTests } from '../agent-registry'
|
|
@@ -104,7 +105,7 @@ function makeTool(overrides: Partial<AiToolDefinition> & Pick<AiToolDefinition,
|
|
|
104
105
|
|
|
105
106
|
async function resolveWithTools(
|
|
106
107
|
tools: AiToolDefinition[],
|
|
107
|
-
options: { mutationPolicy?: AiAgentDefinition['mutationPolicy']; withContainer?: boolean } = {},
|
|
108
|
+
options: { mutationPolicy?: AiAgentDefinition['mutationPolicy']; withContainer?: boolean; authContext?: AiChatRequestContext } = {},
|
|
108
109
|
) {
|
|
109
110
|
for (const definition of tools) {
|
|
110
111
|
registerMcpTool(definition, { moduleId: 'customers' })
|
|
@@ -119,7 +120,7 @@ async function resolveWithTools(
|
|
|
119
120
|
])
|
|
120
121
|
return resolveAiAgentTools({
|
|
121
122
|
agentId: 'customers.assistant',
|
|
122
|
-
authContext: baseAuth,
|
|
123
|
+
authContext: options.authContext ?? baseAuth,
|
|
123
124
|
...(options.withContainer ? { container } : {}),
|
|
124
125
|
})
|
|
125
126
|
}
|
|
@@ -265,6 +266,76 @@ describe('tool replay seam', () => {
|
|
|
265
266
|
})
|
|
266
267
|
})
|
|
267
268
|
|
|
269
|
+
describe('replay authorization', () => {
|
|
270
|
+
const toolName = 'customers.list_people'
|
|
271
|
+
const requiredFeatures = ['customers.people.view', 'customers.companies.view']
|
|
272
|
+
|
|
273
|
+
it.each([
|
|
274
|
+
{ match: 'strict' as const, onMiss: 'error' as const },
|
|
275
|
+
{ match: 'ordered' as const, onMiss: 'live' as const },
|
|
276
|
+
])('refuses recorded output after a required grant is revoked ($match, $onMiss)', async ({ match, onMiss }) => {
|
|
277
|
+
const handler = jest.fn()
|
|
278
|
+
const authContext = { ...baseAuth, features: [...requiredFeatures], isSuperAdmin: false }
|
|
279
|
+
const result = await resolveWithTools([makeTool({ name: toolName, requiredFeatures, handler })], { authContext })
|
|
280
|
+
authContext.features = ['customers.people.view']
|
|
281
|
+
const misses: ToolReplayMiss[] = []
|
|
282
|
+
const observeHit = jest.fn()
|
|
283
|
+
await withToolReplayContext({
|
|
284
|
+
mode: 'replay',
|
|
285
|
+
fixtures: [fixture({ toolName, args: {}, output: { secret: 'recorded data' } })],
|
|
286
|
+
match,
|
|
287
|
+
onMiss,
|
|
288
|
+
observeMiss: (miss) => misses.push(miss),
|
|
289
|
+
observeHit,
|
|
290
|
+
}, async () => {
|
|
291
|
+
await expect(executable(result.tools, 'customers__list_people').execute({}, { toolCallId: 'denied' }))
|
|
292
|
+
.rejects.toMatchObject({ code: 'tool_replay_forbidden', toolName })
|
|
293
|
+
})
|
|
294
|
+
expect(misses).toEqual([expect.objectContaining({
|
|
295
|
+
toolName, reason: 'forbidden', resolution: 'error', occurrence: 0, toolCallId: 'denied',
|
|
296
|
+
})])
|
|
297
|
+
expect(observeHit).not.toHaveBeenCalled()
|
|
298
|
+
expect(handler).not.toHaveBeenCalled()
|
|
299
|
+
})
|
|
300
|
+
|
|
301
|
+
it.each(['replay', 'record'] as const)('checks authorization before lookup in %s mode', async (mode) => {
|
|
302
|
+
const handler = jest.fn()
|
|
303
|
+
const authContext = { ...baseAuth, features: [...requiredFeatures], isSuperAdmin: false }
|
|
304
|
+
const result = await resolveWithTools([makeTool({ name: toolName, requiredFeatures, handler })], { authContext })
|
|
305
|
+
authContext.features = []
|
|
306
|
+
const lookup = jest.fn(() => fixture({ toolName, args: {}, output: 'private mock' }))
|
|
307
|
+
const observeHit = jest.fn()
|
|
308
|
+
const sink = jest.fn()
|
|
309
|
+
const context = mode === 'record'
|
|
310
|
+
? { mode, lookup, observeHit, sink }
|
|
311
|
+
: { mode, lookup, observeHit, fixtures: [], match: 'strict' as const, onMiss: 'live' as const }
|
|
312
|
+
await expect(withToolReplayContext(context, () => executable(result.tools, 'customers__list_people').execute({})))
|
|
313
|
+
.rejects.toMatchObject({ code: 'tool_replay_forbidden', toolName })
|
|
314
|
+
expect(lookup).not.toHaveBeenCalled()
|
|
315
|
+
expect(observeHit).not.toHaveBeenCalled()
|
|
316
|
+
expect(sink).not.toHaveBeenCalled()
|
|
317
|
+
expect(handler).not.toHaveBeenCalled()
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
it.each([
|
|
321
|
+
{ features: requiredFeatures, isSuperAdmin: false },
|
|
322
|
+
{ features: ['customers.*'], isSuperAdmin: false },
|
|
323
|
+
{ features: ['*'], isSuperAdmin: false },
|
|
324
|
+
{ features: [], isSuperAdmin: true },
|
|
325
|
+
])('replays for authorized callers: %j', async (grants) => {
|
|
326
|
+
const handler = jest.fn()
|
|
327
|
+
const result = await resolveWithTools([makeTool({ name: toolName, requiredFeatures, handler })], {
|
|
328
|
+
authContext: { ...baseAuth, ...grants },
|
|
329
|
+
})
|
|
330
|
+
const output = await withToolReplayContext({
|
|
331
|
+
mode: 'replay', fixtures: [fixture({ toolName, args: {}, output: 'authorized data' })],
|
|
332
|
+
match: 'strict', onMiss: 'error',
|
|
333
|
+
}, () => executable(result.tools, 'customers__list_people').execute({}))
|
|
334
|
+
expect(output).toBe('authorized data')
|
|
335
|
+
expect(handler).not.toHaveBeenCalled()
|
|
336
|
+
})
|
|
337
|
+
})
|
|
338
|
+
|
|
268
339
|
describe('replay mode', () => {
|
|
269
340
|
it('returns the recorded output without calling the handler (strict)', async () => {
|
|
270
341
|
const handler = jest.fn(async () => ({ live: true }))
|
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
withToolReplayContext,
|
|
33
33
|
} from './llm-adapters/tool-replay-context'
|
|
34
34
|
import { resolveStagedToolInput } from './tool-input'
|
|
35
|
+
import { hasRequiredFeatures } from './auth'
|
|
35
36
|
|
|
36
37
|
const logger = createLogger('ai_assistant')
|
|
37
38
|
|
|
@@ -300,6 +301,7 @@ function adaptToolToAiSdk(
|
|
|
300
301
|
args,
|
|
301
302
|
isMutation: tool.isMutation === true,
|
|
302
303
|
toolCallId,
|
|
304
|
+
authorized: hasRequiredFeatures(tool.requiredFeatures, ctx.features, ctx.isSuperAdmin),
|
|
303
305
|
})
|
|
304
306
|
if (replayDecision.kind === 'replay') {
|
|
305
307
|
const recordedError = replayDecision.fixture.error
|
|
@@ -19,7 +19,7 @@ export type ToolReplayFixture = {
|
|
|
19
19
|
toolCallId?: string | null
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export type ToolReplayMissReason = 'fixture_missing' | 'mutation_refused'
|
|
22
|
+
export type ToolReplayMissReason = 'fixture_missing' | 'mutation_refused' | 'forbidden'
|
|
23
23
|
|
|
24
24
|
export type ToolReplayMiss = {
|
|
25
25
|
toolName: string
|
|
@@ -58,7 +58,7 @@ export type ToolReplayContext =
|
|
|
58
58
|
sink: (fixture: ToolReplayFixture) => void
|
|
59
59
|
} & ToolReplayLookupHooks)
|
|
60
60
|
|
|
61
|
-
export type ToolReplayErrorCode = 'tool_fixture_missing' | 'tool_replay_mutation_refused'
|
|
61
|
+
export type ToolReplayErrorCode = 'tool_fixture_missing' | 'tool_replay_mutation_refused' | 'tool_replay_forbidden'
|
|
62
62
|
|
|
63
63
|
export class ToolReplayError extends Error {
|
|
64
64
|
readonly code: ToolReplayErrorCode
|
|
@@ -211,11 +211,28 @@ export function resolveToolReplayDecision(input: {
|
|
|
211
211
|
args: unknown
|
|
212
212
|
isMutation: boolean
|
|
213
213
|
toolCallId: string | null
|
|
214
|
+
authorized?: boolean
|
|
214
215
|
}): ToolReplayDecision {
|
|
215
216
|
const scope = toolReplayStorage.getStore()
|
|
216
217
|
if (!scope) return { kind: 'live' }
|
|
217
218
|
const call = claimCall(scope, input.toolName, input.args, input.toolCallId)
|
|
218
219
|
const { context } = scope
|
|
220
|
+
if (context.mode === 'replay' && input.isMutation) {
|
|
221
|
+
reportMiss(context, call, 'mutation_refused', 'error')
|
|
222
|
+
throw new ToolReplayError(
|
|
223
|
+
'tool_replay_mutation_refused',
|
|
224
|
+
input.toolName,
|
|
225
|
+
`[internal] tool_replay_mutation_refused: mutation tool "${input.toolName}" cannot run under tool replay`,
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
if (input.authorized === false) {
|
|
229
|
+
if (context.mode === 'replay') reportMiss(context, call, 'forbidden', 'error')
|
|
230
|
+
throw new ToolReplayError(
|
|
231
|
+
'tool_replay_forbidden',
|
|
232
|
+
input.toolName,
|
|
233
|
+
`[internal] tool_replay_forbidden: insufficient permissions for tool "${input.toolName}"`,
|
|
234
|
+
)
|
|
235
|
+
}
|
|
219
236
|
if (context.mode === 'record') {
|
|
220
237
|
if (!input.isMutation) {
|
|
221
238
|
const mocked = lookupFixture(context, call)
|
|
@@ -226,14 +243,6 @@ export function resolveToolReplayDecision(input: {
|
|
|
226
243
|
}
|
|
227
244
|
return { kind: 'record', call, sink: context.sink }
|
|
228
245
|
}
|
|
229
|
-
if (input.isMutation) {
|
|
230
|
-
reportMiss(context, call, 'mutation_refused', 'error')
|
|
231
|
-
throw new ToolReplayError(
|
|
232
|
-
'tool_replay_mutation_refused',
|
|
233
|
-
input.toolName,
|
|
234
|
-
`[internal] tool_replay_mutation_refused: mutation tool "${input.toolName}" cannot run under tool replay`,
|
|
235
|
-
)
|
|
236
|
-
}
|
|
237
246
|
const mocked = lookupFixture(context, call)
|
|
238
247
|
if (mocked) {
|
|
239
248
|
reportHit(context, call, 'lookup')
|