{"version":3,"file":"use-agent.cjs","names":["DEFAULT_AGENT_ID","useCopilotKit","CopilotKitCoreRuntimeConnectionStatus","ProxiedCopilotRuntimeAgent"],"sources":["../../src/hooks/use-agent.tsx"],"sourcesContent":["import { useCopilotKit } from \"@/providers/CopilotKitProvider\";\nimport { useMemo, useEffect, useReducer, useRef } from \"react\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkitnext/shared\";\nimport { AbstractAgent } from \"@ag-ui/client\";\nimport {\n  ProxiedCopilotRuntimeAgent,\n  CopilotKitCoreRuntimeConnectionStatus,\n} from \"@copilotkitnext/core\";\n\nexport enum UseAgentUpdate {\n  OnMessagesChanged = \"OnMessagesChanged\",\n  OnStateChanged = \"OnStateChanged\",\n  OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n  UseAgentUpdate.OnMessagesChanged,\n  UseAgentUpdate.OnStateChanged,\n  UseAgentUpdate.OnRunStatusChanged,\n];\n\nexport interface UseAgentProps {\n  agentId?: string;\n  updates?: UseAgentUpdate[];\n}\n\nexport function useAgent({ agentId, updates }: UseAgentProps = {}) {\n  agentId ??= DEFAULT_AGENT_ID;\n\n  const { copilotkit } = useCopilotKit();\n  const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n  const updateFlags = useMemo(\n    () => updates ?? ALL_UPDATES,\n    [JSON.stringify(updates)],\n  );\n\n  // Cache provisional agents to avoid creating new references on every render\n  // while the runtime is still connecting. A new reference would cascade into\n  // CopilotChat's connectAgent effect, causing unnecessary HTTP calls.\n  const provisionalAgentCache = useRef<Map<string, ProxiedCopilotRuntimeAgent>>(\n    new Map(),\n  );\n\n  const agent: AbstractAgent = useMemo(() => {\n    const existing = copilotkit.getAgent(agentId);\n    if (existing) {\n      // Real agent found — clear any cached provisional for this ID\n      provisionalAgentCache.current.delete(agentId);\n      return existing;\n    }\n\n    const isRuntimeConfigured = copilotkit.runtimeUrl !== undefined;\n    const status = copilotkit.runtimeConnectionStatus;\n\n    // While runtime is not yet synced, return a provisional runtime agent\n    if (\n      isRuntimeConfigured &&\n      (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n        status === CopilotKitCoreRuntimeConnectionStatus.Connecting)\n    ) {\n      // Return cached provisional if available (keeps reference stable)\n      const cached = provisionalAgentCache.current.get(agentId);\n      if (cached) {\n        // Update headers on the cached agent in case they changed\n        cached.headers = { ...copilotkit.headers };\n        return cached;\n      }\n\n      const provisional = new ProxiedCopilotRuntimeAgent({\n        runtimeUrl: copilotkit.runtimeUrl,\n        agentId,\n        transport: copilotkit.runtimeTransport,\n        runtimeMode: \"pending\",\n      });\n      // Apply current headers so runs/connects inherit them\n      provisional.headers = { ...copilotkit.headers };\n      provisionalAgentCache.current.set(agentId, provisional);\n      return provisional;\n    }\n\n    // Runtime is in Error state — return a provisional agent instead of throwing.\n    // The error has already been emitted through the subscriber system\n    // (RUNTIME_INFO_FETCH_FAILED). Throwing here would crash the React tree;\n    // returning a provisional agent lets onError handlers fire while keeping\n    // the app alive.\n    if (\n      isRuntimeConfigured &&\n      status === CopilotKitCoreRuntimeConnectionStatus.Error\n    ) {\n      const provisional = new ProxiedCopilotRuntimeAgent({\n        runtimeUrl: copilotkit.runtimeUrl,\n        agentId,\n        transport: copilotkit.runtimeTransport,\n        runtimeMode: \"pending\",\n      });\n      provisional.headers = { ...copilotkit.headers };\n      return provisional;\n    }\n\n    // No runtime configured and agent doesn't exist — this is a configuration error.\n    const knownAgents = Object.keys(copilotkit.agents ?? {});\n    const runtimePart = isRuntimeConfigured\n      ? `runtimeUrl=${copilotkit.runtimeUrl}`\n      : \"no runtimeUrl\";\n    throw new Error(\n      `useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` +\n        (knownAgents.length\n          ? `Known agents: [${knownAgents.join(\", \")}]`\n          : \"No agents registered.\") +\n        \" Verify your runtime /info and/or agents__unsafe_dev_only.\",\n    );\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [\n    agentId,\n    copilotkit.agents,\n    copilotkit.runtimeConnectionStatus,\n    copilotkit.runtimeUrl,\n    copilotkit.runtimeTransport,\n    JSON.stringify(copilotkit.headers),\n  ]);\n\n  useEffect(() => {\n    if (updateFlags.length === 0) {\n      return;\n    }\n\n    const handlers: Parameters<AbstractAgent[\"subscribe\"]>[0] = {};\n\n    if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) {\n      // Content stripping for immutableContent renderers is handled by CopilotKitCoreReact\n      handlers.onMessagesChanged = () => {\n        forceUpdate();\n      };\n    }\n\n    if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) {\n      handlers.onStateChanged = forceUpdate;\n    }\n\n    if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {\n      handlers.onRunInitialized = forceUpdate;\n      handlers.onRunFinalized = forceUpdate;\n      handlers.onRunFailed = forceUpdate;\n    }\n\n    const subscription = agent.subscribe(handlers);\n    return () => subscription.unsubscribe();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [agent, forceUpdate, JSON.stringify(updateFlags)]);\n\n  return {\n    agent,\n  };\n}\n"],"mappings":";;;;;;;AASA,IAAY,0DAAL;AACL;AACA;AACA;;;AAGF,MAAM,cAAgC;CACpC,eAAe;CACf,eAAe;CACf,eAAe;CAChB;AAOD,SAAgB,SAAS,EAAE,SAAS,YAA2B,EAAE,EAAE;AACjE,aAAYA;CAEZ,MAAM,EAAE,eAAeC,0CAAe;CACtC,MAAM,GAAG,sCAA2B,MAAM,IAAI,GAAG,EAAE;CAEnD,MAAM,uCACE,WAAW,aACjB,CAAC,KAAK,UAAU,QAAQ,CAAC,CAC1B;CAKD,MAAM,0DACJ,IAAI,KAAK,CACV;CAED,MAAM,iCAAqC;EACzC,MAAM,WAAW,WAAW,SAAS,QAAQ;AAC7C,MAAI,UAAU;AAEZ,yBAAsB,QAAQ,OAAO,QAAQ;AAC7C,UAAO;;EAGT,MAAM,sBAAsB,WAAW,eAAe;EACtD,MAAM,SAAS,WAAW;A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