{"version":3,"file":"a2ui-tool-CD0w1hhG.mjs","names":[],"sources":["../src/a2ui-tool.ts"],"sourcesContent":["/**\n * A2UI subagent tool factory for Mastra agents.\n *\n * Thin adapter over ``@ag-ui/a2ui-toolkit`` — the heavy lifting (op builders,\n * prompt assembly, history walkers, output envelope, and the validate→retry\n * recovery loop) lives in the toolkit so this adapter owns ONLY the Mastra\n * glue: the ``createTool`` decorator, reading the run's messages/context off the\n * tool-execution context, and driving the ``render_a2ui`` structured-output\n * subagent through an ephemeral Mastra ``Agent`` (so model resolution matches\n * the host and the package never couples to a specific ``ai`` version).\n *\n * This is the Mastra sibling of ``getA2UITools`` in ``@ag-ui/langgraph`` and\n * ``@ag-ui/aws-strands`` — same ``A2UIToolParams`` shape, same recovery loop,\n * same envelope. It is the BACKEND-OWNED path: the developer adds the returned\n * tool to their Mastra agent's tools and wires the copilotkit route (or an\n * ``A2UIMiddleware`` direct attach) with ``injectA2UITool: false`` so the\n * runtime renders the surface WITHOUT also injecting its own ``generate_a2ui``\n * (double-bind). Recovery is never in the CopilotKit runtime — it runs here.\n *\n * Example:\n *\n *   import { getA2UITools } from \"@ag-ui/mastra\";\n *   import { openai } from \"@ai-sdk/openai\";\n *   import { Agent } from \"@mastra/core/agent\";\n *\n *   const generateA2ui = getA2UITools({\n *     model: \"openai/gpt-4.1\", // or an AI SDK model object\n *     defaultCatalogId: \"my-catalog\",\n *     recovery: { maxAttempts: 3 },\n *   });\n *\n *   const agent = new Agent({ ..., tools: { generate_a2ui: generateA2ui } });\n *\n * The four pillars, matching langgraph/strands/adk:\n *  1. AUTO-INJECT (easy devex): the MastraAgent bridge injects this tool per run\n *     via ``planA2UIInjection`` when the runtime forwards ``injectA2UITool`` — the\n *     dev wires nothing. Opt out with ``injectA2UITool:false``; customize via the\n *     ``a2ui`` config. (Explicit ``getA2UITools`` is the opt-out / remote path.)\n *  2. PROGRESSIVE STREAMING: the subagent runs via ``.stream()`` and its\n *     ``render_a2ui`` arg deltas are pushed onto the outer agent stream (Mastra\n *     ``writer.custom``); the bridge translates them to inner TOOL_CALL_* so the\n *     surface paints incrementally (see ``renderSubagent``).\n *  3. ERROR RECOVERY: the toolkit's validate→retry loop; invalid never paints,\n *     exhaustion → a tasteful failure envelope.\n *  4. SUBAGENT-BASED: a ``render_a2ui`` structured-output subagent.\n *\n * (Server-side / REMOTE Mastra agents import from ``@ag-ui/mastra/a2ui`` — a\n * bridge-free entry that omits the AbstractAgent bridge so the Mastra CLI bundler\n * needn't resolve its transitive deps.)\n */\n\nimport { createTool } from \"@mastra/core/tools\";\nimport { Agent } from \"@mastra/core/agent\";\nimport { z } from \"zod\";\nimport type { RunAgentInput } from \"@ag-ui/client\";\nimport {\n  GENERATE_A2UI_TOOL_NAME,\n  GENERATE_A2UI_ARG_DESCRIPTIONS,\n  RENDER_A2UI_TOOL_DEF,\n  buildA2UIEnvelope,\n  prepareA2UIRequest,\n  resolveA2UICatalog,\n  resolveA2UIToolParams,\n  splitA2UISchemaContext,\n  wrapErrorEnvelope,\n  runA2UIGenerationWithRecovery,\n  type A2UIGuidelines,\n  type A2UIToolParams,\n  type A2UIAttemptRecord,\n  type A2UIRecoveryConfig,\n  type A2UIValidationCatalog,\n} from \"@ag-ui/a2ui-toolkit\";\n\n/** Name of the render tool the subagent is forced to call. */\nconst RENDER_A2UI_TOOL_NAME = RENDER_A2UI_TOOL_DEF.function.name;\n\n/**\n * Loose type for the subagent model. Typed as ``any`` so the factory accepts any\n * Mastra-compatible model config — a provider-string like ``\"openai/gpt-4.1\"``\n * (resolved by Mastra's own model router, the idiomatic Mastra form) OR an AI SDK\n * model object (``openai(\"gpt-4.1\")``). Running the subagent through a Mastra\n * ``Agent`` (below) means the package never imports ``ai`` directly, so it is\n * immune to consumer ``ai`` / ``@ai-sdk/*`` major-version skew.\n */\nexport type A2UISubagentModel = any;\n\nexport type { A2UIToolParams, A2UIAttemptRecord, A2UIRecoveryConfig };\n\n/**\n * Minimal structural view of the pieces of Mastra's ``ToolExecutionContext``\n * this adapter reads. Typed locally (not imported from ``@mastra/core``) so the\n * adapter tolerates @mastra/core version skew — the fields below are stable\n * across the supported 1.x range.\n */\ninterface A2UIToolExecutionContext {\n  /** Per-run agent context. ``messages`` is the conversation the loop is on. */\n  agent?: { messages?: unknown[] };\n  /**\n   * Mastra request context. The AG-UI Mastra bridge forwards\n   * ``RunAgentInput.context`` (which carries the A2UI catalog schema entry the\n   * ``@ag-ui/a2ui-middleware`` / provider injects) under the ``\"ag-ui\"`` key.\n   */\n  requestContext?: { get?: (key: string) => unknown };\n  /** Mastra ToolStream — used to push progressive render deltas (pillar 2). */\n  writer?: A2UIStreamWriter;\n}\n\n/** Outer tool arguments exposed to the main Mastra agent's planner. */\nconst generateA2UIInputSchema = z.object({\n  intent: z\n    .enum([\"create\", \"update\"])\n    .optional()\n    .describe(GENERATE_A2UI_ARG_DESCRIPTIONS.intent),\n  target_surface_id: z\n    .string()\n    .optional()\n    .describe(GENERATE_A2UI_ARG_DESCRIPTIONS.target_surface_id),\n  changes: z\n    .string()\n    .optional()\n    .describe(GENERATE_A2UI_ARG_DESCRIPTIONS.changes),\n});\n\n/** Zod mirror of ``RENDER_A2UI_TOOL_DEF`` for the forced subagent tool call. */\nconst renderA2UIInputSchema = z.object({\n  surfaceId: z.string().describe(\"Unique surface identifier.\"),\n  components: z\n    .array(z.record(z.string(), z.unknown()))\n    .describe(\n      \"A2UI v0.9 component array (flat format); root component id 'root'.\",\n    ),\n  data: z\n    .record(z.string(), z.unknown())\n    .optional()\n    .describe(\"Optional initial data model for the surface.\"),\n});\n\n/**\n * Read the AG-UI context array the bridge forwarded onto Mastra's request\n * context. Defensive: any shape other than the expected ``{ context: [...] }``\n * degrades to an empty list (no catalog → the subagent falls back to the\n * configured ``defaultCatalogId``), never throws.\n */\nfunction readAgUiContext(\n  requestContext: A2UIToolExecutionContext[\"requestContext\"],\n): Array<Record<string, unknown>> {\n  const entry =\n    typeof requestContext?.get === \"function\"\n      ? requestContext.get(\"ag-ui\")\n      : undefined;\n  const context = (entry as { context?: unknown } | undefined)?.context;\n  return Array.isArray(context)\n    ? (context as Array<Record<string, unknown>>)\n    : [];\n}\n\n/**\n * Drop a trailing in-flight ``generate_a2ui`` assistant tool-call from history\n * before the subagent runs — it is unbalanced (no result yet) and would only\n * confuse the render subagent. Mirrors LangGraph's ``slice(0, -1)`` but is\n * guarded so it only strips when the last message actually is that call.\n */\nfunction stripInFlightGenerateCall(\n  messages: unknown[],\n  toolName: string,\n): unknown[] {\n  const last = messages[messages.length - 1] as\n    | { role?: string; toolCalls?: Array<{ function?: { name?: string } }> }\n    | undefined;\n  const calls = last?.toolCalls;\n  if (\n    last?.role === \"assistant\" &&\n    Array.isArray(calls) &&\n    calls.some((c) => c?.function?.name === toolName)\n  ) {\n    return messages.slice(0, -1);\n  }\n  return messages;\n}\n\n/** Coerce one message's content to plain text for the subagent prompt. */\nfunction messageText(content: unknown): string {\n  if (typeof content === \"string\") return content;\n  if (Array.isArray(content)) {\n    return content\n      .map((part) =>\n        typeof part === \"string\"\n          ? part\n          : typeof (part as { text?: unknown })?.text === \"string\"\n            ? (part as { text: string }).text\n            : \"\",\n      )\n      .join(\"\");\n  }\n  return \"\";\n}\n\n/**\n * Map the run's messages to the ``{ role, content }`` shape ``generateText``\n * accepts. System/tool roles collapse to ``user`` (the subagent only needs the\n * conversational request as context; it is forced to call ``render_a2ui``).\n */\nfunction toModelMessages(\n  messages: unknown[],\n): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n  return messages\n    .map((m) => {\n      const msg = m as { role?: unknown; content?: unknown };\n      const role = msg.role === \"assistant\" ? \"assistant\" : \"user\";\n      return {\n        role: role as \"user\" | \"assistant\",\n        content: messageText(msg.content),\n      };\n    })\n    .filter((m) => m.content.length > 0);\n}\n\n/** AG-UI render-stream chunk type the tool writes onto the outer agent stream\n *  (via Mastra `ToolStream.custom`); the bridge's createChunkProcessor\n *  translates it into synthetic inner render_a2ui TOOL_CALL_* events. */\nexport const A2UI_RENDER_STREAM_TYPE = \"data-a2ui-render\";\n\n/** Minimal writer surface (Mastra `ToolStream`) — only `custom` is used. */\ninterface A2UIStreamWriter {\n  custom?: (chunk: {\n    type: string;\n    payload: Record<string, unknown>;\n  }) => Promise<void> | void;\n}\n\n/**\n * Run the ``render_a2ui`` structured-output subagent once and return its args\n * (``{ surfaceId, components, data }``) — or ``null`` if the model produced no\n * tool call. The recovery loop calls this once per attempt with an\n * error-augmented ``prompt``.\n *\n * The subagent is an ephemeral Mastra ``Agent`` bound to a CAPTURING\n * ``render_a2ui`` tool: forcing ``toolChoice: \"required\"`` with ``maxSteps: 1``\n * makes the model emit exactly one structured render call, whose args the tool's\n * ``execute`` captures. Running through Mastra (rather than a raw ``ai``\n * ``generateText``) resolves the model the way the host agent does and never\n * couples to a specific ``ai`` / ``@ai-sdk/*`` version.\n *\n * PROGRESSIVE STREAMING (pillar 2): the subagent runs via ``.stream()`` and its\n * ``render_a2ui`` tool-call arg deltas are pushed onto the OUTER agent stream via\n * ``writer.custom({type:\"data-a2ui-render\", ...})``. The bridge translates those\n * into inner ``TOOL_CALL_START/ARGS/END`` so the A2UIMiddleware paints the\n * \"building\" skeleton + fills the surface incrementally. A fresh call id per\n * attempt keeps the middleware's retry lifecycle correct; the live call is\n * always closed (end phase) even on error so the wire stays balanced.\n */\nasync function renderSubagent(\n  model: A2UISubagentModel,\n  prompt: string,\n  messages: Array<{ role: \"user\" | \"assistant\"; content: string }>,\n  writer: A2UIStreamWriter | undefined,\n  attempt: number,\n): Promise<Record<string, unknown> | null> {\n  let captured: Record<string, unknown> | null = null;\n\n  const renderTool = createTool({\n    id: RENDER_A2UI_TOOL_NAME,\n    description: RENDER_A2UI_TOOL_DEF.function.description,\n    inputSchema: renderA2UIInputSchema,\n    execute: async (input) => {\n      captured = input as Record<string, unknown>;\n      return \"ok\";\n    },\n  });\n\n  const subagent = new Agent({\n    id: \"a2ui_render_subagent\",\n    name: \"a2ui_render_subagent\",\n    instructions: prompt,\n    model,\n    tools: { [RENDER_A2UI_TOOL_NAME]: renderTool },\n  });\n\n  // Fresh render call id per attempt so the middleware treats each attempt as a\n  // distinct render (building -> retrying -> painted / failed).\n  const callId = `a2ui-render-${attempt}-${RENDER_A2UI_TOOL_NAME}`;\n  let liveOpen = false;\n  const push = async (payload: Record<string, unknown>) => {\n    if (writer?.custom) {\n      await writer.custom({ type: A2UI_RENDER_STREAM_TYPE, payload });\n    }\n  };\n  const openLive = async () => {\n    if (liveOpen) return;\n    liveOpen = true;\n    await push({\n      phase: \"start\",\n      toolCallId: callId,\n      toolName: RENDER_A2UI_TOOL_NAME,\n    });\n  };\n  const closeLive = async () => {\n    if (!liveOpen) return;\n    liveOpen = false;\n    await push({ phase: \"end\", toolCallId: callId });\n  };\n\n  try {\n    const res: any = await subagent.stream(\n      messages as any,\n      {\n        toolChoice: \"required\",\n        maxSteps: 1,\n      } as any,\n    );\n    for await (const chunk of res.fullStream) {\n      const p = (chunk?.payload ?? {}) as Record<string, any>;\n      switch (chunk?.type) {\n        case \"tool-call-input-streaming-start\": {\n          if (p.toolName === RENDER_A2UI_TOOL_NAME) await openLive();\n          break;\n        }\n        case \"tool-call-delta\": {\n          if (p.argsTextDelta != null) {\n            await openLive();\n            await push({\n              phase: \"delta\",\n              toolCallId: callId,\n              argsTextDelta: String(p.argsTextDelta),\n            });\n          }\n          break;\n        }\n        case \"tool-call-input-streaming-end\":\n        case \"tool-call\": {\n          await closeLive();\n          break;\n        }\n        default:\n          break;\n      }\n    }\n  } finally {\n    // Balance the wire even if the stream ended without an end chunk or threw.\n    await closeLive();\n  }\n\n  return captured;\n}\n\n/**\n * Build a Mastra tool that delegates A2UI surface generation to a subagent,\n * with the shared validate→retry recovery loop. Add the returned tool to a\n * Mastra agent's ``tools`` map (conventionally under the key ``generate_a2ui``).\n *\n * @param params Shared ``A2UIToolParams`` (model + behavior knobs). The toolkit\n *   owns the shape and fills defaults via ``resolveA2UIToolParams``.\n */\nexport function getA2UITools<TModel = A2UISubagentModel>(\n  params: A2UIToolParams<TModel>,\n) {\n  const {\n    model,\n    guidelines,\n    defaultSurfaceId,\n    defaultCatalogId,\n    toolName,\n    toolDescription,\n    catalog,\n    recovery,\n    onA2UIAttempt,\n  } = resolveA2UIToolParams(params);\n  const subagentModel = model as A2UISubagentModel;\n\n  return createTool({\n    id: toolName,\n    description: toolDescription,\n    inputSchema: generateA2UIInputSchema,\n    // Returns the a2ui_operations / recovery-failure envelope as a PARSED\n    // OBJECT (not the toolkit's JSON string). The Mastra bridge JSON.stringifies\n    // a tool result once for the wire; returning an object yields SINGLE-encoded\n    // TOOL_CALL_RESULT content, which is what the A2UIMiddleware's envelope +\n    // recovery-failure detectors expect (a string result would be double-encoded\n    // and the failure path — unlike the ops path — would miss it).\n    execute: async (input, context): Promise<unknown> => {\n      const ctx = (context ?? {}) as A2UIToolExecutionContext;\n      const allMessages = Array.isArray(ctx.agent?.messages)\n        ? (ctx.agent!.messages as unknown[])\n        : [];\n      const messages = stripInFlightGenerateCall(allMessages, toolName);\n\n      // The bridge forwards RunAgentInput.context (with the A2UI catalog schema\n      // entry) onto Mastra's request context. Split out the schema entry into\n      // the canonical ``state[\"ag-ui\"]`` shape the toolkit's prompt builder and\n      // catalog resolver expect.\n      const [schemaValue, regularContext] = splitA2UISchemaContext(\n        readAgUiContext(ctx.requestContext),\n      );\n      const state: Record<string, unknown> = {\n        \"ag-ui\": { a2ui_schema: schemaValue, context: regularContext },\n      };\n\n      // Shared: create/update decision, prior-surface lookup, prompt assembly.\n      const prep = prepareA2UIRequest({\n        intent: input.intent,\n        targetSurfaceId: input.target_surface_id,\n        changes: input.changes,\n        messages,\n        state,\n        guidelines,\n      });\n      if (prep.error) return parseEnvelope(wrapErrorEnvelope(prep.error));\n\n      const modelMessages = toModelMessages(messages);\n\n      // Shared: validate→retry loop. Invalid surfaces never paint (the\n      // middleware gate uses the same validator); exhaustion returns a\n      // structured ``a2ui_recovery_exhausted`` envelope so the conversation\n      // stays usable.\n      const { envelope } = await runA2UIGenerationWithRecovery({\n        basePrompt: prep.prompt,\n        catalog,\n        config: recovery,\n        onAttempt: onA2UIAttempt,\n        invokeSubagent: (prompt, attempt) =>\n          renderSubagent(\n            subagentModel,\n            prompt,\n            modelMessages,\n            ctx.writer,\n            attempt,\n          ),\n        buildEnvelope: (args) =>\n          buildA2UIEnvelope({\n            args,\n            isUpdate: prep.isUpdate,\n            targetSurfaceId: input.target_surface_id,\n            prior: prep.prior,\n            defaultSurfaceId,\n            defaultCatalogId,\n          }),\n      });\n      // Always return the real a2ui_operations envelope. The progressive render\n      // (streamed via writer.custom) is keyed to THIS generate_a2ui call — the\n      // bridge flushes the outer call onto the wire before the inner render\n      // deltas — so the runtime paints the streamed surface and this final\n      // envelope under the SAME activity id: the envelope replaces (not\n      // duplicates) the streamed surface, and being an a2ui result it is\n      // intercepted (no residual generate_a2ui tool card). On exhaustion the\n      // envelope carries the a2ui_recovery_exhausted failure instead.\n      return parseEnvelope(envelope);\n    },\n  });\n}\n\n/**\n * Parse the toolkit's JSON envelope string into an object so the Mastra bridge\n * single-encodes it onto the wire (see the execute note above). Falls back to\n * the raw string if it is somehow not valid JSON.\n */\nfunction parseEnvelope(envelope: string): unknown {\n  try {\n    return JSON.parse(envelope);\n  } catch {\n    return envelope;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Auto-injection (pillar 1: easy devex) — mirrors @ag-ui/aws-strands\n// `planA2UIInjection`. The MastraAgent bridge calls this per run: when the\n// runtime/middleware forwarded `injectA2UITool`, it builds the backend-owned\n// `generate_a2ui` tool (recovery included) so the DEVELOPER never hand-wires it.\n// Opt out with `injectA2UITool:false`; customize via the `A2UIInjectConfig` props.\n// ---------------------------------------------------------------------------\n\n/** Marks a tool this adapter auto-injected, so the bridge can refresh (not\n *  \"user-prevails\") its own prior-turn tool on a cached/multi-turn thread. */\nexport const A2UI_AUTOINJECT_MARKER = Symbol.for(\n  \"@ag-ui/mastra.a2uiAutoInjected\",\n);\n\n/** Backend override knobs for auto-injection (mirrors the runtime `injectA2UITool`\n *  flag + the customizable `getA2UITools` properties). All optional. */\nexport interface A2UIInjectConfig<TModel = A2UISubagentModel> {\n  /** Force on/off from the backend (nullish-falls-back FROM forwardedProps —\n   *  an explicit runtime value wins). A string names the injected render tool. */\n  injectA2UITool?: boolean | string;\n  /** Model the render subagent runs. Required for auto-inject unless the bridge\n   *  can infer one from the wrapped agent. */\n  model?: TModel;\n  /** Catalog id stamped on created surfaces (else resolved from run context). */\n  defaultCatalogId?: string;\n  /** Prompt knobs (else the run's component schema becomes the composition guide). */\n  guidelines?: A2UIGuidelines;\n  /** Inline catalog for semantic validation (structural-only when absent). */\n  catalog?: A2UIValidationCatalog;\n  /** Recovery loop config (attempt cap, etc.). */\n  recovery?: A2UIRecoveryConfig;\n  /** Per-attempt observability hook. */\n  onA2UIAttempt?: (record: A2UIAttemptRecord) => void;\n}\n\n/** The per-run injection decision. */\nexport interface A2UIInjectionPlan {\n  /** The `generate_a2ui` Mastra tool to register for this run. */\n  tool: ReturnType<typeof getA2UITools>;\n  /** Name the tool is registered under (`generate_a2ui`). */\n  toolName: string;\n  /** Injected render-tool names to drop so the model calls `generate_a2ui`. */\n  dropToolNames: string[];\n}\n\nexport interface PlanA2UIInjectionInput<TModel = A2UISubagentModel> {\n  /** Model inferred from the wrapped agent (null when none is inferable). */\n  model: TModel | null | undefined;\n  /** The run input — read for `forwardedProps.injectA2UITool` + catalog context. */\n  input: RunAgentInput;\n  /** Tool names already on the agent (USER-PREVAILS dedup). */\n  existingToolNames: string[];\n  /** Backend override config. */\n  config?: A2UIInjectConfig<TModel>;\n  /** Logger for the no-model skip warning. */\n  log?: { warn: (msg: string) => void };\n}\n\n/**\n * Decide whether to auto-inject `generate_a2ui` for this run. Off unless the\n * runtime forwarded `injectA2UITool` (or `config.injectA2UITool` is set);\n * USER-PREVAILS (skip if the dev already wired `generate_a2ui`); skip + warn when\n * no model is available. Otherwise builds the backend recovery tool, resolving\n * the catalog id + composition guide from run context (backend config wins), and\n * drops the middleware-injected render tool so the model calls `generate_a2ui`.\n */\nexport function planA2UIInjection<TModel = A2UISubagentModel>(\n  args: PlanA2UIInjectionInput<TModel>,\n): A2UIInjectionPlan | null {\n  const { input, existingToolNames, config } = args;\n  const log = args.log ?? console;\n\n  // Explicit backend opt-out wins even over a forwarded `true`: an agent that\n  // OWNS a fixed-schema A2UI tool sets `a2ui.injectA2UITool:false` so the bridge\n  // never auto-injects `generate_a2ui` alongside its own direct tool, even when\n  // the runtime blanket-forwards the flag to every A2UI agent.\n  if (config?.injectA2UITool === false) return null;\n\n  const forwarded = input.forwardedProps as\n    | { injectA2UITool?: boolean | string }\n    | undefined;\n  const flag = forwarded?.injectA2UITool ?? config?.injectA2UITool;\n  if (!flag) return null;\n\n  const toolName = GENERATE_A2UI_TOOL_NAME;\n  // USER PREVAILS: never double-inject over a dev-wired generate_a2ui.\n  if (existingToolNames.includes(toolName)) return null;\n\n  const model = config?.model ?? args.model;\n  if (model == null) {\n    log.warn(\n      \"[@ag-ui/mastra] A2UI tool injection requested but no model could be \" +\n        \"inferred from the agent. Skipping auto-injection — pass `a2ui.model` \" +\n        \"or wire getA2UITools() explicitly.\",\n    );\n    return null;\n  }\n\n  const renderToolName =\n    typeof flag === \"string\" ? flag : RENDER_A2UI_TOOL_DEF.function.name;\n\n  // Resolve the frontend catalog id + composition guide from run context so the\n  // auto-injected tool grounds surfaces on the host's catalog with no hardcoding.\n  // Backend config wins.\n  const [schemaValue, regularContext] = splitA2UISchemaContext(\n    input.context as Array<Record<string, unknown>> | undefined,\n  );\n  const state: Record<string, unknown> = {\n    \"ag-ui\": { a2ui_schema: schemaValue, context: regularContext },\n  };\n  const resolved = resolveA2UICatalog(state);\n  const [runtimeSchema, runtimeCatalogId] = resolved ?? [undefined, undefined];\n\n  const defaultCatalogId = config?.defaultCatalogId ?? runtimeCatalogId;\n  let guidelines = config?.guidelines;\n  if (guidelines === undefined && runtimeSchema !== undefined) {\n    guidelines = { compositionGuide: runtimeSchema };\n  }\n\n  const tool = getA2UITools({\n    model: model as A2UISubagentModel,\n    toolName,\n    catalog: config?.catalog,\n    defaultCatalogId,\n    guidelines,\n    recovery: config?.recovery,\n    onA2UIAttempt: config?.onA2UIAttempt,\n  });\n  (tool as { [A2UI_AUTOINJECT_MARKER]?: true })[A2UI_AUTOINJECT_MARKER] = true;\n\n  return { tool, toolName, dropToolNames: [renderToolName] };\n}\n\n/** True if `tool` is a `generate_a2ui` this adapter auto-injected. */\nexport function isAutoInjectedA2UITool(tool: unknown): boolean {\n  return (\n    typeof tool === \"object\" &&\n    tool !== null &&\n    (tool as { [A2UI_AUTOINJECT_MARKER]?: boolean })[A2UI_AUTOINJECT_MARKER] ===\n      true\n  );\n}\n"],"mappings":"uaA0EA,MAAM,EAAwB,EAAqB,SAAS,KAkCtD,EAA0B,EAAE,OAAO,CACvC,OAAQ,EACL,KAAK,CAAC,SAAU,SAAS,CAAC,CAC1B,UAAU,CACV,SAAS,EAA+B,OAAO,CAClD,kBAAmB,EAChB,QAAQ,CACR,UAAU,CACV,SAAS,EAA+B,kBAAkB,CAC7D,QAAS,EACN,QAAQ,CACR,UAAU,CACV,SAAS,EAA+B,QAAQ,CACpD,CAAC,CAGI,EAAwB,EAAE,OAAO,CACrC,UAAW,EAAE,QAAQ,CAAC,SAAS,6BAA6B,CAC5D,WAAY,EACT,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAE,EAAE,SAAS,CAAC,CAAC,CACxC,SACC,qEACD,CACH,KAAM,EACH,OAAO,EAAE,QAAQ,CAAE,EAAE,SAAS,CAAC,CAC/B,UAAU,CACV,SAAS,+CAA+C,CAC5D,CAAC,CAQF,SAAS,EACP,EACgC,CAKhC,IAAM,GAHJ,OAAO,GAAgB,KAAQ,WAC3B,EAAe,IAAI,QAAQ,CAC3B,IAAA,KACwD,QAC9D,OAAO,MAAM,QAAQ,EAAQ,CACxB,EACD,EAAE,CASR,SAAS,EACP,EACA,EACW,CACX,IAAM,EAAO,EAAS,EAAS,OAAS,GAGl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