@economic/agents 0.0.1 → 1.0.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.
package/dist/index.d.mts CHANGED
@@ -1,7 +1,26 @@
1
- import { Connection, ConnectionContext } from "agents";
2
- import { AIChatAgent as AIChatAgent$1, OnChatMessageOptions } from "@cloudflare/ai-chat";
3
- import { LanguageModel, ToolSet, UIMessage, generateText, streamText } from "ai";
1
+ import { Agent as Agent$1, Connection, ConnectionContext } from "agents";
2
+ import { AIChatAgent, OnChatMessageOptions } from "@cloudflare/ai-chat";
3
+ import { LanguageModel, StreamTextOnFinishCallback, ToolSet, UIMessage, generateText, streamText } from "ai";
4
4
 
5
+ //#region src/server/types.d.ts
6
+ /**
7
+ * The context object available throughout an agent's lifetime — passed via
8
+ * `experimental_context` to tool `execute` functions. Contains the typed
9
+ * request body merged with platform capabilities like `logEvent`.
10
+ *
11
+ * Define your own body shape and compose:
12
+ * ```typescript
13
+ * interface MyBody { userTier: "free" | "pro" }
14
+ * type MyContext = AgentToolContext<MyBody>;
15
+ * ```
16
+ */
17
+ type AgentToolContext<TBody = Record<string, unknown>> = TBody & {
18
+ logEvent: (message: string, payload?: Record<string, unknown>) => void | Promise<void>;
19
+ };
20
+ interface AgentEnv {
21
+ AGENT_DB: D1Database;
22
+ }
23
+ //#endregion
5
24
  //#region src/server/features/skills/index.d.ts
6
25
  /**
7
26
  * A named group of related tools that can be loaded together on demand.
@@ -44,22 +63,64 @@ type BuildLLMParamsConfig = Omit<LLMParams, "prompt"> & {
44
63
  */
45
64
  declare function buildLLMParams(config: BuildLLMParamsConfig): LLMParams;
46
65
  //#endregion
