@economic/agents 2.1.7 → 2.2.0

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.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Our agents SDK for building AI agents on Cloudflare Workers. Each agent is a Dur
4
4
 
5
5
  React client: [`@economic/agents-react`](../react/README.md).
6
6
 
7
- > Covers **v2** (`@economic/agents/v2`). The v1 root API (`ChatAgentHarness`, `buildLLMParams`) is deprecated, kept only for migration, and removed in v3.
7
+ > The v1 (`@economic/agents/v1`) API (`ChatAgentHarness`, `buildLLMParams`) is deprecated, kept only for migration, and removed in v3.
8
8
 
9
9
  ## The three classes
10
10
 
@@ -33,7 +33,7 @@ Subclass `Agent` and implement `getModel` and `getSystemPrompt`. Add tools with
33
33
  ```typescript
34
34
  import { openai } from "@ai-sdk/openai";
35
35
  import { callable } from "agents";
36
- import { Agent, tool, type ToolSet } from "@economic/agents/v2";
36
+ import { Agent, tool, type ToolSet } from "@economic/agents";
37
37
  import { z } from "zod";
38
38
 
39
39
  export class SupportAgent extends Agent {
@@ -121,7 +121,7 @@ For a chat UI, extend `ChatAgent` instead of `Agent`. It adds compaction and mes
121
121
 
122
122
  ```typescript
123
123
  import { openai } from "@ai-sdk/openai";
124
- import { ChatAgent } from "@economic/agents/v2";
124
+ import { ChatAgent } from "@economic/agents";
125
125
  import { weatherSkill } from "./skills/weather";
126
126
 
