agents 0.0.0-c3e8618 → 0.0.0-c8f53b8

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/client.js ADDED
@@ -0,0 +1,131 @@
1
+ import {
2
+ __privateAdd,
3
+ __privateGet,
4
+ __privateSet
5
+ } from "./chunk-HMLY7DHA.js";
6
+
7
+ // src/client.ts
8
+ import {
9
+ PartySocket
10
+ } from "partysocket";
11
+ function camelCaseToKebabCase(str) {
12
+ if (str === str.toUpperCase() && str !== str.toLowerCase()) {
13
+ return str.toLowerCase().replace(/_/g, "-");
14
+ }
15
+ let kebabified = str.replace(
16
+ /[A-Z]/g,
17
+ (letter) => `-${letter.toLowerCase()}`
18
+ );
19
+ kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
20
+ return kebabified.replace(/_/g, "-").replace(/-$/, "");
21
+ }
22
+ var _options, _pendingCalls;
23
+ var AgentClient = class extends PartySocket {
24
+ constructor(options) {
25
+ const agentNamespace = camelCaseToKebabCase(options.agent);
26
+ super({
27
+ prefix: "agents",
28
+ party: agentNamespace,
29
+ room: options.name || "default",
30
+ ...options
31
+ });
32
+ __privateAdd(this, _options);
33
+ __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
34
+ this.agent = agentNamespace;
35
+ this.name = options.name || "default";
36
+ __privateSet(this, _options, options);
37
+ this.addEventListener("message", (event) => {
38
+ if (typeof event.data === "string") {
39
+ let parsedMessage;
40
+ try {
41
+ parsedMessage = JSON.parse(event.data);
42
+ } catch (error) {
43
+ return;
44
+ }
45
+ if (parsedMessage.type === "cf_agent_state") {
46
+ __privateGet(this, _options).onStateUpdate?.(parsedMessage.state, "server");
47
+ return;
48
+ }
49
+ if (parsedMessage.type === "rpc") {
50
+ const response = parsedMessage;
51
+ const pending = __privateGet(this, _pendingCalls).get(response.id);
52
+ if (!pending) return;
53
+ if (!response.success) {
54
+ pending.reject(new Error(response.error));
55
+ __privateGet(this, _pendingCalls).delete(response.id);
56
+ pending.stream?.onError?.(response.error);
57
+ return;
58
+ }
59
+ if ("done" in response) {
60
+ if (response.done) {
61
+ pending.resolve(response.result);
62
+ __privateGet(this, _pendingCalls).delete(response.id);
63
+ pending.stream?.onDone?.(response.result);
64
+ } else {
65
+ pending.stream?.onChunk?.(response.result);
66
+ }
67
+ } else {
68
+ pending.resolve(response.result);
69
+ __privateGet(this, _pendingCalls).delete(response.id);
70
+ }
71
+ }
72
+ }
73
+ });
74
+ }
75
+ /**
76
+ * @deprecated Use agentFetch instead
77
+ */
78
+ static fetch(_opts) {
79
+ throw new Error(
80
+ "AgentClient.fetch is not implemented, use agentFetch instead"
81
+ );
82
+ }
83
+ setState(state) {
84
+ this.send(JSON.stringify({ type: "cf_agent_state", state }));
85
+ __privateGet(this, _options).onStateUpdate?.(state, "client");
86
+ }
87
+ /**
88
+ * Call a method on the Agent
89
+ * @param method Name of the method to call
90
+ * @param args Arguments to pass to the method
91
+ * @param streamOptions Options for handling streaming responses
92
+ * @returns Promise that resolves with the method's return value
93
+ */
94
+ async call(method, args = [], streamOptions) {
95
+ return new Promise((resolve, reject) => {
96
+ const id = Math.random().toString(36).slice(2);
97
+ __privateGet(this, _pendingCalls).set(id, {
98
+ resolve: (value) => resolve(value),
99
+ reject,
100
+ stream: streamOptions,
101
+ type: null
102
+ });
103
+ const request = {
104
+ type: "rpc",
105
+ id,
106
+ method,
107
+ args
108
+ };
109
+ this.send(JSON.stringify(request));
110
+ });
111
+ }
112
+ };
113
+ _options = new WeakMap();
114
+ _pendingCalls = new WeakMap();
115
+ function agentFetch(opts, init) {
116
+ const agentNamespace = camelCaseToKebabCase(opts.agent);
117
+ return PartySocket.fetch(
118
+ {
119
+ prefix: "agents",
120
+ party: agentNamespace,
121
+ room: opts.name || "default",
122
+ ...opts
123
+ },
124
+ init
125
+ );
126
+ }
127
+ export {
128
+ AgentClient,
129
+ agentFetch
130
+ };
131
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import {\n PartySocket,\n type PartySocketOptions,\n type PartyFetchOptions,\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nfunction camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n #options: AgentClientOptions<State>;\n #pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.#options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n this.#options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = this.#pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this.#pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this.#pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this.#pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n this.#options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n async call<T = unknown>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this.#pendingCalls.set(id, {\n resolve: (value: unknown) => resolve(value as T),\n reject,\n stream: streamOptions,\n type: null as T,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n prefix: \"agents\",\n party: agentNamespace,\n room: opts.name || \"default\",\n ...opts,\n },\n init\n );\n}\n"],"mappings":"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","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,202 +1,229 @@
1
- import { Server, Connection, PartyServerOptions } from 'partyserver';
2
- export { Connection, ConnectionContext, WSMessage } from 'partyserver';
3
- import { AsyncLocalStorage } from 'node:async_hooks';
4
- import { WorkflowEntrypoint as WorkflowEntrypoint$1 } from 'cloudflare:workers';
1
+ import { Server, Connection, PartyServerOptions } from "partyserver";
2
+ export { Connection, ConnectionContext, WSMessage } from "partyserver";
3
+ import { MCPClientManager } from "./mcp/client.js";
4
+ import "zod";
5
+ import "@modelcontextprotocol/sdk/types.js";
6
+ import "@modelcontextprotocol/sdk/client/index.js";
7
+ import "@modelcontextprotocol/sdk/client/sse.js";
8
+ import "./mcp/do-oauth-client-provider.js";
9
+ import "@modelcontextprotocol/sdk/client/auth.js";
10
+ import "@modelcontextprotocol/sdk/shared/auth.js";
11
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
12
+ import "ai";
5
13
 
6
14
  /**
7
15
  * RPC request message from client
8
16
  */
9
17
  type RPCRequest = {
10
- type: "rpc";
11
- id: string;
12
- method: string;
13
- args: unknown[];
18
+ type: "rpc";
19
+ id: string;
20
+ method: string;
21
+ args: unknown[];
14
22
  };
15
23
  /**
16
24
  * State update message from client
17
25
  */
18
26
  type StateUpdateMessage = {
19
- type: "cf_agent_state";
20
- state: unknown;
27
+ type: "cf_agent_state";
28
+ state: unknown;
21
29
  };
22
30
  /**
23
31
  * RPC response message to client
24
32
  */
25
33
  type RPCResponse = {
26
- type: "rpc";
27
- id: string;
28
- } & ({
29
- success: true;
30
- result: unknown;
31
- done?: false;
32
- } | {
33
- success: true;
34
- result: unknown;
35
- done: true;
36
- } | {
37
- success: false;
38
- error: string;
39
- });
34
+ type: "rpc";
35
+ id: string;
36
+ } & (
37
+ | {
38
+ success: true;
39
+ result: unknown;
40
+ done?: false;
41
+ }
42
+ | {
43
+ success: true;
44
+ result: unknown;
45
+ done: true;
46
+ }
47
+ | {
48
+ success: false;
49
+ error: string;
50
+ }
51
+ );
40
52
  /**
41
53
  * Metadata for a callable method
42
54
  */
