@economic/agents 2.3.9 → 2.3.12

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
@@ -571,5 +571,3 @@ npm install
571
571
  npm test
572
572
  npm run build
573
573
  ```
574
-
575
- .
package/dist/index.d.mts CHANGED
@@ -25,11 +25,6 @@ interface AgentEnv {
25
25
  type SqlFn = InstanceType<typeof Agent$1>["sql"];
26
26
  type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized";
27
27
  type AgentConnectionType = "agent" | "chat" | "assistant";
28
- type AgentConnectionState = {
29
- status: AgentConnectionStatus;
30
- type: AgentConnectionType; /** Set by `Assistant` so clients can derive the sub-agent routing name from state. */
31
- subAgentName?: string;
32
- };
33
28
  //#endregion
34
29
  //#region src/server/util/tools.d.ts
35
30
  type ToolSet = Record<string, Tool>;
@@ -39,8 +34,8 @@ type Tool<Context extends Record<string, unknown> = Record<string, unknown>, INP
39
34
  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>;
40
35
  //#endregion
41
36
  //#region src/server/agents/Agent.d.ts
42
- 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> {
43
- initialState: AgentConnectionState;
37
+ declare abstract class Agent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>, State = unknown> extends Think<Cloudflare.Env & AgentEnv, State> {
38
+ protected agentType: AgentConnectionType;
44
39
  protected clientIp?: string;
45
40
  protected forwardedFor?: string;
46
41
  /**
@@ -51,7 +46,6 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
51
46
  abstract getModel(ctx?: ToolContext<RequestContext, UserContext>): LanguageModel;
52
47
  abstract getSystemPrompt(ctx?: ToolContext<RequestContext, UserContext>): string;
53
48
  onStart(): Promise<void>;
54
- onClose(): Promise<void>;
55
49
  onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
56
50
  configureSession(session: Session): Session;
57
51
  private _toolsForCurrentTurn;
@@ -181,8 +175,8 @@ declare function migrateUserFromV1(deps: MigrationDeps): Promise<{
181
175
  }>;
182
176
  //#endregion
183
177
  //#region src/server/agents/ChatAgent.d.ts
184
- declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Agent<RequestContext, UserContext> {
185
- initialState: AgentConnectionState;
178
+ declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>, State = unknown> extends Agent<RequestContext, UserContext, State> {
179
+ protected agentType: AgentConnectionType;
186
180
  onStart(): Promise<void>;
187
181
  configureSession(session: Session): Session;
188
182
  onChatResponse(_result: ChatResponseResult): Promise<void>;
@@ -224,12 +218,11 @@ type Chat = {
224
218
  declare const DELETE_CHAT_CALLBACK: "deleteChatCallback";
225
219
  //#endregion
226
220
  //#region src/server/agents/Assistant.d.ts
227
- declare abstract class Assistant extends Agent$1<Cloudflare.Env & AgentEnv, AgentConnectionState> {
228
- initialState: AgentConnectionState;
229
- protected abstract agent: SubAgentClass<ChatAgent>;
221
+ declare abstract class Assistant<State = unknown> extends Agent$1<Cloudflare.Env & AgentEnv, State> {
222
+ private _fix;
230
223
  protected abstract fastModel: LanguageModel;
224
+ protected abstract agent: SubAgentClass<ChatAgent>;
231
225
  onStart(): void;
232
- onClose(): Promise<void>;
233
226
  onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
234
227
  createChat(): Promise<string>;
235
228
  deleteChat(id: string): Promise<void>;
@@ -285,4 +278,4 @@ declare function skill<Context extends Record<string, unknown> = Record<string,
285
278
  //#region src/server/index.d.ts
286
279
  declare function getCurrentToolContext(): any;
287
280
  //#endregion
288
- export { Agent, type AgentConnectionState, type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, Assistant, ChatAgent, type FacetStub, type LegacyChatStub, type LegacyMessageFeedback, type MigrationDeps, type Skill, type SkillSource, type Tool, type ToolContext, type ToolSet, getCurrentToolContext, migrateUserFromV1, routeAgentRequest, skill, tool };
281
+ export { Agent, type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, Assistant, ChatAgent, type FacetStub, type LegacyChatStub, type LegacyMessageFeedback, type MigrationDeps, type Skill, type SkillSource, type Tool, type ToolContext, type ToolSet, getCurrentToolContext, migrateUserFromV1, routeAgentRequest, skill, tool };
package/dist/index.mjs CHANGED
@@ -36,12 +36,23 @@ async function registerAgentInstance(db, input) {
36
36
  ON CONFLICT (agent_name, durable_object_name) DO NOTHING`).bind(input.agentName, input.durableObjectName, input.actorId, input.createdAt).run();