127
127
  export class MyChatAgent extends ChatAgent {
@@ -165,7 +165,7 @@ When one user needs a list of conversations — a sidebar, titles, summaries —
165
165
 
166
166
  ```typescript
167
167
  import { openai } from "@ai-sdk/openai";
168
- import { Assistant } from "@economic/agents/v2";
168
+ import { Assistant } from "@economic/agents";
169
169
  import { MyChatAgent } from "./chat-agent";
170
170
 
171
171
  export class MyAssistant extends Assistant {
@@ -210,7 +210,7 @@ Checked in `Agent.onStart` when a connection opens:
210
210
  `tool()` wraps an `ai` SDK tool with an optional `authorize(ctx)`. Return always-on tools from `getTools()`:
211
211
 
212
212
  ```typescript
213
- import { tool, type ToolSet } from "@economic/agents/v2";
213
+ import { tool, type ToolSet } from "@economic/agents";
214
214
  import { z } from "zod";
215
215
 
216
216
  getTools(): ToolSet {
@@ -232,7 +232,7 @@ getTools(): ToolSet {
232
232
  The tool context is the second argument to `execute` — `experimental_context`:
233
233
 
234
234
  ```typescript
235
- import { tool, type ToolContext } from "@economic/agents/v2";
235
+ import { tool, type ToolContext } from "@economic/agents";
236
236
  import { z } from "zod";
237
237
 
238
238
  interface RequestBody {
@@ -256,7 +256,7 @@ const call_api = tool({
256
256
  A skill bundles markdown `instructions` with optional tools. Only `description` sits in the system prompt; the model loads the instructions and tools on demand via the built-in `load_context` tool.
257
257
 
258
258
  ```typescript
259
- import { skill, tool } from "@economic/agents/v2";
259
+ import { skill, tool } from "@economic/agents";
260
260
  import { z } from "zod";
261
261
 
262
262
  export const weatherSkill = skill({
@@ -343,7 +343,7 @@ Emitted per turn from the `ai` SDK's OpenTelemetry spans, no setup beyond bindin
343
343
 
344
344
  ## API reference
345
345
 
346
- Imported from `@economic/agents/v2` unless noted.
346
+ Imported from `@economic/agents` unless noted.
347
347
 
348
348
  ### Classes
349
349
 
@@ -392,3 +392,5 @@ npm install
392
392
  npm test
393
393
  npm run build
394
394
  ```
395
+
396
+ .
package/dist/index.d.mts CHANGED
@@ -1,278 +1,256 @@
1
1
  import { t as JwtAuthConfig } from "./index-DzOC3mNl.mjs";
2
- import { LanguageModel, StreamTextOnFinishCallback, ToolSet, UIMessage, generateText, streamText } from "ai";
3
- import { Agent as Agent$1, AgentOptions, Connection, ConnectionContext } from "agents";
4
- import { AIChatAgent, ChatResponseResult, OnChatMessageOptions } from "@cloudflare/ai-chat";
5
-
6
- //#region src/server/shared/features/skills/index.d.ts
7
- /**
8
- * A named group of related tools that can be loaded together on demand.
9
- *
10
- * The agent starts with only its always-on tools active. When the LLM calls
11
- * activate_skill with a skill name, that skill's tools become available for
12
- * the rest of the conversation.
13
- */
14
- interface Skill {
15
- name: string;
16
- /** One-line description shown in the activate_skill tool schema */
17
- description: string;
18
- /**
19
- * Guidance text for this skill — e.g. rate limits, preferred patterns,
20
- * when to use each tool. Injected into the `## Tools` section of the
21
- * system prompt via `buildSystemPrompt` in `llm.ts` whenever this skill
22
- * is loaded.
23
- */
24
- guidance?: string;
25
- tools: ToolSet;
26
- }
27
- //#endregion
28
- //#region src/server/shared/util/llm.d.ts
29
- type LLMParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0];
30
- type BuildLLMParamsConfig = Omit<LLMParams, "prompt"> & {
31
- /** Skill names loaded in previous turns. Pass `await this.getLoadedSkills()`. */activeSkills?: string[]; /** Skills available for on-demand loading this turn. */
32
- skills?: Skill[];
33
- };
34
- /**
35
- * Builds the parameter object for a Vercel AI SDK `streamText` or `generateText` call.
36
- *
37
- * Handles skill wiring (`activate_skill`, `list_capabilities`, `prepareStep`).
38
- *
39
- * The returned object can be spread directly into `streamText` or `generateText`:
40
- *
41
- * ```typescript
42
- * const params = buildLLMParams({ ... });
43
- * return streamText(params).toUIMessageStreamResponse();
44
- * ```
45
- */
46
- declare function buildLLMParams(config: BuildLLMParamsConfig): LLMParams;
47
- //#endregion
48
- //#region src/server/v1/types.d.ts
2
+ import { ChatResponseResult, Session, StepConfig, Think, ToolCallContext, ToolCallDecision, TurnConfig, TurnContext } from "@cloudflare/think";
3
+ import { JSONValue, LanguageModel, Tool as Tool$1, UIMessage } from "ai";
4
+ import { Agent as Agent$1, Connection, ConnectionContext, SubAgentClass } from "agents";
5
+ //#region src/server/v2/types.d.ts
49
6
  /**
50
7
  * The context object available throughout an agent's lifetime — passed via
51
- * `experimental_context` to tool `execute` functions.
52
- *
53
- * Define your own body shape and compose:
54
- * ```typescript
55
- * interface MyBody { userTier: "free" | "pro" }
56
- * type MyContext = AgentToolContext<MyBody>;
8
+ * `experimental_context` to tool `execute` functions. Contains the typed
9
+ * request body merged with platform capabilities like `logEvent`.ext = AgentToolContext<MyBody>;
57
10
  * ```
58
11
  */
59
- type AgentToolContext<TBody = Record<string, unknown>, TUserContext = Record<string, unknown> | undefined> = TBody & {
60
- _userContext?: TUserContext;
12
+ type ToolContext<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext = Record<string, unknown> | undefined> = RequestContext & {
13
+ _userContext?: UserContext;
61
14
  };
62
15
  interface AgentEnv {
63
16
  AGENT_DB: D1Database;
64
17
  AGENTS_AUDIT_LOGS: R2Bucket;
65
18
  AGENTS_ANALYTICS: AnalyticsEngineDataset;
19
+ SKILLS_BUCKET: R2Bucket;
66
20
  }
67
- interface ChatAgentEnv extends AgentEnv {}
21
+ type SqlFn = InstanceType<typeof Agent$1>["sql"];
22
+ type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized";
23
+ type AgentConnectionType = "agent" | "chat" | "assistant";
24
+ type AgentConnectionState = {
25
+ status: AgentConnectionStatus;
26
+ type: AgentConnectionType; /** Set by `Assistant` so clients can derive the sub-agent routing name from state. */
27
+ subAgentName?: string;
28
+ };
68
29
  //#endregion
69
- //#region src/server/v1/route-agent-request.d.ts
70
- declare function routeAgentRequest<Env>(request: Request, env: Env, options?: AgentOptions<Env>): Promise<Response | null>;
30
+ //#region src/server/v2/util/tools.d.ts
31
+ type ToolSet = Record<string, Tool>;
32
+ type Tool<Context extends Record<string, unknown> = Record<string, unknown>, INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = Tool$1<INPUT, OUTPUT> & {
33
+ authorize?: (ctx: Context) => boolean;
34
+ };
35
+ declare function tool<Context extends Record<string, unknown> = Record<string, unknown>, INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any>(tool: Tool<Context, INPUT, OUTPUT>): Tool$1<INPUT, OUTPUT>;
71
36
  //#endregion
72
- //#region src/server/v1/agent/Agent.d.ts
73
- /**
74
- * Base agent for Cloudflare Agents SDK Durable Objects with lazy skill loading
75
- * and `buildLLMParams` wiring.
76
- *
77
- * Handles CF infrastructure concerns: DO SQLite persistence for loaded skill state.
78
- *
79
- * For chat agents with message history, compaction, and conversation recording,
80
- * extend {@link ChatAgent} instead.
81
- */
82
- declare abstract class Agent<Env extends Cloudflare.Env = Cloudflare.Env, TUserContext extends Record<string, unknown> = Record<string, unknown>> extends Agent$1<Env & AgentEnv> {
37
+ //#region src/server/v2/util/skills.d.ts
38
+ interface Skill<Context extends Record<string, unknown> = Record<string, unknown>> {
39
+ name: string;
40
+ description: string;
41
+ instructions: string;
42
+ tools?: Record<string, Tool<Context>>;
43
+ authorize?: (ctx: Context) => boolean;
44
+ }
45
+ declare function skill<Context extends Record<string, unknown> = Record<string, unknown>>(definition: Skill<Context>): Skill<Context>;
46
+ //#endregion
47
+ //#region src/server/v2/agents/Agent.d.ts
48
+ declare function getCurrentToolContext(): any;
49
+ declare abstract class Agent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Think<Cloudflare.Env & AgentEnv, AgentConnectionState> {
50
+ initialState: AgentConnectionState;
83
51
  protected clientIp?: string;
84
52
  protected forwardedFor?: string;
85
- /**
86
- * Override to enable JWT authentication on WebSocket connections.
87
- * Return the auth config based on the incoming request, or undefined to skip auth.
88
- *
89
- * @param request - The WebSocket upgrade request
90
- * @returns JWT auth config or undefined to skip authentication
91
- */
92
- protected getJwtAuthConfig?(request: Request): JwtAuthConfig<Record<string, unknown>> | undefined;
93
- /**
94
- * The user context for the session.
95
- * Define getUserContext to set a user context.
96
- */
97
- protected get userContext(): TUserContext;
98
- /**
99
- * Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
100
- * This method should not have side effects - return a single object from it.
101
- * @returns The user context from the request.
102
- * @param jwtToken - A valid JWT token following authentication.
103
- */
104
- protected getUserContext?(jwtToken: string): Promise<TUserContext>;
105
53
  /**
106
54
  * Returns the user ID from the durable object name.
107
55
  */
108
- protected getUserId(): string;
56
+ protected getActorIdFromDurableObjectName(): string;
57
+ protected getParentAgent<T extends Agent$1>(): T | undefined;
58
+ abstract getModel(ctx?: ToolContext<RequestContext, UserContext>): LanguageModel;
59
+ abstract getSystemPrompt(ctx?: ToolContext<RequestContext, UserContext>): string;
60
+ configureSession(session: Session): Session;
61
+ onStart(): Promise<void>;
62
+ onClose(): Promise<void>;
109
63
  onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
110
64
  /**
111
- * Builds the parameter object for a `streamText` or `generateText` call,
112
- * pre-filling `activeSkills` from this agent instance.
113
- */
114
- protected buildLLMParams<TBody = Record<string, unknown>>(config: Omit<BuildLLMParamsConfig, "messages"> & {
115
- options?: OnChatMessageOptions;
116
- }): Promise<LLMParams>;
117
- }
118
- //#endregion
119
- //#region src/server/v1/agent-chat/features/conversations/rating.d.ts
120
- interface MessageRating {
121
- rating: number;
122
- comment?: string;
123
- }
124
- //#endregion
125
- //#region src/server/v1/agent-chat/ChatAgent.d.ts
126
- /**
127
- * Chat agent for Cloudflare Agents SDK: lazy skill loading, message persistence,
128
- * compaction, and conversation metadata in D1.
129
- *
130
- * Handles CF infrastructure concerns: DO SQLite for loaded skill state,
131
- * stripping skill meta-tool messages before persistence, and history replay to
132
- * newly connected clients.
133
- *
134
- * Skill loading, compaction, and LLM calls use `buildLLMParams` from
135
- * `@economic/agents` inside `onChatMessage`.
136
- */
137
- declare abstract class ChatAgent<Env extends Cloudflare.Env = Cloudflare.Env, TUserContext extends Record<string, unknown> = Record<string, unknown>> extends AIChatAgent<Env & ChatAgentEnv> {
138
- initialState: {
139
- status: string;
140
- type: string;
141
- };
142
- /**
143
- * The binding of the Durable Object instance for this agent.
65
+ * Merges the client request `body` into `experimental_context` for tools
66
+ * returned from {@link getTools} only (Think-internal tools are unchanged).
67
+ *
68
+ * If you override `beforeTurn`, call `super.beforeTurn(ctx)` and merge
69
+ * `returned.tools` into your own `TurnConfig.tools` if you return tools.
144
70
  */
145
- protected abstract get binding(): {
146
- getByName(name: string): {
147
- destroy(): Promise<void>;
148
- };
149
- };
71
+ beforeTurn(ctx: TurnContext): Promise<void | TurnConfig>;
150
72
  /**
151
- * Fast/cheap language model used for background tasks: compaction and conversation summarization.
152
- *
153
- * Declare this on every subclass:
73
+ * Sets active tools based on skills that might be loaded in the current turn.
154
74
  *
155
- * ```typescript
156
- * protected fastModel = google("gemini-2.0-flash");
157
- * ```
158
- *
159
- * To disable compaction for a specific call, pass `maxMessagesBeforeCompaction: undefined`
160
- * to `buildLLMParams` rather than omitting or nulling out `fastModel`.
75
+ * @param ctx - The prepare step context.
76
+ * @returns The step config.
161
77
  */
162
- protected abstract getFastModel(): LanguageModel;
78
+ beforeStep(): Promise<StepConfig | void>;
79
+ beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void>;
80
+ private _buildToolContext;
81
+ getTools(): ToolSet;
163
82
  /**
164
- * Number of days of inactivity before the full conversation is deleted.
165
- *
166
- * Leave `undefined` to disable automatic retention cleanup.
83
+ * Returns the remote skills to be loaded from SKILLS_BUCKET.
84
+ * @returns The remote skills to be loaded from SKILLS_BUCKET.
167
85
  */
168
- protected conversationRetentionDays?: number;
86
+ protected getRemoteSkills(): string[];
169
87
  /**
170
- * Number of recent messages to keep verbatim when compaction runs.
171
- * Older messages beyond this count are summarised into a single system message.
172
- * Used as the default when `maxMessagesBeforeCompaction` is not provided to `buildLLMParams`.
173
- *
174
- * Default is 15.
88
+ * Returns the skills to load for the agent.
89
+ * @returns The skills to load for the agent.
175
90
  */
176
- protected maxMessagesBeforeCompaction?: number | undefined;
177
- protected clientIp?: string;
178
- protected forwardedFor?: string;
91
+ protected getSkills(): Skill[];
92
+ private _getAuthorizedTools;
93
+ private _getAuthorizedSkills;
94
+ /** Store the pending user context request to defer awaiting it until after the connection is established */
95
+ private _requestContext?;
179
96
  /**
180
97
  * Override to enable JWT authentication on WebSocket connections.
181
98
  * Return the auth config based on the incoming request, or undefined to skip auth.
99
+ * Do not add side effects to this method - return a single JwtAuthConfig from it.
182
100
  *
183
- * @param request - The WebSocket upgrade request
101
+ * @param env - The worker environment variables
184
102
  * @returns JWT auth config or undefined to skip authentication
185
103
  */
186
- protected getJwtAuthConfig?(request: Request): JwtAuthConfig<Record<string, unknown>> | undefined;
104
+ static getJwtAuthConfig?(env: Cloudflare.Env): JwtAuthConfig<Record<string, unknown>> | undefined;
105
+ /** Store the pending user context request to defer awaiting it until after the connection is established */
106
+ private _pendingUserContextRequest?;
187
107
  /**
188
108
  * The user context for the session.
189
109
  * Define getUserContext to set a user context.
190
110
  */
191
- protected get userContext(): TUserContext;
111
+ private _userContext?;
192
112
  /**
193
113
  * Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
194
114
  * This method should not have side effects - return a single object from it.
195
115
  * @returns The user context from the request.
196
116
  * @param jwtToken - A valid JWT token following authentication.
197
117
  */
198
- protected getUserContext?(jwtToken: string): Promise<TUserContext>;
199
- /**
200
- * Returns the user ID from the durable object name.
201
- */
202
- protected getUserId(): string;
203
- onStart(): void;
204
- onClose(): Promise<void>;
205
- onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
206
- protected _pendingUserContextRequest?: Promise<void>;
207
- /**
208
- * Builds the parameter object for a `streamText` or `generateText` call,
209
- * pre-filling `messages`, `activeSkills`, and `fastModel` from this agent instance.
210
- *
211
- * **Compaction** runs automatically when `fastModel` is set on the class, using
212
- * `DEFAULT_MAX_MESSAGES_BEFORE_COMPACTION` (30) as the threshold. Override the
213
- * threshold by setting `maxMessagesBeforeCompaction` on the class. Disable compaction
214
- * entirely by setting `maxMessagesBeforeCompaction = undefined` explicitly.
215
- */
216
- protected buildLLMParams<TBody = Record<string, unknown>>(config: BuildLLMParamsConfig & {
217
- options?: OnChatMessageOptions;
218
- }): Promise<LLMParams>;
219
- persistMessages(messages: UIMessage[], excludeBroadcastIds?: string[], options?: {
220
- _deleteStaleRows?: boolean;
221
- }): Promise<void>;
222
- protected onChatResponse(result: ChatResponseResult): Promise<void>;
223
- rateMessage(messageId: string, rating: number, comment?: string): Promise<void>;
224
- getMessageRatings(): Promise<Record<string, MessageRating>>;
225
- getConversations(): Promise<Record<string, unknown>[]>;
226
- /**
227
- * Exports this conversation's persisted message history for the v1 -> v2
228
- * migration. Called over DO RPC by the v2 `Assistant` while migrating a
229
- * user's chats into facets. `this.messages` is loaded from the
230
- * `cf_ai_chat_agent_messages` table when the DO wakes.
231
- *
232
- * Read-only: does not mutate or delete any state.
233
- */
118
+ protected getUserContext?(jwtToken: string): Promise<UserContext>;
119
+ }
120
+ //#endregion
121
+ //#region src/server/v2/features/messages.d.ts
122
+ type MessageFeedback = {
123
+ message_id: string;
124
+ rating: number;
125
+ comment?: string;
126
+ created_at: number;
127
+ updated_at: number;
128
+ };
129
+ //#endregion
130
+ //#region src/server/v2/features/migration.d.ts
131
+ /** Per-message feedback carried over from a v1 conversation during migration. */
132
+ type LegacyMessageFeedback = {
133
+ messageId: string;
134
+ rating: number;
135
+ comment?: string;
136
+ };
137
+ /** Minimal RPC surface of a v1 chat DO needed to read its history. */
138
+ interface LegacyChatStub {
234
139
  exportForMigration(): Promise<{
235
140
  messages: UIMessage[];
236
141
  }>;
237
- deleteConversation(id: string): Promise<boolean>;
238
- destroy(): Promise<void>;
239
- private deleteConversationCallback;
240
- private scheduleConversationForAutoDeletion;
241
142
  }
143
+ /** Minimal RPC surface of a freshly created v2 chat facet needed to seed history. */
144
+ interface FacetStub {
145
+ importLegacyMessages(messages: UIMessage[], feedback: LegacyMessageFeedback[]): Promise<void>;
146
+ }
147
+ /**
148
+ * Dependencies for {@link migrateUserFromV1}, injected by the `Assistant` so
149
+ * this module never needs to touch the DO's protected members directly.
150
+ */
151
+ type MigrationDeps = {
152
+ /** The `Assistant` DO's bound `sql` tag (used to register migrated chats). */sql: SqlFn; /** Shared D1 database holding v1 `conversations` and `message_ratings`. */
153
+ db: D1Database; /** The user being migrated (the `Assistant` DO name). */
154
+ userId: string; /** Resolves a v1 chat DO stub by its `userId:chatId` name. */
155
+ legacyNamespace: {
156
+ getByName(name: string): LegacyChatStub;
157
+ }; /** Creates (or resolves) a v2 chat facet for the given chat id and returns its stub. */
158
+ createFacet: (chatId: string) => Promise<FacetStub>;
159
+ };
160
+ /**
161
+ * Migrates all of a user's v1 chats into v2 facets, lazily and idempotently.
162
+ *
163
+ * v1 chats are enumerated from the shared D1 `conversations` table (DOs cannot
164
+ * be listed directly). For each chat we read its persisted messages from the v1
165
+ * DO over RPC, create a fresh facet, seed its history and feedback, register it
166
+ * on the parent `Assistant` with its original title/summary/timestamps, and
167
+ * finally delete the v1 `conversations` (+ `message_ratings`) rows.
168
+ *
169
+ * The conversations row IS the to-do marker: deleting it last means a migrated
170
+ * chat never reappears, while a chat that errored keeps its row and is simply
171
+ * retried on the next connection. No extra bookkeeping tables are needed. The
172
+ * v1 DO is left untouched and self-expires via v1 retention, so its messages
173
+ * remain as a backstop until then.
174
+ */
175
+ declare function migrateUserFromV1(deps: MigrationDeps): Promise<{
176
+ migrated: number;
177
+ failed: number;
178
+ }>;
242
179
  //#endregion
243
- //#region src/server/v1/agent-chat/ChatAgentHarness.d.ts
244
- declare abstract class ChatAgentHarness<Env extends Cloudflare.Env, RequestBody extends Record<string, unknown> = Record<string, unknown>, SessionIdentity extends Record<string, unknown> = Record<string, unknown>> extends ChatAgent<Env, SessionIdentity> {
245
- get binding(): {
246
- getByName(name: string): {
247
- destroy(): Promise<void>;
248
- };
249
- };
250
- conversationRetentionDays: number;
180
+ //#region src/server/v2/agents/ChatAgent.d.ts
181
+ declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Agent<RequestContext, UserContext> {
182
+ initialState: AgentConnectionState;
183
+ onStart(): Promise<void>;
184
+ configureSession(session: Session): Session;
185
+ onChatResponse(_result: ChatResponseResult): Promise<void>;
251
186
  /**
252
- * Returns the model for the agent.
253
- * @param ctx - The context object for the agent built from the request body.
254
- * @returns The model for the agent.
187
+ * Submit feedback for a message by its id.
188
+ * @param messageId - The id of the message to give feedback on.
189
+ * @param rating - The rating to give the message. 1 = thumbs up, -1 = thumbs down.
190
+ * @returns The message id and the rating.
255
191
  */
256
- abstract getModel(ctx: AgentToolContext<RequestBody>): LanguageModel;
192
+ submitMessageFeedback(messageId: string, rating: number, comment?: string): Promise<void>;
257
193
  /**
258
- * Returns the system prompt for the agent.
259
- * @param ctx - The context object for the agent built from the request body.
260
- * @returns The system prompt for the agent.
194
+ * Returns all message feedback for the current chat.
195
+ * @returns All message feedback for the current chat.
261
196
  */
262
- abstract getSystemPrompt(ctx: AgentToolContext<RequestBody>): string;
197
+ getMessageFeedback(): Promise<Record<string, MessageFeedback>>;
263
198
  /**
264
- * Returns the tools for the agent.
265
- * @param ctx - The context object for the agent built from the request body.
266
- * @returns The tools for the agent.
199
+ * Imports a v1 conversation's history into this facet's session storage.
200
+ *
201
+ * Called over DO RPC by the v2 `Assistant` during the lazy v1 -> v2
202
+ * migration. Messages are appended in order as a single linear thread
203
+ * (each message parented to the previous one) using
204
+ * `appendMessageToHistory`, which writes durably to the session WITHOUT
205
+ * triggering a model turn. Any carried-over feedback is then written to
206
+ * `assistant_messages_feedback`.
207
+ *
208
+ * Safe to skip persisting if there is nothing to import.
267
209
  */
268
- getTools(_ctx: AgentToolContext<RequestBody>): ToolSet;
210
+ importLegacyMessages(messages: UIMessage[], feedback?: LegacyMessageFeedback[]): Promise<void>;
211
+ }
212
+ //#endregion
213
+ //#region src/server/v2/features/chats.d.ts
214
+ type Chat = {
215
+ durable_object_name: string;
216
+ title?: string;
217
+ summary?: string;
218
+ created_at: number;
219
+ updated_at: number;
220
+ };
221
+ declare const DELETE_CHAT_CALLBACK: "deleteChatCallback";
222
+ //#endregion
223
+ //#region src/server/v2/agents/Assistant.d.ts
224
+ declare abstract class Assistant extends Agent$1<Cloudflare.Env, AgentConnectionState> {
225
+ initialState: AgentConnectionState;
226
+ protected abstract agent: SubAgentClass<ChatAgent>;
227
+ protected abstract fastModel: LanguageModel;
228
+ /**
229
+ * Binding name of the legacy v1 chat Durable Object class, used to migrate a
230
+ * user's v1 chats into facets the first time they connect. Set this on the
231
+ * concrete subclass to enable lazy v1 -> v2 migration; leave undefined to
232
+ * disable it (e.g. for greenfield deployments with no v1 data).
233
+ */
234
+ protected legacyBinding?: keyof Cloudflare.Env;
235
+ /** In-flight migration, shared across concurrent connections to this DO. */
236
+ private _migrationPromise?;
237
+ onStart(): void;
238
+ onClose(): Promise<void>;
239
+ onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
269
240
  /**
270
- * Returns the skills for the agent.
271
- * @param ctx - The context object for the agent built from the request body.
272
- * @returns The skills for the agent.
241
+ * Runs the lazy v1 -> v2 migration for this user. Concurrent connections to
242
+ * this DO share a single in-flight run. Idempotency across runs/restarts is
243
+ * handled by `migrateUserFromV1` deleting each chat's v1 `conversations` row,
244
+ * so an already-migrated chat is never re-enumerated.
273
245
  */
274
- getSkills(_ctx: AgentToolContext<RequestBody>): Skill[];
275
- onChatMessage(onFinish: StreamTextOnFinishCallback<ToolSet>, options?: OnChatMessageOptions): Promise<Response>;
246
+ private ensureMigrated;
247
+ private runMigration;
248
+ createChat(): Promise<string>;
249
+ deleteChat(id: string): Promise<void>;
250
+ getChats(): Promise<Chat[]>;
251
+ recordChatTurn(durableObjectName: string, messages: UIMessage[]): Promise<void>;
252
+ private [DELETE_CHAT_CALLBACK];
253
+ private scheduleChatForAutoDeletion;
276
254
  }
277
255
  //#endregion
278
- export { Agent, type AgentToolContext, type BuildLLMParamsConfig, ChatAgent, ChatAgentHarness, type Skill, buildLLMParams, routeAgentRequest };
256
+ export { Agent, type AgentConnectionState, type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, Assistant, ChatAgent, type FacetStub, type LegacyChatStub, type LegacyMessageFeedback, type MigrationDeps, type Skill, type Tool, type ToolContext, type ToolSet, getCurrentToolContext, migrateUserFromV1, skill, tool };