@copilotkit/runtime 1.59.5 → 1.60.1

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.
Files changed (42) hide show
  1. package/dist/agent/index.cjs +16 -6
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts.map +1 -1
  4. package/dist/agent/index.d.mts.map +1 -1
  5. package/dist/agent/index.mjs +16 -6
  6. package/dist/agent/index.mjs.map +1 -1
  7. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  8. package/dist/lib/runtime/copilot-runtime.d.cts +0 -8
  9. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  10. package/dist/lib/runtime/copilot-runtime.d.mts +0 -8
  11. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  12. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  13. package/dist/package.cjs +6 -6
  14. package/dist/package.mjs +6 -6
  15. package/dist/v2/runtime/handlers/get-runtime-info.cjs +4 -0
  16. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  17. package/dist/v2/runtime/handlers/get-runtime-info.mjs +4 -0
  18. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  19. package/dist/v2/runtime/handlers/intelligence/run.cjs +4 -1
  20. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  21. package/dist/v2/runtime/handlers/intelligence/run.mjs +4 -1
  22. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  23. package/dist/v2/runtime/handlers/intelligence/threads.cjs +4 -1
  24. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  25. package/dist/v2/runtime/handlers/intelligence/threads.mjs +4 -1
  26. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  27. package/dist/v2/runtime/intelligence-platform/client.cjs +18 -6
  28. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  29. package/dist/v2/runtime/intelligence-platform/client.d.cts +2 -0
  30. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  31. package/dist/v2/runtime/intelligence-platform/client.d.mts +2 -0
  32. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  33. package/dist/v2/runtime/intelligence-platform/client.mjs +18 -6
  34. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  35. package/package.json +7 -7
  36. package/skills/runtime/SKILL.md +2 -2
  37. package/skills/runtime/references/agent-runners.md +6 -6
  38. package/skills/runtime/references/intelligence-mode.md +9 -13
  39. package/skills/runtime/references/setup-endpoint.md +1 -1
  40. package/skills/runtime/references/wiring-agno.md +5 -4
  41. package/skills/runtime/references/wiring-external-agents.md +20 -20
  42. package/skills/runtime/references/wiring-langgraph.md +5 -6
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback","randomUUID"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAaA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAkThB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAA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,QACkC;AAClC,SAAO,MAAKA,QACV,SACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,QACpD;GACE,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,GAAI,OAAO,kBAAkB,SACzB,EAAE,eAAe,OAAO,eAAe,GACvC,EAAE;GACP,CACF;;CAGH,MAAM,mBAAmB,QAGa;EACpC,MAAM,KAAK,IAAI,gBAAgB,EAAE,QAAQ,OAAO,QAAQ,CAAC,CAAC,UAAU;AACpE,SAAO,MAAKA,QACV,OACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,aAAa,KAClE;;CAGH,MAAM,eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QACxB,QACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WACpD;GACE,QAAQ,OAAO;GACf,SAAS,OAAO;GACjB,CACF,IAGgB;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
1
+ {"version":3,"file":"client.mjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback","randomUUID"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId, userId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadSummary> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadMessagesResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAaA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAkThB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,4BAA6B,OAAO,4BAA4B;AAErE,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;;;;;;;;;;;;;;;;;;;;CAsBhD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;;;;;;;;;;CAajD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB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Aa,KAClE;;CAGH,MAAM,eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QACxB,QACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WACpD;GACE,QAAQ,OAAO;GACf,SAAS,OAAO;GACjB,CACF,IAGgB;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/runtime",
3
- "version": "1.59.5",
3
+ "version": "1.60.1",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -65,11 +65,11 @@
65
65
  "access": "public"
66
66
  },
67
67
  "dependencies": {
68
- "@ag-ui/a2ui-middleware": "0.0.6",
69
- "@ag-ui/client": "0.0.53",
70
- "@ag-ui/core": "0.0.53",
71
- "@ag-ui/encoder": "0.0.53",
72
- "@ag-ui/langgraph": "0.0.37",
68
+ "@ag-ui/a2ui-middleware": "0.0.8",
69
+ "@ag-ui/client": "0.0.57",
70
+ "@ag-ui/core": "0.0.57",
71
+ "@ag-ui/encoder": "0.0.57",
72
+ "@ag-ui/langgraph": "0.0.41",
73
73
  "@ag-ui/mcp-apps-middleware": "0.0.3",
74
74
  "@ag-ui/mcp-middleware": "0.0.1",
75
75
  "@ai-sdk/anthropic": "^3.0.49",
@@ -105,7 +105,7 @@
105
105
  "uuid": "^10.0.0",
106
106
  "ws": "^8.18.0",
107
107
  "zod": "^3.23.3",
108
- "@copilotkit/shared": "1.59.5"
108
+ "@copilotkit/shared": "1.60.1"
109
109
  },