37
37
  }
38
38
  //#endregion
39
+ //#region src/server/util/agent.ts
40
+ function sendConnectionStatus(connection, status) {
41
+ connection.send(JSON.stringify({
42
+ type: "connection_status",
43
+ status
44
+ }));
45
+ }
46
+ function sendAgentType(connection, agentType) {
47
+ connection.send(JSON.stringify({
48
+ type: "agent_type",
49
+ agentType
50
+ }));
51
+ }
52
+ //#endregion
39
53
  //#region src/server/agents/Agent.ts
40
54
  var Agent = class extends Think {
41
- initialState = {
42
- status: "connecting",
43
- type: "agent"
44
- };
55
+ agentType = "agent";
45
56
  clientIp;
46
57
  forwardedFor;
47
58
  /**
@@ -58,10 +69,6 @@ var Agent = class extends Think {
58
69
  }
59
70
  }
60
71
  async onStart() {
61
- this.setState({
62
- ...this.initialState,
63
- status: "connecting"
64
- });
65
72
  let hasCorrectBindings = true;
66
73
  if (!this.env.AGENTS_DB) {
67
74
  hasCorrectBindings = false;
@@ -72,22 +79,12 @@ var Agent = class extends Think {
72
79
  console.error("[Agent] Connection rejected: no AGENTS_AUDIT_LOGS bound. Audit logs are required.");
73
80
  }
74
81
  if (!this.env.AGENTS_ANALYTICS) console.warn("[Agent] No AGENTS_ANALYTICS bound. Analytics will not be collected.");
75
- if (!hasCorrectBindings) {
76
- this.setState({
77
- ...this.initialState,
78
- status: "disconnected"
79
- });
80
- throw new Error("Could not connect to agent, bindings not found");
81
- }
82
+ if (!hasCorrectBindings) throw new Error("Could not connect to agent, bindings not found");
82
83
  this.registerInstance();
83
84
  }
84
- async onClose() {
85
- this.setState({
86
- ...this.initialState,
87
- status: "disconnected"
88
- });
89
- }
90
85
  async onConnect(connection, ctx) {
86
+ sendAgentType(connection, this.agentType);
87
+ sendConnectionStatus(connection, "connecting");
91
88
  this.clientIp = ctx.request.headers.get("CF-Connecting-IP") ?? ctx.request.headers.get("X-Forwarded-For")?.split(",")[0]?.trim();
92
89
  this.forwardedFor = ctx.request.headers.get("X-Forwarded-For") ?? void 0;
93
90
  const getJwtAuthConfig = this.constructor.getJwtAuthConfig;
@@ -98,37 +95,24 @@ var Agent = class extends Think {
98
95
  try {
99
96
  result = await verifyJwt(ctx.request, config);
100
97
  } catch (error) {
101
- this.setState({
102
- ...this.initialState,
103
- status: "unauthorized"
104
- });
98
+ sendConnectionStatus(connection, "unauthorized");
105
99
  console.error(`[Agent] JWT verification error - ${error}`);
106
100
  connection.close(4001, "Unauthorized");
107
101
  return;
108
102
  }
109
103
  if (!result.success) {
110
- this.setState({
111
- ...this.initialState,
112
- status: "unauthorized"
113
- });
104
+ sendConnectionStatus(connection, "unauthorized");
114
105
  console.error(`[Agent] JWT verification error - ${result.message}`);
115
106
  connection.close(result.status === 401 ? 4001 : 4003, result.message);
116
107
  return;
117
108
  }
118
- connection.setState({
119
- authenticated: true,
120
- claims: result.claims
121
- });
122
109
  const token = extractTokenFromConnectRequest(ctx.request);
123
110
  if (token && this.getUserContext) this._pendingUserContextRequest = this.getUserContext(token).then((userContext) => {
124
111
  this.userContext = userContext;
125
112
  });
126
113
  }
127
114
  }
128
- this.setState({
129
- ...this.initialState,
130
- status: "connected"
131
- });
115
+ sendConnectionStatus(connection, "connected");
132
116
  }
133
117
  configureSession(session) {
134
118
  return session.withContext("soul", { provider: { get: async () => {
@@ -629,39 +613,20 @@ var Assistant = class extends Agent$1 {
629
613
  ]
630
614
  ], 0, void 0, Agent$1).e;
631
615
  }
632
- initialState = (_initProto$1(this), {
633
- status: "connecting",
634
- type: "assistant"
635
- });
616
+ _fix = (_initProto$1(this), "fix");
636
617
  onStart() {
637
- this.setState({
638
- ...this.initialState,
639
- status: "connecting",
640
- subAgentName: this.agent.name
641
- });
642
618
  ensureChatsTableExists(this.sql.bind(this));
643
619
  let hasCorrectBindings = true;
644
620
  if (!this.env.AGENTS_DB) {
645
621
  hasCorrectBindings = false;
646
622
  console.warn("[Agent] Connection rejected: no AGENTS_DB bound. Agents database is required for registration.");
647
623
  }
648
- if (!hasCorrectBindings) {
649
- this.setState({
650
- ...this.initialState,
651
- status: "disconnected"
652
- });
653
- throw new Error("Could not connect to agent, bindings not found");
654
- }
624
+ if (!hasCorrectBindings) throw new Error("Could not connect to agent, bindings not found");
655
625
  this.registerInstance();
656
626
  }
657
- async onClose() {
658
- this.setState({
659
- ...this.initialState,
660
- status: "disconnected",
661
- subAgentName: this.agent.name
662
- });
663
- }
664
627
  async onConnect(connection, ctx) {
628
+ sendAgentType(connection, "assistant");
629
+ sendConnectionStatus(connection, "connecting");
665
630
  const getJwtAuthConfig = this.agent.getJwtAuthConfig;
666
631
  if (getJwtAuthConfig) {
667
632
  const config = getJwtAuthConfig(this.env);
@@ -670,37 +635,21 @@ var Assistant = class extends Agent$1 {
670
635
  try {
671
636
  result = await verifyJwt(ctx.request, config);
672
637
  } catch (error) {
673
- this.setState({
674
- ...this.initialState,
675
- status: "unauthorized",
676
- subAgentName: this.agent.name
677
- });
638
+ sendConnectionStatus(connection, "unauthorized");
678
639
  console.error(`[Assistant] JWT verification error - ${error}`);
679
640
  connection.close(4001, "Unauthorized");
680
641
  return;
681
642
  }
682
643
  if (!result.success) {
683
- this.setState({
684
- ...this.initialState,
685
- status: "unauthorized",
686
- subAgentName: this.agent.name
687
- });
644
+ sendConnectionStatus(connection, "unauthorized");
688
645
  console.error(`[Assistant] JWT verification error - ${result.message}`);
689
646
  connection.close(result.status === 401 ? 4001 : 4003, result.message);
690
647
  return;
691
648
  }
692
- connection.setState({
693
- authenticated: true,
694
- claims: result.claims
695
- });
696
649
  }
697
650
  }
698
651
  await this.ensureMigrated();
699
- this.setState({
700
- ...this.initialState,
701
- status: "connected",
702
- subAgentName: this.agent.name
703
- });
652
+ sendConnectionStatus(connection, "connected");
704
653
  }
705
654
  async createChat() {
706
655
  const id = nanoid();
@@ -997,10 +946,7 @@ var ChatAgent = class extends Agent {
997
946
  "getMessageFeedback"
998
947
  ]], 0, void 0, Agent).e;
999
948
  }
1000
- initialState = (_initProto(this), {
1001
- status: "connecting",
1002
- type: "chat"
1003
- });
949
+ agentType = (_initProto(this), "chat");
1004
950
  async onStart() {
1005
951
  await super.onStart();
1006
952
  ensureFeedbackTableExists(this.sql.bind(this));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@economic/agents",
3
- "version": "2.3.9",
3
+ "version": "2.3.12",
4
4
  "description": "A starter for creating a TypeScript package.",
5
5
  "license": "MIT",
6
6
  "files": [