43
55
  type CallableMetadata = {
44
- /** Optional description of what the method does */
45
- description?: string;
46
- /** Whether the method supports streaming responses */
47
- streaming?: boolean;
56
+ /** Optional description of what the method does */
57
+ description?: string;
58
+ /** Whether the method supports streaming responses */
59
+ streaming?: boolean;
48
60
  };
49
61
  /**
50
62
  * Decorator that marks a method as callable by clients
51
63
  * @param metadata Optional metadata about the callable method
52
64
  */
53
- declare function unstable_callable(metadata?: CallableMetadata): <This, Args extends unknown[], Return>(target: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext) => (this: This, ...args: Args) => Return;
54
- /**
55
- * A class for creating workflow entry points that can be used with Cloudflare Workers
56
- */
57
- declare class WorkflowEntrypoint extends WorkflowEntrypoint$1 {
58
- }
65
+ declare function unstable_callable(
66
+ metadata?: CallableMetadata
67
+ ): <This, Args extends unknown[], Return>(
68
+ target: (this: This, ...args: Args) => Return,
69
+ context: ClassMethodDecoratorContext
70
+ ) => (this: This, ...args: Args) => Return;
59
71
  /**
60
72
  * Represents a scheduled task within an Agent
61
73
  * @template T Type of the payload data
62
74
  */