47
- //#region src/server/agents/AIChatAgent.d.ts
48
- interface AIChatAgentEnv {
49
- AGENT_DB: D1Database;
66
+ //#region src/server/agents/Agent.d.ts
67
+ /**
68
+ * Base agent for Cloudflare Agents SDK Durable Objects with lazy skill loading,
69
+ * audit logging, and `buildLLMParams` wiring.
70
+ *
71
+ * Handles CF infrastructure concerns: DO SQLite persistence for loaded skill state
72
+ * and writing audit events to D1.
73
+ *
74
+ * For chat agents with message history, compaction, and conversation recording,
75
+ * extend {@link ChatAgent} instead.
76
+ */
77
+ declare abstract class Agent<Env extends Cloudflare.Env = Cloudflare.Env> extends Agent$1<Env & AgentEnv> {
78
+ /**
79
+ * Returns the user ID from the durable object name.
80
+ */
81
+ protected getUserId(): string;
82
+ onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
83
+ /**
84
+ * Writes an audit event to D1 if `AGENT_DB` is bound on the environment,
85
+ * otherwise silently does nothing.
86
+ *
87
+ * Called automatically at the end of each LLM turn (from `onFinish` in
88
+ * `buildLLMParams`). Also available via `experimental_context.logEvent` in tool
89
+ * `execute` functions.
90
+ */
91
+ protected logEvent(message: string, payload?: Record<string, unknown>): Promise<void>;
92
+ /**
93
+ * Builds the parameter object for a `streamText` or `generateText` call,
94
+ * pre-filling `activeSkills` from this agent instance.
95
+ * Injects `logEvent` into `experimental_context` and wires `onFinish` for
96
+ * turn-completed audit events.
97
+ */
98
+ protected buildLLMParams<TBody = Record<string, unknown>>(config: Omit<BuildLLMParamsConfig, "messages"> & {
99
+ options?: OnChatMessageOptions;
100
+ }): Promise<LLMParams>;
50
101
  }
102
+ //#endregion
103
+ //#region src/server/agents/ChatAgent.d.ts
51
104
  /**
52
- * Base class for Cloudflare Agents SDK chat agents with lazy skill loading
53
- * and built-in audit logging.
105
+ * Chat agent for Cloudflare Agents SDK: lazy skill loading, audit logging,
106
+ * message persistence, compaction, and conversation metadata in D1.
54
107
  *
55
- * Handles CF infrastructure concerns only: DO SQLite persistence for loaded
56
- * skill state, stripping skill meta-tool messages before persistence, history
57
- * replay to newly connected clients, and writing audit events to D1.
108
+ * Handles CF infrastructure concerns: DO SQLite for loaded skill state,
109
+ * stripping skill meta-tool messages before persistence, history replay to
110
+ * newly connected clients, and audit events to D1.
58
111
  *
59
- * Skill loading, compaction, and LLM communication are delegated to
60
- * `buildLLMParams` from `@economic/agents`, which you call inside `onChatMessage`.
112
+ * Skill loading, compaction, and LLM calls use `buildLLMParams` from
113
+ * `@economic/agents` inside `onChatMessage`.
61
114
  */
62
- declare abstract class AIChatAgent<Env extends Cloudflare.Env & AIChatAgentEnv = Cloudflare.Env & AIChatAgentEnv> extends AIChatAgent$1<Env> {
115
+ declare abstract class ChatAgent<Env extends Cloudflare.Env = Cloudflare.Env> extends AIChatAgent<Env & AgentEnv> {
116
+ /**
117
+ * The binding of the Durable Object instance for this agent.
118
+ */
119
+ protected abstract get binding(): {
120
+ getByName(name: string): {
121
+ destroy(): Promise<void>;
122
+ };
123
+ };
63
124
  /**
64
125
  * Fast/cheap language model used for background tasks: compaction and conversation summarization.
65
126
  *
@@ -72,7 +133,7 @@ declare abstract class AIChatAgent<Env extends Cloudflare.Env & AIChatAgentEnv =
72
133
  * To disable compaction for a specific call, pass `maxMessagesBeforeCompaction: undefined`
73
134
  * to `buildLLMParams` rather than omitting or nulling out `fastModel`.
74
135
  */
75
- protected abstract fastModel: LanguageModel;
136
+ protected abstract getFastModel(): LanguageModel;
76
137
  /**
77
138
  * Number of days of inactivity before the full conversation is deleted.
78
139
  *
@@ -96,47 +157,46 @@ declare abstract class AIChatAgent<Env extends Cloudflare.Env & AIChatAgentEnv =
96
157
  * Writes an audit event to D1 if `AGENT_DB` is bound on the environment,
97
158
  * otherwise silently does nothing.
98
159
  *
99
- * Called automatically after every turn (from `persistMessages`) and on
100
- * non-clean finish reasons (from `buildLLMParams`). Also available via
101
- * `experimental_context.log` in tool `execute` functions.
160
+ * Called automatically at the end of each LLM turn (from `onFinish` in
161
+ * `buildLLMParams`). Also available via `experimental_context.logEvent` in tool
162
+ * `execute` functions.
102
163
  */
103
- protected log(message: string, payload?: Record<string, unknown>): Promise<void>;
164
+ protected logEvent(message: string, payload?: Record<string, unknown>): Promise<void>;
104
165
  /**
105
166
  * Builds the parameter object for a `streamText` or `generateText` call,
106
167
  * pre-filling `messages`, `activeSkills`, and `fastModel` from this agent instance.
107
- * Injects `log` into `experimental_context` and logs non-clean finish reasons.
168
+ * Injects `logEvent` into `experimental_context` and wires `onFinish` for
169
+ * turn-completed audit events and conversation recording.
108
170
  *
109
171
  * **Compaction** runs automatically when `fastModel` is set on the class, using
110
172
  * `DEFAULT_MAX_MESSAGES_BEFORE_COMPACTION` (30) as the threshold. Override the
111
173
  * threshold by setting `maxMessagesBeforeCompaction` on the class. Disable compaction
112
174
  * entirely by setting `maxMessagesBeforeCompaction = undefined` explicitly.
113
- * ```
114
175
  */
115
176
  protected buildLLMParams<TBody = Record<string, unknown>>(config: BuildLLMParamsConfig & {
116
177
  options?: OnChatMessageOptions;
117
178
  }): Promise<LLMParams>;
118
179
  /**
119
180
  * Extracts skill state from activate_skill results, persists to DO SQLite,
120
- * logs a turn summary, then strips all skill meta-tool messages before
121
- * delegating to super.
181
+ * then strips all skill meta-tool messages before delegating to super.
122
182
  *
123
183
  * 1. Scans activate_skill tool results for SKILL_STATE_SENTINEL. When found,
124
184
  * the embedded JSON array of loaded skill names is written to DO SQLite.
125
185
  *
126
- * 2. Logs a turn summary via `log()`. Best-effort: fire-and-forget.
186
+ * 2. Strips all activate_skill and list_capabilities messages from history.
127
187
  *
128
- * 3. Strips all activate_skill and list_capabilities messages from history.
129
- *
130
- * 4. Delegates to super.persistMessages for message storage and WS broadcast.
188
+ * 3. Delegates to super.persistMessages for message storage and WS broadcast.
131
189
  */
132
190
  persistMessages(messages: UIMessage[], excludeBroadcastIds?: string[], options?: {
133
191
  _deleteStaleRows?: boolean;
134
192
  }): Promise<void>;
135
193
  getConversations(): Promise<Record<string, unknown>[]>;
194
+ deleteConversation(id: string): Promise<boolean>;
195
+ destroy(): Promise<void>;
136
196
  /**
137
197
  * Records this conversation in the `conversations` D1 table and triggers
138
198
  * LLM-based title/summary generation when appropriate. Called automatically
139
- * from `persistMessages` after every turn.
199
+ * from `onFinish` in `buildLLMParams` after each completed LLM turn.
140
200
  *
141
201
  * On the first turn (no existing row), awaits `generateTitleAndSummary` and
142
202
  * inserts the row with title and summary already populated. On subsequent
@@ -145,25 +205,43 @@ declare abstract class AIChatAgent<Env extends Cloudflare.Env & AIChatAgentEnv =
145
205
  * over). Neither path blocks the response to the client.
146
206
  */
147
207
  private recordConversation;
148
- private deleteConversation;
208
+ private deleteConversationCallback;
149
209
  private scheduleConversationForDeletion;
150
- private clearConversationMemoryState;
151
210
  }
152
211
  //#endregion
153
- //#region src/server/types.d.ts
154
- /**
155
- * The context object available throughout an agent's lifetime — passed via
156
- * `experimental_context` to tool `execute` functions. Contains the typed
157
- * request body merged with platform capabilities like `log`.
158
- *
159
- * Define your own body shape and compose:
160
- * ```typescript
161
- * interface MyBody { userTier: "free" | "pro" }
162
- * type MyContext = AgentToolContext<MyBody>;
163
- * ```
164
- */
165
- type AgentToolContext<TBody = Record<string, unknown>> = TBody & {
166
- log: (message: string, payload?: Record<string, unknown>) => void | Promise<void>;
167
- };
212
+ //#region src/server/harnesses/ChatAgentHarness.d.ts
213
+ declare abstract class ChatAgentHarness<Env extends Cloudflare.Env, RequestBody extends Record<string, unknown> = Record<string, unknown>> extends ChatAgent<Env> {
214
+ get binding(): {
215
+ getByName(name: string): {
216
+ destroy(): Promise<void>;
217
+ };
218
+ };
219
+ conversationRetentionDays: number;
220
+ /**
221
+ * Returns the model for the agent.
222
+ * @param ctx - The context object for the agent built from the request body.
223
+ * @returns The model for the agent.
224
+ */
225
+ abstract getModel(ctx: AgentToolContext<RequestBody>): LanguageModel;
226
+ /**
227
+ * Returns the system prompt for the agent.
228
+ * @param ctx - The context object for the agent built from the request body.
229
+ * @returns The system prompt for the agent.
230
+ */
231
+ abstract getSystemPrompt(ctx: AgentToolContext<RequestBody>): string;
232
+ /**
233
+ * Returns the tools for the agent.
234
+ * @param ctx - The context object for the agent built from the request body.
235
+ * @returns The tools for the agent.
236
+ */
237
+ getTools(_ctx: AgentToolContext<RequestBody>): ToolSet;
238
+ /**
239
+ * Returns the skills for the agent.
240
+ * @param ctx - The context object for the agent built from the request body.
241
+ * @returns The skills for the agent.
242
+ */
243
+ getSkills(_ctx: AgentToolContext<RequestBody>): Skill[];
244
+ onChatMessage(onFinish: StreamTextOnFinishCallback<ToolSet>, options?: OnChatMessageOptions): Promise<Response>;
245
+ }
168
246
  //#endregion
169
- export { AIChatAgent, type AgentToolContext, type BuildLLMParamsConfig, type Skill, buildLLMParams };
247
+ export { Agent, type AgentToolContext, type BuildLLMParamsConfig, ChatAgent, ChatAgentHarness, type Skill, buildLLMParams };