110
110
  "devDependencies": {
111
111
  "@copilotkit/aimock": "latest",
@@ -73,7 +73,7 @@ export default { fetch: handler };
73
73
  | Mounting on any fetch-native server (Cloudflare Workers, Bun, Deno, Vercel Edge, Next.js App Router, React Router v7, TanStack Start) or delegating from Express/Node | `references/setup-endpoint.md` |
74
74
  | Auth / logging / rate-limit / request-scoped guards via `hooks.onRequest` / `hooks.onBeforeHandler` (preferred) or legacy `beforeRequestMiddleware` / `afterRequestMiddleware` | `references/middleware.md` |
75
75
  | Choosing between `InMemoryAgentRunner`, `SqliteAgentRunner`, or a custom subclass — including thread-locking semantics and the runner/Intelligence mutual exclusion | `references/agent-runners.md` (+ `-in-memory.md`, `-sqlite.md`, `-custom.md` for backend-specific detail) |
76
- | Enabling durable threads + realtime websocket via CopilotKit Cloud (Intelligence is **Cloud-only**, not self-hostable) | `references/intelligence-mode.md` |
76
+ | Enabling durable threads + realtime websocket via CopilotKit Intelligence (a **managed service**, not self-hostable) | `references/intelligence-mode.md` |
77
77
  | Voice transcription — implementing a `TranscriptionService` subclass for the `/transcribe` endpoint | `references/transcription.md` |
78
78
  | Instantiating `BuiltInAgent` — Simple Mode (classic) or Factory Mode with TanStack AI (preferred AG-UI-compliant default), AI SDK, or custom factory | `references/built-in-agent.md` (+ `-factory-modes.md`, `-helper-utilities.md`, `-model-identifiers.md`) |
79
79
  | Defining server-side tools via `defineTool` for `BuiltInAgent.config.tools` (Simple Mode only) | `references/server-side-tools.md` |
@@ -85,7 +85,7 @@ export default { fetch: handler };
85
85
  - `createCopilotRuntimeHandler` is the canonical primitive. `createCopilotExpressHandler` / `createCopilotHonoHandler` exist but are **avoid at all costs** — delegate from Express/Hono routes to the fetch primitive instead.
86
86
  - `publicLicenseKey` is the canonical provider-side field. `publicApiKey` is a **deprecated alias** — expect to see it in legacy code, emit the canonical name in new code.
87
87
  - Intelligence mode auto-wires `IntelligenceAgentRunner`. Passing both `runner` and `intelligence` to `CopilotRuntime` is rejected at construction.
88
- - Intelligence mode targets CopilotKit Cloud (`api.cloud.copilotkit.ai`) and is **not self-hostable**.
88
+ - Intelligence mode targets the managed CopilotKit Intelligence service (`api.cloud.copilotkit.ai`) and is **not self-hostable**.
89
89
  - `hooks.onRequest` runs **before** `beforeRequestMiddleware` (hook-based middleware wins for Response short-circuits). `beforeRequestMiddleware` runs **after** `hooks.onRequest` (see `fetch-handler.ts:136-147`).
90
90
  - `identifyUser` (Intelligence) does **not** forward thrown `Response` objects — convert to 500. Gate auth rejection in `hooks.onRequest`, which does forward Responses.
91
91
  - `agents__unsafe_dev_only` and `selfManagedAgents` are dev-only aliases of each other; do not reach for them in production. Either signals that the SPA is in dev mode.
@@ -87,7 +87,7 @@ that surfaces to the client depends on the runtime mode:
87
87
  - **Intelligence mode** — the Intelligence platform returns HTTP `409` when a lock is
88
88
  held. The client core maps this to `CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED`
89
89
  and fires `onError({ code: "agent_thread_locked", ... })`. Handle this in
90
- `<CopilotKitProvider onError>`.
90
+ `<CopilotKit onError>` (the `CopilotKit` provider from `@copilotkit/react-core/v2`).
91
91
  - **SSE mode** (default, in-memory / SQLite runners) — the runner throws
92
92
  synchronously and the handler returns a plain `500` JSON body like
93
93
  `{ "error": "Failed to run agent", "message": "Thread already running" }`.
@@ -96,9 +96,9 @@ that surfaces to the client depends on the runtime mode:
96
96
 
97
97
  ```tsx
98
98
  // client — Intelligence mode (typed code)
99
- import { CopilotKitProvider } from "@copilotkit/react-core/v2";
99
+ import { CopilotKit } from "@copilotkit/react-core/v2";
100
100
 
101
- <CopilotKitProvider
101
+ <CopilotKit
102
102
  onError={({ code }) => {
103
103
  if (code === "agent_thread_locked") {
104
104
  alert("Agent is busy — wait for the current response to finish.");
@@ -181,7 +181,7 @@ new CopilotRuntime({
181
181
  ```
182
182
 
183
183
  `CopilotIntelligenceRuntimeOptions` does not declare a `runner` field — Intelligence mode
184
- auto-wires `IntelligenceAgentRunner` pointed at the Cloud socket. Excess-property checks will
184
+ auto-wires `IntelligenceAgentRunner` pointed at the Intelligence service socket. Excess-property checks will
185
185
  flag a `runner:` key on an Intelligence-shaped options object as a type error, and at runtime
186
186
  the auto-wired Intelligence runner wins regardless of what you pass.
187
187
 
@@ -261,7 +261,7 @@ const [busy, setBusy] = useState(false);
261
261
 
262
262
  Both runners throw `"Thread already running"` on concurrent runs. Debounce on the client.
263
263
  In Intelligence mode you can additionally handle `code === "agent_thread_locked"` in
264
- `<CopilotKitProvider onError>`; SSE mode surfaces only a generic 500 with that message.
264
+ `<CopilotKit onError>`; SSE mode surfaces only a generic 500 with that message.
265
265
 
266
266
  Source: `packages/runtime/src/v2/runtime/runner/in-memory.ts:110`;
267
267
  `packages/core/src/intelligence-agent.ts:368-369`.
@@ -299,6 +299,6 @@ Source: `packages/runtime/src/v2/runtime/runner/in-memory.ts:63-96`.
299
299
 
300
300
  ## See also
301
301
 
302
- - `copilotkit/intelligence-mode` — managed durability alternative (Cloud-only)
302
+ - `copilotkit/intelligence-mode` — managed durability alternative (CopilotKit Intelligence managed service, not self-hostable)
303
303
  - `copilotkit/setup-endpoint` — runner is passed via the CopilotRuntime constructor
304
304
  - `copilotkit/scale-to-multi-agent` — horizontal scaling considerations
@@ -7,7 +7,7 @@ stabilizing and `organizationId` is reserved for future self-hosted deployments.
7
7
  need on-prem durable threads today, use SSE mode with a persistent runner
8
8
  (`SqliteAgentRunner` or a custom one) instead.
9
9
 
10
- Obtain `apiKey` and `organizationId` from the CopilotKit Cloud dashboard.
10
+ Obtain `apiKey` and `organizationId` from the CopilotKit Intelligence dashboard.
11
11
 
12
12
  ### URL format
13
13
 
@@ -40,8 +40,8 @@ import {
40
40
  const intelligence = new CopilotKitIntelligence({
41
41
  apiUrl: "https://api.copilotkit.ai",
42
42
  wsUrl: "wss://api.copilotkit.ai",
43
- apiKey: process.env.COPILOTKIT_CLOUD_API_KEY!,
44
- organizationId: process.env.COPILOTKIT_CLOUD_ORG_ID!,
43
+ apiKey: process.env.COPILOTKIT_INTELLIGENCE_API_KEY!,
44
+ organizationId: process.env.COPILOTKIT_INTELLIGENCE_ORG_ID!,
45
45
  });
46
46
 
47
47
  const runtime = new CopilotRuntime({
@@ -134,14 +134,10 @@ and an `intelligence.wsUrl`, `CopilotKitCore` auto-switches from SSE to the webs
134
134
  transport. The React integration just points at the runtime URL:
135
135
 
136
136
  ```tsx
137
- import { CopilotKitProvider } from "@copilotkit/react-core/v2";
137
+ import { CopilotKit } from "@copilotkit/react-core/v2";
138
138
 
139
139
  export function App({ children }: { children: React.ReactNode }) {
140
- return (
141
- <CopilotKitProvider runtimeUrl="/api/copilotkit">
142
- {children}
143
- </CopilotKitProvider>
144
- );
140
+ return <CopilotKit runtimeUrl="/api/copilotkit">{children}</CopilotKit>;
145
141
  }
146
142
  ```
147
143
 
@@ -197,8 +193,8 @@ Correct:
197
193
  new CopilotKitIntelligence({
198
194
  apiUrl: "https://api.copilotkit.ai",
199
195
  wsUrl: "wss://api.copilotkit.ai",
200
- apiKey: process.env.COPILOTKIT_CLOUD_API_KEY!,
201
- organizationId: process.env.COPILOTKIT_CLOUD_ORG_ID!,
196
+ apiKey: process.env.COPILOTKIT_INTELLIGENCE_API_KEY!,
197
+ organizationId: process.env.COPILOTKIT_INTELLIGENCE_ORG_ID!,
202
198
  });
203
199
  // For on-prem durability without Intelligence: SSE mode + SqliteAgentRunner.
204
200
  ```
@@ -242,7 +238,7 @@ new CopilotRuntime({
242
238
  ```
243
239
 
244
240
  `CopilotIntelligenceRuntimeOptions` excludes `runner` at the type level. Intelligence
245
- forces its own `IntelligenceAgentRunner` tied to the Cloud WebSocket; a user-supplied
241
+ forces its own `IntelligenceAgentRunner` tied to the Intelligence service WebSocket; a user-supplied
246
242
  runner is rejected.
247
243
 
248
244
  Source: `packages/runtime/src/v2/runtime/core/runtime.ts:149-173,285-294`.
@@ -325,7 +321,7 @@ new CopilotRuntime({
325
321
  ```
326
322
 
327
323
  `generateThreadNames` defaults to `true`. Every newly created thread triggers an extra
328
- LLM call on the Cloud side to generate a short name, billed against your Cloud quota.
324
+ LLM call on the Intelligence service side to generate a short name, billed against your Intelligence quota.
329
325
 
330
326
  Source: `packages/runtime/src/v2/runtime/core/runtime.ts` (generateThreadNames default).
331
327
 
@@ -436,7 +436,7 @@ fetch("/api/copilotkit", {
436
436
  body: input,
437
437
  }),
438
438
  });
439
- // On the client, pair with <CopilotKitProvider useSingleEndpoint />.
439
+ // On the client, pair with <CopilotKit useSingleEndpoint /> from "@copilotkit/react-core/v2".
440
440
  ```
441
441
 
442
442
  Single-route expects a POST envelope with `{ method, params, body }`; URL-pattern calls 404.
@@ -1,9 +1,10 @@
1
- Agno — wired via `@ag-ui/agno`. Requires an `/agui` URL suffix.
1
+ Agno — wired via the generic `HttpAgent` from `@ag-ui/client`. Requires an `/agui` URL
2
+ suffix.
2
3
 
3
4
  ## Install
4
5
 
5
6
  ```bash
6
- pnpm add @ag-ui/agno
7
+ pnpm add @ag-ui/client
7
8
  ```
8
9
 
9
10
  ## Minimal wire-up
@@ -13,11 +14,11 @@ import {
13
14
  CopilotRuntime,
14
15
  createCopilotRuntimeHandler,
15
16
  } from "@copilotkit/runtime/v2";
16
- import { AgnoAgent } from "@ag-ui/agno";
17
+ import { HttpAgent } from "@ag-ui/client";
17
18
 
18
19
  const runtime = new CopilotRuntime({
19
20
  agents: {
20
- default: new AgnoAgent({
21
+ default: new HttpAgent({
21
22
  url: process.env.AGNO_URL ?? "http://localhost:8000/agui",
22
23
  }),
23
24
  },
@@ -3,20 +3,20 @@
3
3
  `CopilotRuntime` takes any `AbstractAgent` subclass. Every framework below ships a
4
4
  ready-made subclass you construct and hand to `agents: { ... }`.
5
5
 
6
- | Framework | Package | Construct |
7
- | ------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
8
- | Mastra | `@ag-ui/mastra` | `MastraAgent.getLocalAgents({ mastra, resourceId? })` (record; `resourceId` required only when the agent has Memory enabled) |
9
- | LangGraph | `@ag-ui/langgraph` | `new LangGraphAgent({ deploymentUrl, graphId })` |
10
- | CrewAI Crews | `@ag-ui/crewai` | `new CrewAIAgent({ url })` |
11
- | CrewAI Flows | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
12
- | PydanticAI | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
13
- | Google ADK | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
14
- | LlamaIndex | `@ag-ui/llamaindex` | `new LlamaIndexAgent({ url: ".../run" })` (`/run` suffix) |
15
- | Agno | `@ag-ui/agno` | `new AgnoAgent({ url: ".../agui" })` (`/agui` suffix) |
16
- | AWS Strands | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
17
- | Microsoft Agent Framework | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
18
- | AG2 | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
19
- | A2A | `@ag-ui/a2a` | `new A2AAgent({ a2aClient })` (pre-built `A2AClient`, not a URL) |
6
+ | Framework | Package | Construct |
7
+ | ------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
8
+ | Mastra | `@ag-ui/mastra` | `MastraAgent.getLocalAgents({ mastra, resourceId? })` (record; `resourceId` required only when the agent has Memory enabled) |
9
+ | LangGraph | `@copilotkit/runtime/langgraph` | `new LangGraphAgent({ deploymentUrl, graphId })` |
10
+ | CrewAI Crews | `@ag-ui/crewai` | `new CrewAIAgent({ url })` |
11
+ | CrewAI Flows | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
12
+ | PydanticAI | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
13
+ | Google ADK | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
14
+ | LlamaIndex | `@ag-ui/llamaindex` | `new LlamaIndexAgent({ url: ".../run" })` (`/run` suffix) |
15
+ | Agno | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url: ".../agui" })` (`/agui` suffix) |
16
+ | AWS Strands | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
17
+ | Microsoft Agent Framework | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
18
+ | AG2 | `@ag-ui/client` (HttpAgent) | `new HttpAgent({ url })` |
19
+ | A2A | `@ag-ui/a2a` | `new A2AAgent({ a2aClient })` (pre-built `A2AClient`, not a URL) |
20
20
 
21
21
  MCP Apps is NOT a framework — it's a runtime middleware:
22
22
  `new CopilotRuntime({ agents, mcpApps: { servers: [...] } })`. See
@@ -85,7 +85,7 @@ import {
85
85
  CopilotRuntime,
86
86
  createCopilotRuntimeHandler,
87
87
  } from "@copilotkit/runtime/v2";
88
- import { LangGraphAgent } from "@ag-ui/langgraph";
88
+ import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
89
89
 
90
90
  const runtime = new CopilotRuntime({
91
91
  agents: {
@@ -114,7 +114,7 @@ import {
114
114
  CopilotRuntime,
115
115
  createCopilotRuntimeHandler,
116
116
  } from "@copilotkit/runtime/v2";
117
- import { LangGraphAgent } from "@ag-ui/langgraph";
117
+ import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
118
118
  import { CrewAIAgent } from "@ag-ui/crewai";
119
119
  import { HttpAgent } from "@ag-ui/client";
120
120
 
@@ -170,7 +170,7 @@ export default { fetch: handler };
170
170
  Wrong:
171
171
 
172
172
  ```typescript
173
- import { LangGraphAgent } from "@ag-ui/langgraph";
173
+ import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
174
174
 
175
175
  new LangGraphAgent({ deploymentUrl: "/api/copilotkit", graphId: "agent" });
176
176
  ```
@@ -221,17 +221,17 @@ Wrong:
221
221
 
222
222
  ```typescript
223
223
  import { LlamaIndexAgent } from "@ag-ui/llamaindex";
224
- import { AgnoAgent } from "@ag-ui/agno";
224
+ import { HttpAgent } from "@ag-ui/client";
225
225
 
226
226
  new LlamaIndexAgent({ url: "http://localhost:8000" });
227
- new AgnoAgent({ url: "http://localhost:8000" });
227
+ new HttpAgent({ url: "http://localhost:8000" });
228
228
  ```
229
229
 
230
230
  Correct:
231
231
 
232
232
  ```typescript
233
233
  new LlamaIndexAgent({ url: "http://localhost:8000/run" });
234
- new AgnoAgent({ url: "http://localhost:8000/agui" });
234
+ new HttpAgent({ url: "http://localhost:8000/agui" });
235
235
  ```
236
236
 
237
237
  LlamaIndex requires a `/run` suffix, Agno requires `/agui`. The generic HttpAgent fallback
@@ -1,11 +1,10 @@
1
- LangGraph — wired via `@ag-ui/langgraph`. Supports LangGraph Platform deployments and
2
- self-hosted LangGraph servers.
1
+ LangGraph — wired via `@copilotkit/runtime/langgraph`. Supports LangGraph Platform
2
+ deployments and self-hosted LangGraph servers.
3
3
 
4
4
  ## Install
5
5
 
6
- ```bash
7
- pnpm add @ag-ui/langgraph
8
- ```
6
+ `LangGraphAgent` (and `LangGraphHttpAgent` for self-hosted AG-UI LangGraph servers)
7
+ ship with `@copilotkit/runtime` — no separate install needed.
9
8
 
10
9
  ## Minimal wire-up
11
10
 
@@ -14,7 +13,7 @@ import {
14
13
  CopilotRuntime,
15
14
  createCopilotRuntimeHandler,
16
15
  } from "@copilotkit/runtime/v2";
17
- import { LangGraphAgent } from "@ag-ui/langgraph";
16
+ import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
18
17
 
19
18
  const runtime = new CopilotRuntime({
20
19
  agents: {