{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n  attachIntelligenceEnterpriseLearning,\n  cloneAgentForRequest,\n  configureAgentForRequest,\n  parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n  resolveLocalThreadOwner,\n  threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n  runtime,\n  request,\n  agentId,\n}: RunAgentParameters) {\n  const startTime = Date.now();\n  const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n  (runtime.telemetry ?? telemetry).capture(\n    \"oss.runtime.copilot_request_created\",\n    {\n      \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n      requestType: \"run\",\n      \"cloud.api_key_provided\": !!publicApiKey,\n      ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n    },\n  );\n\n  try {\n    const agent = await cloneAgentForRequest(runtime, agentId, request);\n    if (agent instanceof Response) {\n      return agent;\n    }\n\n    // Ensure the clone carries the registry key so InMemoryAgentRunner can\n    // tag historic runs with the correct agentId for filtering.\n    agent.agentId = agentId;\n\n    // Parse the body before configuring middleware: middleware configuration\n    // needs the A2UI catalog signal the React provider forwards (see\n    // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n    // the run itself is kicked off later, so this is safe. The body is read\n    // from a clone, so `identifyUser` can still read the original request.\n    const parsed = await parseRunRequest(request.clone());\n    if (parsed instanceof Response) {\n      return parsed;\n    }\n    // An app's analytics context is for Intelligence's lock request alone, so\n    // it is taken off the input before anything hands that input to an agent.\n    const { input, analyticsContext } = takeAnalyticsContext(parsed);\n\n    // A thread belongs to the identity of its first run. Running needs no\n    // configured identity (anonymous runs keep working), but nobody may add to\n    // a thread that another identity owns.\n    let ownerId: string | undefined;\n    if (!isIntelligenceRuntime(runtime)) {\n      const owner = await resolveLocalThreadOwner({\n        runtime,\n        request,\n        operation: \"run\",\n      });\n      if (owner instanceof Response) return owner;\n      if (\n        enforcesThreadOwnership(runtime.runner) &&\n        !(await runtime.runner.isThreadAccessible(input.threadId, {\n          ownerId: owner,\n        }))\n      ) {\n        return threadAccessDeniedResponse();\n      }\n      ownerId = owner;\n    }\n\n    // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n    // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n    // `a2ui` config required.\n    const providerA2UIHasCatalog =\n      (input.forwardedProps as Record<string, unknown> | undefined)\n        ?.a2uiCatalogAvailable === true;\n    // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n    // transport of this run.\n    const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n      input.forwardedProps,\n    )?.metadata.extensions.copilotkit_transport;\n\n    configureAgentForRequest({\n      runtime,\n      request,\n      agentId,\n      agent,\n      providerA2UIHasCatalog,\n      providerGenerativeUITransport,\n      isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n        input.forwardedProps ?? {},\n        \"__proxiedMCPRequest\",\n      ),\n    });\n    const memoryResponse = await attachIntelligenceEnterpriseLearning({\n      runtime,\n      request,\n      agent,\n    });\n    if (memoryResponse instanceof Response) return memoryResponse;\n\n    agent.setMessages(input.messages);\n    agent.setState(input.state);\n    agent.threadId = input.threadId;\n\n    if (runtime.debug?.lifecycle && runtime.debugLogger) {\n      runtime.debugLogger.debug(\n        { agentName: agentId, threadId: input.threadId },\n        \"Agent run started\",\n      );\n    }\n\n    if (isIntelligenceRuntime(runtime)) {\n      return handleIntelligenceRun({\n        runtime,\n        request,\n        agentId,\n        agent,\n        input,\n        analyticsContext,\n        startTime,\n      });\n    }\n\n    return handleSseRun({\n      runtime,\n      request,\n      agent,\n      input,\n      agentId,\n      debug: runtime.debug,\n      logger: runtime.debugLogger,\n      startTime,\n      ownerId,\n    });\n  } catch (error) {\n    getRuntimeErrorReporter(runtime)?.report({\n      request,\n      error,\n      operation: \"agent.run\",\n      agentId,\n      phase: \"common\",\n      startTime,\n    });\n    console.error(\"Error running agent:\", error);\n    console.error(\n      \"Error stack:\",\n      error instanceof Error ? error.stack : \"No stack trace\",\n    );\n    console.error(\"Error details:\", {\n      name: error instanceof Error ? error.name : \"Unknown\",\n      message: error instanceof Error ? error.message : String(error),\n      cause: error instanceof Error ? error.cause : undefined,\n    });\n\n    return new Response(\n      JSON.stringify({\n        error: \"Failed to run agent\",\n        message: error instanceof Error ? error.message : \"Unknown error\",\n      }),\n      {\n        status: 500,\n        headers: { \"Content-Type\": \"application/json\" },\n      },\n    );\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAa,WAAW,QAC/B,uCACA;EACE,4BAA4B,MAAM,sBAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,GAAG,EAAE;EACjE,CACF;AAED,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAOhB,MAAM,SAAS,MAAM,gBAAgB,QAAQ,OAAO,CAAC;AACrD,MAAI,kBAAkB,SACpB,QAAO;EAIT,MAAM,EAAE,OAAO,qBAAqB,qB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