UNPKG

@copilotkit/runtime

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

504 lines 18.8 kB
import "reflect-metadata"; //#region src/v2/runtime/intelligence-platform/client.d.ts /** * Client for the CopilotKit Intelligence Platform REST API. * * Construct the client once and pass it to any consumers that need it * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`): * * ```ts * import { CopilotKitIntelligence, CopilotRuntime } from "@copilotkit/runtime"; * * const intelligence = new CopilotKitIntelligence({ * apiUrl: "https://api.copilotkit.ai", * wsUrl: "wss://api.copilotkit.ai", * apiKey: process.env.COPILOTKIT_API_KEY!, * }); * * const runtime = new CopilotRuntime({ * agents, * intelligence, * }); * ``` */ /** Payload passed to `onThreadDeleted` listeners. */ interface ThreadDeletedPayload { threadId: string; userId: string; agentId: string; } interface CopilotKitIntelligenceConfig { /** Base URL of the intelligence platform API, e.g. "https://api.copilotkit.ai" */ apiUrl: string; /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */ wsUrl: string; /** API key for authenticating with the intelligence platform */ apiKey: string; /** * Enable Enterprise Learning — expose the Intelligence platform's * built-in tools (bash + thread/memory tools) to agent runs on an * intelligence runtime that resolve a user. Attached uniformly across * agent frameworks by `attachIntelligenceEnterpriseLearning` via * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey * baked into the transport headers for that request's clone. * * Defaults to `false` — opt-in. Existing intelligence setups continue * to work without these tools unless they flip this flag. */ enableEnterpriseLearning?: boolean; /** * Initial listener invoked after a thread is created. * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners. */ onThreadCreated?: (thread: ThreadSummary) => void; /** * Initial listener invoked after a thread is updated. * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners. */ onThreadUpdated?: (thread: ThreadSummary) => void; /** * Initial listener invoked after a thread is deleted. * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners. */ onThreadDeleted?: (params: ThreadDeletedPayload) => void; } /** * Summary metadata for a single thread returned by the platform. * * This is the shape returned by list, get, create, and update operations. * It does not include the thread's message history — use * {@link CopilotKitIntelligence.getThreadMessages} for that. */ interface ThreadSummary { /** Platform-assigned unique identifier. */ id: string; /** Human-readable display name, or `null` if the thread has not been named. */ name: string | null; /** ISO-8601 timestamp of the most recent agent run on this thread. */ lastRunAt?: string; /** ISO-8601 timestamp of the most recent metadata update. */ lastUpdatedAt?: string; /** ISO-8601 timestamp when the thread was created. */ createdAt?: string; /** ISO-8601 timestamp when the thread was last updated. */ updatedAt?: string; /** Whether the thread has been archived. Archived threads are excluded from default list results. */ archived?: boolean; /** The agent that owns this thread. */ agentId?: string; /** The user who created this thread. */ createdById?: string; /** The organization this thread belongs to. */ organizationId?: string; } /** Response from listing threads for a user/agent pair. */ interface ListThreadsResponse { /** The matching threads, sorted by the platform's default ordering. */ threads: ThreadSummary[]; /** Join code for subscribing to realtime metadata updates for these threads. */ joinCode: string; /** Short-lived token for authenticating the realtime subscription. */ joinToken?: string; /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */ nextCursor?: string | null; } /** * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}. * * Additional platform-specific fields can be passed as extra keys and will be * forwarded to the PATCH request body. */ interface UpdateThreadRequest { /** New human-readable display name for the thread. */ name?: string; [key: string]: unknown; } /** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */ interface CreateThreadRequest { /** Client-generated unique identifier for the new thread. */ threadId: string; /** The user creating the thread. Used for authorization and scoping. */ userId: string; /** The agent this thread belongs to. */ agentId: string; /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */ name?: string; } /** Credentials returned when locking or joining a thread's realtime channel. */ interface ThreadConnectionResponse { /** Canonical platform thread identifier for the run or connection. */ threadId: string; /** Canonical platform run identifier for an active run lock. */ runId?: string; /** Short-lived token for authenticating the Phoenix channel join. */ joinToken: string; /** Lock metadata echoed back by the platform. */ lock?: ThreadLockInfo; } interface SubscribeToThreadsRequest { userId: string; } interface SubscribeToThreadsResponse { joinToken: string; } type ConnectThreadResponse = ThreadConnectionResponse | null; interface AcquireThreadLockResponse extends ThreadConnectionResponse { /** Canonical platform run identifier for the acquired lock. */ runId: string; } /** * Parameters for annotating a thread event via * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId` * from the customer's BFF auth before calling this; the platform prefixes * it with the project id at write time. * * `payload` is the type-specific JSON blob for the annotation (e.g. a * `"user_action"` event carries the recorded fields, a * `"set_learning_containers"` event carries the container list). The exact * shape per type is validated by the Intelligence backend; canonical shapes * are documented on the Intelligence react-core side. */ interface AnnotateParams { /** The user the annotation belongs to. */ userId: string; /** The thread the annotation is associated with. May be unknown to the platform. */ threadId: string; /** * Discriminator identifying the annotation type. * Must match a type known to the Intelligence platform * (e.g. `"user_action"`, `"set_learning_containers"`). */ type: string; /** Type-specific payload. Shape varies by `type`. */ payload?: unknown; /** * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted, * a UUID is auto-generated. Every call hits the platform's idempotent * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the * same id collapses to the original row. */ clientEventId?: string; /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */ occurredAt?: string; } /** Response from {@link CopilotKitIntelligence.annotate}. */ interface AnnotateResponse { /** Database id of the annotation row (BIGINT, returned as a string). */ id: string; /** * True when the platform recognized the `clientEventId` as a retry of * a previous call and returned the original row id instead of inserting * a new one. */ duplicate: boolean; } /** A single message within a thread's persisted history. */ interface ThreadMessage { /** Unique identifier for this message. */ id: string; /** Message role, e.g. `"user"`, `"assistant"`, `"tool"`. */ role: string; /** Text content of the message. May be absent for tool-call-only messages. */ content?: string; /** Tool calls initiated by this message (assistant role only). */ toolCalls?: Array<{ id: string; name: string; /** JSON-encoded arguments passed to the tool. */ args: string; }>; /** For tool-result messages, the ID of the tool call this message responds to. */ toolCallId?: string; } /** Response from {@link CopilotKitIntelligence.getThreadMessages}. */ interface ThreadMessagesResponse { messages: ThreadMessage[]; } /** * Persisted AG-UI event for the inspector's debugging views. The platform * stores raw events keyed by run; the `_inspect` route returns them in * replay order (oldest first) across every run that targeted the thread. */ interface ThreadInspectEvent { type: string; [key: string]: unknown; } /** * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the * `ThreadEventsResult` shape returned by the platform's * `GET /api/_inspect/threads/:id/events` endpoint. */ interface ThreadEventsResponse { events: ThreadInspectEvent[]; /** Row IDs the platform failed to decode (raw column corrupted). */ decodeErrorRowIds: string[]; /** True when the platform hit its per-thread event cap. */ truncated: boolean; } /** * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the * discriminated `ThreadStateResult` returned by the platform's * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902 * STATE_DELTA events on top of the latest STATE_SNAPSHOT. */ type ThreadStateResponse = { kind: "no-snapshot"; } | { kind: "snapshot-decode-error"; } | { kind: "snapshot"; state: unknown; skippedDeltas: number; }; interface AcquireThreadLockRequest { threadId: string; runId: string; userId: string; agentId: string; /** Custom Redis key prefix for the lock (default: "thread"). */ lockKeyPrefix?: string; /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */ ttlSeconds?: number; } interface RenewThreadLockRequest { threadId: string; runId: string; /** New TTL to set on the lock in seconds. */ ttlSeconds: number; /** Must match the prefix used when acquiring. */ lockKeyPrefix?: string; } interface CleanupThreadLockRequest { threadId: string; runId: string; } interface RenewThreadLockResponse { ttlSeconds: number; } interface ThreadLockInfo { key: string; ttlSeconds: number | null; } declare class CopilotKitIntelligence { #private; constructor(config: CopilotKitIntelligenceConfig); /** * Register a listener invoked whenever a thread is created. * * Multiple listeners can be registered. Each call returns an unsubscribe * function that removes the listener when called. * * @param callback - Receives the newly created {@link ThreadSummary}. * @returns A function that removes this listener when called. * * @example * ```ts * const unsubscribe = intelligence.onThreadCreated((thread) => { * console.log("Thread created:", thread.id); * }); * // later… * unsubscribe(); * ``` */ onThreadCreated(callback: (thread: ThreadSummary) => void): () => void; /** * Register a listener invoked whenever a thread is updated (including archive). * * Multiple listeners can be registered. Each call returns an unsubscribe * function that removes the listener when called. * * @param callback - Receives the updated {@link ThreadSummary}. * @returns A function that removes this listener when called. */ onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void; /** * Register a listener invoked whenever a thread is deleted. * * Multiple listeners can be registered. Each call returns an unsubscribe * function that removes the listener when called. * * @param callback - Receives the {@link ThreadDeletedPayload} identifying * the deleted thread. * @returns A function that removes this listener when called. */ onThreadDeleted(callback: (params: ThreadDeletedPayload) => void): () => void; ɵgetApiUrl(): string; ɵgetRunnerWsUrl(): string; ɵgetClientWsUrl(): string; ɵgetRunnerAuthToken(): string; /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */ ɵgetApiKey(): string; /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */ ɵisEnterpriseLearningEnabled(): boolean; /** * List all non-archived threads for a given user and agent. * * @param params.userId - User whose threads to list. * @param params.agentId - Agent whose threads to list. * @returns The thread list along with realtime subscription credentials. * @throws {@link PlatformRequestError} on non-2xx responses. */ listThreads(params: { userId: string; agentId: string; includeArchived?: boolean; limit?: number; cursor?: string; }): Promise<ListThreadsResponse>; ɵsubscribeToThreads(params: SubscribeToThreadsRequest): Promise<SubscribeToThreadsResponse>; /** * Update thread metadata (e.g. name). * * Triggers the `onThreadUpdated` lifecycle callback on success. * * @returns The updated thread summary. * @throws {@link PlatformRequestError} on non-2xx responses. */ updateThread(params: { threadId: string; userId: string; agentId: string; updates: UpdateThreadRequest; }): Promise<ThreadSummary>; /** * Create a new thread on the platform. * * Triggers the `onThreadCreated` lifecycle callback on success. * * @returns The newly created thread summary. * @throws {@link PlatformRequestError} with status 409 if a thread with the * same `threadId` already exists. */ createThread(params: CreateThreadRequest): Promise<ThreadSummary>; /** * Fetch a single thread by ID. * * @returns The thread summary. * @throws {@link PlatformRequestError} with status 404 if the thread does * not exist. */ getThread(params: { threadId: string; }): Promise<ThreadSummary>; /** * Get an existing thread or create it if it does not exist. * * Handles the race where a concurrent request creates the thread between * the initial 404 and the subsequent `createThread` call by catching the * 409 Conflict and retrying the get. * * Triggers the `onThreadCreated` lifecycle callback when a new thread is * created. * * @returns An object containing the thread and a `created` flag indicating * whether the thread was newly created (`true`) or already existed (`false`). * @throws {@link PlatformRequestError} on non-2xx responses other than * 404 (get) and 409 (create race). */ getOrCreateThread(params: CreateThreadRequest): Promise<{ thread: ThreadSummary; created: boolean; }>; /** * Fetch the full message history for a thread. * * @returns All persisted messages in chronological order. * @throws {@link PlatformRequestError} on non-2xx responses. */ getThreadMessages(params: { threadId: string; }): Promise<ThreadMessagesResponse>; /** * Fetch the persisted AG-UI event stream for a thread. * * Backed by the platform's `GET /api/_inspect/threads/:id/events` * introspection endpoint (see Intelligence PR #144). Events are returned * in replay order across every run that targeted the thread. The * `_inspect/` prefix flags this as debug-only — production code paths * must not depend on it. * * @throws {@link PlatformRequestError} on non-2xx responses. */ getThreadEvents(params: { threadId: string; }): Promise<ThreadEventsResponse>; /** * Fetch the current agent state for a thread. * * Backed by the platform's `GET /api/_inspect/threads/:id/state` * introspection endpoint (see Intelligence PR #144). The platform folds * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so * the returned state reflects the thread's current state — not just the * last snapshot. The discriminated response distinguishes "no snapshot * persisted yet" from "snapshot present" so consumers can render the * correct empty state. * * @throws {@link PlatformRequestError} on non-2xx responses. */ getThreadState(params: { threadId: string; }): Promise<ThreadStateResponse>; /** * Mark a thread as archived. * * Archived threads are excluded from {@link listThreads} results. * Triggers the `onThreadUpdated` lifecycle callback on success. * * @throws {@link PlatformRequestError} on non-2xx responses. */ archiveThread(params: { threadId: string; userId: string; agentId: string; }): Promise<void>; /** * Permanently delete a thread and its message history. * * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback * on success. * * @throws {@link PlatformRequestError} on non-2xx responses. */ deleteThread(params: { threadId: string; userId: string; agentId: string; }): Promise<void>; /** * Annotate a thread event on the Intelligence platform's general annotation * endpoint (`PUT /connector/annotate/:clientEventId`). * * This is the generalized replacement for the old * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports * multiple annotation types via the `type` discriminator: * - `"user_action"` — records a user UI interaction for the self-learning loop. * - `"set_learning_containers"` — sets the learning containers for a thread. * * `userId` must be resolved on the runtime side before calling this — the * platform prefixes it with the project id from the API key. * * Always hits the idempotent `PUT /connector/annotate/:clientEventId` * endpoint. A retry with the same `clientEventId` returns * `{ id: <original>, duplicate: true }` instead of creating a new row. * When `clientEventId` is omitted, a UUID is auto-generated for this call. * * @throws {@link PlatformRequestError} on non-2xx responses, OR when the * platform returns an empty 2xx body (which would otherwise corrupt the * caller's typed result). */ annotate(params: AnnotateParams): Promise<AnnotateResponse>; ɵacquireThreadLock(params: AcquireThreadLockRequest): Promise<AcquireThreadLockResponse>; ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void>; ɵrenewThreadLock(params: RenewThreadLockRequest): Promise<RenewThreadLockResponse>; ɵgetActiveJoinCode(params: { threadId: string; userId: string; }): Promise<ThreadConnectionResponse>; ɵconnectThread(params: { threadId: string; userId: string; agentId: string; }): Promise<ConnectThreadResponse>; } //#endregion export { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest }; //# sourceMappingURL=client.d.mts.map