63
75
  type Schedule<T = string> = {
64
- /** Unique identifier for the schedule */
65
- id: string;
66
- /** Name of the method to be called */
67
- callback: string;
68
- /** Data to be passed to the callback */
69
- payload: T;
70
- } & ({
71
- /** Type of schedule for one-time execution at a specific time */
72
- type: "scheduled";
73
- /** Timestamp when the task should execute */
74
- time: number;
75
- } | {
76
- /** Type of schedule for delayed execution */
77
- type: "delayed";
78
- /** Timestamp when the task should execute */
79
- time: number;
80
- /** Number of seconds to delay execution */
81
- delayInSeconds: number;
82
- } | {
83
- /** Type of schedule for recurring execution based on cron expression */
84
- type: "cron";
85
- /** Timestamp for the next execution */
86
- time: number;
87
- /** Cron expression defining the schedule */
88
- cron: string;
89
- });
90
- declare const unstable_context: AsyncLocalStorage<{
91
- agent: Agent<unknown>;
92
- connection: Connection | undefined;
93
- request: Request | undefined;
94
- }>;
76
+ /** Unique identifier for the schedule */
77
+ id: string;
78
+ /** Name of the method to be called */
79
+ callback: string;
80
+ /** Data to be passed to the callback */
81
+ payload: T;
82
+ } & (
83
+ | {
84
+ /** Type of schedule for one-time execution at a specific time */
85
+ type: "scheduled";
86
+ /** Timestamp when the task should execute */
87
+ time: number;
88
+ }
89
+ | {
90
+ /** Type of schedule for delayed execution */
91
+ type: "delayed";
92
+ /** Timestamp when the task should execute */
93
+ time: number;
94
+ /** Number of seconds to delay execution */
95
+ delayInSeconds: number;
96
+ }
97
+ | {
98
+ /** Type of schedule for recurring execution based on cron expression */
99
+ type: "cron";
100
+ /** Timestamp for the next execution */
101
+ time: number;
102
+ /** Cron expression defining the schedule */
103
+ cron: string;
104
+ }
105
+ );
106
+ declare function getCurrentAgent<
107
+ T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
108
+ >(): {
109
+ agent: T | undefined;
110
+ connection: Connection | undefined;
111
+ request: Request<unknown, CfProperties<unknown>> | undefined;
112
+ };
95
113
  /**
96
114
  * Base class for creating Agent implementations
97
115
  * @template Env Environment type containing bindings
98
116
  * @template State State type to store within the Agent
99
117
  */
