copilotkit 0.1.0
copilotkit: ^0.1.0 copied to clipboard
Pure Dart core of the CopilotKit SDK. Connects to a Copilot Runtime over AG-UI to run agents, frontend tools, shared state and threads.
CopilotKit #
Developed with 💙 by Very Good Ventures 🦄
The pure Dart core of the CopilotKit SDK. It
connects to a Copilot Runtime over AG-UI to run agents, frontend tools,
shared state and threads, with no Flutter dependency. For a Flutter app, use
copilotkit_flutter, which
re-exports this package.
Installation 💻 #
Requires Dart 3.13 or later.
dart pub add copilotkit
Messages #
The conversation is CopilotAgentState.messages, a list of Messages:
UserMessage, AssistantMessage (text, tool calls or both),
SystemMessage, DeveloperMessage and ToolMessage. They're
copilotkit models: the SDK talks to the runtime over AG-UI, but doesn't
expose ag_ui types, so apps don't depend on ag_ui. A message the SDK
doesn't model, like reasoning, is kept as an UnsupportedMessage and sent
back to the runtime unchanged.
await client.runAgent(
'default',
message: UserMessage(id: const Uuid().v4(), content: 'Hi'),
);
for (final message in client.agent('default').state.messages) {
switch (message) {
case UserMessage(:final content):
print('user: $content');
case AssistantMessage(:final content, :final toolCalls):
print('assistant: ${content ?? ''} (${toolCalls.length} tool calls)');
case _:
break;
}
}
Shared state #
An agent's CopilotAgentState.sharedState is sent with every run as the
run's state, and the agent updates it with STATE_SNAPSHOT and
STATE_DELTA events. The app edits it through the agent:
client.agent('default')
..setSharedState(const SharedState({'theme': 'dark'}))
..patchSharedState(const [StatePatchAdd(path: '/units', value: 'metric')])
..setMessages([]); // e.g. to reset the conversation
await client.runAgent('default'); // sends the edits above
Edits apply right away, so the next run sends them. A snapshot from the
runtime replaces a local edit, like in the AG-UI client. patchSharedState
takes RFC 6902 operations; when one does not apply the state stays as it was
and a FormatException is thrown.
Tools #
Register a ClientTool with client.registerTool; the client sends every
registered tool to the agent on each run. There are two kinds:
FrontendToolruns a handler in the app and sends its result back. Without a handler the result is'';followUp: falseends the turn instead of running the agent again.HumanInTheLoopToolhas no handler: the result is the user's answer.
A tool's parameters is an ack schema.
copilotkit doesn't re-export ack, so add it to your app with
dart pub add ack and import it:
import 'package:ack/ack.dart';
client.registerTool(HumanInTheLoopTool(
name: 'confirmAction',
description: 'Ask the user to confirm an action before doing it.',
parameters: Ack.object({'action': Ack.string()}),
decode: ConfirmAction.fromJson,
));
When the agent calls a human-in-the-loop tool and its run has finished
streaming, the call is marked with ToolCallView.awaitingResponse and listed
in CopilotAgentState.awaitingResponseIds. The turn waits until the app calls
respondToToolCall for the call, whenever the user decides; a String
result is sent as it is, anything else JSON-encoded. The answer becomes the
tool message and the agent runs again, unless the tool sets followUp: false.
client.respondToToolCall(call.id, {'decision': 'approve'});
The agent's isRunning stays true while a call waits, because the turn is
still open (runAgent does nothing and returns false until it ends); use
awaitingResponseIds to tell the agent waits for the user. Stopping the agent
answers the call as cancelled, so a stop always ends the turn. So does
unregistering the tool while a call waits. Several calls can wait together
and be answered in any order. An answer for an unknown, already answered or
non-human-in-the-loop call is ignored. See
ADR 0009.
Trajectories #
Warning
Experimental. Trajectories are in early access on CopilotKit Intelligence
and need the project to be enabled for them. Without that, the channel
join is refused with entitlement_unavailable and capture stops. The
batch and receipt format is taken from CopilotKit's docs and hasn't been
tested against a live project yet, so it may change.
A trajectory records what the user does in the app, for Automatic Learning: Intelligence links it to the threads the user ran and learns from both.
await client.startTrajectory(); // completes with the id, or null
client.emitTrajectoryEvent('deal.approved', {'dealId': 'd-1'});
await client.stopTrajectory();
Events are batched and sent over the runtime's real-time service: every
2 seconds, at 50 events, or before 64 KiB, with 16 KiB per event at most.
Each thread an agent runs on while capturing is linked to the trajectory.
Problems, such as a project without trajectories
(TRAJECTORIES_NOT_ENABLED), go to onError as a TrajectoryException.
A dropped connection reconnects; a refusal ends the capture. Names of
TrajectoryBuiltInEvents are kept for the SDK's own collectors.
Web and CORS #
The core has no dart:io dependency and runs on the web, compiled to
JavaScript or WebAssembly: package:http uses fetch there (BrowserClient),
which streams the response body, so events arrive as the runtime sends them,
and stopping a run aborts the request. The core needs http 1.6.0 or later,
which fixes cancelling a response body that is waiting for data.
A browser only lets a page call a runtime on another origin when the runtime
allows it with CORS headers. Every run and stop is a POST with
Content-Type: application/json, so the browser first sends a preflight
OPTIONS request to agent/<id>/run and agent/<id>/stop/<thread>. The
runtime has to answer it, and the real responses, with:
| Header | Value |
|---|---|
Access-Control-Allow-Origin |
The origin of the app, e.g. https://app.example.com, or * |
Access-Control-Allow-Methods |
POST, OPTIONS |
Access-Control-Allow-Headers |
content-type, plus every header your headers builder returns, such as authorization or x-session-id |
- Name
authorizationexplicitly:Access-Control-Allow-Headers: *does not cover it, so a runtime that only answers*rejects requests that carry a bearer token. Access-Control-Allow-Origin: *can't be combined with credentials: a browser rejects a credentialed response with a wildcard origin, so a runtime that allows credentials must answer with the exact origin. The SDK does not send cookies (withCredentialsis off), so authenticate with theheadersbuilder instead.- The runtime must not buffer the event stream: it answers with
Cache-Control: no-cache, and a proxy or CDN in front of it must pass the chunks through, or events arrive in one batch at the end. - A browser keeps at most six HTTP/1.1 connections per origin and each running agent holds one open, so serve the runtime over HTTP/2 when an app runs several agents at once.
The Copilot Runtime sets these headers with cors: true, which allows every
origin and * headers (not authorization, see above), and takes a config
for anything stricter:
createCopilotNodeListener({
runtime,
basePath: '/api/copilotkit',
cors: {
origin: ['https://app.example.com'],
allowHeaders: ['content-type', 'authorization', 'x-session-id'],
},
});
Contributing #
To run the tests and the checks CI runs, see CONTRIBUTING.md.