@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 +10 -8
- package/dist/index.d.mts +197 -219
- package/dist/index.mjs +574 -784
- package/dist/v1.d.mts +278 -0
- package/dist/v1.mjs +931 -0
- package/package.json +2 -2
- package/dist/v2.d.mts +0 -256
- package/dist/v2.mjs +0 -721
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@economic/agents",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "A starter for creating a TypeScript package.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"exports": {
|
|
16
16
|
".": "./dist/index.mjs",
|
|
17
17
|
"./cli": "./dist/cli.mjs",
|
|
18
|
-
"./
|
|
18
|
+
"./v1": "./dist/v1.mjs",
|
|
19
19
|
"./package.json": "./package.json"
|
|
20
20
|
},
|
|
21
21
|
"scripts": {
|
package/dist/v2.d.mts
DELETED
|
@@ -1,256 +0,0 @@
|
|
|
1
|
-
import { t as JwtAuthConfig } from "./index-DzOC3mNl.mjs";
|
|
2
|
-
import { JSONValue, LanguageModel, Tool as Tool$1, UIMessage } from "ai";
|
|
3
|
-
import { Agent as Agent$1, Connection, ConnectionContext, SubAgentClass } from "agents";
|
|
4
|
-
import { ChatResponseResult, Session, StepConfig, Think, ToolCallContext, ToolCallDecision, TurnConfig, TurnContext } from "@cloudflare/think";
|
|
5
|
-
//#region src/server/v2/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`.ext = AgentToolContext<MyBody>;
|
|
10
|
-
* ```
|
|
11
|
-
*/
|
|
12
|
-
type ToolContext<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext = Record<string, unknown> | undefined> = RequestContext & {
|
|
13
|
-
_userContext?: UserContext;
|
|
14
|
-
};
|
|
15
|
-
interface AgentEnv {
|
|
16
|
-
AGENT_DB: D1Database;
|
|
17
|
-
AGENTS_AUDIT_LOGS: R2Bucket;
|
|
18
|
-
AGENTS_ANALYTICS: AnalyticsEngineDataset;
|
|
19
|
-
SKILLS_BUCKET: R2Bucket;
|
|
20
|
-
}
|
|
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
|
-
};
|
|
29
|
-
//#endregion
|
|
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>;
|
|
36
|
-
//#endregion
|
|
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;
|
|
51
|
-
protected clientIp?: string;
|
|
52
|
-
protected forwardedFor?: string;
|
|
53
|
-
/**
|
|
54
|
-
* Returns the user ID from the durable object name.
|
|
55
|
-
*/
|
|
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>;
|
|
63
|
-
onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
|
|
64
|
-
/**
|
|
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.
|
|
70
|
-
*/
|
|
71
|
-
beforeTurn(ctx: TurnContext): Promise<void | TurnConfig>;
|
|
72
|
-
/**
|
|
73
|
-
* Sets active tools based on skills that might be loaded in the current turn.
|
|
74
|
-
*
|
|
75
|
-
* @param ctx - The prepare step context.
|
|
76
|
-
* @returns The step config.
|
|
77
|
-
*/
|
|
78
|
-
beforeStep(): Promise<StepConfig | void>;
|
|
79
|
-
beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void>;
|
|
80
|
-
private _buildToolContext;
|
|
81
|
-
getTools(): ToolSet;
|
|
82
|
-
/**
|
|
83
|
-
* Returns the remote skills to be loaded from SKILLS_BUCKET.
|
|
84
|
-
* @returns The remote skills to be loaded from SKILLS_BUCKET.
|
|
85
|
-
*/
|
|
86
|
-
protected getRemoteSkills(): string[];
|
|
87
|
-
/**
|
|
88
|
-
* Returns the skills to load for the agent.
|
|
89
|
-
* @returns The skills to load for the agent.
|
|
90
|
-
*/
|
|
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?;
|
|
96
|
-
/**
|
|
97
|
-
* Override to enable JWT authentication on WebSocket connections.
|
|
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.
|
|
100
|
-
*
|
|
101
|
-
* @param env - The worker environment variables
|
|
102
|
-
* @returns JWT auth config or undefined to skip authentication
|
|
103
|
-
*/
|
|
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?;
|
|
107
|
-
/**
|
|
108
|
-
* The user context for the session.
|
|
109
|
-
* Define getUserContext to set a user context.
|
|
110
|
-
*/
|
|
111
|
-
private _userContext?;
|
|
112
|
-
/**
|
|
113
|
-
* Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
|
|
114
|
-
* This method should not have side effects - return a single object from it.
|
|
115
|
-
* @returns The user context from the request.
|
|
116
|
-
* @param jwtToken - A valid JWT token following authentication.
|
|
117
|
-
*/
|
|
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 {
|
|
139
|
-
exportForMigration(): Promise<{
|
|
140
|
-
messages: UIMessage[];
|
|
141
|
-
}>;
|
|
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
|
-
}>;
|
|
179
|
-
//#endregion
|
|
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>;
|
|
186
|
-
/**
|
|
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.
|
|
191
|
-
*/
|
|
192
|
-
submitMessageFeedback(messageId: string, rating: number, comment?: string): Promise<void>;
|
|
193
|
-
/**
|
|
194
|
-
* Returns all message feedback for the current chat.
|
|
195
|
-
* @returns All message feedback for the current chat.
|
|
196
|
-
*/
|
|
197
|
-
getMessageFeedback(): Promise<Record<string, MessageFeedback>>;
|
|
198
|
-
/**
|
|
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.
|
|
209
|
-
*/
|
|
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>;
|
|
240
|
-
/**
|
|
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.
|
|
245
|
-
*/
|
|
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;
|
|
254
|
-
}
|
|
255
|
-
//#endregion
|
|
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 };
|