100
118
  declare class Agent<Env, State = unknown> extends Server<Env> {
101
- #private;
102
- /**
103
- * Initial state for the Agent
104
- * Override to provide default state values
105
- */
106
- initialState: State;
107
- /**
108
- * Current state of the Agent
109
- */
110
- get state(): State;
111
- /**
112
- * Agent configuration options
113
- */
114
- static options: {
115
- /** Whether the Agent should hibernate when inactive */
116
- hibernate: boolean;
119
+ #private;
120
+ mcp: MCPClientManager;
121
+ /**
122
+ * Initial state for the Agent
123
+ * Override to provide default state values
124
+ */
125
+ initialState: State;
126
+ /**
127
+ * Current state of the Agent
128
+ */
129
+ get state(): State;
130
+ /**
131
+ * Agent configuration options
132
+ */
133
+ static options: {
134
+ /** Whether the Agent should hibernate when inactive */
135
+ hibernate: boolean;
136
+ };
137
+ /**
138
+ * Execute SQL queries against the Agent's database
139
+ * @template T Type of the returned rows
140
+ * @param strings SQL query template strings
141
+ * @param values Values to be inserted into the query
142
+ * @returns Array of query results
143
+ */
144
+ sql<T = Record<string, string | number | boolean | null>>(
145
+ strings: TemplateStringsArray,
146
+ ...values: (string | number | boolean | null)[]
147
+ ): T[];
148
+ constructor(ctx: AgentContext, env: Env);
149
+ /**
150
+ * Update the Agent's state
151
+ * @param state New state to set
152
+ */
153
+ setState(state: State): void;
154
+ /**
155
+ * Called when the Agent's state is updated
156
+ * @param state Updated state
157
+ * @param source Source of the state update ("server" or a client connection)
158
+ */
159
+ onStateUpdate(state: State | undefined, source: Connection | "server"): void;
160
+ /**
161
+ * Called when the Agent receives an email
162
+ * @param email Email message to process
163
+ */
164
+ onEmail(email: ForwardableEmailMessage): Promise<void>;
165
+ onError(connection: Connection, error: unknown): void | Promise<void>;
166
+ onError(error: unknown): void | Promise<void>;
167
+ /**
168
+ * Render content (not implemented in base class)
169
+ */
170
+ render(): void;
171
+ /**
172
+ * Schedule a task to be executed in the future
173
+ * @template T Type of the payload data
174
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
175
+ * @param callback Name of the method to call
176
+ * @param payload Data to pass to the callback
177
+ * @returns Schedule object representing the scheduled task
178
+ */
179
+ schedule<T = string>(
180
+ when: Date | string | number,
181
+ callback: keyof this,
182
+ payload?: T
183
+ ): Promise<Schedule<T>>;
184
+ /**
185
+ * Get a scheduled task by ID
186
+ * @template T Type of the payload data
187
+ * @param id ID of the scheduled task
188
+ * @returns The Schedule object or undefined if not found
189
+ */
190
+ getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
191
+ /**
192
+ * Get scheduled tasks matching the given criteria
193
+ * @template T Type of the payload data
194
+ * @param criteria Criteria to filter schedules
195
+ * @returns Array of matching Schedule objects
196
+ */
197
+ getSchedules<T = string>(criteria?: {
198
+ id?: string;
199
+ type?: "scheduled" | "delayed" | "cron";
200
+ timeRange?: {
201
+ start?: Date;
202
+ end?: Date;
117
203
  };
118
- /**
119
- * Execute SQL queries against the Agent's database
120
- * @template T Type of the returned rows
121
- * @param strings SQL query template strings
122
- * @param values Values to be inserted into the query
123
- * @returns Array of query results
124
- */
125
- sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
126
- constructor(ctx: AgentContext, env: Env);
127
- /**
128
- * Update the Agent's state
129
- * @param state New state to set
130
- */
131
- setState(state: State): void;
132
- /**
133
- * Called when the Agent's state is updated
134
- * @param state Updated state
135
- * @param source Source of the state update ("server" or a client connection)
136
- */
137
- onStateUpdate(state: State | undefined, source: Connection | "server"): void;
138
- /**
139
- * Called when the Agent receives an email
140
- * @param email Email message to process
141
- */
142
- onEmail(email: ForwardableEmailMessage): Promise<void>;
143
- onError(connection: Connection, error: unknown): void | Promise<void>;
144
- onError(error: unknown): void | Promise<void>;
145
- /**
146
- * Render content (not implemented in base class)
147
- */
148
- render(): void;
149
- /**
150
- * Schedule a task to be executed in the future
151
- * @template T Type of the payload data
152
- * @param when When to execute the task (Date, seconds delay, or cron expression)
153
- * @param callback Name of the method to call
154
- * @param payload Data to pass to the callback
155
- * @returns Schedule object representing the scheduled task
156
- */
157
- schedule<T = string>(when: Date | string | number, callback: keyof this, payload?: T): Promise<Schedule<T>>;
158
- /**
159
- * Get a scheduled task by ID
160
- * @template T Type of the payload data
161
- * @param id ID of the scheduled task
162
- * @returns The Schedule object or undefined if not found
163
- */
164
- getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
165
- /**
166
- * Get scheduled tasks matching the given criteria
167
- * @template T Type of the payload data
168
- * @param criteria Criteria to filter schedules
169
- * @returns Array of matching Schedule objects
170
- */
171
- getSchedules<T = string>(criteria?: {
172
- id?: string;
173
- type?: "scheduled" | "delayed" | "cron";
174
- timeRange?: {
175
- start?: Date;
176
- end?: Date;
177
- };
178
- }): Schedule<T>[];
179
- /**
180
- * Cancel a scheduled task
181
- * @param id ID of the task to cancel
182
- * @returns true if the task was cancelled, false otherwise
183
- */
184
- cancelSchedule(id: string): Promise<boolean>;
185
- /**
186
- * Method called when an alarm fires
187
- * Executes any scheduled tasks that are due
188
- */
189
- alarm(): Promise<void>;
190
- /**
191
- * Destroy the Agent, removing all state and scheduled tasks
192
- */
193
- destroy(): Promise<void>;
204
+ }): Schedule<T>[];
205
+ /**
206
+ * Cancel a scheduled task
207
+ * @param id ID of the task to cancel
208
+ * @returns true if the task was cancelled, false otherwise
209
+ */
210
+ cancelSchedule(id: string): Promise<boolean>;
211
+ /**
212
+ * Method called when an alarm fires
213
+ * Executes any scheduled tasks that are due
214
+ */
215
+ alarm(): Promise<void>;
216
+ /**
217
+ * Destroy the Agent, removing all state and scheduled tasks
218
+ */
219
+ destroy(): Promise<void>;
194
220
  }
195
221
  /**
196
222
  * Namespace for creating Agent instances
197
223
  * @template Agentic Type of the Agent class
198
224
  */
199
- type AgentNamespace<Agentic extends Agent<unknown>> = DurableObjectNamespace<Agentic>;
225
+ type AgentNamespace<Agentic extends Agent<unknown>> =
226
+ DurableObjectNamespace<Agentic>;
200
227
  /**
201
228
  * Agent's durable context
202
229
  */
@@ -205,10 +232,10 @@ type AgentContext = DurableObjectState;
205
232
  * Configuration options for Agent routing
206
233
  */
207
234
  type AgentOptions<Env> = PartyServerOptions<Env> & {
208
- /**
209
- * Whether to enable CORS for the Agent
210
- */
211
- cors?: boolean | HeadersInit | undefined;
235
+ /**
236
+ * Whether to enable CORS for the Agent
237
+ */
238
+ cors?: boolean | HeadersInit | undefined;
212
239
  };
213
240
  /**
214
241
  * Route a request to the appropriate Agent
@@ -217,14 +244,22 @@ type AgentOptions<Env> = PartyServerOptions<Env> & {
217
244
  * @param options Routing options
218
245
  * @returns Response from the Agent or undefined if no route matched
219
246
  */
220
- declare function routeAgentRequest<Env>(request: Request, env: Env, options?: AgentOptions<Env>): Promise<Response | null>;
247
+ declare function routeAgentRequest<Env>(
248
+ request: Request,
249
+ env: Env,
250
+ options?: AgentOptions<Env>
251
+ ): Promise<Response | null>;
221
252
  /**
222
253
  * Route an email to the appropriate Agent
223
254
  * @param email Email message to route
224
255
  * @param env Environment containing Agent bindings
225
256
  * @param options Routing options
226
257
  */
227
- declare function routeAgentEmail<Env>(email: ForwardableEmailMessage, env: Env, options?: AgentOptions<Env>): Promise<void>;
258
+ declare function routeAgentEmail<Env>(
259
+ email: ForwardableEmailMessage,
260
+ env: Env,
261
+ options?: AgentOptions<Env>
262
+ ): Promise<void>;
228
263
  /**
229
264
  * Get or create an Agent by name
230
265
  * @template Env Environment type containing bindings
@@ -234,26 +269,46 @@ declare function routeAgentEmail<Env>(email: ForwardableEmailMessage, env: Env,
234
269
  * @param options Options for Agent creation
235
270
  * @returns Promise resolving to an Agent instance stub
236
271
  */
237
- declare function getAgentByName<Env, T extends Agent<Env>>(namespace: AgentNamespace<T>, name: string, options?: {
272
+ declare function getAgentByName<Env, T extends Agent<Env>>(
273
+ namespace: AgentNamespace<T>,
274
+ name: string,
275
+ options?: {
238
276
  jurisdiction?: DurableObjectJurisdiction;
239
277
  locationHint?: DurableObjectLocationHint;
240
- }): Promise<DurableObjectStub<T>>;
278
+ }
279
+ ): Promise<DurableObjectStub<T>>;
241
280
  /**
242
281
  * A wrapper for streaming responses in callable methods
243
282
  */
244
283
  declare class StreamingResponse {
245
- #private;
246
- constructor(connection: Connection, id: string);
247
- /**
248
- * Send a chunk of data to the client
249
- * @param chunk The data to send
250
- */
251
- send(chunk: unknown): void;
252
- /**
253
- * End the stream and send the final chunk (if any)
254
- * @param finalChunk Optional final chunk of data to send
255
- */
256
- end(finalChunk?: unknown): void;
284
+ #private;
285
+ constructor(connection: Connection, id: string);
286
+ /**
287
+ * Send a chunk of data to the client
288
+ * @param chunk The data to send
289
+ */
290
+ send(chunk: unknown): void;
291
+ /**
292
+ * End the stream and send the final chunk (if any)
293
+ * @param finalChunk Optional final chunk of data to send
294
+ */
295
+ end(finalChunk?: unknown): void;
257
296
  }
258
297
 
259
- export { Agent, type AgentContext, type AgentNamespace, type AgentOptions, type CallableMetadata, type RPCRequest, type RPCResponse, type Schedule, type StateUpdateMessage, StreamingResponse, WorkflowEntrypoint, getAgentByName, routeAgentEmail, routeAgentRequest, unstable_callable, unstable_context };
298
+ export {
299
+ Agent,
300
+ type AgentContext,
301
+ type AgentNamespace,
302
+ type AgentOptions,
303
+ type CallableMetadata,
304
+ type RPCRequest,
305
+ type RPCResponse,
306
+ type Schedule,
307
+ type StateUpdateMessage,
308
+ StreamingResponse,
309
+ getAgentByName,
310
+ getCurrentAgent,
311
+ routeAgentEmail,
312
+ routeAgentRequest,
313
+ unstable_callable,
314
+ };
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ import {
2
+ Agent,
3
+ StreamingResponse,
4
+ getAgentByName,
5
+ getCurrentAgent,
6
+ routeAgentEmail,
7
+ routeAgentRequest,
8
+ unstable_callable
9
+ } from "./chunk-HD4VEHBA.js";
10
+ import "./chunk-Q5ZBHY4Z.js";
11
+ import "./chunk-HMLY7DHA.js";
12
+ export {
13
+ Agent,
14
+ StreamingResponse,
15
+ getAgentByName,
16
+ getCurrentAgent,
17
+ routeAgentEmail,
18
+ routeAgentRequest,
19
+ unstable_callable
20
+ };
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}