@economic/agents 2.1.6 → 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/dist/v1.d.mts ADDED
@@ -0,0 +1,278 @@
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
49
+ /**
50
+ * 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>;
57
+ * ```
58
+ */
59
+ type AgentToolContext<TBody = Record<string, unknown>, TUserContext = Record<string, unknown> | undefined> = TBody & {
60
+ _userContext?: TUserContext;
61
+ };
62
+ interface AgentEnv {
63
+ AGENT_DB: D1Database;
64
+ AGENTS_AUDIT_LOGS: R2Bucket;
65
+ AGENTS_ANALYTICS: AnalyticsEngineDataset;
66
+ }
67
+ interface ChatAgentEnv extends AgentEnv {}
68
+ //#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>;
71
+ //#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> {
83
+ protected clientIp?: string;
84
+ 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
+ /**
106
+ * Returns the user ID from the durable object name.
107
+ */
108
+ protected getUserId(): string;
109
+ onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
110
+ /**
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.
144
+ */
145
+ protected abstract get binding(): {
146
+ getByName(name: string): {
147
+ destroy(): Promise<void>;
148
+ };
149
+ };
150
+ /**
151
+ * Fast/cheap language model used for background tasks: compaction and conversation summarization.
152
+ *
153
+ * Declare this on every subclass:
154
+ *
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`.
161
+ */
162
+ protected abstract getFastModel(): LanguageModel;
163
+ /**
164
+ * Number of days of inactivity before the full conversation is deleted.
165
+ *
166
+ * Leave `undefined` to disable automatic retention cleanup.
167
+ */
168
+ protected conversationRetentionDays?: number;
169
+ /**
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.
175
+ */
176
+ protected maxMessagesBeforeCompaction?: number | undefined;
177
+ protected clientIp?: string;
178
+ protected forwardedFor?: string;
179
+ /**
180
+ * Override to enable JWT authentication on WebSocket connections.
181
+ * Return the auth config based on the incoming request, or undefined to skip auth.
182
+ *
183
+ * @param request - The WebSocket upgrade request
184
+ * @returns JWT auth config or undefined to skip authentication
185
+ */
186
+ protected getJwtAuthConfig?(request: Request): JwtAuthConfig<Record<string, unknown>> | undefined;
187
+ /**
188
+ * The user context for the session.
189
+ * Define getUserContext to set a user context.
190
+ */
191
+ protected get userContext(): TUserContext;
192
+ /**
193
+ * Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
194
+ * This method should not have side effects - return a single object from it.
195
+ * @returns The user context from the request.
196
+ * @param jwtToken - A valid JWT token following authentication.
197
+ */
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
+ */
234
+ exportForMigration(): Promise<{
235
+ messages: UIMessage[];
236
+ }>;
237
+ deleteConversation(id: string): Promise<boolean>;
238
+ destroy(): Promise<void>;
239
+ private deleteConversationCallback;
240
+ private scheduleConversationForAutoDeletion;
241
+ }
242
+ //#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;
251
+ /**
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.
255
+ */
256
+ abstract getModel(ctx: AgentToolContext<RequestBody>): LanguageModel;
257
+ /**
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.
261
+ */
262
+ abstract getSystemPrompt(ctx: AgentToolContext<RequestBody>): string;
263
+ /**
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.
267
+ */
268
+ getTools(_ctx: AgentToolContext<RequestBody>): ToolSet;
269
+ /**
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.
273
+ */
274
+ getSkills(_ctx: AgentToolContext<RequestBody>): Skill[];
275
+ onChatMessage(onFinish: StreamTextOnFinishCallback<ToolSet>, options?: OnChatMessageOptions): Promise<Response>;
276
+ }
277
+ //#endregion
278
+ export { Agent, type AgentToolContext, type BuildLLMParamsConfig, ChatAgent, ChatAgentHarness, type Skill, buildLLMParams, routeAgentRequest };